diff --git a/index.html b/index.html deleted file mode 100644 index 587f5d5..0000000 --- a/index.html +++ /dev/null @@ -1 +0,0 @@ -Temp diff --git a/lib/godoc/godocs.js b/lib/godoc/godocs.js new file mode 100644 index 0000000..ec9f37a --- /dev/null +++ b/lib/godoc/godocs.js @@ -0,0 +1,571 @@ +// Copyright 2012 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +/* A little code to ease navigation of these documents. + * + * On window load we: + * + Bind search box hint placeholder show/hide events (bindSearchEvents) + * + Generate a table of contents (generateTOC) + * + Bind foldable sections (bindToggles) + * + Bind links to foldable sections (bindToggleLinks) + */ + +(function() { +'use strict'; + +// Mobile-friendly topbar menu +$(function() { + var menu = $('#menu'); + var menuButton = $('#menu-button'); + var menuButtonArrow = $('#menu-button-arrow'); + menuButton.click(function(event) { + menu.toggleClass('menu-visible'); + menuButtonArrow.toggleClass('vertical-flip'); + event.preventDefault(); + return false; + }); +}); + +function bindSearchEvents() { + + var search = $('#search'); + if (search.length === 0) { + return; // no search box + } + + function clearInactive() { + if (search.is('.inactive')) { + search.val(''); + search.removeClass('inactive'); + } + } + + function restoreInactive() { + if (search.val() !== '') { + return; + } + search.val(search.attr('placeholder')); + search.addClass('inactive'); + } + + search.on('focus', clearInactive); + search.on('blur', restoreInactive); + + restoreInactive(); +} + +/* Generates a table of contents: looks for h2 and h3 elements and generates + * links. "Decorates" the element with id=="nav" with this table of contents. + */ +function generateTOC() { + if ($('#manual-nav').length > 0) { + return; + } + + var nav = $('#nav'); + if (nav.length === 0) { + return; + } + + var toc_items = []; + $(nav).nextAll('h2, h3').each(function() { + var node = this; + if (node.id == '') + node.id = 'tmp_' + toc_items.length; + var link = $('').attr('href', '#' + node.id).text($(node).text()); + var item; + if ($(node).is('h2')) { + item = $('
'); + } else { // h3 + item = $('
'); + } + item.append(link); + toc_items.push(item); + }); + if (toc_items.length <= 1) { + return; + } + + var dl1 = $('
'); + var dl2 = $('
'); + + var split_index = (toc_items.length / 2) + 1; + if (split_index < 8) { + split_index = toc_items.length; + } + for (var i = 0; i < split_index; i++) { + dl1.append(toc_items[i]); + } + for (/* keep using i */; i < toc_items.length; i++) { + dl2.append(toc_items[i]); + } + + var tocTable = $('').appendTo(nav); + var tocBody = $('').appendTo(tocTable); + var tocRow = $('').appendTo(tocBody); + + // 1st column + $(']","i"),bv=/^(?:checkbox|radio)$/,bw=/checked\s*(?:[^=]|=\s*.checked.)/i,bx=/\/(java|ecma)script/i,by=/^\s*\s*$/g,bz={option:[1,""],legend:[1,"
","
"],thead:[1,"
').appendTo(tocRow).append(dl1); + // 2nd column + $('').appendTo(tocRow).append(dl2); +} + +function bindToggle(el) { + $('.toggleButton', el).click(function() { + if ($(el).is('.toggle')) { + $(el).addClass('toggleVisible').removeClass('toggle'); + } else { + $(el).addClass('toggle').removeClass('toggleVisible'); + } + }); +} +function bindToggles(selector) { + $(selector).each(function(i, el) { + bindToggle(el); + }); +} + +function bindToggleLink(el, prefix) { + $(el).click(function() { + var href = $(el).attr('href'); + var i = href.indexOf('#'+prefix); + if (i < 0) { + return; + } + var id = '#' + prefix + href.slice(i+1+prefix.length); + if ($(id).is('.toggle')) { + $(id).find('.toggleButton').first().click(); + } + }); +} +function bindToggleLinks(selector, prefix) { + $(selector).each(function(i, el) { + bindToggleLink(el, prefix); + }); +} + +function setupDropdownPlayground() { + if (!$('#page').is('.wide')) { + return; // don't show on front page + } + var button = $('#playgroundButton'); + var div = $('#playground'); + var setup = false; + button.toggle(function() { + button.addClass('active'); + div.show(); + if (setup) { + return; + } + setup = true; + playground({ + 'codeEl': $('.code', div), + 'outputEl': $('.output', div), + 'runEl': $('.run', div), + 'fmtEl': $('.fmt', div), + 'shareEl': $('.share', div), + 'shareRedirect': '//play.golang.org/p/' + }); + }, + function() { + button.removeClass('active'); + div.hide(); + }); + button.show(); + $('#menu').css('min-width', '+=60'); +} + +function setupInlinePlayground() { + 'use strict'; + // Set up playground when each element is toggled. + $('div.play').each(function (i, el) { + // Set up playground for this example. + var setup = function() { + var code = $('.code', el); + playground({ + 'codeEl': code, + 'outputEl': $('.output', el), + 'runEl': $('.run', el), + 'fmtEl': $('.fmt', el), + 'shareEl': $('.share', el), + 'shareRedirect': '//play.golang.org/p/' + }); + + // Make the code textarea resize to fit content. + var resize = function() { + code.height(0); + var h = code[0].scrollHeight; + code.height(h+20); // minimize bouncing. + code.closest('.input').height(h); + }; + code.on('keydown', resize); + code.on('keyup', resize); + code.keyup(); // resize now. + }; + + // If example already visible, set up playground now. + if ($(el).is(':visible')) { + setup(); + return; + } + + // Otherwise, set up playground when example is expanded. + var built = false; + $(el).closest('.toggle').click(function() { + // Only set up once. + if (!built) { + setup(); + built = true; + } + }); + }); +} + +// fixFocus tries to put focus to div#page so that keyboard navigation works. +function fixFocus() { + var page = $('div#page'); + var topbar = $('div#topbar'); + page.css('outline', 0); // disable outline when focused + page.attr('tabindex', -1); // and set tabindex so that it is focusable + $(window).resize(function (evt) { + // only focus page when the topbar is at fixed position (that is, it's in + // front of page, and keyboard event will go to the former by default.) + // by focusing page, keyboard event will go to page so that up/down arrow, + // space, etc. will work as expected. + if (topbar.css('position') == "fixed") + page.focus(); + }).resize(); +} + +function toggleHash() { + var hash = $(window.location.hash); + if (hash.is('.toggle')) { + hash.find('.toggleButton').first().click(); + } +} + +function personalizeInstallInstructions() { + var prefix = '?download='; + var s = window.location.search; + if (s.indexOf(prefix) != 0) { + // No 'download' query string; bail. + return; + } + + var filename = s.substr(prefix.length); + var filenameRE = /^go1\.\d+(\.\d+)?([a-z0-9]+)?\.([a-z0-9]+)(-[a-z0-9]+)?(-osx10\.[68])?\.([a-z.]+)$/; + $('.downloadFilename').text(filename); + $('.hideFromDownload').hide(); + var m = filenameRE.exec(filename); + if (!m) { + // Can't interpret file name; bail. + return; + } + + var os = m[3]; + var ext = m[6]; + if (ext != 'tar.gz') { + $('#tarballInstructions').hide(); + } + if (os != 'darwin' || ext != 'pkg') { + $('#darwinPackageInstructions').hide(); + } + if (os != 'windows') { + $('#windowsInstructions').hide(); + $('.testUnix').show(); + $('.testWindows').hide(); + } else { + if (ext != 'msi') { + $('#windowsInstallerInstructions').hide(); + } + if (ext != 'zip') { + $('#windowsZipInstructions').hide(); + } + $('.testUnix').hide(); + $('.testWindows').show(); + } + + var download = "https://storage.googleapis.com/golang/" + filename; + + var message = $('

'+ + 'Your download should begin shortly. '+ + 'If it does not, click this link.

'); + message.find('a').attr('href', download); + message.insertAfter('#nav'); + + window.location = download; +} + +$(document).ready(function() { + bindSearchEvents(); + generateTOC(); + bindToggles(".toggle"); + bindToggles(".toggleVisible"); + bindToggleLinks(".exampleLink", "example_"); + bindToggleLinks(".overviewLink", ""); + bindToggleLinks(".examplesLink", ""); + bindToggleLinks(".indexLink", ""); + setupDropdownPlayground(); + setupInlinePlayground(); + fixFocus(); + setupTypeInfo(); + setupCallgraphs(); + toggleHash(); + personalizeInstallInstructions(); + + // godoc.html defines window.initFuncs in the tag, and root.html and + // codewalk.js push their on-page-ready functions to the list. + // We execute those functions here, to avoid loading jQuery until the page + // content is loaded. + for (var i = 0; i < window.initFuncs.length; i++) window.initFuncs[i](); +}); + +// -- analysis --------------------------------------------------------- + +// escapeHTML returns HTML for s, with metacharacters quoted. +// It is safe for use in both elements and attributes +// (unlike the "set innerText, read innerHTML" trick). +function escapeHTML(s) { + return s.replace(/&/g, '&'). + replace(/\"/g, '"'). + replace(/\'/g, '''). + replace(//g, '>'); +} + +// makeAnchor returns HTML for an element, given an anchorJSON object. +function makeAnchor(json) { + var html = escapeHTML(json.Text); + if (json.Href != "") { + html = "" + html + ""; + } + return html; +} + +function showLowFrame(html) { + var lowframe = document.getElementById('lowframe'); + lowframe.style.height = "200px"; + lowframe.innerHTML = "

" + html + "

\n" + + "
" +}; + +document.hideLowFrame = function() { + var lowframe = document.getElementById('lowframe'); + lowframe.style.height = "0px"; +} + +// onClickCallers is the onclick action for the 'func' tokens of a +// function declaration. +document.onClickCallers = function(index) { + var data = document.ANALYSIS_DATA[index] + if (data.Callers.length == 1 && data.Callers[0].Sites.length == 1) { + document.location = data.Callers[0].Sites[0].Href; // jump to sole caller + return; + } + + var html = "Callers of " + escapeHTML(data.Callee) + ":
\n"; + for (var i = 0; i < data.Callers.length; i++) { + var caller = data.Callers[i]; + html += "" + escapeHTML(caller.Func) + ""; + var sites = caller.Sites; + if (sites != null && sites.length > 0) { + html += " at line "; + for (var j = 0; j < sites.length; j++) { + if (j > 0) { + html += ", "; + } + html += "" + makeAnchor(sites[j]) + ""; + } + } + html += "
\n"; + } + showLowFrame(html); +}; + +// onClickCallees is the onclick action for the '(' token of a function call. +document.onClickCallees = function(index) { + var data = document.ANALYSIS_DATA[index] + if (data.Callees.length == 1) { + document.location = data.Callees[0].Href; // jump to sole callee + return; + } + + var html = "Callees of this " + escapeHTML(data.Descr) + ":
\n"; + for (var i = 0; i < data.Callees.length; i++) { + html += "" + makeAnchor(data.Callees[i]) + "
\n"; + } + showLowFrame(html); +}; + +// onClickTypeInfo is the onclick action for identifiers declaring a named type. +document.onClickTypeInfo = function(index) { + var data = document.ANALYSIS_DATA[index]; + var html = "Type " + data.Name + ": " + + "      (size=" + data.Size + ", align=" + data.Align + ")
\n"; + html += implementsHTML(data); + html += methodsetHTML(data); + showLowFrame(html); +}; + +// implementsHTML returns HTML for the implements relation of the +// specified TypeInfoJSON value. +function implementsHTML(info) { + var html = ""; + if (info.ImplGroups != null) { + for (var i = 0; i < info.ImplGroups.length; i++) { + var group = info.ImplGroups[i]; + var x = "" + escapeHTML(group.Descr) + " "; + for (var j = 0; j < group.Facts.length; j++) { + var fact = group.Facts[j]; + var y = "" + makeAnchor(fact.Other) + ""; + if (fact.ByKind != null) { + html += escapeHTML(fact.ByKind) + " type " + y + " implements " + x; + } else { + html += x + " implements " + y; + } + html += "
\n"; + } + } + } + return html; +} + + +// methodsetHTML returns HTML for the methodset of the specified +// TypeInfoJSON value. +function methodsetHTML(info) { + var html = ""; + if (info.Methods != null) { + for (var i = 0; i < info.Methods.length; i++) { + html += "" + makeAnchor(info.Methods[i]) + "
\n"; + } + } + return html; +} + +// onClickComm is the onclick action for channel "make" and "<-" +// send/receive tokens. +document.onClickComm = function(index) { + var ops = document.ANALYSIS_DATA[index].Ops + if (ops.length == 1) { + document.location = ops[0].Op.Href; // jump to sole element + return; + } + + var html = "Operations on this channel:
\n"; + for (var i = 0; i < ops.length; i++) { + html += makeAnchor(ops[i].Op) + " by " + escapeHTML(ops[i].Fn) + "
\n"; + } + if (ops.length == 0) { + html += "(none)
\n"; + } + showLowFrame(html); +}; + +$(window).load(function() { + // Scroll window so that first selection is visible. + // (This means we don't need to emit id='L%d' spans for each line.) + // TODO(adonovan): ideally, scroll it so that it's under the pointer, + // but I don't know how to get the pointer y coordinate. + var elts = document.getElementsByClassName("selection"); + if (elts.length > 0) { + elts[0].scrollIntoView() + } +}); + +// setupTypeInfo populates the "Implements" and "Method set" toggle for +// each type in the package doc. +function setupTypeInfo() { + for (var i in document.ANALYSIS_DATA) { + var data = document.ANALYSIS_DATA[i]; + + var el = document.getElementById("implements-" + i); + if (el != null) { + // el != null => data is TypeInfoJSON. + if (data.ImplGroups != null) { + el.innerHTML = implementsHTML(data); + el.parentNode.parentNode.style.display = "block"; + } + } + + var el = document.getElementById("methodset-" + i); + if (el != null) { + // el != null => data is TypeInfoJSON. + if (data.Methods != null) { + el.innerHTML = methodsetHTML(data); + el.parentNode.parentNode.style.display = "block"; + } + } + } +} + +function setupCallgraphs() { + if (document.CALLGRAPH == null) { + return + } + document.getElementById("pkg-callgraph").style.display = "block"; + + var treeviews = document.getElementsByClassName("treeview"); + for (var i = 0; i < treeviews.length; i++) { + var tree = treeviews[i]; + if (tree.id == null || tree.id.indexOf("callgraph-") != 0) { + continue; + } + var id = tree.id.substring("callgraph-".length); + $(tree).treeview({collapsed: true, animated: "fast"}); + document.cgAddChildren(tree, tree, [id]); + tree.parentNode.parentNode.style.display = "block"; + } +} + +document.cgAddChildren = function(tree, ul, indices) { + if (indices != null) { + for (var i = 0; i < indices.length; i++) { + var li = cgAddChild(tree, ul, document.CALLGRAPH[indices[i]]); + if (i == indices.length - 1) { + $(li).addClass("last"); + } + } + } + $(tree).treeview({animated: "fast", add: ul}); +} + +// cgAddChild adds an
  • element for document.CALLGRAPH node cgn to +// the parent
      element ul. tree is the tree's root
        element. +function cgAddChild(tree, ul, cgn) { + var li = document.createElement("li"); + ul.appendChild(li); + li.className = "closed"; + + var code = document.createElement("code"); + + if (cgn.Callees != null) { + $(li).addClass("expandable"); + + // Event handlers and innerHTML updates don't play nicely together, + // hence all this explicit DOM manipulation. + var hitarea = document.createElement("div"); + hitarea.className = "hitarea expandable-hitarea"; + li.appendChild(hitarea); + + li.appendChild(code); + + var childUL = document.createElement("ul"); + li.appendChild(childUL); + childUL.setAttribute('style', "display: none;"); + + var onClick = function() { + document.cgAddChildren(tree, childUL, cgn.Callees); + hitarea.removeEventListener('click', onClick) + }; + hitarea.addEventListener('click', onClick); + + } else { + li.appendChild(code); + } + code.innerHTML += " " + makeAnchor(cgn.Func); + return li +} + +})(); diff --git a/lib/godoc/images/treeview-black-line.gif b/lib/godoc/images/treeview-black-line.gif new file mode 100644 index 0000000..e549687 Binary files /dev/null and b/lib/godoc/images/treeview-black-line.gif differ diff --git a/lib/godoc/images/treeview-black.gif b/lib/godoc/images/treeview-black.gif new file mode 100644 index 0000000..b718d17 Binary files /dev/null and b/lib/godoc/images/treeview-black.gif differ diff --git a/lib/godoc/images/treeview-default-line.gif b/lib/godoc/images/treeview-default-line.gif new file mode 100644 index 0000000..37114d3 Binary files /dev/null and b/lib/godoc/images/treeview-default-line.gif differ diff --git a/lib/godoc/images/treeview-default.gif b/lib/godoc/images/treeview-default.gif new file mode 100644 index 0000000..76eee60 Binary files /dev/null and b/lib/godoc/images/treeview-default.gif differ diff --git a/lib/godoc/images/treeview-gray-line.gif b/lib/godoc/images/treeview-gray-line.gif new file mode 100644 index 0000000..3760044 Binary files /dev/null and b/lib/godoc/images/treeview-gray-line.gif differ diff --git a/lib/godoc/images/treeview-gray.gif b/lib/godoc/images/treeview-gray.gif new file mode 100644 index 0000000..cfdf1ab Binary files /dev/null and b/lib/godoc/images/treeview-gray.gif differ diff --git a/lib/godoc/jquery.js b/lib/godoc/jquery.js new file mode 100644 index 0000000..bc3fbc8 --- /dev/null +++ b/lib/godoc/jquery.js @@ -0,0 +1,2 @@ +/*! jQuery v1.8.2 jquery.com | jquery.org/license */ +(function(a,b){function G(a){var b=F[a]={};return p.each(a.split(s),function(a,c){b[c]=!0}),b}function J(a,c,d){if(d===b&&a.nodeType===1){var e="data-"+c.replace(I,"-$1").toLowerCase();d=a.getAttribute(e);if(typeof d=="string"){try{d=d==="true"?!0:d==="false"?!1:d==="null"?null:+d+""===d?+d:H.test(d)?p.parseJSON(d):d}catch(f){}p.data(a,c,d)}else d=b}return d}function K(a){var b;for(b in a){if(b==="data"&&p.isEmptyObject(a[b]))continue;if(b!=="toJSON")return!1}return!0}function ba(){return!1}function bb(){return!0}function bh(a){return!a||!a.parentNode||a.parentNode.nodeType===11}function bi(a,b){do a=a[b];while(a&&a.nodeType!==1);return a}function bj(a,b,c){b=b||0;if(p.isFunction(b))return p.grep(a,function(a,d){var e=!!b.call(a,d,a);return e===c});if(b.nodeType)return p.grep(a,function(a,d){return a===b===c});if(typeof b=="string"){var d=p.grep(a,function(a){return a.nodeType===1});if(be.test(b))return p.filter(b,d,!c);b=p.filter(b,d)}return p.grep(a,function(a,d){return p.inArray(a,b)>=0===c})}function bk(a){var b=bl.split("|"),c=a.createDocumentFragment();if(c.createElement)while(b.length)c.createElement(b.pop());return c}function bC(a,b){return a.getElementsByTagName(b)[0]||a.appendChild(a.ownerDocument.createElement(b))}function bD(a,b){if(b.nodeType!==1||!p.hasData(a))return;var c,d,e,f=p._data(a),g=p._data(b,f),h=f.events;if(h){delete g.handle,g.events={};for(c in h)for(d=0,e=h[c].length;d").appendTo(e.body),c=b.css("display");b.remove();if(c==="none"||c===""){bI=e.body.appendChild(bI||p.extend(e.createElement("iframe"),{frameBorder:0,width:0,height:0}));if(!bJ||!bI.createElement)bJ=(bI.contentWindow||bI.contentDocument).document,bJ.write(""),bJ.close();b=bJ.body.appendChild(bJ.createElement(a)),c=bH(b,"display"),e.body.removeChild(bI)}return bS[a]=c,c}function ci(a,b,c,d){var e;if(p.isArray(b))p.each(b,function(b,e){c||ce.test(a)?d(a,e):ci(a+"["+(typeof e=="object"?b:"")+"]",e,c,d)});else if(!c&&p.type(b)==="object")for(e in b)ci(a+"["+e+"]",b[e],c,d);else d(a,b)}function cz(a){return function(b,c){typeof b!="string"&&(c=b,b="*");var d,e,f,g=b.toLowerCase().split(s),h=0,i=g.length;if(p.isFunction(c))for(;h)[^>]*$|#([\w\-]*)$)/,v=/^<(\w+)\s*\/?>(?:<\/\1>|)$/,w=/^[\],:{}\s]*$/,x=/(?:^|:|,)(?:\s*\[)+/g,y=/\\(?:["\\\/bfnrt]|u[\da-fA-F]{4})/g,z=/"[^"\\\r\n]*"|true|false|null|-?(?:\d\d*\.|)\d+(?:[eE][\-+]?\d+|)/g,A=/^-ms-/,B=/-([\da-z])/gi,C=function(a,b){return(b+"").toUpperCase()},D=function(){e.addEventListener?(e.removeEventListener("DOMContentLoaded",D,!1),p.ready()):e.readyState==="complete"&&(e.detachEvent("onreadystatechange",D),p.ready())},E={};p.fn=p.prototype={constructor:p,init:function(a,c,d){var f,g,h,i;if(!a)return this;if(a.nodeType)return this.context=this[0]=a,this.length=1,this;if(typeof a=="string"){a.charAt(0)==="<"&&a.charAt(a.length-1)===">"&&a.length>=3?f=[null,a,null]:f=u.exec(a);if(f&&(f[1]||!c)){if(f[1])return c=c instanceof p?c[0]:c,i=c&&c.nodeType?c.ownerDocument||c:e,a=p.parseHTML(f[1],i,!0),v.test(f[1])&&p.isPlainObject(c)&&this.attr.call(a,c,!0),p.merge(this,a);g=e.getElementById(f[2]);if(g&&g.parentNode){if(g.id!==f[2])return d.find(a);this.length=1,this[0]=g}return this.context=e,this.selector=a,this}return!c||c.jquery?(c||d).find(a):this.constructor(c).find(a)}return p.isFunction(a)?d.ready(a):(a.selector!==b&&(this.selector=a.selector,this.context=a.context),p.makeArray(a,this))},selector:"",jquery:"1.8.2",length:0,size:function(){return this.length},toArray:function(){return k.call(this)},get:function(a){return a==null?this.toArray():a<0?this[this.length+a]:this[a]},pushStack:function(a,b,c){var d=p.merge(this.constructor(),a);return d.prevObject=this,d.context=this.context,b==="find"?d.selector=this.selector+(this.selector?" ":"")+c:b&&(d.selector=this.selector+"."+b+"("+c+")"),d},each:function(a,b){return p.each(this,a,b)},ready:function(a){return p.ready.promise().done(a),this},eq:function(a){return a=+a,a===-1?this.slice(a):this.slice(a,a+1)},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},slice:function(){return this.pushStack(k.apply(this,arguments),"slice",k.call(arguments).join(","))},map:function(a){return this.pushStack(p.map(this,function(b,c){return a.call(b,c,b)}))},end:function(){return this.prevObject||this.constructor(null)},push:j,sort:[].sort,splice:[].splice},p.fn.init.prototype=p.fn,p.extend=p.fn.extend=function(){var a,c,d,e,f,g,h=arguments[0]||{},i=1,j=arguments.length,k=!1;typeof h=="boolean"&&(k=h,h=arguments[1]||{},i=2),typeof h!="object"&&!p.isFunction(h)&&(h={}),j===i&&(h=this,--i);for(;i0)return;d.resolveWith(e,[p]),p.fn.trigger&&p(e).trigger("ready").off("ready")},isFunction:function(a){return p.type(a)==="function"},isArray:Array.isArray||function(a){return p.type(a)==="array"},isWindow:function(a){return a!=null&&a==a.window},isNumeric:function(a){return!isNaN(parseFloat(a))&&isFinite(a)},type:function(a){return a==null?String(a):E[m.call(a)]||"object"},isPlainObject:function(a){if(!a||p.type(a)!=="object"||a.nodeType||p.isWindow(a))return!1;try{if(a.constructor&&!n.call(a,"constructor")&&!n.call(a.constructor.prototype,"isPrototypeOf"))return!1}catch(c){return!1}var d;for(d in a);return d===b||n.call(a,d)},isEmptyObject:function(a){var b;for(b in a)return!1;return!0},error:function(a){throw new Error(a)},parseHTML:function(a,b,c){var d;return!a||typeof a!="string"?null:(typeof b=="boolean"&&(c=b,b=0),b=b||e,(d=v.exec(a))?[b.createElement(d[1])]:(d=p.buildFragment([a],b,c?null:[]),p.merge([],(d.cacheable?p.clone(d.fragment):d.fragment).childNodes)))},parseJSON:function(b){if(!b||typeof b!="string")return null;b=p.trim(b);if(a.JSON&&a.JSON.parse)return a.JSON.parse(b);if(w.test(b.replace(y,"@").replace(z,"]").replace(x,"")))return(new Function("return "+b))();p.error("Invalid JSON: "+b)},parseXML:function(c){var d,e;if(!c||typeof c!="string")return null;try{a.DOMParser?(e=new DOMParser,d=e.parseFromString(c,"text/xml")):(d=new ActiveXObject("Microsoft.XMLDOM"),d.async="false",d.loadXML(c))}catch(f){d=b}return(!d||!d.documentElement||d.getElementsByTagName("parsererror").length)&&p.error("Invalid XML: "+c),d},noop:function(){},globalEval:function(b){b&&r.test(b)&&(a.execScript||function(b){a.eval.call(a,b)})(b)},camelCase:function(a){return a.replace(A,"ms-").replace(B,C)},nodeName:function(a,b){return a.nodeName&&a.nodeName.toLowerCase()===b.toLowerCase()},each:function(a,c,d){var e,f=0,g=a.length,h=g===b||p.isFunction(a);if(d){if(h){for(e in a)if(c.apply(a[e],d)===!1)break}else for(;f0&&a[0]&&a[i-1]||i===0||p.isArray(a));if(j)for(;h-1)i.splice(c,1),e&&(c<=g&&g--,c<=h&&h--)}),this},has:function(a){return p.inArray(a,i)>-1},empty:function(){return i=[],this},disable:function(){return i=j=c=b,this},disabled:function(){return!i},lock:function(){return j=b,c||l.disable(),this},locked:function(){return!j},fireWith:function(a,b){return b=b||[],b=[a,b.slice?b.slice():b],i&&(!d||j)&&(e?j.push(b):k(b)),this},fire:function(){return l.fireWith(this,arguments),this},fired:function(){return!!d}};return l},p.extend({Deferred:function(a){var b=[["resolve","done",p.Callbacks("once memory"),"resolved"],["reject","fail",p.Callbacks("once memory"),"rejected"],["notify","progress",p.Callbacks("memory")]],c="pending",d={state:function(){return c},always:function(){return e.done(arguments).fail(arguments),this},then:function(){var a=arguments;return p.Deferred(function(c){p.each(b,function(b,d){var f=d[0],g=a[b];e[d[1]](p.isFunction(g)?function(){var a=g.apply(this,arguments);a&&p.isFunction(a.promise)?a.promise().done(c.resolve).fail(c.reject).progress(c.notify):c[f+"With"](this===e?c:this,[a])}:c[f])}),a=null}).promise()},promise:function(a){return a!=null?p.extend(a,d):d}},e={};return d.pipe=d.then,p.each(b,function(a,f){var g=f[2],h=f[3];d[f[1]]=g.add,h&&g.add(function(){c=h},b[a^1][2].disable,b[2][2].lock),e[f[0]]=g.fire,e[f[0]+"With"]=g.fireWith}),d.promise(e),a&&a.call(e,e),e},when:function(a){var b=0,c=k.call(arguments),d=c.length,e=d!==1||a&&p.isFunction(a.promise)?d:0,f=e===1?a:p.Deferred(),g=function(a,b,c){return function(d){b[a]=this,c[a]=arguments.length>1?k.call(arguments):d,c===h?f.notifyWith(b,c):--e||f.resolveWith(b,c)}},h,i,j;if(d>1){h=new Array(d),i=new Array(d),j=new Array(d);for(;b
        a",c=n.getElementsByTagName("*"),d=n.getElementsByTagName("a")[0],d.style.cssText="top:1px;float:left;opacity:.5";if(!c||!c.length)return{};f=e.createElement("select"),g=f.appendChild(e.createElement("option")),h=n.getElementsByTagName("input")[0],b={leadingWhitespace:n.firstChild.nodeType===3,tbody:!n.getElementsByTagName("tbody").length,htmlSerialize:!!n.getElementsByTagName("link").length,style:/top/.test(d.getAttribute("style")),hrefNormalized:d.getAttribute("href")==="/a",opacity:/^0.5/.test(d.style.opacity),cssFloat:!!d.style.cssFloat,checkOn:h.value==="on",optSelected:g.selected,getSetAttribute:n.className!=="t",enctype:!!e.createElement("form").enctype,html5Clone:e.createElement("nav").cloneNode(!0).outerHTML!=="<:nav>",boxModel:e.compatMode==="CSS1Compat",submitBubbles:!0,changeBubbles:!0,focusinBubbles:!1,deleteExpando:!0,noCloneEvent:!0,inlineBlockNeedsLayout:!1,shrinkWrapBlocks:!1,reliableMarginRight:!0,boxSizingReliable:!0,pixelPosition:!1},h.checked=!0,b.noCloneChecked=h.cloneNode(!0).checked,f.disabled=!0,b.optDisabled=!g.disabled;try{delete n.test}catch(o){b.deleteExpando=!1}!n.addEventListener&&n.attachEvent&&n.fireEvent&&(n.attachEvent("onclick",m=function(){b.noCloneEvent=!1}),n.cloneNode(!0).fireEvent("onclick"),n.detachEvent("onclick",m)),h=e.createElement("input"),h.value="t",h.setAttribute("type","radio"),b.radioValue=h.value==="t",h.setAttribute("checked","checked"),h.setAttribute("name","t"),n.appendChild(h),i=e.createDocumentFragment(),i.appendChild(n.lastChild),b.checkClone=i.cloneNode(!0).cloneNode(!0).lastChild.checked,b.appendChecked=h.checked,i.removeChild(h),i.appendChild(n);if(n.attachEvent)for(k in{submit:!0,change:!0,focusin:!0})j="on"+k,l=j in n,l||(n.setAttribute(j,"return;"),l=typeof n[j]=="function"),b[k+"Bubbles"]=l;return p(function(){var c,d,f,g,h="padding:0;margin:0;border:0;display:block;overflow:hidden;",i=e.getElementsByTagName("body")[0];if(!i)return;c=e.createElement("div"),c.style.cssText="visibility:hidden;border:0;width:0;height:0;position:static;top:0;margin-top:1px",i.insertBefore(c,i.firstChild),d=e.createElement("div"),c.appendChild(d),d.innerHTML="
        t
        ",f=d.getElementsByTagName("td"),f[0].style.cssText="padding:0;margin:0;border:0;display:none",l=f[0].offsetHeight===0,f[0].style.display="",f[1].style.display="none",b.reliableHiddenOffsets=l&&f[0].offsetHeight===0,d.innerHTML="",d.style.cssText="box-sizing:border-box;-moz-box-sizing:border-box;-webkit-box-sizing:border-box;padding:1px;border:1px;display:block;width:4px;margin-top:1%;position:absolute;top:1%;",b.boxSizing=d.offsetWidth===4,b.doesNotIncludeMarginInBodyOffset=i.offsetTop!==1,a.getComputedStyle&&(b.pixelPosition=(a.getComputedStyle(d,null)||{}).top!=="1%",b.boxSizingReliable=(a.getComputedStyle(d,null)||{width:"4px"}).width==="4px",g=e.createElement("div"),g.style.cssText=d.style.cssText=h,g.style.marginRight=g.style.width="0",d.style.width="1px",d.appendChild(g),b.reliableMarginRight=!parseFloat((a.getComputedStyle(g,null)||{}).marginRight)),typeof d.style.zoom!="undefined"&&(d.innerHTML="",d.style.cssText=h+"width:1px;padding:1px;display:inline;zoom:1",b.inlineBlockNeedsLayout=d.offsetWidth===3,d.style.display="block",d.style.overflow="visible",d.innerHTML="
        ",d.firstChild.style.width="5px",b.shrinkWrapBlocks=d.offsetWidth!==3,c.style.zoom=1),i.removeChild(c),c=d=f=g=null}),i.removeChild(n),c=d=f=g=h=i=n=null,b}();var H=/(?:\{[\s\S]*\}|\[[\s\S]*\])$/,I=/([A-Z])/g;p.extend({cache:{},deletedIds:[],uuid:0,expando:"jQuery"+(p.fn.jquery+Math.random()).replace(/\D/g,""),noData:{embed:!0,object:"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000",applet:!0},hasData:function(a){return a=a.nodeType?p.cache[a[p.expando]]:a[p.expando],!!a&&!K(a)},data:function(a,c,d,e){if(!p.acceptData(a))return;var f,g,h=p.expando,i=typeof c=="string",j=a.nodeType,k=j?p.cache:a,l=j?a[h]:a[h]&&h;if((!l||!k[l]||!e&&!k[l].data)&&i&&d===b)return;l||(j?a[h]=l=p.deletedIds.pop()||p.guid++:l=h),k[l]||(k[l]={},j||(k[l].toJSON=p.noop));if(typeof c=="object"||typeof c=="function")e?k[l]=p.extend(k[l],c):k[l].data=p.extend(k[l].data,c);return f=k[l],e||(f.data||(f.data={}),f=f.data),d!==b&&(f[p.camelCase(c)]=d),i?(g=f[c],g==null&&(g=f[p.camelCase(c)])):g=f,g},removeData:function(a,b,c){if(!p.acceptData(a))return;var d,e,f,g=a.nodeType,h=g?p.cache:a,i=g?a[p.expando]:p.expando;if(!h[i])return;if(b){d=c?h[i]:h[i].data;if(d){p.isArray(b)||(b in d?b=[b]:(b=p.camelCase(b),b in d?b=[b]:b=b.split(" ")));for(e=0,f=b.length;e1,null,!1))},removeData:function(a){return this.each(function(){p.removeData(this,a)})}}),p.extend({queue:function(a,b,c){var d;if(a)return b=(b||"fx")+"queue",d=p._data(a,b),c&&(!d||p.isArray(c)?d=p._data(a,b,p.makeArray(c)):d.push(c)),d||[]},dequeue:function(a,b){b=b||"fx";var c=p.queue(a,b),d=c.length,e=c.shift(),f=p._queueHooks(a,b),g=function(){p.dequeue(a,b)};e==="inprogress"&&(e=c.shift(),d--),e&&(b==="fx"&&c.unshift("inprogress"),delete f.stop,e.call(a,g,f)),!d&&f&&f.empty.fire()},_queueHooks:function(a,b){var c=b+"queueHooks";return p._data(a,c)||p._data(a,c,{empty:p.Callbacks("once memory").add(function(){p.removeData(a,b+"queue",!0),p.removeData(a,c,!0)})})}}),p.fn.extend({queue:function(a,c){var d=2;return typeof a!="string"&&(c=a,a="fx",d--),arguments.length1)},removeAttr:function(a){return this.each(function(){p.removeAttr(this,a)})},prop:function(a,b){return p.access(this,p.prop,a,b,arguments.length>1)},removeProp:function(a){return a=p.propFix[a]||a,this.each(function(){try{this[a]=b,delete this[a]}catch(c){}})},addClass:function(a){var b,c,d,e,f,g,h;if(p.isFunction(a))return this.each(function(b){p(this).addClass(a.call(this,b,this.className))});if(a&&typeof a=="string"){b=a.split(s);for(c=0,d=this.length;c=0)d=d.replace(" "+c[f]+" "," ");e.className=a?p.trim(d):""}}}return this},toggleClass:function(a,b){var c=typeof a,d=typeof b=="boolean";return p.isFunction(a)?this.each(function(c){p(this).toggleClass(a.call(this,c,this.className,b),b)}):this.each(function(){if(c==="string"){var e,f=0,g=p(this),h=b,i=a.split(s);while(e=i[f++])h=d?h:!g.hasClass(e),g[h?"addClass":"removeClass"](e)}else if(c==="undefined"||c==="boolean")this.className&&p._data(this,"__className__",this.className),this.className=this.className||a===!1?"":p._data(this,"__className__")||""})},hasClass:function(a){var b=" "+a+" ",c=0,d=this.length;for(;c=0)return!0;return!1},val:function(a){var c,d,e,f=this[0];if(!arguments.length){if(f)return c=p.valHooks[f.type]||p.valHooks[f.nodeName.toLowerCase()],c&&"get"in c&&(d=c.get(f,"value"))!==b?d:(d=f.value,typeof d=="string"?d.replace(P,""):d==null?"":d);return}return e=p.isFunction(a),this.each(function(d){var f,g=p(this);if(this.nodeType!==1)return;e?f=a.call(this,d,g.val()):f=a,f==null?f="":typeof f=="number"?f+="":p.isArray(f)&&(f=p.map(f,function(a){return a==null?"":a+""})),c=p.valHooks[this.type]||p.valHooks[this.nodeName.toLowerCase()];if(!c||!("set"in c)||c.set(this,f,"value")===b)this.value=f})}}),p.extend({valHooks:{option:{get:function(a){var b=a.attributes.value;return!b||b.specified?a.value:a.text}},select:{get:function(a){var b,c,d,e,f=a.selectedIndex,g=[],h=a.options,i=a.type==="select-one";if(f<0)return null;c=i?f:0,d=i?f+1:h.length;for(;c=0}),c.length||(a.selectedIndex=-1),c}}},attrFn:{},attr:function(a,c,d,e){var f,g,h,i=a.nodeType;if(!a||i===3||i===8||i===2)return;if(e&&p.isFunction(p.fn[c]))return p(a)[c](d);if(typeof a.getAttribute=="undefined")return p.prop(a,c,d);h=i!==1||!p.isXMLDoc(a),h&&(c=c.toLowerCase(),g=p.attrHooks[c]||(T.test(c)?M:L));if(d!==b){if(d===null){p.removeAttr(a,c);return}return g&&"set"in g&&h&&(f=g.set(a,d,c))!==b?f:(a.setAttribute(c,d+""),d)}return g&&"get"in g&&h&&(f=g.get(a,c))!==null?f:(f=a.getAttribute(c),f===null?b:f)},removeAttr:function(a,b){var c,d,e,f,g=0;if(b&&a.nodeType===1){d=b.split(s);for(;g=0}})});var V=/^(?:textarea|input|select)$/i,W=/^([^\.]*|)(?:\.(.+)|)$/,X=/(?:^|\s)hover(\.\S+|)\b/,Y=/^key/,Z=/^(?:mouse|contextmenu)|click/,$=/^(?:focusinfocus|focusoutblur)$/,_=function(a){return p.event.special.hover?a:a.replace(X,"mouseenter$1 mouseleave$1")};p.event={add:function(a,c,d,e,f){var g,h,i,j,k,l,m,n,o,q,r;if(a.nodeType===3||a.nodeType===8||!c||!d||!(g=p._data(a)))return;d.handler&&(o=d,d=o.handler,f=o.selector),d.guid||(d.guid=p.guid++),i=g.events,i||(g.events=i={}),h=g.handle,h||(g.handle=h=function(a){return typeof p!="undefined"&&(!a||p.event.triggered!==a.type)?p.event.dispatch.apply(h.elem,arguments):b},h.elem=a),c=p.trim(_(c)).split(" ");for(j=0;j=0&&(s=s.slice(0,-1),i=!0),s.indexOf(".")>=0&&(t=s.split("."),s=t.shift(),t.sort());if((!f||p.event.customEvent[s])&&!p.event.global[s])return;c=typeof c=="object"?c[p.expando]?c:new p.Event(s,c):new p.Event(s),c.type=s,c.isTrigger=!0,c.exclusive=i,c.namespace=t.join("."),c.namespace_re=c.namespace?new RegExp("(^|\\.)"+t.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,m=s.indexOf(":")<0?"on"+s:"";if(!f){h=p.cache;for(j in h)h[j].events&&h[j].events[s]&&p.event.trigger(c,d,h[j].handle.elem,!0);return}c.result=b,c.target||(c.target=f),d=d!=null?p.makeArray(d):[],d.unshift(c),n=p.event.special[s]||{};if(n.trigger&&n.trigger.apply(f,d)===!1)return;q=[[f,n.bindType||s]];if(!g&&!n.noBubble&&!p.isWindow(f)){r=n.delegateType||s,k=$.test(r+s)?f:f.parentNode;for(l=f;k;k=k.parentNode)q.push([k,r]),l=k;l===(f.ownerDocument||e)&&q.push([l.defaultView||l.parentWindow||a,r])}for(j=0;j=0:p.find(m,this,null,[f]).length),h[m]&&j.push(l);j.length&&u.push({elem:f,matches:j})}o.length>q&&u.push({elem:this,matches:o.slice(q)});for(d=0;d0?this.on(b,null,a,c):this.trigger(b)},Y.test(b)&&(p.event.fixHooks[b]=p.event.keyHooks),Z.test(b)&&(p.event.fixHooks[b]=p.event.mouseHooks)}),function(a,b){function bc(a,b,c,d){c=c||[],b=b||r;var e,f,i,j,k=b.nodeType;if(!a||typeof a!="string")return c;if(k!==1&&k!==9)return[];i=g(b);if(!i&&!d)if(e=P.exec(a))if(j=e[1]){if(k===9){f=b.getElementById(j);if(!f||!f.parentNode)return c;if(f.id===j)return c.push(f),c}else if(b.ownerDocument&&(f=b.ownerDocument.getElementById(j))&&h(b,f)&&f.id===j)return c.push(f),c}else{if(e[2])return w.apply(c,x.call(b.getElementsByTagName(a),0)),c;if((j=e[3])&&_&&b.getElementsByClassName)return w.apply(c,x.call(b.getElementsByClassName(j),0)),c}return bp(a.replace(L,"$1"),b,c,d,i)}function bd(a){return function(b){var c=b.nodeName.toLowerCase();return c==="input"&&b.type===a}}function be(a){return function(b){var c=b.nodeName.toLowerCase();return(c==="input"||c==="button")&&b.type===a}}function bf(a){return z(function(b){return b=+b,z(function(c,d){var e,f=a([],c.length,b),g=f.length;while(g--)c[e=f[g]]&&(c[e]=!(d[e]=c[e]))})})}function bg(a,b,c){if(a===b)return c;var d=a.nextSibling;while(d){if(d===b)return-1;d=d.nextSibling}return 1}function bh(a,b){var c,d,f,g,h,i,j,k=C[o][a];if(k)return b?0:k.slice(0);h=a,i=[],j=e.preFilter;while(h){if(!c||(d=M.exec(h)))d&&(h=h.slice(d[0].length)),i.push(f=[]);c=!1;if(d=N.exec(h))f.push(c=new q(d.shift())),h=h.slice(c.length),c.type=d[0].replace(L," ");for(g in e.filter)(d=W[g].exec(h))&&(!j[g]||(d=j[g](d,r,!0)))&&(f.push(c=new q(d.shift())),h=h.slice(c.length),c.type=g,c.matches=d);if(!c)break}return b?h.length:h?bc.error(a):C(a,i).slice(0)}function bi(a,b,d){var e=b.dir,f=d&&b.dir==="parentNode",g=u++;return b.first?function(b,c,d){while(b=b[e])if(f||b.nodeType===1)return a(b,c,d)}:function(b,d,h){if(!h){var i,j=t+" "+g+" ",k=j+c;while(b=b[e])if(f||b.nodeType===1){if((i=b[o])===k)return b.sizset;if(typeof i=="string"&&i.indexOf(j)===0){if(b.sizset)return b}else{b[o]=k;if(a(b,d,h))return b.sizset=!0,b;b.sizset=!1}}}else while(b=b[e])if(f||b.nodeType===1)if(a(b,d,h))return b}}function bj(a){return a.length>1?function(b,c,d){var e=a.length;while(e--)if(!a[e](b,c,d))return!1;return!0}:a[0]}function bk(a,b,c,d,e){var f,g=[],h=0,i=a.length,j=b!=null;for(;h-1},h,!0),m=[function(a,c,d){return!g&&(d||c!==l)||((b=c).nodeType?j(a,c,d):k(a,c,d))}];for(;i1&&bj(m),i>1&&a.slice(0,i-1).join("").replace(L,"$1"),c,i0,f=a.length>0,g=function(h,i,j,k,m){var n,o,p,q=[],s=0,u="0",x=h&&[],y=m!=null,z=l,A=h||f&&e.find.TAG("*",m&&i.parentNode||i),B=t+=z==null?1:Math.E;y&&(l=i!==r&&i,c=g.el);for(;(n=A[u])!=null;u++){if(f&&n){for(o=0;p=a[o];o++)if(p(n,i,j)){k.push(n);break}y&&(t=B,c=++g.el)}d&&((n=!p&&n)&&s--,h&&x.push(n))}s+=u;if(d&&u!==s){for(o=0;p=b[o];o++)p(x,q,i,j);if(h){if(s>0)while(u--)!x[u]&&!q[u]&&(q[u]=v.call(k));q=bk(q)}w.apply(k,q),y&&!h&&q.length>0&&s+b.length>1&&bc.uniqueSort(k)}return y&&(t=B,l=z),x};return g.el=0,d?z(g):g}function bo(a,b,c,d){var e=0,f=b.length;for(;e2&&(j=h[0]).type==="ID"&&b.nodeType===9&&!f&&e.relative[h[1].type]){b=e.find.ID(j.matches[0].replace(V,""),b,f)[0];if(!b)return c;a=a.slice(h.shift().length)}for(g=W.POS.test(a)?-1:h.length-1;g>=0;g--){j=h[g];if(e.relative[k=j.type])break;if(l=e.find[k])if(d=l(j.matches[0].replace(V,""),R.test(h[0].type)&&b.parentNode||b,f)){h.splice(g,1),a=d.length&&h.join("");if(!a)return w.apply(c,x.call(d,0)),c;break}}}return i(a,m)(d,b,f,c,R.test(a)),c}function bq(){}var c,d,e,f,g,h,i,j,k,l,m=!0,n="undefined",o=("sizcache"+Math.random()).replace(".",""),q=String,r=a.document,s=r.documentElement,t=0,u=0,v=[].pop,w=[].push,x=[].slice,y=[].indexOf||function(a){var b=0,c=this.length;for(;be.cacheLength&&delete a[b.shift()],a[c]=d},a)},B=A(),C=A(),D=A(),E="[\\x20\\t\\r\\n\\f]",F="(?:\\\\.|[-\\w]|[^\\x00-\\xa0])+",G=F.replace("w","w#"),H="([*^$|!~]?=)",I="\\["+E+"*("+F+")"+E+"*(?:"+H+E+"*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|("+G+")|)|)"+E+"*\\]",J=":("+F+")(?:\\((?:(['\"])((?:\\\\.|[^\\\\])*?)\\2|([^()[\\]]*|(?:(?:"+I+")|[^:]|\\\\.)*|.*))\\)|)",K=":(even|odd|eq|gt|lt|nth|first|last)(?:\\("+E+"*((?:-\\d)?\\d*)"+E+"*\\)|)(?=[^-]|$)",L=new RegExp("^"+E+"+|((?:^|[^\\\\])(?:\\\\.)*)"+E+"+$","g"),M=new RegExp("^"+E+"*,"+E+"*"),N=new RegExp("^"+E+"*([\\x20\\t\\r\\n\\f>+~])"+E+"*"),O=new RegExp(J),P=/^(?:#([\w\-]+)|(\w+)|\.([\w\-]+))$/,Q=/^:not/,R=/[\x20\t\r\n\f]*[+~]/,S=/:not\($/,T=/h\d/i,U=/input|select|textarea|button/i,V=/\\(?!\\)/g,W={ID:new RegExp("^#("+F+")"),CLASS:new RegExp("^\\.("+F+")"),NAME:new RegExp("^\\[name=['\"]?("+F+")['\"]?\\]"),TAG:new RegExp("^("+F.replace("w","w*")+")"),ATTR:new RegExp("^"+I),PSEUDO:new RegExp("^"+J),POS:new RegExp(K,"i"),CHILD:new RegExp("^:(only|nth|first|last)-child(?:\\("+E+"*(even|odd|(([+-]|)(\\d*)n|)"+E+"*(?:([+-]|)"+E+"*(\\d+)|))"+E+"*\\)|)","i"),needsContext:new RegExp("^"+E+"*[>+~]|"+K,"i")},X=function(a){var b=r.createElement("div");try{return a(b)}catch(c){return!1}finally{b=null}},Y=X(function(a){return a.appendChild(r.createComment("")),!a.getElementsByTagName("*").length}),Z=X(function(a){return a.innerHTML="",a.firstChild&&typeof a.firstChild.getAttribute!==n&&a.firstChild.getAttribute("href")==="#"}),$=X(function(a){a.innerHTML="";var b=typeof a.lastChild.getAttribute("multiple");return b!=="boolean"&&b!=="string"}),_=X(function(a){return a.innerHTML="",!a.getElementsByClassName||!a.getElementsByClassName("e").length?!1:(a.lastChild.className="e",a.getElementsByClassName("e").length===2)}),ba=X(function(a){a.id=o+0,a.innerHTML="
        ",s.insertBefore(a,s.firstChild);var b=r.getElementsByName&&r.getElementsByName(o).length===2+r.getElementsByName(o+0).length;return d=!r.getElementById(o),s.removeChild(a),b});try{x.call(s.childNodes,0)[0].nodeType}catch(bb){x=function(a){var b,c=[];for(;b=this[a];a++)c.push(b);return c}}bc.matches=function(a,b){return bc(a,null,null,b)},bc.matchesSelector=function(a,b){return bc(b,null,null,[a]).length>0},f=bc.getText=function(a){var b,c="",d=0,e=a.nodeType;if(e){if(e===1||e===9||e===11){if(typeof a.textContent=="string")return a.textContent;for(a=a.firstChild;a;a=a.nextSibling)c+=f(a)}else if(e===3||e===4)return a.nodeValue}else for(;b=a[d];d++)c+=f(b);return c},g=bc.isXML=function(a){var b=a&&(a.ownerDocument||a).documentElement;return b?b.nodeName!=="HTML":!1},h=bc.contains=s.contains?function(a,b){var c=a.nodeType===9?a.documentElement:a,d=b&&b.parentNode;return a===d||!!(d&&d.nodeType===1&&c.contains&&c.contains(d))}:s.compareDocumentPosition?function(a,b){return b&&!!(a.compareDocumentPosition(b)&16)}:function(a,b){while(b=b.parentNode)if(b===a)return!0;return!1},bc.attr=function(a,b){var c,d=g(a);return d||(b=b.toLowerCase()),(c=e.attrHandle[b])?c(a):d||$?a.getAttribute(b):(c=a.getAttributeNode(b),c?typeof a[b]=="boolean"?a[b]?b:null:c.specified?c.value:null:null)},e=bc.selectors={cacheLength:50,createPseudo:z,match:W,attrHandle:Z?{}:{href:function(a){return a.getAttribute("href",2)},type:function(a){return a.getAttribute("type")}},find:{ID:d?function(a,b,c){if(typeof b.getElementById!==n&&!c){var d=b.getElementById(a);return d&&d.parentNode?[d]:[]}}:function(a,c,d){if(typeof c.getElementById!==n&&!d){var e=c.getElementById(a);return e?e.id===a||typeof e.getAttributeNode!==n&&e.getAttributeNode("id").value===a?[e]:b:[]}},TAG:Y?function(a,b){if(typeof b.getElementsByTagName!==n)return b.getElementsByTagName(a)}:function(a,b){var c=b.getElementsByTagName(a);if(a==="*"){var d,e=[],f=0;for(;d=c[f];f++)d.nodeType===1&&e.push(d);return e}return c},NAME:ba&&function(a,b){if(typeof b.getElementsByName!==n)return b.getElementsByName(name)},CLASS:_&&function(a,b,c){if(typeof b.getElementsByClassName!==n&&!c)return b.getElementsByClassName(a)}},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(a){return a[1]=a[1].replace(V,""),a[3]=(a[4]||a[5]||"").replace(V,""),a[2]==="~="&&(a[3]=" "+a[3]+" "),a.slice(0,4)},CHILD:function(a){return a[1]=a[1].toLowerCase(),a[1]==="nth"?(a[2]||bc.error(a[0]),a[3]=+(a[3]?a[4]+(a[5]||1):2*(a[2]==="even"||a[2]==="odd")),a[4]=+(a[6]+a[7]||a[2]==="odd")):a[2]&&bc.error(a[0]),a},PSEUDO:function(a){var b,c;if(W.CHILD.test(a[0]))return null;if(a[3])a[2]=a[3];else if(b=a[4])O.test(b)&&(c=bh(b,!0))&&(c=b.indexOf(")",b.length-c)-b.length)&&(b=b.slice(0,c),a[0]=a[0].slice(0,c)),a[2]=b;return a.slice(0,3)}},filter:{ID:d?function(a){return a=a.replace(V,""),function(b){return b.getAttribute("id")===a}}:function(a){return a=a.replace(V,""),function(b){var c=typeof b.getAttributeNode!==n&&b.getAttributeNode("id");return c&&c.value===a}},TAG:function(a){return a==="*"?function(){return!0}:(a=a.replace(V,"").toLowerCase(),function(b){return b.nodeName&&b.nodeName.toLowerCase()===a})},CLASS:function(a){var b=B[o][a];return b||(b=B(a,new RegExp("(^|"+E+")"+a+"("+E+"|$)"))),function(a){return b.test(a.className||typeof a.getAttribute!==n&&a.getAttribute("class")||"")}},ATTR:function(a,b,c){return function(d,e){var f=bc.attr(d,a);return f==null?b==="!=":b?(f+="",b==="="?f===c:b==="!="?f!==c:b==="^="?c&&f.indexOf(c)===0:b==="*="?c&&f.indexOf(c)>-1:b==="$="?c&&f.substr(f.length-c.length)===c:b==="~="?(" "+f+" ").indexOf(c)>-1:b==="|="?f===c||f.substr(0,c.length+1)===c+"-":!1):!0}},CHILD:function(a,b,c,d){return a==="nth"?function(a){var b,e,f=a.parentNode;if(c===1&&d===0)return!0;if(f){e=0;for(b=f.firstChild;b;b=b.nextSibling)if(b.nodeType===1){e++;if(a===b)break}}return e-=d,e===c||e%c===0&&e/c>=0}:function(b){var c=b;switch(a){case"only":case"first":while(c=c.previousSibling)if(c.nodeType===1)return!1;if(a==="first")return!0;c=b;case"last":while(c=c.nextSibling)if(c.nodeType===1)return!1;return!0}}},PSEUDO:function(a,b){var c,d=e.pseudos[a]||e.setFilters[a.toLowerCase()]||bc.error("unsupported pseudo: "+a);return d[o]?d(b):d.length>1?(c=[a,a,"",b],e.setFilters.hasOwnProperty(a.toLowerCase())?z(function(a,c){var e,f=d(a,b),g=f.length;while(g--)e=y.call(a,f[g]),a[e]=!(c[e]=f[g])}):function(a){return d(a,0,c)}):d}},pseudos:{not:z(function(a){var b=[],c=[],d=i(a.replace(L,"$1"));return d[o]?z(function(a,b,c,e){var f,g=d(a,null,e,[]),h=a.length;while(h--)if(f=g[h])a[h]=!(b[h]=f)}):function(a,e,f){return b[0]=a,d(b,null,f,c),!c.pop()}}),has:z(function(a){return function(b){return bc(a,b).length>0}}),contains:z(function(a){return function(b){return(b.textContent||b.innerText||f(b)).indexOf(a)>-1}}),enabled:function(a){return a.disabled===!1},disabled:function(a){return a.disabled===!0},checked:function(a){var b=a.nodeName.toLowerCase();return b==="input"&&!!a.checked||b==="option"&&!!a.selected},selected:function(a){return a.parentNode&&a.parentNode.selectedIndex,a.selected===!0},parent:function(a){return!e.pseudos.empty(a)},empty:function(a){var b;a=a.firstChild;while(a){if(a.nodeName>"@"||(b=a.nodeType)===3||b===4)return!1;a=a.nextSibling}return!0},header:function(a){return T.test(a.nodeName)},text:function(a){var b,c;return a.nodeName.toLowerCase()==="input"&&(b=a.type)==="text"&&((c=a.getAttribute("type"))==null||c.toLowerCase()===b)},radio:bd("radio"),checkbox:bd("checkbox"),file:bd("file"),password:bd("password"),image:bd("image"),submit:be("submit"),reset:be("reset"),button:function(a){var b=a.nodeName.toLowerCase();return b==="input"&&a.type==="button"||b==="button"},input:function(a){return U.test(a.nodeName)},focus:function(a){var b=a.ownerDocument;return a===b.activeElement&&(!b.hasFocus||b.hasFocus())&&(!!a.type||!!a.href)},active:function(a){return a===a.ownerDocument.activeElement},first:bf(function(a,b,c){return[0]}),last:bf(function(a,b,c){return[b-1]}),eq:bf(function(a,b,c){return[c<0?c+b:c]}),even:bf(function(a,b,c){for(var d=0;d=0;)a.push(d);return a}),gt:bf(function(a,b,c){for(var d=c<0?c+b:c;++d",a.querySelectorAll("[selected]").length||e.push("\\["+E+"*(?:checked|disabled|ismap|multiple|readonly|selected|value)"),a.querySelectorAll(":checked").length||e.push(":checked")}),X(function(a){a.innerHTML="

        ",a.querySelectorAll("[test^='']").length&&e.push("[*^$]="+E+"*(?:\"\"|'')"),a.innerHTML="",a.querySelectorAll(":enabled").length||e.push(":enabled",":disabled")}),e=new RegExp(e.join("|")),bp=function(a,d,f,g,h){if(!g&&!h&&(!e||!e.test(a))){var i,j,k=!0,l=o,m=d,n=d.nodeType===9&&a;if(d.nodeType===1&&d.nodeName.toLowerCase()!=="object"){i=bh(a),(k=d.getAttribute("id"))?l=k.replace(c,"\\$&"):d.setAttribute("id",l),l="[id='"+l+"'] ",j=i.length;while(j--)i[j]=l+i[j].join("");m=R.test(a)&&d.parentNode||d,n=i.join(",")}if(n)try{return w.apply(f,x.call(m.querySelectorAll(n),0)),f}catch(p){}finally{k||d.removeAttribute("id")}}return b(a,d,f,g,h)},h&&(X(function(b){a=h.call(b,"div");try{h.call(b,"[test!='']:sizzle"),f.push("!=",J)}catch(c){}}),f=new RegExp(f.join("|")),bc.matchesSelector=function(b,c){c=c.replace(d,"='$1']");if(!g(b)&&!f.test(c)&&(!e||!e.test(c)))try{var i=h.call(b,c);if(i||a||b.document&&b.document.nodeType!==11)return i}catch(j){}return bc(c,null,null,[b]).length>0})}(),e.pseudos.nth=e.pseudos.eq,e.filters=bq.prototype=e.pseudos,e.setFilters=new bq,bc.attr=p.attr,p.find=bc,p.expr=bc.selectors,p.expr[":"]=p.expr.pseudos,p.unique=bc.uniqueSort,p.text=bc.getText,p.isXMLDoc=bc.isXML,p.contains=bc.contains}(a);var bc=/Until$/,bd=/^(?:parents|prev(?:Until|All))/,be=/^.[^:#\[\.,]*$/,bf=p.expr.match.needsContext,bg={children:!0,contents:!0,next:!0,prev:!0};p.fn.extend({find:function(a){var b,c,d,e,f,g,h=this;if(typeof a!="string")return p(a).filter(function(){for(b=0,c=h.length;b0)for(e=d;e=0:p.filter(a,this).length>0:this.filter(a).length>0)},closest:function(a,b){var c,d=0,e=this.length,f=[],g=bf.test(a)||typeof a!="string"?p(a,b||this.context):0;for(;d-1:p.find.matchesSelector(c,a)){f.push(c);break}c=c.parentNode}}return f=f.length>1?p.unique(f):f,this.pushStack(f,"closest",a)},index:function(a){return a?typeof a=="string"?p.inArray(this[0],p(a)):p.inArray(a.jquery?a[0]:a,this):this[0]&&this[0].parentNode?this.prevAll().length:-1},add:function(a,b){var c=typeof a=="string"?p(a,b):p.makeArray(a&&a.nodeType?[a]:a),d=p.merge(this.get(),c);return this.pushStack(bh(c[0])||bh(d[0])?d:p.unique(d))},addBack:function(a){return this.add(a==null?this.prevObject:this.prevObject.filter(a))}}),p.fn.andSelf=p.fn.addBack,p.each({parent:function(a){var b=a.parentNode;return b&&b.nodeType!==11?b:null},parents:function(a){return p.dir(a,"parentNode")},parentsUntil:function(a,b,c){return p.dir(a,"parentNode",c)},next:function(a){return bi(a,"nextSibling")},prev:function(a){return bi(a,"previousSibling")},nextAll:function(a){return p.dir(a,"nextSibling")},prevAll:function(a){return p.dir(a,"previousSibling")},nextUntil:function(a,b,c){return p.dir(a,"nextSibling",c)},prevUntil:function(a,b,c){return p.dir(a,"previousSibling",c)},siblings:function(a){return p.sibling((a.parentNode||{}).firstChild,a)},children:function(a){return p.sibling(a.firstChild)},contents:function(a){return p.nodeName(a,"iframe")?a.contentDocument||a.contentWindow.document:p.merge([],a.childNodes)}},function(a,b){p.fn[a]=function(c,d){var e=p.map(this,b,c);return bc.test(a)||(d=c),d&&typeof d=="string"&&(e=p.filter(d,e)),e=this.length>1&&!bg[a]?p.unique(e):e,this.length>1&&bd.test(a)&&(e=e.reverse()),this.pushStack(e,a,k.call(arguments).join(","))}}),p.extend({filter:function(a,b,c){return c&&(a=":not("+a+")"),b.length===1?p.find.matchesSelector(b[0],a)?[b[0]]:[]:p.find.matches(a,b)},dir:function(a,c,d){var e=[],f=a[c];while(f&&f.nodeType!==9&&(d===b||f.nodeType!==1||!p(f).is(d)))f.nodeType===1&&e.push(f),f=f[c];return e},sibling:function(a,b){var c=[];for(;a;a=a.nextSibling)a.nodeType===1&&a!==b&&c.push(a);return c}});var bl="abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",bm=/ jQuery\d+="(?:null|\d+)"/g,bn=/^\s+/,bo=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,bp=/<([\w:]+)/,bq=/
  • ","
    "],tr:[2,"","
    "],td:[3,"","
    "],col:[2,"","
    "],area:[1,"",""],_default:[0,"",""]},bA=bk(e),bB=bA.appendChild(e.createElement("div"));bz.optgroup=bz.option,bz.tbody=bz.tfoot=bz.colgroup=bz.caption=bz.thead,bz.th=bz.td,p.support.htmlSerialize||(bz._default=[1,"X
    ","
    "]),p.fn.extend({text:function(a){return p.access(this,function(a){return a===b?p.text(this):this.empty().append((this[0]&&this[0].ownerDocument||e).createTextNode(a))},null,a,arguments.length)},wrapAll:function(a){if(p.isFunction(a))return this.each(function(b){p(this).wrapAll(a.call(this,b))});if(this[0]){var b=p(a,this[0].ownerDocument).eq(0).clone(!0);this[0].parentNode&&b.insertBefore(this[0]),b.map(function(){var a=this;while(a.firstChild&&a.firstChild.nodeType===1)a=a.firstChild;return a}).append(this)}return this},wrapInner:function(a){return p.isFunction(a)?this.each(function(b){p(this).wrapInner(a.call(this,b))}):this.each(function(){var b=p(this),c=b.contents();c.length?c.wrapAll(a):b.append(a)})},wrap:function(a){var b=p.isFunction(a);return this.each(function(c){p(this).wrapAll(b?a.call(this,c):a)})},unwrap:function(){return this.parent().each(function(){p.nodeName(this,"body")||p(this).replaceWith(this.childNodes)}).end()},append:function(){return this.domManip(arguments,!0,function(a){(this.nodeType===1||this.nodeType===11)&&this.appendChild(a)})},prepend:function(){return this.domManip(arguments,!0,function(a){(this.nodeType===1||this.nodeType===11)&&this.insertBefore(a,this.firstChild)})},before:function(){if(!bh(this[0]))return this.domManip(arguments,!1,function(a){this.parentNode.insertBefore(a,this)});if(arguments.length){var a=p.clean(arguments);return this.pushStack(p.merge(a,this),"before",this.selector)}},after:function(){if(!bh(this[0]))return this.domManip(arguments,!1,function(a){this.parentNode.insertBefore(a,this.nextSibling)});if(arguments.length){var a=p.clean(arguments);return this.pushStack(p.merge(this,a),"after",this.selector)}},remove:function(a,b){var c,d=0;for(;(c=this[d])!=null;d++)if(!a||p.filter(a,[c]).length)!b&&c.nodeType===1&&(p.cleanData(c.getElementsByTagName("*")),p.cleanData([c])),c.parentNode&&c.parentNode.removeChild(c);return this},empty:function(){var a,b=0;for(;(a=this[b])!=null;b++){a.nodeType===1&&p.cleanData(a.getElementsByTagName("*"));while(a.firstChild)a.removeChild(a.firstChild)}return this},clone:function(a,b){return a=a==null?!1:a,b=b==null?a:b,this.map(function(){return p.clone(this,a,b)})},html:function(a){return p.access(this,function(a){var c=this[0]||{},d=0,e=this.length;if(a===b)return c.nodeType===1?c.innerHTML.replace(bm,""):b;if(typeof a=="string"&&!bs.test(a)&&(p.support.htmlSerialize||!bu.test(a))&&(p.support.leadingWhitespace||!bn.test(a))&&!bz[(bp.exec(a)||["",""])[1].toLowerCase()]){a=a.replace(bo,"<$1>");try{for(;d1&&typeof j=="string"&&bw.test(j))return this.each(function(){p(this).domManip(a,c,d)});if(p.isFunction(j))return this.each(function(e){var f=p(this);a[0]=j.call(this,e,c?f.html():b),f.domManip(a,c,d)});if(this[0]){e=p.buildFragment(a,this,k),g=e.fragment,f=g.firstChild,g.childNodes.length===1&&(g=f);if(f){c=c&&p.nodeName(f,"tr");for(h=e.cacheable||l-1;i0?this.clone(!0):this).get(),p(g[e])[b](d),f=f.concat(d);return this.pushStack(f,a,g.selector)}}),p.extend({clone:function(a,b,c){var d,e,f,g;p.support.html5Clone||p.isXMLDoc(a)||!bu.test("<"+a.nodeName+">")?g=a.cloneNode(!0):(bB.innerHTML=a.outerHTML,bB.removeChild(g=bB.firstChild));if((!p.support.noCloneEvent||!p.support.noCloneChecked)&&(a.nodeType===1||a.nodeType===11)&&!p.isXMLDoc(a)){bE(a,g),d=bF(a),e=bF(g);for(f=0;d[f];++f)e[f]&&bE(d[f],e[f])}if(b){bD(a,g);if(c){d=bF(a),e=bF(g);for(f=0;d[f];++f)bD(d[f],e[f])}}return d=e=null,g},clean:function(a,b,c,d){var f,g,h,i,j,k,l,m,n,o,q,r,s=b===e&&bA,t=[];if(!b||typeof b.createDocumentFragment=="undefined")b=e;for(f=0;(h=a[f])!=null;f++){typeof h=="number"&&(h+="");if(!h)continue;if(typeof h=="string")if(!br.test(h))h=b.createTextNode(h);else{s=s||bk(b),l=b.createElement("div"),s.appendChild(l),h=h.replace(bo,"<$1>"),i=(bp.exec(h)||["",""])[1].toLowerCase(),j=bz[i]||bz._default,k=j[0],l.innerHTML=j[1]+h+j[2];while(k--)l=l.lastChild;if(!p.support.tbody){m=bq.test(h),n=i==="table"&&!m?l.firstChild&&l.firstChild.childNodes:j[1]===""&&!m?l.childNodes:[];for(g=n.length-1;g>=0;--g)p.nodeName(n[g],"tbody")&&!n[g].childNodes.length&&n[g].parentNode.removeChild(n[g])}!p.support.leadingWhitespace&&bn.test(h)&&l.insertBefore(b.createTextNode(bn.exec(h)[0]),l.firstChild),h=l.childNodes,l.parentNode.removeChild(l)}h.nodeType?t.push(h):p.merge(t,h)}l&&(h=l=s=null);if(!p.support.appendChecked)for(f=0;(h=t[f])!=null;f++)p.nodeName(h,"input")?bG(h):typeof h.getElementsByTagName!="undefined"&&p.grep(h.getElementsByTagName("input"),bG);if(c){q=function(a){if(!a.type||bx.test(a.type))return d?d.push(a.parentNode?a.parentNode.removeChild(a):a):c.appendChild(a)};for(f=0;(h=t[f])!=null;f++)if(!p.nodeName(h,"script")||!q(h))c.appendChild(h),typeof h.getElementsByTagName!="undefined"&&(r=p.grep(p.merge([],h.getElementsByTagName("script")),q),t.splice.apply(t,[f+1,0].concat(r)),f+=r.length)}return t},cleanData:function(a,b){var c,d,e,f,g=0,h=p.expando,i=p.cache,j=p.support.deleteExpando,k=p.event.special;for(;(e=a[g])!=null;g++)if(b||p.acceptData(e)){d=e[h],c=d&&i[d];if(c){if(c.events)for(f in c.events)k[f]?p.event.remove(e,f):p.removeEvent(e,f,c.handle);i[d]&&(delete i[d],j?delete e[h]:e.removeAttribute?e.removeAttribute(h):e[h]=null,p.deletedIds.push(d))}}}}),function(){var a,b;p.uaMatch=function(a){a=a.toLowerCase();var b=/(chrome)[ \/]([\w.]+)/.exec(a)||/(webkit)[ \/]([\w.]+)/.exec(a)||/(opera)(?:.*version|)[ \/]([\w.]+)/.exec(a)||/(msie) ([\w.]+)/.exec(a)||a.indexOf("compatible")<0&&/(mozilla)(?:.*? rv:([\w.]+)|)/.exec(a)||[];return{browser:b[1]||"",version:b[2]||"0"}},a=p.uaMatch(g.userAgent),b={},a.browser&&(b[a.browser]=!0,b.version=a.version),b.chrome?b.webkit=!0:b.webkit&&(b.safari=!0),p.browser=b,p.sub=function(){function a(b,c){return new a.fn.init(b,c)}p.extend(!0,a,this),a.superclass=this,a.fn=a.prototype=this(),a.fn.constructor=a,a.sub=this.sub,a.fn.init=function c(c,d){return d&&d instanceof p&&!(d instanceof a)&&(d=a(d)),p.fn.init.call(this,c,d,b)},a.fn.init.prototype=a.fn;var b=a(e);return a}}();var bH,bI,bJ,bK=/alpha\([^)]*\)/i,bL=/opacity=([^)]*)/,bM=/^(top|right|bottom|left)$/,bN=/^(none|table(?!-c[ea]).+)/,bO=/^margin/,bP=new RegExp("^("+q+")(.*)$","i"),bQ=new RegExp("^("+q+")(?!px)[a-z%]+$","i"),bR=new RegExp("^([-+])=("+q+")","i"),bS={},bT={position:"absolute",visibility:"hidden",display:"block"},bU={letterSpacing:0,fontWeight:400},bV=["Top","Right","Bottom","Left"],bW=["Webkit","O","Moz","ms"],bX=p.fn.toggle;p.fn.extend({css:function(a,c){return p.access(this,function(a,c,d){return d!==b?p.style(a,c,d):p.css(a,c)},a,c,arguments.length>1)},show:function(){return b$(this,!0)},hide:function(){return b$(this)},toggle:function(a,b){var c=typeof a=="boolean";return p.isFunction(a)&&p.isFunction(b)?bX.apply(this,arguments):this.each(function(){(c?a:bZ(this))?p(this).show():p(this).hide()})}}),p.extend({cssHooks:{opacity:{get:function(a,b){if(b){var c=bH(a,"opacity");return c===""?"1":c}}}},cssNumber:{fillOpacity:!0,fontWeight:!0,lineHeight:!0,opacity:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{"float":p.support.cssFloat?"cssFloat":"styleFloat"},style:function(a,c,d,e){if(!a||a.nodeType===3||a.nodeType===8||!a.style)return;var f,g,h,i=p.camelCase(c),j=a.style;c=p.cssProps[i]||(p.cssProps[i]=bY(j,i)),h=p.cssHooks[c]||p.cssHooks[i];if(d===b)return h&&"get"in h&&(f=h.get(a,!1,e))!==b?f:j[c];g=typeof d,g==="string"&&(f=bR.exec(d))&&(d=(f[1]+1)*f[2]+parseFloat(p.css(a,c)),g="number");if(d==null||g==="number"&&isNaN(d))return;g==="number"&&!p.cssNumber[i]&&(d+="px");if(!h||!("set"in h)||(d=h.set(a,d,e))!==b)try{j[c]=d}catch(k){}},css:function(a,c,d,e){var f,g,h,i=p.camelCase(c);return c=p.cssProps[i]||(p.cssProps[i]=bY(a.style,i)),h=p.cssHooks[c]||p.cssHooks[i],h&&"get"in h&&(f=h.get(a,!0,e)),f===b&&(f=bH(a,c)),f==="normal"&&c in bU&&(f=bU[c]),d||e!==b?(g=parseFloat(f),d||p.isNumeric(g)?g||0:f):f},swap:function(a,b,c){var d,e,f={};for(e in b)f[e]=a.style[e],a.style[e]=b[e];d=c.call(a);for(e in b)a.style[e]=f[e];return d}}),a.getComputedStyle?bH=function(b,c){var d,e,f,g,h=a.getComputedStyle(b,null),i=b.style;return h&&(d=h[c],d===""&&!p.contains(b.ownerDocument,b)&&(d=p.style(b,c)),bQ.test(d)&&bO.test(c)&&(e=i.width,f=i.minWidth,g=i.maxWidth,i.minWidth=i.maxWidth=i.width=d,d=h.width,i.width=e,i.minWidth=f,i.maxWidth=g)),d}:e.documentElement.currentStyle&&(bH=function(a,b){var c,d,e=a.currentStyle&&a.currentStyle[b],f=a.style;return e==null&&f&&f[b]&&(e=f[b]),bQ.test(e)&&!bM.test(b)&&(c=f.left,d=a.runtimeStyle&&a.runtimeStyle.left,d&&(a.runtimeStyle.left=a.currentStyle.left),f.left=b==="fontSize"?"1em":e,e=f.pixelLeft+"px",f.left=c,d&&(a.runtimeStyle.left=d)),e===""?"auto":e}),p.each(["height","width"],function(a,b){p.cssHooks[b]={get:function(a,c,d){if(c)return a.offsetWidth===0&&bN.test(bH(a,"display"))?p.swap(a,bT,function(){return cb(a,b,d)}):cb(a,b,d)},set:function(a,c,d){return b_(a,c,d?ca(a,b,d,p.support.boxSizing&&p.css(a,"boxSizing")==="border-box"):0)}}}),p.support.opacity||(p.cssHooks.opacity={get:function(a,b){return bL.test((b&&a.currentStyle?a.currentStyle.filter:a.style.filter)||"")?.01*parseFloat(RegExp.$1)+"":b?"1":""},set:function(a,b){var c=a.style,d=a.currentStyle,e=p.isNumeric(b)?"alpha(opacity="+b*100+")":"",f=d&&d.filter||c.filter||"";c.zoom=1;if(b>=1&&p.trim(f.replace(bK,""))===""&&c.removeAttribute){c.removeAttribute("filter");if(d&&!d.filter)return}c.filter=bK.test(f)?f.replace(bK,e):f+" "+e}}),p(function(){p.support.reliableMarginRight||(p.cssHooks.marginRight={get:function(a,b){return p.swap(a,{display:"inline-block"},function(){if(b)return bH(a,"marginRight")})}}),!p.support.pixelPosition&&p.fn.position&&p.each(["top","left"],function(a,b){p.cssHooks[b]={get:function(a,c){if(c){var d=bH(a,b);return bQ.test(d)?p(a).position()[b]+"px":d}}}})}),p.expr&&p.expr.filters&&(p.expr.filters.hidden=function(a){return a.offsetWidth===0&&a.offsetHeight===0||!p.support.reliableHiddenOffsets&&(a.style&&a.style.display||bH(a,"display"))==="none"},p.expr.filters.visible=function(a){return!p.expr.filters.hidden(a)}),p.each({margin:"",padding:"",border:"Width"},function(a,b){p.cssHooks[a+b]={expand:function(c){var d,e=typeof c=="string"?c.split(" "):[c],f={};for(d=0;d<4;d++)f[a+bV[d]+b]=e[d]||e[d-2]||e[0];return f}},bO.test(a)||(p.cssHooks[a+b].set=b_)});var cd=/%20/g,ce=/\[\]$/,cf=/\r?\n/g,cg=/^(?:color|date|datetime|datetime-local|email|hidden|month|number|password|range|search|tel|text|time|url|week)$/i,ch=/^(?:select|textarea)/i;p.fn.extend({serialize:function(){return p.param(this.serializeArray())},serializeArray:function(){return this.map(function(){return this.elements?p.makeArray(this.elements):this}).filter(function(){return this.name&&!this.disabled&&(this.checked||ch.test(this.nodeName)||cg.test(this.type))}).map(function(a,b){var c=p(this).val();return c==null?null:p.isArray(c)?p.map(c,function(a,c){return{name:b.name,value:a.replace(cf,"\r\n")}}):{name:b.name,value:c.replace(cf,"\r\n")}}).get()}}),p.param=function(a,c){var d,e=[],f=function(a,b){b=p.isFunction(b)?b():b==null?"":b,e[e.length]=encodeURIComponent(a)+"="+encodeURIComponent(b)};c===b&&(c=p.ajaxSettings&&p.ajaxSettings.traditional);if(p.isArray(a)||a.jquery&&!p.isPlainObject(a))p.each(a,function(){f(this.name,this.value)});else for(d in a)ci(d,a[d],c,f);return e.join("&").replace(cd,"+")};var cj,ck,cl=/#.*$/,cm=/^(.*?):[ \t]*([^\r\n]*)\r?$/mg,cn=/^(?:about|app|app\-storage|.+\-extension|file|res|widget):$/,co=/^(?:GET|HEAD)$/,cp=/^\/\//,cq=/\?/,cr=/)<[^<]*)*<\/script>/gi,cs=/([?&])_=[^&]*/,ct=/^([\w\+\.\-]+:)(?:\/\/([^\/?#:]*)(?::(\d+)|)|)/,cu=p.fn.load,cv={},cw={},cx=["*/"]+["*"];try{ck=f.href}catch(cy){ck=e.createElement("a"),ck.href="",ck=ck.href}cj=ct.exec(ck.toLowerCase())||[],p.fn.load=function(a,c,d){if(typeof a!="string"&&cu)return cu.apply(this,arguments);if(!this.length)return this;var e,f,g,h=this,i=a.indexOf(" ");return i>=0&&(e=a.slice(i,a.length),a=a.slice(0,i)),p.isFunction(c)?(d=c,c=b):c&&typeof c=="object"&&(f="POST"),p.ajax({url:a,type:f,dataType:"html",data:c,complete:function(a,b){d&&h.each(d,g||[a.responseText,b,a])}}).done(function(a){g=arguments,h.html(e?p("
    ").append(a.replace(cr,"")).find(e):a)}),this},p.each("ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split(" "),function(a,b){p.fn[b]=function(a){return this.on(b,a)}}),p.each(["get","post"],function(a,c){p[c]=function(a,d,e,f){return p.isFunction(d)&&(f=f||e,e=d,d=b),p.ajax({type:c,url:a,data:d,success:e,dataType:f})}}),p.extend({getScript:function(a,c){return p.get(a,b,c,"script")},getJSON:function(a,b,c){return p.get(a,b,c,"json")},ajaxSetup:function(a,b){return b?cB(a,p.ajaxSettings):(b=a,a=p.ajaxSettings),cB(a,b),a},ajaxSettings:{url:ck,isLocal:cn.test(cj[1]),global:!0,type:"GET",contentType:"application/x-www-form-urlencoded; charset=UTF-8",processData:!0,async:!0,accepts:{xml:"application/xml, text/xml",html:"text/html",text:"text/plain",json:"application/json, text/javascript","*":cx},contents:{xml:/xml/,html:/html/,json:/json/},responseFields:{xml:"responseXML",text:"responseText"},converters:{"* text":a.String,"text html":!0,"text json":p.parseJSON,"text xml":p.parseXML},flatOptions:{context:!0,url:!0}},ajaxPrefilter:cz(cv),ajaxTransport:cz(cw),ajax:function(a,c){function y(a,c,f,i){var k,s,t,u,w,y=c;if(v===2)return;v=2,h&&clearTimeout(h),g=b,e=i||"",x.readyState=a>0?4:0,f&&(u=cC(l,x,f));if(a>=200&&a<300||a===304)l.ifModified&&(w=x.getResponseHeader("Last-Modified"),w&&(p.lastModified[d]=w),w=x.getResponseHeader("Etag"),w&&(p.etag[d]=w)),a===304?(y="notmodified",k=!0):(k=cD(l,u),y=k.state,s=k.data,t=k.error,k=!t);else{t=y;if(!y||a)y="error",a<0&&(a=0)}x.status=a,x.statusText=(c||y)+"",k?o.resolveWith(m,[s,y,x]):o.rejectWith(m,[x,y,t]),x.statusCode(r),r=b,j&&n.trigger("ajax"+(k?"Success":"Error"),[x,l,k?s:t]),q.fireWith(m,[x,y]),j&&(n.trigger("ajaxComplete",[x,l]),--p.active||p.event.trigger("ajaxStop"))}typeof a=="object"&&(c=a,a=b),c=c||{};var d,e,f,g,h,i,j,k,l=p.ajaxSetup({},c),m=l.context||l,n=m!==l&&(m.nodeType||m instanceof p)?p(m):p.event,o=p.Deferred(),q=p.Callbacks("once memory"),r=l.statusCode||{},t={},u={},v=0,w="canceled",x={readyState:0,setRequestHeader:function(a,b){if(!v){var c=a.toLowerCase();a=u[c]=u[c]||a,t[a]=b}return this},getAllResponseHeaders:function(){return v===2?e:null},getResponseHeader:function(a){var c;if(v===2){if(!f){f={};while(c=cm.exec(e))f[c[1].toLowerCase()]=c[2]}c=f[a.toLowerCase()]}return c===b?null:c},overrideMimeType:function(a){return v||(l.mimeType=a),this},abort:function(a){return a=a||w,g&&g.abort(a),y(0,a),this}};o.promise(x),x.success=x.done,x.error=x.fail,x.complete=q.add,x.statusCode=function(a){if(a){var b;if(v<2)for(b in a)r[b]=[r[b],a[b]];else b=a[x.status],x.always(b)}return this},l.url=((a||l.url)+"").replace(cl,"").replace(cp,cj[1]+"//"),l.dataTypes=p.trim(l.dataType||"*").toLowerCase().split(s),l.crossDomain==null&&(i=ct.exec(l.url.toLowerCase())||!1,l.crossDomain=i&&i.join(":")+(i[3]?"":i[1]==="http:"?80:443)!==cj.join(":")+(cj[3]?"":cj[1]==="http:"?80:443)),l.data&&l.processData&&typeof l.data!="string"&&(l.data=p.param(l.data,l.traditional)),cA(cv,l,c,x);if(v===2)return x;j=l.global,l.type=l.type.toUpperCase(),l.hasContent=!co.test(l.type),j&&p.active++===0&&p.event.trigger("ajaxStart");if(!l.hasContent){l.data&&(l.url+=(cq.test(l.url)?"&":"?")+l.data,delete l.data),d=l.url;if(l.cache===!1){var z=p.now(),A=l.url.replace(cs,"$1_="+z);l.url=A+(A===l.url?(cq.test(l.url)?"&":"?")+"_="+z:"")}}(l.data&&l.hasContent&&l.contentType!==!1||c.contentType)&&x.setRequestHeader("Content-Type",l.contentType),l.ifModified&&(d=d||l.url,p.lastModified[d]&&x.setRequestHeader("If-Modified-Since",p.lastModified[d]),p.etag[d]&&x.setRequestHeader("If-None-Match",p.etag[d])),x.setRequestHeader("Accept",l.dataTypes[0]&&l.accepts[l.dataTypes[0]]?l.accepts[l.dataTypes[0]]+(l.dataTypes[0]!=="*"?", "+cx+"; q=0.01":""):l.accepts["*"]);for(k in l.headers)x.setRequestHeader(k,l.headers[k]);if(!l.beforeSend||l.beforeSend.call(m,x,l)!==!1&&v!==2){w="abort";for(k in{success:1,error:1,complete:1})x[k](l[k]);g=cA(cw,l,c,x);if(!g)y(-1,"No Transport");else{x.readyState=1,j&&n.trigger("ajaxSend",[x,l]),l.async&&l.timeout>0&&(h=setTimeout(function(){x.abort("timeout")},l.timeout));try{v=1,g.send(t,y)}catch(B){if(v<2)y(-1,B);else throw B}}return x}return x.abort()},active:0,lastModified:{},etag:{}});var cE=[],cF=/\?/,cG=/(=)\?(?=&|$)|\?\?/,cH=p.now();p.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var a=cE.pop()||p.expando+"_"+cH++;return this[a]=!0,a}}),p.ajaxPrefilter("json jsonp",function(c,d,e){var f,g,h,i=c.data,j=c.url,k=c.jsonp!==!1,l=k&&cG.test(j),m=k&&!l&&typeof i=="string"&&!(c.contentType||"").indexOf("application/x-www-form-urlencoded")&&cG.test(i);if(c.dataTypes[0]==="jsonp"||l||m)return f=c.jsonpCallback=p.isFunction(c.jsonpCallback)?c.jsonpCallback():c.jsonpCallback,g=a[f],l?c.url=j.replace(cG,"$1"+f):m?c.data=i.replace(cG,"$1"+f):k&&(c.url+=(cF.test(j)?"&":"?")+c.jsonp+"="+f),c.converters["script json"]=function(){return h||p.error(f+" was not called"),h[0]},c.dataTypes[0]="json",a[f]=function(){h=arguments},e.always(function(){a[f]=g,c[f]&&(c.jsonpCallback=d.jsonpCallback,cE.push(f)),h&&p.isFunction(g)&&g(h[0]),h=g=b}),"script"}),p.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/javascript|ecmascript/},converters:{"text script":function(a){return p.globalEval(a),a}}}),p.ajaxPrefilter("script",function(a){a.cache===b&&(a.cache=!1),a.crossDomain&&(a.type="GET",a.global=!1)}),p.ajaxTransport("script",function(a){if(a.crossDomain){var c,d=e.head||e.getElementsByTagName("head")[0]||e.documentElement;return{send:function(f,g){c=e.createElement("script"),c.async="async",a.scriptCharset&&(c.charset=a.scriptCharset),c.src=a.url,c.onload=c.onreadystatechange=function(a,e){if(e||!c.readyState||/loaded|complete/.test(c.readyState))c.onload=c.onreadystatechange=null,d&&c.parentNode&&d.removeChild(c),c=b,e||g(200,"success")},d.insertBefore(c,d.firstChild)},abort:function(){c&&c.onload(0,1)}}}});var cI,cJ=a.ActiveXObject?function(){for(var a in cI)cI[a](0,1)}:!1,cK=0;p.ajaxSettings.xhr=a.ActiveXObject?function(){return!this.isLocal&&cL()||cM()}:cL,function(a){p.extend(p.support,{ajax:!!a,cors:!!a&&"withCredentials"in a})}(p.ajaxSettings.xhr()),p.support.ajax&&p.ajaxTransport(function(c){if(!c.crossDomain||p.support.cors){var d;return{send:function(e,f){var g,h,i=c.xhr();c.username?i.open(c.type,c.url,c.async,c.username,c.password):i.open(c.type,c.url,c.async);if(c.xhrFields)for(h in c.xhrFields)i[h]=c.xhrFields[h];c.mimeType&&i.overrideMimeType&&i.overrideMimeType(c.mimeType),!c.crossDomain&&!e["X-Requested-With"]&&(e["X-Requested-With"]="XMLHttpRequest");try{for(h in e)i.setRequestHeader(h,e[h])}catch(j){}i.send(c.hasContent&&c.data||null),d=function(a,e){var h,j,k,l,m;try{if(d&&(e||i.readyState===4)){d=b,g&&(i.onreadystatechange=p.noop,cJ&&delete cI[g]);if(e)i.readyState!==4&&i.abort();else{h=i.status,k=i.getAllResponseHeaders(),l={},m=i.responseXML,m&&m.documentElement&&(l.xml=m);try{l.text=i.responseText}catch(a){}try{j=i.statusText}catch(n){j=""}!h&&c.isLocal&&!c.crossDomain?h=l.text?200:404:h===1223&&(h=204)}}}catch(o){e||f(-1,o)}l&&f(h,j,l,k)},c.async?i.readyState===4?setTimeout(d,0):(g=++cK,cJ&&(cI||(cI={},p(a).unload(cJ)),cI[g]=d),i.onreadystatechange=d):d()},abort:function(){d&&d(0,1)}}}});var cN,cO,cP=/^(?:toggle|show|hide)$/,cQ=new RegExp("^(?:([-+])=|)("+q+")([a-z%]*)$","i"),cR=/queueHooks$/,cS=[cY],cT={"*":[function(a,b){var c,d,e=this.createTween(a,b),f=cQ.exec(b),g=e.cur(),h=+g||0,i=1,j=20;if(f){c=+f[2],d=f[3]||(p.cssNumber[a]?"":"px");if(d!=="px"&&h){h=p.css(e.elem,a,!0)||c||1;do i=i||".5",h=h/i,p.style(e.elem,a,h+d);while(i!==(i=e.cur()/g)&&i!==1&&--j)}e.unit=d,e.start=h,e.end=f[1]?h+(f[1]+1)*c:c}return e}]};p.Animation=p.extend(cW,{tweener:function(a,b){p.isFunction(a)?(b=a,a=["*"]):a=a.split(" ");var c,d=0,e=a.length;for(;d-1,j={},k={},l,m;i?(k=e.position(),l=k.top,m=k.left):(l=parseFloat(g)||0,m=parseFloat(h)||0),p.isFunction(b)&&(b=b.call(a,c,f)),b.top!=null&&(j.top=b.top-f.top+l),b.left!=null&&(j.left=b.left-f.left+m),"using"in b?b.using.call(a,j):e.css(j)}},p.fn.extend({position:function(){if(!this[0])return;var a=this[0],b=this.offsetParent(),c=this.offset(),d=c_.test(b[0].nodeName)?{top:0,left:0}:b.offset();return c.top-=parseFloat(p.css(a,"marginTop"))||0,c.left-=parseFloat(p.css(a,"marginLeft"))||0,d.top+=parseFloat(p.css(b[0],"borderTopWidth"))||0,d.left+=parseFloat(p.css(b[0],"borderLeftWidth"))||0,{top:c.top-d.top,left:c.left-d.left}},offsetParent:function(){return this.map(function(){var a=this.offsetParent||e.body;while(a&&!c_.test(a.nodeName)&&p.css(a,"position")==="static")a=a.offsetParent;return a||e.body})}}),p.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(a,c){var d=/Y/.test(c);p.fn[a]=function(e){return p.access(this,function(a,e,f){var g=da(a);if(f===b)return g?c in g?g[c]:g.document.documentElement[e]:a[e];g?g.scrollTo(d?p(g).scrollLeft():f,d?f:p(g).scrollTop()):a[e]=f},a,e,arguments.length,null)}}),p.each({Height:"height",Width:"width"},function(a,c){p.each({padding:"inner"+a,content:c,"":"outer"+a},function(d,e){p.fn[e]=function(e,f){var g=arguments.length&&(d||typeof e!="boolean"),h=d||(e===!0||f===!0?"margin":"border");return p.access(this,function(c,d,e){var f;return p.isWindow(c)?c.document.documentElement["client"+a]:c.nodeType===9?(f=c.documentElement,Math.max(c.body["scroll"+a],f["scroll"+a],c.body["offset"+a],f["offset"+a],f["client"+a])):e===b?p.css(c,d,e,h):p.style(c,d,e,h)},c,g?e:b,g,null)}})}),a.jQuery=a.$=p,typeof define=="function"&&define.amd&&define.amd.jQuery&&define("jquery",[],function(){return p})})(window); \ No newline at end of file diff --git a/lib/godoc/jquery.treeview.css b/lib/godoc/jquery.treeview.css new file mode 100644 index 0000000..d65cd1f --- /dev/null +++ b/lib/godoc/jquery.treeview.css @@ -0,0 +1,76 @@ +/* https://github.com/jzaefferer/jquery-treeview/blob/master/jquery.treeview.css */ +/* License: MIT. */ +.treeview, .treeview ul { + padding: 0; + margin: 0; + list-style: none; +} + +.treeview ul { + background-color: white; + margin-top: 4px; +} + +.treeview .hitarea { + background: url(images/treeview-default.gif) -64px -25px no-repeat; + height: 16px; + width: 16px; + margin-left: -16px; + float: left; + cursor: pointer; +} +/* fix for IE6 */ +* html .hitarea { + display: inline; + float:none; +} + +.treeview li { + margin: 0; + padding: 3px 0pt 3px 16px; +} + +.treeview a.selected { + background-color: #eee; +} + +#treecontrol { margin: 1em 0; display: none; } + +.treeview .hover { color: red; cursor: pointer; } + +.treeview li { background: url(images/treeview-default-line.gif) 0 0 no-repeat; } +.treeview li.collapsable, .treeview li.expandable { background-position: 0 -176px; } + +.treeview .expandable-hitarea { background-position: -80px -3px; } + +.treeview li.last { background-position: 0 -1766px } +.treeview li.lastCollapsable, .treeview li.lastExpandable { background-image: url(images/treeview-default.gif); } +.treeview li.lastCollapsable { background-position: 0 -111px } +.treeview li.lastExpandable { background-position: -32px -67px } + +.treeview div.lastCollapsable-hitarea, .treeview div.lastExpandable-hitarea { background-position: 0; } + +.treeview-red li { background-image: url(http://localhost:6060/lib/godoc/images/treeview-red-line.gif); } +.treeview-red .hitarea, .treeview-red li.lastCollapsable, .treeview-red li.lastExpandable { background-image: url(http://localhost:6060/lib/godoc/images/treeview-red.gif); } + +.treeview-black li { background-image: url(images/treeview-black-line.gif); } +.treeview-black .hitarea, .treeview-black li.lastCollapsable, .treeview-black li.lastExpandable { background-image: url(images/treeview-black.gif); } + +.treeview-gray li { background-image: url(images/treeview-gray-line.gif); } +.treeview-gray .hitarea, .treeview-gray li.lastCollapsable, .treeview-gray li.lastExpandable { background-image: url(images/treeview-gray.gif); } + +.treeview-famfamfam li { background-image: url(http://localhost:6060/lib/godoc/images/treeview-famfamfam-line.gif); } +.treeview-famfamfam .hitarea, .treeview-famfamfam li.lastCollapsable, .treeview-famfamfam li.lastExpandable { background-image: url(http://localhost:6060/lib/godoc/images/treeview-famfamfam.gif); } + +.treeview .placeholder { + background: url(http://localhost:6060/lib/godoc/images/ajax-loader.gif) 0 0 no-repeat; + height: 16px; + width: 16px; + display: block; +} + +.filetree li { padding: 3px 0 2px 16px; } +.filetree span.folder, .filetree span.file { padding: 1px 0 1px 16px; display: block; } +.filetree span.folder { background: url(http://localhost:6060/lib/godoc/images/folder.gif) 0 0 no-repeat; } +.filetree li.expandable span.folder { background: url(http://localhost:6060/lib/godoc/images/folder-closed.gif) 0 0 no-repeat; } +.filetree span.file { background: url(http://localhost:6060/lib/godoc/images/file.gif) 0 0 no-repeat; } diff --git a/lib/godoc/jquery.treeview.edit.js b/lib/godoc/jquery.treeview.edit.js new file mode 100644 index 0000000..9895b02 --- /dev/null +++ b/lib/godoc/jquery.treeview.edit.js @@ -0,0 +1,39 @@ +/* https://github.com/jzaefferer/jquery-treeview/blob/master/jquery.treeview.edit.js */ +/* License: MIT. */ +(function($) { + var CLASSES = $.treeview.classes; + var proxied = $.fn.treeview; + $.fn.treeview = function(settings) { + settings = $.extend({}, settings); + if (settings.add) { + return this.trigger("add", [settings.add]); + } + if (settings.remove) { + return this.trigger("remove", [settings.remove]); + } + return proxied.apply(this, arguments).bind("add", function(event, branches) { + $(branches).prev() + .removeClass(CLASSES.last) + .removeClass(CLASSES.lastCollapsable) + .removeClass(CLASSES.lastExpandable) + .find(">.hitarea") + .removeClass(CLASSES.lastCollapsableHitarea) + .removeClass(CLASSES.lastExpandableHitarea); + $(branches).find("li").andSelf().prepareBranches(settings).applyClasses(settings, $(this).data("toggler")); + }).bind("remove", function(event, branches) { + var prev = $(branches).prev(); + var parent = $(branches).parent(); + $(branches).remove(); + prev.filter(":last-child").addClass(CLASSES.last) + .filter("." + CLASSES.expandable).replaceClass(CLASSES.last, CLASSES.lastExpandable).end() + .find(">.hitarea").replaceClass(CLASSES.expandableHitarea, CLASSES.lastExpandableHitarea).end() + .filter("." + CLASSES.collapsable).replaceClass(CLASSES.last, CLASSES.lastCollapsable).end() + .find(">.hitarea").replaceClass(CLASSES.collapsableHitarea, CLASSES.lastCollapsableHitarea); + if (parent.is(":not(:has(>))") && parent[0] != this) { + parent.parent().removeClass(CLASSES.collapsable).removeClass(CLASSES.expandable) + parent.siblings(".hitarea").andSelf().remove(); + } + }); + }; + +})(jQuery); diff --git a/lib/godoc/jquery.treeview.js b/lib/godoc/jquery.treeview.js new file mode 100644 index 0000000..356af23 --- /dev/null +++ b/lib/godoc/jquery.treeview.js @@ -0,0 +1,256 @@ +/* + * Treeview 1.4.1 - jQuery plugin to hide and show branches of a tree + * + * http://bassistance.de/jquery-plugins/jquery-plugin-treeview/ + * http://docs.jquery.com/Plugins/Treeview + * + * Copyright (c) 2007 Jörn Zaefferer + * + * Dual licensed under the MIT and GPL licenses: + * http://www.opensource.org/licenses/mit-license.php + * http://www.gnu.org/licenses/gpl.html + * + * Revision: $Id: jquery.treeview.js 5759 2008-07-01 07:50:28Z joern.zaefferer $ + * + */ + +;(function($) { + + // TODO rewrite as a widget, removing all the extra plugins + $.extend($.fn, { + swapClass: function(c1, c2) { + var c1Elements = this.filter('.' + c1); + this.filter('.' + c2).removeClass(c2).addClass(c1); + c1Elements.removeClass(c1).addClass(c2); + return this; + }, + replaceClass: function(c1, c2) { + return this.filter('.' + c1).removeClass(c1).addClass(c2).end(); + }, + hoverClass: function(className) { + className = className || "hover"; + return this.hover(function() { + $(this).addClass(className); + }, function() { + $(this).removeClass(className); + }); + }, + heightToggle: function(animated, callback) { + animated ? + this.animate({ height: "toggle" }, animated, callback) : + this.each(function(){ + jQuery(this)[ jQuery(this).is(":hidden") ? "show" : "hide" ](); + if(callback) + callback.apply(this, arguments); + }); + }, + heightHide: function(animated, callback) { + if (animated) { + this.animate({ height: "hide" }, animated, callback); + } else { + this.hide(); + if (callback) + this.each(callback); + } + }, + prepareBranches: function(settings) { + if (!settings.prerendered) { + // mark last tree items + this.filter(":last-child:not(ul)").addClass(CLASSES.last); + // collapse whole tree, or only those marked as closed, anyway except those marked as open + this.filter((settings.collapsed ? "" : "." + CLASSES.closed) + ":not(." + CLASSES.open + ")").find(">ul").hide(); + } + // return all items with sublists + return this.filter(":has(>ul)"); + }, + applyClasses: function(settings, toggler) { + // TODO use event delegation + this.filter(":has(>ul):not(:has(>a))").find(">span").unbind("click.treeview").bind("click.treeview", function(event) { + // don't handle click events on children, eg. checkboxes + if ( this == event.target ) + toggler.apply($(this).next()); + }).add( $("a", this) ).hoverClass(); + + if (!settings.prerendered) { + // handle closed ones first + this.filter(":has(>ul:hidden)") + .addClass(CLASSES.expandable) + .replaceClass(CLASSES.last, CLASSES.lastExpandable); + + // handle open ones + this.not(":has(>ul:hidden)") + .addClass(CLASSES.collapsable) + .replaceClass(CLASSES.last, CLASSES.lastCollapsable); + + // create hitarea if not present + var hitarea = this.find("div." + CLASSES.hitarea); + if (!hitarea.length) + hitarea = this.prepend("
    ").find("div." + CLASSES.hitarea); + hitarea.removeClass().addClass(CLASSES.hitarea).each(function() { + var classes = ""; + $.each($(this).parent().attr("class").split(" "), function() { + classes += this + "-hitarea "; + }); + $(this).addClass( classes ); + }) + } + + // apply event to hitarea + this.find("div." + CLASSES.hitarea).click( toggler ); + }, + treeview: function(settings) { + + settings = $.extend({ + cookieId: "treeview" + }, settings); + + if ( settings.toggle ) { + var callback = settings.toggle; + settings.toggle = function() { + return callback.apply($(this).parent()[0], arguments); + }; + } + + // factory for treecontroller + function treeController(tree, control) { + // factory for click handlers + function handler(filter) { + return function() { + // reuse toggle event handler, applying the elements to toggle + // start searching for all hitareas + toggler.apply( $("div." + CLASSES.hitarea, tree).filter(function() { + // for plain toggle, no filter is provided, otherwise we need to check the parent element + return filter ? $(this).parent("." + filter).length : true; + }) ); + return false; + }; + } + // click on first element to collapse tree + $("a:eq(0)", control).click( handler(CLASSES.collapsable) ); + // click on second to expand tree + $("a:eq(1)", control).click( handler(CLASSES.expandable) ); + // click on third to toggle tree + $("a:eq(2)", control).click( handler() ); + } + + // handle toggle event + function toggler() { + $(this) + .parent() + // swap classes for hitarea + .find(">.hitarea") + .swapClass( CLASSES.collapsableHitarea, CLASSES.expandableHitarea ) + .swapClass( CLASSES.lastCollapsableHitarea, CLASSES.lastExpandableHitarea ) + .end() + // swap classes for parent li + .swapClass( CLASSES.collapsable, CLASSES.expandable ) + .swapClass( CLASSES.lastCollapsable, CLASSES.lastExpandable ) + // find child lists + .find( ">ul" ) + // toggle them + .heightToggle( settings.animated, settings.toggle ); + if ( settings.unique ) { + $(this).parent() + .siblings() + // swap classes for hitarea + .find(">.hitarea") + .replaceClass( CLASSES.collapsableHitarea, CLASSES.expandableHitarea ) + .replaceClass( CLASSES.lastCollapsableHitarea, CLASSES.lastExpandableHitarea ) + .end() + .replaceClass( CLASSES.collapsable, CLASSES.expandable ) + .replaceClass( CLASSES.lastCollapsable, CLASSES.lastExpandable ) + .find( ">ul" ) + .heightHide( settings.animated, settings.toggle ); + } + } + this.data("toggler", toggler); + + function serialize() { + function binary(arg) { + return arg ? 1 : 0; + } + var data = []; + branches.each(function(i, e) { + data[i] = $(e).is(":has(>ul:visible)") ? 1 : 0; + }); + $.cookie(settings.cookieId, data.join(""), settings.cookieOptions ); + } + + function deserialize() { + var stored = $.cookie(settings.cookieId); + if ( stored ) { + var data = stored.split(""); + branches.each(function(i, e) { + $(e).find(">ul")[ parseInt(data[i]) ? "show" : "hide" ](); + }); + } + } + + // add treeview class to activate styles + this.addClass("treeview"); + + // prepare branches and find all tree items with child lists + var branches = this.find("li").prepareBranches(settings); + + switch(settings.persist) { + case "cookie": + var toggleCallback = settings.toggle; + settings.toggle = function() { + serialize(); + if (toggleCallback) { + toggleCallback.apply(this, arguments); + } + }; + deserialize(); + break; + case "location": + var current = this.find("a").filter(function() { + return this.href.toLowerCase() == location.href.toLowerCase(); + }); + if ( current.length ) { + // TODO update the open/closed classes + var items = current.addClass("selected").parents("ul, li").add( current.next() ).show(); + if (settings.prerendered) { + // if prerendered is on, replicate the basic class swapping + items.filter("li") + .swapClass( CLASSES.collapsable, CLASSES.expandable ) + .swapClass( CLASSES.lastCollapsable, CLASSES.lastExpandable ) + .find(">.hitarea") + .swapClass( CLASSES.collapsableHitarea, CLASSES.expandableHitarea ) + .swapClass( CLASSES.lastCollapsableHitarea, CLASSES.lastExpandableHitarea ); + } + } + break; + } + + branches.applyClasses(settings, toggler); + + // if control option is set, create the treecontroller and show it + if ( settings.control ) { + treeController(this, settings.control); + $(settings.control).show(); + } + + return this; + } + }); + + // classes used by the plugin + // need to be styled via external stylesheet, see first example + $.treeview = {}; + var CLASSES = ($.treeview.classes = { + open: "open", + closed: "closed", + expandable: "expandable", + expandableHitarea: "expandable-hitarea", + lastExpandableHitarea: "lastExpandable-hitarea", + collapsable: "collapsable", + collapsableHitarea: "collapsable-hitarea", + lastCollapsableHitarea: "lastCollapsable-hitarea", + lastCollapsable: "lastCollapsable", + lastExpandable: "lastExpandable", + last: "last", + hitarea: "hitarea" + }); + +})(jQuery); diff --git a/lib/godoc/style.css b/lib/godoc/style.css new file mode 100644 index 0000000..48a8caf --- /dev/null +++ b/lib/godoc/style.css @@ -0,0 +1,773 @@ +body { + margin: 0; + font-family: Arial, sans-serif; + font-size: 16px; + background-color: #fff; + line-height: 1.3em; +} +pre, +code { + font-family: Menlo, monospace; + font-size: 14px; +} +pre { + line-height: 1.4em; + overflow-x: auto; +} +pre .comment { + color: #006600; +} +pre .highlight, +pre .highlight-comment, +pre .selection-highlight, +pre .selection-highlight-comment { + background: #FFFF00; +} +pre .selection, +pre .selection-comment { + background: #FF9632; +} +pre .ln { + color: #999; +} +body { + color: #222; +} +a, +.exampleHeading .text { + color: #375EAB; + text-decoration: none; +} +a:hover, +.exampleHeading .text:hover { + text-decoration: underline; +} +p, li { + max-width: 800px; + word-wrap: break-word; +} +p, +pre, +ul, +ol { + margin: 20px; +} +pre { + background: #EFEFEF; + padding: 10px; + + -webkit-border-radius: 5px; + -moz-border-radius: 5px; + border-radius: 5px; +} + +h1, +h2, +h3, +h4, +.rootHeading { + margin: 20px 0 20px; + padding: 0; + color: #375EAB; + font-weight: bold; +} +h1 { + font-size: 28px; + line-height: 1; +} +h2 { + font-size: 20px; + background: #E0EBF5; + padding: 8px; + line-height: 1.25; + font-weight: normal; +} +h2 a { + font-weight: bold; +} +h3 { + font-size: 20px; +} +h3, +h4 { + margin: 20px 5px; +} +h4 { + font-size: 16px; +} +.rootHeading { + font-size: 20px; + margin: 0; +} + +dl { + margin: 20px; +} +dd { + margin: 0 0 0 20px; +} +dl, +dd { + font-size: 14px; +} +div#nav table td { + vertical-align: top; +} + + +.pkg-dir { + padding: 0 10px; +} +.pkg-dir table { + border-collapse: collapse; + border-spacing: 0; +} +.pkg-name { + padding-right: 10px; +} +.alert { + color: #AA0000; +} + +.top-heading { + float: left; + padding: 21px 0; + font-size: 20px; + font-weight: normal; +} +.top-heading a { + color: #222; + text-decoration: none; +} + +div#topbar { + background: #E0EBF5; + height: 64px; + overflow: hidden; +} + +body { + text-align: center; +} +div#page { + width: 100%; +} +div#page > .container, +div#topbar > .container { + text-align: left; + margin-left: auto; + margin-right: auto; + padding: 0 20px; +} +div#topbar > .container, +div#page > .container { + max-width: 950px; +} +div#page.wide > .container, +div#topbar.wide > .container { + max-width: none; +} +div#plusone { + float: right; + clear: right; + margin-top: 5px; +} + +div#footer { + text-align: center; + color: #666; + font-size: 14px; + margin: 40px 0; +} + +div#menu > a, +div#menu > input, +div#learn .buttons a, +div.play .buttons a, +div#blog .read a, +#menu-button { + padding: 10px; + + text-decoration: none; + font-size: 16px; + + -webkit-border-radius: 5px; + -moz-border-radius: 5px; + border-radius: 5px; +} +div#playground .buttons a, +div#menu > a, +div#menu > input, +#menu-button { + border: 1px solid #375EAB; +} +div#playground .buttons a, +div#menu > a, +#menu-button { + color: white; + background: #375EAB; +} +#playgroundButton.active { + background: white; + color: #375EAB; +} +a#start, +div#learn .buttons a, +div.play .buttons a, +div#blog .read a { + color: #222; + border: 1px solid #375EAB; + background: #E0EBF5; +} +.download { + width: 150px; +} + +div#menu { + text-align: right; + padding: 10px; + white-space: nowrap; + max-height: 0; + -moz-transition: max-height .25s linear; + transition: max-height .25s linear; + width: 100%; +} +div#menu.menu-visible { + max-height: 500px; +} +div#menu > a, +#menu-button { + margin: 10px 2px; + padding: 10px; +} +div#menu > input { + position: relative; + top: 1px; + width: 140px; + background: white; + color: #222; + box-sizing: border-box; +} +div#menu > input.inactive { + color: #999; +} + +#menu-button { + display: none; + position: absolute; + right: 5px; + top: 0; + margin-right: 5px; +} +#menu-button-arrow { + display: inline-block; +} +.vertical-flip { + transform: rotate(-180deg); +} + +div.left { + float: left; + clear: left; + margin-right: 2.5%; +} +div.right { + float: right; + clear: right; + margin-left: 2.5%; +} +div.left, +div.right { + width: 45%; +} + +div#learn, +div#about { + padding-top: 20px; +} +div#learn h2, +div#about { + margin: 0; +} +div#about { + font-size: 20px; + margin: 0 auto 30px; +} +div#gopher { + background: url(http://localhost:6060/doc/gopher/frontpage.png) no-repeat; + background-position: center top; + height: 155px; +} +a#start { + display: block; + padding: 10px; + + text-align: center; + text-decoration: none; + + -webkit-border-radius: 5px; + -moz-border-radius: 5px; + border-radius: 5px; +} +a#start .big { + display: block; + font-weight: bold; + font-size: 20px; +} +a#start .desc { + display: block; + font-size: 14px; + font-weight: normal; + margin-top: 5px; +} + +div#learn .popout { + float: right; + display: block; + cursor: pointer; + font-size: 12px; + background: url(http://localhost:6060/doc/share.png) no-repeat; + background-position: right top; + padding: 5px 27px; +} +div#learn pre, +div#learn textarea { + padding: 0; + margin: 0; + font-family: Menlo, monospace; + font-size: 14px; +} +div#learn .input { + padding: 10px; + margin-top: 10px; + height: 150px; + + -webkit-border-top-left-radius: 5px; + -webkit-border-top-right-radius: 5px; + -moz-border-radius-topleft: 5px; + -moz-border-radius-topright: 5px; + border-top-left-radius: 5px; + border-top-right-radius: 5px; +} +div#learn .input textarea { + width: 100%; + height: 100%; + border: none; + outline: none; + resize: none; +} +div#learn .output { + border-top: none !important; + + padding: 10px; + height: 59px; + overflow: auto; + + -webkit-border-bottom-right-radius: 5px; + -webkit-border-bottom-left-radius: 5px; + -moz-border-radius-bottomright: 5px; + -moz-border-radius-bottomleft: 5px; + border-bottom-right-radius: 5px; + border-bottom-left-radius: 5px; +} +div#learn .output pre { + padding: 0; + + -webkit-border-radius: 0; + -moz-border-radius: 0; + border-radius: 0; +} +div#learn .input, +div#learn .input textarea, +div#learn .output, +div#learn .output pre { + background: #FFFFD8; +} +div#learn .input, +div#learn .output { + border: 1px solid #375EAB; +} +div#learn .buttons { + float: right; + padding: 20px 0 10px 0; + text-align: right; +} +div#learn .buttons a { + height: 16px; + margin-left: 5px; + padding: 10px; +} +div#learn .toys { + margin-top: 8px; +} +div#learn .toys select { + border: 1px solid #375EAB; + margin: 0; +} +div#learn .output .exit { + display: none; +} + +div#video { + max-width: 100%; +} +div#blog, +div#video { + margin-top: 40px; +} +div#blog > a, +div#blog > div, +div#blog > h2, +div#video > a, +div#video > div, +div#video > h2 { + margin-bottom: 10px; +} +div#blog .title, +div#video .title { + display: block; + font-size: 20px; +} +div#blog .when { + color: #666; + font-size: 14px; +} +div#blog .read { + text-align: right; +} + +.toggleButton { cursor: pointer; } +.toggle .collapsed { display: block; } +.toggle .expanded { display: none; } +.toggleVisible .collapsed { display: none; } +.toggleVisible .expanded { display: block; } + +table.codetable { margin-left: auto; margin-right: auto; border-style: none; } +table.codetable td { padding-right: 10px; } +hr { border-style: none; border-top: 1px solid black; } + +img.gopher { + float: right; + margin-left: 10px; + margin-bottom: 10px; + z-index: -1; +} +h2 { clear: right; } + +/* example and drop-down playground */ +div.play { + padding: 0 20px 40px 20px; +} +div.play pre, +div.play textarea, +div.play .lines { + padding: 0; + margin: 0; + font-family: Menlo, monospace; + font-size: 14px; +} +div.play .input { + padding: 10px; + margin-top: 10px; + + -webkit-border-top-left-radius: 5px; + -webkit-border-top-right-radius: 5px; + -moz-border-radius-topleft: 5px; + -moz-border-radius-topright: 5px; + border-top-left-radius: 5px; + border-top-right-radius: 5px; + + overflow: hidden; +} +div.play .input textarea { + width: 100%; + height: 100%; + border: none; + outline: none; + resize: none; + + overflow: hidden; +} +div#playground .input textarea { + overflow: auto; + resize: auto; +} +div.play .output { + border-top: none !important; + + padding: 10px; + max-height: 200px; + overflow: auto; + + -webkit-border-bottom-right-radius: 5px; + -webkit-border-bottom-left-radius: 5px; + -moz-border-radius-bottomright: 5px; + -moz-border-radius-bottomleft: 5px; + border-bottom-right-radius: 5px; + border-bottom-left-radius: 5px; +} +div.play .output pre { + padding: 0; + + -webkit-border-radius: 0; + -moz-border-radius: 0; + border-radius: 0; +} +div.play .input, +div.play .input textarea, +div.play .output, +div.play .output pre { + background: #FFFFD8; +} +div.play .input, +div.play .output { + border: 1px solid #375EAB; +} +div.play .buttons { + float: right; + padding: 20px 0 10px 0; + text-align: right; +} +div.play .buttons a { + height: 16px; + margin-left: 5px; + padding: 10px; + cursor: pointer; +} +.output .stderr { + color: #933; +} +.output .system { + color: #999; +} + +/* drop-down playground */ +#playgroundButton, +div#playground { + /* start hidden; revealed by javascript */ + display: none; +} +div#playground { + position: absolute; + top: 63px; + right: 20px; + padding: 0 10px 10px 10px; + z-index: 1; + text-align: left; + background: #E0EBF5; + + border: 1px solid #B0BBC5; + border-top: none; + + -webkit-border-bottom-left-radius: 5px; + -webkit-border-bottom-right-radius: 5px; + -moz-border-radius-bottomleft: 5px; + -moz-border-radius-bottomright: 5px; + border-bottom-left-radius: 5px; + border-bottom-right-radius: 5px; +} +div#playground .code { + width: 520px; + height: 200px; +} +div#playground .output { + height: 100px; +} + +/* Inline runnable snippets (play.js/initPlayground) */ +#content .code pre, #content .playground pre, #content .output pre { + margin: 0; + padding: 0; + background: none; + border: none; + outline: 0px solid transparent; + overflow: auto; +} +#content .playground .number, #content .code .number { + color: #999; +} +#content .code, #content .playground, #content .output { + width: auto; + margin: 20px; + padding: 10px; + -webkit-border-radius: 5px; + -moz-border-radius: 5px; + border-radius: 5px; +} +#content .code, #content .playground { + background: #e9e9e9; +} +#content .output { + background: #202020; +} +#content .output .stdout, #content .output pre { + color: #e6e6e6; +} +#content .output .stderr, #content .output .error { + color: rgb(244, 74, 63); +} +#content .output .system, #content .output .exit { + color: rgb(255, 209, 77) +} +#content .buttons { + position: relative; + float: right; + top: -50px; + right: 30px; +} +#content .output .buttons { + top: -60px; + right: 0; + height: 0; +} +#content .buttons .kill { + display: none; + visibility: hidden; +} +a.error { + font-weight: bold; + color: white; + background-color: darkred; + border-bottom-left-radius: 4px; + border-bottom-right-radius: 4px; + border-top-left-radius: 4px; + border-top-right-radius: 4px; + padding: 2px 4px 2px 4px; /* TRBL */ +} + + +#heading-narrow { + display: none; +} + +.downloading { + background: #F9F9BE; + padding: 10px; + text-align: center; + border-radius: 5px; +} + +@media (max-width: 930px) { + #heading-wide { + display: none; + } + #heading-narrow { + display: block; + } +} + + +@media (max-width: 760px) { + .container .left, + .container .right { + width: auto; + float: none; + } + + div#about { + max-width: 500px; + text-align: center; + } +} + +@media (min-width: 700px) and (max-width: 1000px) { + div#menu > a { + margin: 5px 0; + font-size: 14px; + } + + div#menu > input { + font-size: 14px; + } +} + +@media (max-width: 700px) { + body { + font-size: 15px; + } + + pre, + code { + font-size: 13px; + } + + div#page > .container { + padding: 0 10px; + } + + div#topbar { + height: auto; + padding: 10px; + } + + div#topbar > .container { + padding: 0; + } + + #heading-wide { + display: block; + } + #heading-narrow { + display: none; + } + + .top-heading { + float: none; + display: inline-block; + padding: 12px; + } + + div#menu { + padding: 0; + min-width: 0; + text-align: left; + float: left; + } + + div#menu > a, + div#menu > input { + display: block; + margin-left: 0; + margin-right: 0; + } + + div#menu > input { + width: 100%; + } + + #menu-button { + display: inline-block; + } + + p, + pre, + ul, + ol { + margin: 10px; + } + + .pkg-synopsis { + display: none; + } + + img.gopher { + display: none; + } +} + +@media (max-width: 480px) { + #heading-wide { + display: none; + } + #heading-narrow { + display: block; + } +} + +@media print { + pre { + background: #FFF; + border: 1px solid #BBB; + white-space: pre-wrap; + } +} diff --git a/pkg/C/index.html b/pkg/C/index.html new file mode 100644 index 0000000..bb36204 --- /dev/null +++ b/pkg/C/index.html @@ -0,0 +1,474 @@ + + + + + + + + cgo - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Command cgo

    + + + + + + + + + + + + + + +

    +Cgo enables the creation of Go packages that call C code. +

    +

    Using cgo with the go command

    +

    +To use cgo write normal Go code that imports a pseudo-package "C". +The Go code can then refer to types such as C.size_t, variables such +as C.stdout, or functions such as C.putchar. +

    +

    +If the import of "C" is immediately preceded by a comment, that +comment, called the preamble, is used as a header when compiling +the C parts of the package. For example: +

    +
    // #include <stdio.h>
    +// #include <errno.h>
    +import "C"
    +
    +

    +The preamble may contain any C code, including function and variable +declarations and definitions. These may then be referred to from Go +code as though they were defined in the package "C". All names +declared in the preamble may be used, even if they start with a +lower-case letter. Exception: static variables in the preamble may +not be referenced from Go code; static functions are permitted. +

    +

    +See $GOROOT/misc/cgo/stdio and $GOROOT/misc/cgo/gmp for examples. See +"C? Go? Cgo!" for an introduction to using cgo: +https://golang.org/doc/articles/c_go_cgo.html. +

    +

    +CFLAGS, CPPFLAGS, CXXFLAGS and LDFLAGS may be defined with pseudo #cgo +directives within these comments to tweak the behavior of the C or C++ +compiler. Values defined in multiple directives are concatenated +together. The directive can include a list of build constraints limiting its +effect to systems satisfying one of the constraints +(see https://golang.org/pkg/go/build/#hdr-Build_Constraints for details about the constraint syntax). +For example: +

    +
    // #cgo CFLAGS: -DPNG_DEBUG=1
    +// #cgo amd64 386 CFLAGS: -DX86=1
    +// #cgo LDFLAGS: -lpng
    +// #include <png.h>
    +import "C"
    +
    +

    +Alternatively, CPPFLAGS and LDFLAGS may be obtained via the pkg-config +tool using a '#cgo pkg-config:' directive followed by the package names. +For example: +

    +
    // #cgo pkg-config: png cairo
    +// #include <png.h>
    +import "C"
    +
    +

    +When building, the CGO_CFLAGS, CGO_CPPFLAGS, CGO_CXXFLAGS and +CGO_LDFLAGS environment variables are added to the flags derived from +these directives. Package-specific flags should be set using the +directives, not the environment variables, so that builds work in +unmodified environments. +

    +

    +All the cgo CPPFLAGS and CFLAGS directives in a package are concatenated and +used to compile C files in that package. All the CPPFLAGS and CXXFLAGS +directives in a package are concatenated and used to compile C++ files in that +package. All the LDFLAGS directives in any package in the program are +concatenated and used at link time. All the pkg-config directives are +concatenated and sent to pkg-config simultaneously to add to each appropriate +set of command-line flags. +

    +

    +When the cgo directives are parsed, any occurrence of the string ${SRCDIR} +will be replaced by the absolute path to the directory containing the source +file. This allows pre-compiled static libraries to be included in the package +directory and linked properly. +For example if package foo is in the directory /go/src/foo: +

    +
    // #cgo LDFLAGS: -L${SRCDIR}/libs -lfoo
    +
    +

    +Will be expanded to: +

    +
    // #cgo LDFLAGS: -L/go/src/foo/libs -lfoo
    +
    +

    +When the Go tool sees that one or more Go files use the special import +"C", it will look for other non-Go files in the directory and compile +them as part of the Go package. Any .c, .s, or .S files will be +compiled with the C compiler. Any .cc, .cpp, or .cxx files will be +compiled with the C++ compiler. Any .h, .hh, .hpp, or .hxx files will +not be compiled separately, but, if these header files are changed, +the C and C++ files will be recompiled. The default C and C++ +compilers may be changed by the CC and CXX environment variables, +respectively; those environment variables may include command line +options. +

    +

    +The cgo tool is enabled by default for native builds on systems where +it is expected to work. It is disabled by default when +cross-compiling. You can control this by setting the CGO_ENABLED +environment variable when running the go tool: set it to 1 to enable +the use of cgo, and to 0 to disable it. The go tool will set the +build constraint "cgo" if cgo is enabled. +

    +

    +When cross-compiling, you must specify a C cross-compiler for cgo to +use. You can do this by setting the CC_FOR_TARGET environment +variable when building the toolchain using make.bash, or by setting +the CC environment variable any time you run the go tool. The +CXX_FOR_TARGET and CXX environment variables work in a similar way for +C++ code. +

    +

    Go references to C

    +

    +Within the Go file, C's struct field names that are keywords in Go +can be accessed by prefixing them with an underscore: if x points at a C +struct with a field named "type", x._type accesses the field. +C struct fields that cannot be expressed in Go, such as bit fields +or misaligned data, are omitted in the Go struct, replaced by +appropriate padding to reach the next field or the end of the struct. +

    +

    +The standard C numeric types are available under the names +C.char, C.schar (signed char), C.uchar (unsigned char), +C.short, C.ushort (unsigned short), C.int, C.uint (unsigned int), +C.long, C.ulong (unsigned long), C.longlong (long long), +C.ulonglong (unsigned long long), C.float, C.double, +C.complexfloat (complex float), and C.complexdouble (complex double). +The C type void* is represented by Go's unsafe.Pointer. +The C types __int128_t and __uint128_t are represented by [16]byte. +

    +

    +To access a struct, union, or enum type directly, prefix it with +struct_, union_, or enum_, as in C.struct_stat. +

    +

    +The size of any C type T is available as C.sizeof_T, as in +C.sizeof_struct_stat. +

    +

    +As Go doesn't have support for C's union type in the general case, +C's union types are represented as a Go byte array with the same length. +

    +

    +Go structs cannot embed fields with C types. +

    +

    +Go code can not refer to zero-sized fields that occur at the end of +non-empty C structs. To get the address of such a field (which is the +only operation you can do with a zero-sized field) you must take the +address of the struct and add the size of the struct. +

    +

    +Cgo translates C types into equivalent unexported Go types. +Because the translations are unexported, a Go package should not +expose C types in its exported API: a C type used in one Go package +is different from the same C type used in another. +

    +

    +Any C function (even void functions) may be called in a multiple +assignment context to retrieve both the return value (if any) and the +C errno variable as an error (use _ to skip the result value if the +function returns void). For example: +

    +
    n, err := C.sqrt(-1)
    +_, err := C.voidFunc()
    +
    +

    +Calling C function pointers is currently not supported, however you can +declare Go variables which hold C function pointers and pass them +back and forth between Go and C. C code may call function pointers +received from Go. For example: +

    +
    package main
    +
    +// typedef int (*intFunc) ();
    +//
    +// int
    +// bridge_int_func(intFunc f)
    +// {
    +//		return f();
    +// }
    +//
    +// int fortytwo()
    +// {
    +//	    return 42;
    +// }
    +import "C"
    +import "fmt"
    +
    +func main() {
    +	f := C.intFunc(C.fortytwo)
    +	fmt.Println(int(C.bridge_int_func(f)))
    +	// Output: 42
    +}
    +
    +

    +In C, a function argument written as a fixed size array +actually requires a pointer to the first element of the array. +C compilers are aware of this calling convention and adjust +the call accordingly, but Go cannot. In Go, you must pass +the pointer to the first element explicitly: C.f(&C.x[0]). +

    +

    +A few special functions convert between Go and C types +by making copies of the data. In pseudo-Go definitions: +

    +
    // Go string to C string
    +// The C string is allocated in the C heap using malloc.
    +// It is the caller's responsibility to arrange for it to be
    +// freed, such as by calling C.free (be sure to include stdlib.h
    +// if C.free is needed).
    +func C.CString(string) *C.char
    +
    +// C string to Go string
    +func C.GoString(*C.char) string
    +
    +// C data with explicit length to Go string
    +func C.GoStringN(*C.char, C.int) string
    +
    +// C data with explicit length to Go []byte
    +func C.GoBytes(unsafe.Pointer, C.int) []byte
    +
    +

    C references to Go

    +

    +Go functions can be exported for use by C code in the following way: +

    +
    //export MyFunction
    +func MyFunction(arg1, arg2 int, arg3 string) int64 {...}
    +
    +//export MyFunction2
    +func MyFunction2(arg1, arg2 int, arg3 string) (int64, *C.char) {...}
    +
    +

    +They will be available in the C code as: +

    +
    extern int64 MyFunction(int arg1, int arg2, GoString arg3);
    +extern struct MyFunction2_return MyFunction2(int arg1, int arg2, GoString arg3);
    +
    +

    +found in the _cgo_export.h generated header, after any preambles +copied from the cgo input files. Functions with multiple +return values are mapped to functions returning a struct. +Not all Go types can be mapped to C types in a useful way. +

    +

    +Using //export in a file places a restriction on the preamble: +since it is copied into two different C output files, it must not +contain any definitions, only declarations. If a file contains both +definitions and declarations, then the two output files will produce +duplicate symbols and the linker will fail. To avoid this, definitions +must be placed in preambles in other files, or in C source files. +

    +

    Passing pointers

    +

    +Go is a garbage collected language, and the garbage collector needs to +know the location of every pointer to Go memory. Because of this, +there are restrictions on passing pointers between Go and C. +

    +

    +In this section the term Go pointer means a pointer to memory +allocated by Go (such as by using the & operator or calling the +predefined new function) and the term C pointer means a pointer to +memory allocated by C (such as by a call to C.malloc). Whether a +pointer is a Go pointer or a C pointer is a dynamic property +determined by how the memory was allocated; it has nothing to do with +the type of the pointer. +

    +

    +Go code may pass a Go pointer to C provided the Go memory to which it +points does not contain any Go pointers. The C code must preserve +this property: it must not store any Go pointers in Go memory, even +temporarily. When passing a pointer to a field in a struct, the Go +memory in question is the memory occupied by the field, not the entire +struct. When passing a pointer to an element in an array or slice, +the Go memory in question is the entire array or the entire backing +array of the slice. +

    +

    +C code may not keep a copy of a Go pointer after the call returns. +

    +

    +A Go function called by C code may not return a Go pointer. A Go +function called by C code may take C pointers as arguments, and it may +store non-pointer or C pointer data through those pointers, but it may +not store a Go pointer in memory pointed to by a C pointer. A Go +function called by C code may take a Go pointer as an argument, but it +must preserve the property that the Go memory to which it points does +not contain any Go pointers. +

    +

    +Go code may not store a Go pointer in C memory. C code may store Go +pointers in C memory, subject to the rule above: it must stop storing +the Go pointer when the C function returns. +

    +

    +These rules are checked dynamically at runtime. The checking is +controlled by the cgocheck setting of the GODEBUG environment +variable. The default setting is GODEBUG=cgocheck=1, which implements +reasonably cheap dynamic checks. These checks may be disabled +entirely using GODEBUG=cgocheck=0. Complete checking of pointer +handling, at some cost in run time, is available via GODEBUG=cgocheck=2. +

    +

    +It is possible to defeat this enforcement by using the unsafe package, +and of course there is nothing stopping the C code from doing anything +it likes. However, programs that break these rules are likely to fail +in unexpected and unpredictable ways. +

    +

    Using cgo directly

    +

    +Usage: +

    +
    go tool cgo [cgo options] [-- compiler options] gofiles...
    +
    +

    +Cgo transforms the specified input Go source files into several output +Go and C source files. +

    +

    +The compiler options are passed through uninterpreted when +invoking the C compiler to compile the C parts of the package. +

    +

    +The following options are available when running cgo directly: +

    +
    -dynimport file
    +	Write list of symbols imported by file. Write to
    +	-dynout argument or to standard output. Used by go
    +	build when building a cgo package.
    +-dynout file
    +	Write -dynimport output to file.
    +-dynpackage package
    +	Set Go package for -dynimport output.
    +-dynlinker
    +	Write dynamic linker as part of -dynimport output.
    +-godefs
    +	Write out input file in Go syntax replacing C package
    +	names with real values. Used to generate files in the
    +	syscall package when bootstrapping a new target.
    +-objdir directory
    +	Put all generated files in directory.
    +-importpath string
    +	The import path for the Go package. Optional; used for
    +	nicer comments in the generated files.
    +-exportheader file
    +	If there are any exported functions, write the
    +	generated export declarations to file.
    +	C code can #include this to see the declarations.
    +-gccgo
    +	Generate output for the gccgo compiler rather than the
    +	gc compiler.
    +-gccgoprefix prefix
    +	The -fgo-prefix option to be used with gccgo.
    +-gccgopkgpath path
    +	The -fgo-pkgpath option to be used with gccgo.
    +-import_runtime_cgo
    +	If set (which it is by default) import runtime/cgo in
    +	generated output.
    +-import_syscall
    +	If set (which it is by default) import syscall in
    +	generated output.
    +-debug-define
    +	Debugging option. Print #defines.
    +-debug-gcc
    +	Debugging option. Trace C compiler execution and output.
    +
    + + + + + + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/bufio/index.html b/pkg/bufio/index.html new file mode 100644 index 0000000..c702ffa --- /dev/null +++ b/pkg/bufio/index.html @@ -0,0 +1,1276 @@ + + + + + + + + bufio - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Package bufio

    + + + + + + + + + + + + + + +
    +
    +
    import "bufio"
    +
    +
    +
    Overview
    +
    Index
    + +
    Examples
    + + +
    +
    + +
    + +
    +

    Overview ▾

    +

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

    + +
    +
    + + +
    + +
    +

    Index ▾

    + + +
    +
    + +
    Constants
    + + +
    Variables
    + + + +
    func ScanBytes(data []byte, atEOF bool) (advance int, token []byte, err error)
    + + +
    func ScanLines(data []byte, atEOF bool) (advance int, token []byte, err error)
    + + +
    func ScanRunes(data []byte, atEOF bool) (advance int, token []byte, err error)
    + + +
    func ScanWords(data []byte, atEOF bool) (advance int, token []byte, err error)
    + + + +
    type ReadWriter
    + + +
        func NewReadWriter(r *Reader, w *Writer) *ReadWriter
    + + + + +
    type Reader
    + + +
        func NewReader(rd io.Reader) *Reader
    + + +
        func NewReaderSize(rd io.Reader, size int) *Reader
    + + + +
        func (b *Reader) Buffered() int
    + + +
        func (b *Reader) Discard(n int) (discarded int, err error)
    + + +
        func (b *Reader) Peek(n int) ([]byte, error)
    + + +
        func (b *Reader) Read(p []byte) (n int, err error)
    + + +
        func (b *Reader) ReadByte() (c byte, err error)
    + + +
        func (b *Reader) ReadBytes(delim byte) (line []byte, err error)
    + + +
        func (b *Reader) ReadLine() (line []byte, isPrefix bool, err error)
    + + +
        func (b *Reader) ReadRune() (r rune, size int, err error)
    + + +
        func (b *Reader) ReadSlice(delim byte) (line []byte, err error)
    + + +
        func (b *Reader) ReadString(delim byte) (line string, err error)
    + + +
        func (b *Reader) Reset(r io.Reader)
    + + +
        func (b *Reader) UnreadByte() error
    + + +
        func (b *Reader) UnreadRune() error
    + + +
        func (b *Reader) WriteTo(w io.Writer) (n int64, err error)
    + + + +
    type Scanner
    + + +
        func NewScanner(r io.Reader) *Scanner
    + + + +
        func (s *Scanner) Buffer(buf []byte, max int)
    + + +
        func (s *Scanner) Bytes() []byte
    + + +
        func (s *Scanner) Err() error
    + + +
        func (s *Scanner) Scan() bool
    + + +
        func (s *Scanner) Split(split SplitFunc)
    + + +
        func (s *Scanner) Text() string
    + + + +
    type SplitFunc
    + + + + +
    type Writer
    + + +
        func NewWriter(w io.Writer) *Writer
    + + +
        func NewWriterSize(w io.Writer, size int) *Writer
    + + + +
        func (b *Writer) Available() int
    + + +
        func (b *Writer) Buffered() int
    + + +
        func (b *Writer) Flush() error
    + + +
        func (b *Writer) ReadFrom(r io.Reader) (n int64, err error)
    + + +
        func (b *Writer) Reset(w io.Writer)
    + + +
        func (b *Writer) Write(p []byte) (nn int, err error)
    + + +
        func (b *Writer) WriteByte(c byte) error
    + + +
        func (b *Writer) WriteRune(r rune) (size int, err error)
    + + +
        func (b *Writer) WriteString(s string) (int, error)
    + + + +
    +
    + + + + + + +

    Package files

    +

    + + + bufio.go + + scan.go + + +

    + +
    +
    + + + + +

    Constants

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

    Variables

    + +
    var (
    +    ErrInvalidUnreadByte = errors.New("bufio: invalid use of UnreadByte")
    +    ErrInvalidUnreadRune = errors.New("bufio: invalid use of UnreadRune")
    +    ErrBufferFull        = errors.New("bufio: buffer full")
    +    ErrNegativeCount     = errors.New("bufio: negative count")
    +)
    + + +
    var (
    +    ErrTooLong         = errors.New("bufio.Scanner: token too long")
    +    ErrNegativeAdvance = errors.New("bufio.Scanner: SplitFunc returns negative advance count")
    +    ErrAdvanceTooFar   = errors.New("bufio.Scanner: SplitFunc returns advance count beyond input")
    +)
    +

    +Errors returned by Scanner. +

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

    +ErrFinalToken is a special sentinel error value. It is intended to be +returned by a Split function to indicate that the token being delivered +with the error is the last token and scanning should stop after this one. +After ErrFinalToken is received by Scan, scanning stops with no error. +The value is useful to stop processing early or when it is necessary to +deliver a final empty token. One could achieve the same behavior +with a custom error value but providing one here is tidier. +See the emptyFinalToken example for a use of this value. +

    + + + + + + +

    func ScanBytes

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

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

    + + + + + + + +

    func ScanLines

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

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

    + + + + + + + +

    func ScanRunes

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

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

    + + + + + + + +

    func ScanWords

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

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

    + + + + + + + + +

    type ReadWriter

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

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

    + + + + + + + + + + + + +

    func NewReadWriter

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

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

    + + + + + + + + + +

    type Reader

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

    +Reader implements buffering for an io.Reader object. +

    + + + + + + + + + + + + +

    func NewReader

    +
    func NewReader(rd io.Reader) *Reader
    +

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

    + + + + + +

    func NewReaderSize

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

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

    + + + + + + + +

    func (*Reader) Buffered

    +
    func (b *Reader) Buffered() int
    +

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

    + + + + + + +

    func (*Reader) Discard

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

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

    +

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

    + + + + + + +

    func (*Reader) Peek

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

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

    + + + + + + +

    func (*Reader) Read

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

    +Read reads data into p. +It returns the number of bytes read into p. +The bytes are taken from at most one Read on the underlying Reader, +hence n may be less than len(p). +At EOF, the count will be zero and err will be io.EOF. +

    + + + + + + +

    func (*Reader) ReadByte

    +
    func (b *Reader) ReadByte() (c byte, err error)
    +

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

    + + + + + + +

    func (*Reader) ReadBytes

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

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

    + + + + + + +

    func (*Reader) ReadLine

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

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

    +

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

    +

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

    + + + + + + +

    func (*Reader) ReadRune

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

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

    + + + + + + +

    func (*Reader) ReadSlice

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

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

    + + + + + + +

    func (*Reader) ReadString

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

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

    + + + + + + +

    func (*Reader) Reset

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

    +Reset discards any buffered data, resets all state, and switches +the buffered reader to read from r. +

    + + + + + + +

    func (*Reader) UnreadByte

    +
    func (b *Reader) UnreadByte() error
    +

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

    + + + + + + +

    func (*Reader) UnreadRune

    +
    func (b *Reader) UnreadRune() error
    +

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

    + + + + + + +

    func (*Reader) WriteTo

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

    +WriteTo implements io.WriterTo. +

    + + + + + + + + +

    type Scanner

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

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

    +

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

    + + + + + + +
    + +
    +

    Example (Custom)

    +

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

    + + +

    Code:

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

    Output:

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

    Example (EmptyFinalToken)

    +

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

    + + +

    Code:

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

    Output:

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

    Example (Lines)

    +

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

    + + +

    Code:

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

    Example (Words)

    +

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

    + + +

    Code:

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

    Output:

    +
    15
    +
    + + +
    +
    + + + + + + +

    func NewScanner

    +
    func NewScanner(r io.Reader) *Scanner
    +

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

    + + + + + + + +

    func (*Scanner) Buffer

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

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

    +

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

    +

    +Buffer panics if it is called after scanning has started. +

    + + + + + + +

    func (*Scanner) Bytes

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

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

    + + + + + + +

    func (*Scanner) Err

    +
    func (s *Scanner) Err() error
    +

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

    + + + + + + +

    func (*Scanner) Scan

    +
    func (s *Scanner) Scan() bool
    +

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

    + + + + + + +

    func (*Scanner) Split

    +
    func (s *Scanner) Split(split SplitFunc)
    +

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

    +

    +Split panics if it is called after scanning has started. +

    + + + + + + +

    func (*Scanner) Text

    +
    func (s *Scanner) Text() string
    +

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

    + + + + + + + + +

    type SplitFunc

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

    +SplitFunc is the signature of the split function used to tokenize the +input. The arguments are an initial substring of the remaining unprocessed +data and a flag, atEOF, that reports whether the Reader has no more data +to give. The return values are the number of bytes to advance the input +and the next token to return to the user, plus an error, if any. If the +data does not yet hold a complete token, for instance if it has no newline +while scanning lines, SplitFunc can return (0, nil, nil) to signal the +Scanner to read more data into the slice and try again with a longer slice +starting at the same point in the input. +

    +

    +If the returned error is non-nil, scanning stops and the error +is returned to the client. +

    +

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

    + + + + + + + + + + + + + + + + +

    type Writer

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

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

    + + + + + + +
    + +
    +

    Example

    + + + +

    Code:

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

    Output:

    +
    Hello, world!
    +
    + + +
    +
    + + + + + + +

    func NewWriter

    +
    func NewWriter(w io.Writer) *Writer
    +

    +NewWriter returns a new Writer whose buffer has the default size. +

    + + + + + +

    func NewWriterSize

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

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

    + + + + + + + +

    func (*Writer) Available

    +
    func (b *Writer) Available() int
    +

    +Available returns how many bytes are unused in the buffer. +

    + + + + + + +

    func (*Writer) Buffered

    +
    func (b *Writer) Buffered() int
    +

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

    + + + + + + +

    func (*Writer) Flush

    +
    func (b *Writer) Flush() error
    +

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

    + + + + + + +

    func (*Writer) ReadFrom

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

    +ReadFrom implements io.ReaderFrom. +

    + + + + + + +

    func (*Writer) Reset

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

    +Reset discards any unflushed buffered data, clears any error, and +resets b to write its output to w. +

    + + + + + + +

    func (*Writer) Write

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

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

    + + + + + + +

    func (*Writer) WriteByte

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

    +WriteByte writes a single byte. +

    + + + + + + +

    func (*Writer) WriteRune

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

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

    + + + + + + +

    func (*Writer) WriteString

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

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

    + + + + + + + + + + + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/builtin/index.html b/pkg/builtin/index.html new file mode 100644 index 0000000..3bbc5ac --- /dev/null +++ b/pkg/builtin/index.html @@ -0,0 +1,1239 @@ + + + + + + + + builtin - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Package builtin

    + + + + + + + + + + + + + + +
    +
    +
    import "builtin"
    +
    +
    +
    Overview
    +
    Index
    + + +
    +
    + +
    + +
    +

    Overview ▾

    +

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

    + +
    +
    + + + + + + + +

    Constants

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

    +true and false are the two untyped boolean values. +

    + + +
    const iota = 0 // Untyped int.
    +
    +

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

    + + + + +

    Variables

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

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

    + + + + + + +

    func append

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

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

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

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

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

    func cap

    +
    func cap(v Type) int
    +

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

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

    func close

    +
    func close(c chan<- Type)
    +

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

    +
    x, ok := <-c
    +
    +

    +will also set ok to false for a closed channel. +

    + + + + + + + +

    func complex

    +
    func complex(r, i FloatType) ComplexType
    +

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

    + + + + + + + +

    func copy

    +
    func copy(dst, src []Type) int
    +

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

    + + + + + + + +

    func delete

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

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

    + + + + + + + +

    func imag

    +
    func imag(c ComplexType) FloatType
    +

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

    + + + + + + + +

    func len

    +
    func len(v Type) int
    +

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

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

    func make

    +
    func make(Type, size IntegerType) Type
    +

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

    +
    Slice: The size specifies the length. The capacity of the slice is
    +equal to its length. A second integer argument may be provided to
    +specify a different capacity; it must be no smaller than the
    +length, so make([]int, 0, 10) allocates a slice of length 0 and
    +capacity 10.
    +Map: An initial allocation is made according to the size but the
    +resulting map has length 0. The size may be omitted, in which case
    +a small starting size is allocated.
    +Channel: The channel's buffer is initialized with the specified
    +buffer capacity. If zero, or the size is omitted, the channel is
    +unbuffered.
    +
    + + + + + + + +

    func new

    +
    func new(Type) *Type
    +

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

    + + + + + + + +

    func panic

    +
    func panic(v interface{})
    +

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

    + + + + + + + +

    func print

    +
    func print(args ...Type)
    +

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

    + + + + + + + +

    func println

    +
    func println(args ...Type)
    +

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

    + + + + + + + +

    func real

    +
    func real(c ComplexType) FloatType
    +

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

    + + + + + + + +

    func recover

    +
    func recover() interface{}
    +

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

    + + + + + + + + +

    type ComplexType

    +
    type ComplexType complex64
    +

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

    + + + + + + + + + + + + + + + + +

    type FloatType

    +
    type FloatType float32
    +

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

    + + + + + + + + + + + + + + + + +

    type IntegerType

    +
    type IntegerType int
    +

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

    + + + + + + + + + + + + + + + + +

    type Type

    +
    type Type int
    +

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

    + + + + + + + + + + + + + + + + +

    type Type1

    +
    type Type1 int
    +

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

    + + + + + + + + + + + + + + + + +

    type bool

    +
    type bool bool
    +

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

    + + + + + + + + + + + + + + + + +

    type byte

    +
    type byte byte
    +

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

    + + + + + + + + + + + + + + + + +

    type complex128

    +
    type complex128 complex128
    +

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

    + + + + + + + + + + + + + + + + +

    type complex64

    +
    type complex64 complex64
    +

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

    + + + + + + + + + + + + + + + + +

    type error

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

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

    + + + + + + + + + + + + + + + + +

    type float32

    +
    type float32 float32
    +

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

    + + + + + + + + + + + + + + + + +

    type float64

    +
    type float64 float64
    +

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

    + + + + + + + + + + + + + + + + +

    type int

    +
    type int int
    +

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

    + + + + + + + + + + + + + + + + +

    type int16

    +
    type int16 int16
    +

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

    + + + + + + + + + + + + + + + + +

    type int32

    +
    type int32 int32
    +

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

    + + + + + + + + + + + + + + + + +

    type int64

    +
    type int64 int64
    +

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

    + + + + + + + + + + + + + + + + +

    type int8

    +
    type int8 int8
    +

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

    + + + + + + + + + + + + + + + + +

    type rune

    +
    type rune rune
    +

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

    + + + + + + + + + + + + + + + + +

    type string

    +
    type string string
    +

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

    + + + + + + + + + + + + + + + + +

    type uint

    +
    type uint uint
    +

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

    + + + + + + + + + + + + + + + + +

    type uint16

    +
    type uint16 uint16
    +

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

    + + + + + + + + + + + + + + + + +

    type uint32

    +
    type uint32 uint32
    +

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

    + + + + + + + + + + + + + + + + +

    type uint64

    +
    type uint64 uint64
    +

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

    + + + + + + + + + + + + + + + + +

    type uint8

    +
    type uint8 uint8
    +

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

    + + + + + + + + + + + + + + + + +

    type uintptr

    +
    type uintptr uintptr
    +

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

    + + + + + + + + + + + + + + + + + + + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/bytes/index.html b/pkg/bytes/index.html new file mode 100644 index 0000000..31120e7 --- /dev/null +++ b/pkg/bytes/index.html @@ -0,0 +1,1733 @@ + + + + + + + + bytes - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Package bytes

    + + + + + + + + + + + + + + +
    +
    +
    import "bytes"
    +
    +
    +
    Overview
    +
    Index
    + +
    Examples
    + + +
    +
    + +
    + +
    +

    Overview ▾

    +

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

    + +
    +
    + + +
    + +
    +

    Index ▾

    + + +
    +
    + +
    Constants
    + + +
    Variables
    + + + +
    func Compare(a, b []byte) int
    + + +
    func Contains(b, subslice []byte) bool
    + + +
    func Count(s, sep []byte) int
    + + +
    func Equal(a, b []byte) bool
    + + +
    func EqualFold(s, t []byte) bool
    + + +
    func Fields(s []byte) [][]byte
    + + +
    func FieldsFunc(s []byte, f func(rune) bool) [][]byte
    + + +
    func HasPrefix(s, prefix []byte) bool
    + + +
    func HasSuffix(s, suffix []byte) bool
    + + +
    func Index(s, sep []byte) int
    + + +
    func IndexAny(s []byte, chars string) int
    + + +
    func IndexByte(s []byte, c byte) int
    + + +
    func IndexFunc(s []byte, f func(r rune) bool) int
    + + +
    func IndexRune(s []byte, r rune) int
    + + +
    func Join(s [][]byte, sep []byte) []byte
    + + +
    func LastIndex(s, sep []byte) int
    + + +
    func LastIndexAny(s []byte, chars string) int
    + + +
    func LastIndexByte(s []byte, c byte) int
    + + +
    func LastIndexFunc(s []byte, f func(r rune) bool) int
    + + +
    func Map(mapping func(r rune) rune, s []byte) []byte
    + + +
    func Repeat(b []byte, count int) []byte
    + + +
    func Replace(s, old, new []byte, n int) []byte
    + + +
    func Runes(s []byte) []rune
    + + +
    func Split(s, sep []byte) [][]byte
    + + +
    func SplitAfter(s, sep []byte) [][]byte
    + + +
    func SplitAfterN(s, sep []byte, n int) [][]byte
    + + +
    func SplitN(s, sep []byte, n int) [][]byte
    + + +
    func Title(s []byte) []byte
    + + +
    func ToLower(s []byte) []byte
    + + +
    func ToLowerSpecial(_case unicode.SpecialCase, s []byte) []byte
    + + +
    func ToTitle(s []byte) []byte
    + + +
    func ToTitleSpecial(_case unicode.SpecialCase, s []byte) []byte
    + + +
    func ToUpper(s []byte) []byte
    + + +
    func ToUpperSpecial(_case unicode.SpecialCase, s []byte) []byte
    + + +
    func Trim(s []byte, cutset string) []byte
    + + +
    func TrimFunc(s []byte, f func(r rune) bool) []byte
    + + +
    func TrimLeft(s []byte, cutset string) []byte
    + + +
    func TrimLeftFunc(s []byte, f func(r rune) bool) []byte
    + + +
    func TrimPrefix(s, prefix []byte) []byte
    + + +
    func TrimRight(s []byte, cutset string) []byte
    + + +
    func TrimRightFunc(s []byte, f func(r rune) bool) []byte
    + + +
    func TrimSpace(s []byte) []byte
    + + +
    func TrimSuffix(s, suffix []byte) []byte
    + + + +
    type Buffer
    + + +
        func NewBuffer(buf []byte) *Buffer
    + + +
        func NewBufferString(s string) *Buffer
    + + + +
        func (b *Buffer) Bytes() []byte
    + + +
        func (b *Buffer) Cap() int
    + + +
        func (b *Buffer) Grow(n int)
    + + +
        func (b *Buffer) Len() int
    + + +
        func (b *Buffer) Next(n int) []byte
    + + +
        func (b *Buffer) Read(p []byte) (n int, err error)
    + + +
        func (b *Buffer) ReadByte() (c byte, err error)
    + + +
        func (b *Buffer) ReadBytes(delim byte) (line []byte, err error)
    + + +
        func (b *Buffer) ReadFrom(r io.Reader) (n int64, err error)
    + + +
        func (b *Buffer) ReadRune() (r rune, size int, err error)
    + + +
        func (b *Buffer) ReadString(delim byte) (line string, err error)
    + + +
        func (b *Buffer) Reset()
    + + +
        func (b *Buffer) String() string
    + + +
        func (b *Buffer) Truncate(n int)
    + + +
        func (b *Buffer) UnreadByte() error
    + + +
        func (b *Buffer) UnreadRune() error
    + + +
        func (b *Buffer) Write(p []byte) (n int, err error)
    + + +
        func (b *Buffer) WriteByte(c byte) error
    + + +
        func (b *Buffer) WriteRune(r rune) (n int, err error)
    + + +
        func (b *Buffer) WriteString(s string) (n int, err error)
    + + +
        func (b *Buffer) WriteTo(w io.Writer) (n int64, err error)
    + + + +
    type Reader
    + + +
        func NewReader(b []byte) *Reader
    + + + +
        func (r *Reader) Len() int
    + + +
        func (r *Reader) Read(b []byte) (n int, err error)
    + + +
        func (r *Reader) ReadAt(b []byte, off int64) (n int, err error)
    + + +
        func (r *Reader) ReadByte() (b byte, err error)
    + + +
        func (r *Reader) ReadRune() (ch rune, size int, err error)
    + + +
        func (r *Reader) Seek(offset int64, whence int) (int64, error)
    + + +
        func (r *Reader) Size() int64
    + + +
        func (r *Reader) UnreadByte() error
    + + +
        func (r *Reader) UnreadRune() error
    + + +
        func (r *Reader) WriteTo(w io.Writer) (n int64, err error)
    + + + + +
    Bugs
    + + +
    +
    + + +
    +

    Examples

    +
    + +
    Buffer
    + +
    Buffer (Reader)
    + +
    Compare
    + +
    Compare (Search)
    + +
    TrimPrefix
    + +
    TrimSuffix
    + +
    +
    + + + +

    Package files

    +

    + + + buffer.go + + bytes.go + + bytes_decl.go + + reader.go + + +

    + +
    +
    + + + + +

    Constants

    + +
    const MinRead = 512
    +

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

    + + + + +

    Variables

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

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

    + + + + + + +

    func Compare

    +
    func Compare(a, b []byte) int
    +

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

    + +
    + +
    +

    Example

    + + + +

    Code:

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

    func Contains

    +
    func Contains(b, subslice []byte) bool
    +

    +Contains reports whether subslice is within b. +

    + + + + + + + +

    func Count

    +
    func Count(s, sep []byte) int
    +

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

    + + + + + + + +

    func Equal

    +
    func Equal(a, b []byte) bool
    +

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

    + + + + + + + +

    func EqualFold

    +
    func EqualFold(s, t []byte) bool
    +

    +EqualFold reports whether s and t, interpreted as UTF-8 strings, +are equal under Unicode case-folding. +

    + + + + + + + +

    func Fields

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

    +Fields splits the slice s around each instance of one or more consecutive white space +characters, returning a slice of subslices of s or an empty list if s contains only white space. +

    + + + + + + + +

    func FieldsFunc

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

    +FieldsFunc interprets s as a sequence of UTF-8-encoded Unicode code points. +It splits the slice s at each run of code points c satisfying f(c) and +returns a slice of subslices of s. If all code points in s satisfy f(c), or +len(s) == 0, an empty slice is returned. +FieldsFunc makes no guarantees about the order in which it calls f(c). +If f does not return consistent results for a given c, FieldsFunc may crash. +

    + + + + + + + +

    func HasPrefix

    +
    func HasPrefix(s, prefix []byte) bool
    +

    +HasPrefix tests whether the byte slice s begins with prefix. +

    + + + + + + + +

    func HasSuffix

    +
    func HasSuffix(s, suffix []byte) bool
    +

    +HasSuffix tests whether the byte slice s ends with suffix. +

    + + + + + + + +

    func Index

    +
    func Index(s, sep []byte) int
    +

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

    + + + + + + + +

    func IndexAny

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

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

    + + + + + + + +

    func IndexByte

    +
    func IndexByte(s []byte, c byte) int
    +

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

    + + + + + + + +

    func IndexFunc

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

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

    + + + + + + + +

    func IndexRune

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

    +IndexRune interprets s as a sequence of UTF-8-encoded Unicode code points. +It returns the byte index of the first occurrence in s of the given rune. +It returns -1 if rune is not present in s. +

    + + + + + + + +

    func Join

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

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

    + + + + + + + +

    func LastIndex

    +
    func LastIndex(s, sep []byte) int
    +

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

    + + + + + + + +

    func LastIndexAny

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

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

    + + + + + + + +

    func LastIndexByte

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

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

    + + + + + + + +

    func LastIndexFunc

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

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

    + + + + + + + +

    func Map

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

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

    + + + + + + + +

    func Repeat

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

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

    + + + + + + + +

    func Replace

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

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

    + + + + + + + +

    func Runes

    +
    func Runes(s []byte) []rune
    +

    +Runes returns a slice of runes (Unicode code points) equivalent to s. +

    + + + + + + + +

    func Split

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

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

    + + + + + + + +

    func SplitAfter

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

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

    + + + + + + + +

    func SplitAfterN

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

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

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

    func SplitN

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

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

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

    func Title

    +
    func Title(s []byte) []byte
    +

    +Title returns a copy of s with all Unicode letters that begin words +mapped to their title case. +

    +

    +BUG(rsc): The rule Title uses for word boundaries does not handle Unicode punctuation properly. +

    + + + + + + + +

    func ToLower

    +
    func ToLower(s []byte) []byte
    +

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

    + + + + + + + +

    func ToLowerSpecial

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

    +ToLowerSpecial returns a copy of the byte slice s with all Unicode letters mapped to their +lower case, giving priority to the special casing rules. +

    + + + + + + + +

    func ToTitle

    +
    func ToTitle(s []byte) []byte
    +

    +ToTitle returns a copy of the byte slice s with all Unicode letters mapped to their title case. +

    + + + + + + + +

    func ToTitleSpecial

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

    +ToTitleSpecial returns a copy of the byte slice s with all Unicode letters mapped to their +title case, giving priority to the special casing rules. +

    + + + + + + + +

    func ToUpper

    +
    func ToUpper(s []byte) []byte
    +

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

    + + + + + + + +

    func ToUpperSpecial

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

    +ToUpperSpecial returns a copy of the byte slice s with all Unicode letters mapped to their +upper case, giving priority to the special casing rules. +

    + + + + + + + +

    func Trim

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

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

    + + + + + + + +

    func TrimFunc

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

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

    + + + + + + + +

    func TrimLeft

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

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

    + + + + + + + +

    func TrimLeftFunc

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

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

    + + + + + + + +

    func TrimPrefix

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

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

    + +
    + +
    +

    Example

    + + + +

    Code:

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

    Output:

    +
    Hello, world!
    +
    + + +
    +
    + + + + + + +

    func TrimRight

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

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

    + + + + + + + +

    func TrimRightFunc

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

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

    + + + + + + + +

    func TrimSpace

    +
    func TrimSpace(s []byte) []byte
    +

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

    + + + + + + + +

    func TrimSuffix

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

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

    + +
    + +
    +

    Example

    + + + +

    Code:

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

    Output:

    +
    Hello, world!
    +
    + + +
    +
    + + + + + + + +

    type Buffer

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

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

    + + + + + + +
    + +
    +

    Example

    + + + +

    Code:

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

    Output:

    +
    Hello world!
    +
    + + +
    +
    +
    + +
    +

    Example (Reader)

    + + + +

    Code:

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

    Output:

    +
    Gophers rule!
    +
    + + +
    +
    + + + + + + +

    func NewBuffer

    +
    func NewBuffer(buf []byte) *Buffer
    +

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

    +

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

    + + + + + +

    func NewBufferString

    +
    func NewBufferString(s string) *Buffer
    +

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

    +

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

    + + + + + + + +

    func (*Buffer) Bytes

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

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

    + + + + + + +

    func (*Buffer) Cap

    +
    func (b *Buffer) Cap() int
    +

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

    + + + + + + +

    func (*Buffer) Grow

    +
    func (b *Buffer) Grow(n int)
    +

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

    + + + + + + +

    func (*Buffer) Len

    +
    func (b *Buffer) Len() int
    +

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

    + + + + + + +

    func (*Buffer) Next

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

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

    + + + + + + +

    func (*Buffer) Read

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

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

    + + + + + + +

    func (*Buffer) ReadByte

    +
    func (b *Buffer) ReadByte() (c byte, err error)
    +

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

    + + + + + + +

    func (*Buffer) ReadBytes

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

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

    + + + + + + +

    func (*Buffer) ReadFrom

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

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

    + + + + + + +

    func (*Buffer) ReadRune

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

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

    + + + + + + +

    func (*Buffer) ReadString

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

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

    + + + + + + +

    func (*Buffer) Reset

    +
    func (b *Buffer) Reset()
    +

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

    + + + + + + +

    func (*Buffer) String

    +
    func (b *Buffer) String() string
    +

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

    + + + + + + +

    func (*Buffer) Truncate

    +
    func (b *Buffer) Truncate(n int)
    +

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

    + + + + + + +

    func (*Buffer) UnreadByte

    +
    func (b *Buffer) UnreadByte() error
    +

    +UnreadByte unreads the last byte returned by the most recent +read operation. If write has happened since the last read, UnreadByte +returns an error. +

    + + + + + + +

    func (*Buffer) UnreadRune

    +
    func (b *Buffer) UnreadRune() error
    +

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

    + + + + + + +

    func (*Buffer) Write

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

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

    + + + + + + +

    func (*Buffer) WriteByte

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

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

    + + + + + + +

    func (*Buffer) WriteRune

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

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

    + + + + + + +

    func (*Buffer) WriteString

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

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

    + + + + + + +

    func (*Buffer) WriteTo

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

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

    + + + + + + + + +

    type Reader

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

    +A Reader implements the io.Reader, io.ReaderAt, io.WriterTo, io.Seeker, +io.ByteScanner, and io.RuneScanner interfaces by reading from +a byte slice. +Unlike a Buffer, a Reader is read-only and supports seeking. +

    + + + + + + + + + + + + +

    func NewReader

    +
    func NewReader(b []byte) *Reader
    +

    +NewReader returns a new Reader reading from b. +

    + + + + + + + +

    func (*Reader) Len

    +
    func (r *Reader) Len() int
    +

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

    + + + + + + +

    func (*Reader) Read

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

    func (*Reader) ReadAt

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

    func (*Reader) ReadByte

    +
    func (r *Reader) ReadByte() (b byte, err error)
    + + + + + + +

    func (*Reader) ReadRune

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

    func (*Reader) Seek

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

    +Seek implements the io.Seeker interface. +

    + + + + + + +

    func (*Reader) Size

    +
    func (r *Reader) Size() int64
    +

    +Size returns the original length of the underlying byte slice. +Size is the number of bytes available for reading via ReadAt. +The returned value is always the same and is not affected by calls +to any other method. +

    + + + + + + +

    func (*Reader) UnreadByte

    +
    func (r *Reader) UnreadByte() error
    + + + + + + +

    func (*Reader) UnreadRune

    +
    func (r *Reader) UnreadRune() error
    + + + + + + +

    func (*Reader) WriteTo

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

    +WriteTo implements the io.WriterTo interface. +

    + + + + + + + + + + +

    Bugs

    +
      + +
    • The rule Title uses for word boundaries does not handle Unicode punctuation properly. +
    • + +
    + + + + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/crypto/aes/index.html b/pkg/crypto/aes/index.html new file mode 100644 index 0000000..1354a1f --- /dev/null +++ b/pkg/crypto/aes/index.html @@ -0,0 +1,277 @@ + + + + + + + + aes - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Package aes

    + + + + + + + + + + + + + + +
    +
    +
    import "crypto/aes"
    +
    +
    +
    Overview
    +
    Index
    + + +
    +
    + +
    + +
    +

    Overview ▾

    +

    +Package aes implements AES encryption (formerly Rijndael), as defined in +U.S. Federal Information Processing Standards Publication 197. +

    + +
    +
    + + +
    + +
    +

    Index ▾

    + + + + + + + +

    Package files

    +

    + + + aes_gcm.go + + block.go + + cipher.go + + cipher_asm.go + + const.go + + +

    + +
    +
    + + + + +

    Constants

    + +
    const BlockSize = 16
    +

    +The AES block size in bytes. +

    + + + + + + + +

    func NewCipher

    +
    func NewCipher(key []byte) (cipher.Block, error)
    +

    +NewCipher creates and returns a new cipher.Block. +The key argument should be the AES key, +either 16, 24, or 32 bytes to select +AES-128, AES-192, or AES-256. +

    + + + + + + + + +

    type KeySizeError

    +
    type KeySizeError int
    + + + + + + + + + + + + + + +

    func (KeySizeError) Error

    +
    func (k KeySizeError) Error() string
    + + + + + + + + + + + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/crypto/cipher/index.html b/pkg/crypto/cipher/index.html new file mode 100644 index 0000000..aa405dc --- /dev/null +++ b/pkg/crypto/cipher/index.html @@ -0,0 +1,1017 @@ + + + + + + + + cipher - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Package cipher

    + + + + + + + + + + + + + + +
    +
    +
    import "crypto/cipher"
    +
    +
    +
    Overview
    +
    Index
    + +
    Examples
    + + +
    +
    + +
    + +
    +

    Overview ▾

    +

    +Package cipher implements standard block cipher modes that can be wrapped +around low-level block cipher implementations. +See http://csrc.nist.gov/groups/ST/toolkit/BCM/current_modes.html +and NIST Special Publication 800-38A. +

    + +
    +
    + + + + + + + + + + + + +

    type AEAD

    +
    type AEAD interface {
    +    // NonceSize returns the size of the nonce that must be passed to Seal
    +    // and Open.
    +    NonceSize() int
    +
    +    // Overhead returns the maximum difference between the lengths of a
    +    // plaintext and its ciphertext.
    +    Overhead() int
    +
    +    // Seal encrypts and authenticates plaintext, authenticates the
    +    // additional data and appends the result to dst, returning the updated
    +    // slice. The nonce must be NonceSize() bytes long and unique for all
    +    // time, for a given key.
    +    //
    +    // The plaintext and dst may alias exactly or not at all. To reuse
    +    // plaintext's storage for the encrypted output, use plaintext[:0] as dst.
    +    Seal(dst, nonce, plaintext, additionalData []byte) []byte
    +
    +    // Open decrypts and authenticates ciphertext, authenticates the
    +    // additional data and, if successful, appends the resulting plaintext
    +    // to dst, returning the updated slice. The nonce must be NonceSize()
    +    // bytes long and both it and the additional data must match the
    +    // value passed to Seal.
    +    //
    +    // The ciphertext and dst may alias exactly or not at all. To reuse
    +    // ciphertext's storage for the decrypted output, use ciphertext[:0] as dst.
    +    //
    +    // Even if the function fails, the contents of dst, up to its capacity,
    +    // may be overwritten.
    +    Open(dst, nonce, ciphertext, additionalData []byte) ([]byte, error)
    +}
    +

    +AEAD is a cipher mode providing authenticated encryption with associated +data. For a description of the methodology, see +

    +
    https://en.wikipedia.org/wiki/Authenticated_encryption
    +
    + + + + + + + + + + + + +

    func NewGCM

    +
    func NewGCM(cipher Block) (AEAD, error)
    +

    +NewGCM returns the given 128-bit, block cipher wrapped in Galois Counter Mode +with the standard nonce length. +

    + + + + + +

    func NewGCMWithNonceSize

    +
    func NewGCMWithNonceSize(cipher Block, size int) (AEAD, error)
    +

    +NewGCMWithNonceSize returns the given 128-bit, block cipher wrapped in Galois +Counter Mode, which accepts nonces of the given length. +

    +

    +Only use this function if you require compatibility with an existing +cryptosystem that uses non-standard nonce lengths. All other users should use +NewGCM, which is faster and more resistant to misuse. +

    + + + + + + + + + +

    type Block

    +
    type Block interface {
    +    // BlockSize returns the cipher's block size.
    +    BlockSize() int
    +
    +    // Encrypt encrypts the first block in src into dst.
    +    // Dst and src may point at the same memory.
    +    Encrypt(dst, src []byte)
    +
    +    // Decrypt decrypts the first block in src into dst.
    +    // Dst and src may point at the same memory.
    +    Decrypt(dst, src []byte)
    +}
    +

    +A Block represents an implementation of block cipher +using a given key. It provides the capability to encrypt +or decrypt individual blocks. The mode implementations +extend that capability to streams of blocks. +

    + + + + + + + + + + + + + + + + +

    type BlockMode

    +
    type BlockMode interface {
    +    // BlockSize returns the mode's block size.
    +    BlockSize() int
    +
    +    // CryptBlocks encrypts or decrypts a number of blocks. The length of
    +    // src must be a multiple of the block size. Dst and src may point to
    +    // the same memory.
    +    CryptBlocks(dst, src []byte)
    +}
    +

    +A BlockMode represents a block cipher running in a block-based mode (CBC, +ECB etc). +

    + + + + + + + + + + + + +

    func NewCBCDecrypter

    +
    func NewCBCDecrypter(b Block, iv []byte) BlockMode
    +

    +NewCBCDecrypter returns a BlockMode which decrypts in cipher block chaining +mode, using the given Block. The length of iv must be the same as the +Block's block size and must match the iv used to encrypt the data. +

    + +
    + +
    +

    Example

    + + + +

    Code:

    +
    key := []byte("example key 1234")
    +ciphertext, _ := hex.DecodeString("f363f3ccdcb12bb883abf484ba77d9cd7d32b5baecb3d4b1b3e0e4beffdb3ded")
    +
    +block, err := aes.NewCipher(key)
    +if err != nil {
    +    panic(err)
    +}
    +
    +// The IV needs to be unique, but not secure. Therefore it's common to
    +// include it at the beginning of the ciphertext.
    +if len(ciphertext) < aes.BlockSize {
    +    panic("ciphertext too short")
    +}
    +iv := ciphertext[:aes.BlockSize]
    +ciphertext = ciphertext[aes.BlockSize:]
    +
    +// CBC mode always works in whole blocks.
    +if len(ciphertext)%aes.BlockSize != 0 {
    +    panic("ciphertext is not a multiple of the block size")
    +}
    +
    +mode := cipher.NewCBCDecrypter(block, iv)
    +
    +// CryptBlocks can work in-place if the two arguments are the same.
    +mode.CryptBlocks(ciphertext, ciphertext)
    +
    +// If the original plaintext lengths are not a multiple of the block
    +// size, padding would have to be added when encrypting, which would be
    +// removed at this point. For an example, see
    +// https://tools.ietf.org/html/rfc5246#section-6.2.3.2. However, it's
    +// critical to note that ciphertexts must be authenticated (i.e. by
    +// using crypto/hmac) before being decrypted in order to avoid creating
    +// a padding oracle.
    +
    +fmt.Printf("%s\n", ciphertext)
    +
    + +

    Output:

    +
    exampleplaintext
    +
    + + +
    +
    + + + + +

    func NewCBCEncrypter

    +
    func NewCBCEncrypter(b Block, iv []byte) BlockMode
    +

    +NewCBCEncrypter returns a BlockMode which encrypts in cipher block chaining +mode, using the given Block. The length of iv must be the same as the +Block's block size. +

    + +
    + +
    +

    Example

    + + + +

    Code:

    +
    +key := []byte("example key 1234")
    +plaintext := []byte("exampleplaintext")
    +
    +// CBC mode works on blocks so plaintexts may need to be padded to the
    +// next whole block. For an example of such padding, see
    +// https://tools.ietf.org/html/rfc5246#section-6.2.3.2. Here we'll
    +// assume that the plaintext is already of the correct length.
    +if len(plaintext)%aes.BlockSize != 0 {
    +    panic("plaintext is not a multiple of the block size")
    +}
    +
    +block, err := aes.NewCipher(key)
    +if err != nil {
    +    panic(err)
    +}
    +
    +// The IV needs to be unique, but not secure. Therefore it's common to
    +// include it at the beginning of the ciphertext.
    +ciphertext := make([]byte, aes.BlockSize+len(plaintext))
    +iv := ciphertext[:aes.BlockSize]
    +if _, err := io.ReadFull(rand.Reader, iv); err != nil {
    +    panic(err)
    +}
    +
    +mode := cipher.NewCBCEncrypter(block, iv)
    +mode.CryptBlocks(ciphertext[aes.BlockSize:], plaintext)
    +
    +// It's important to remember that ciphertexts must be authenticated
    +// (i.e. by using crypto/hmac) as well as being encrypted in order to
    +// be secure.
    +
    +fmt.Printf("%x\n", ciphertext)
    +
    + + +
    +
    + + + + + + + + +

    type Stream

    +
    type Stream interface {
    +    // XORKeyStream XORs each byte in the given slice with a byte from the
    +    // cipher's key stream. Dst and src may point to the same memory.
    +    // If len(dst) < len(src), XORKeyStream should panic. It is acceptable
    +    // to pass a dst bigger than src, and in that case, XORKeyStream will
    +    // only update dst[:len(src)] and will not touch the rest of dst.
    +    XORKeyStream(dst, src []byte)
    +}
    +

    +A Stream represents a stream cipher. +

    + + + + + + + + + + + + +

    func NewCFBDecrypter

    +
    func NewCFBDecrypter(block Block, iv []byte) Stream
    +

    +NewCFBDecrypter returns a Stream which decrypts with cipher feedback mode, +using the given Block. The iv must be the same length as the Block's block +size. +

    + +
    + +
    +

    Example

    + + + +

    Code:

    +
    key := []byte("example key 1234")
    +ciphertext, _ := hex.DecodeString("22277966616d9bc47177bd02603d08c9a67d5380d0fe8cf3b44438dff7b9")
    +
    +block, err := aes.NewCipher(key)
    +if err != nil {
    +    panic(err)
    +}
    +
    +// The IV needs to be unique, but not secure. Therefore it's common to
    +// include it at the beginning of the ciphertext.
    +if len(ciphertext) < aes.BlockSize {
    +    panic("ciphertext too short")
    +}
    +iv := ciphertext[:aes.BlockSize]
    +ciphertext = ciphertext[aes.BlockSize:]
    +
    +stream := cipher.NewCFBDecrypter(block, iv)
    +
    +// XORKeyStream can work in-place if the two arguments are the same.
    +stream.XORKeyStream(ciphertext, ciphertext)
    +fmt.Printf("%s", ciphertext)
    +
    + +

    Output:

    +
    some plaintext
    +
    + + +
    +
    + + + + +

    func NewCFBEncrypter

    +
    func NewCFBEncrypter(block Block, iv []byte) Stream
    +

    +NewCFBEncrypter returns a Stream which encrypts with cipher feedback mode, +using the given Block. The iv must be the same length as the Block's block +size. +

    + +
    + +
    +

    Example

    + + + +

    Code:

    +
    +key := []byte("example key 1234")
    +plaintext := []byte("some plaintext")
    +
    +block, err := aes.NewCipher(key)
    +if err != nil {
    +    panic(err)
    +}
    +
    +// The IV needs to be unique, but not secure. Therefore it's common to
    +// include it at the beginning of the ciphertext.
    +ciphertext := make([]byte, aes.BlockSize+len(plaintext))
    +iv := ciphertext[:aes.BlockSize]
    +if _, err := io.ReadFull(rand.Reader, iv); err != nil {
    +    panic(err)
    +}
    +
    +stream := cipher.NewCFBEncrypter(block, iv)
    +stream.XORKeyStream(ciphertext[aes.BlockSize:], plaintext)
    +
    +// It's important to remember that ciphertexts must be authenticated
    +// (i.e. by using crypto/hmac) as well as being encrypted in order to
    +// be secure.
    +
    + + +
    +
    + + + + +

    func NewCTR

    +
    func NewCTR(block Block, iv []byte) Stream
    +

    +NewCTR returns a Stream which encrypts/decrypts using the given Block in +counter mode. The length of iv must be the same as the Block's block size. +

    + +
    + +
    +

    Example

    + + + +

    Code:

    +
    key := []byte("example key 1234")
    +plaintext := []byte("some plaintext")
    +
    +block, err := aes.NewCipher(key)
    +if err != nil {
    +    panic(err)
    +}
    +
    +// The IV needs to be unique, but not secure. Therefore it's common to
    +// include it at the beginning of the ciphertext.
    +ciphertext := make([]byte, aes.BlockSize+len(plaintext))
    +iv := ciphertext[:aes.BlockSize]
    +if _, err := io.ReadFull(rand.Reader, iv); err != nil {
    +    panic(err)
    +}
    +
    +stream := cipher.NewCTR(block, iv)
    +stream.XORKeyStream(ciphertext[aes.BlockSize:], plaintext)
    +
    +// It's important to remember that ciphertexts must be authenticated
    +// (i.e. by using crypto/hmac) as well as being encrypted in order to
    +// be secure.
    +
    +// CTR mode is the same for both encryption and decryption, so we can
    +// also decrypt that ciphertext with NewCTR.
    +
    +plaintext2 := make([]byte, len(plaintext))
    +stream = cipher.NewCTR(block, iv)
    +stream.XORKeyStream(plaintext2, ciphertext[aes.BlockSize:])
    +
    +fmt.Printf("%s\n", plaintext2)
    +
    + +

    Output:

    +
    some plaintext
    +
    + + +
    +
    + + + + +

    func NewOFB

    +
    func NewOFB(b Block, iv []byte) Stream
    +

    +NewOFB returns a Stream that encrypts or decrypts using the block cipher b +in output feedback mode. The initialization vector iv's length must be equal +to b's block size. +

    + +
    + +
    +

    Example

    + + + +

    Code:

    +
    key := []byte("example key 1234")
    +plaintext := []byte("some plaintext")
    +
    +block, err := aes.NewCipher(key)
    +if err != nil {
    +    panic(err)
    +}
    +
    +// The IV needs to be unique, but not secure. Therefore it's common to
    +// include it at the beginning of the ciphertext.
    +ciphertext := make([]byte, aes.BlockSize+len(plaintext))
    +iv := ciphertext[:aes.BlockSize]
    +if _, err := io.ReadFull(rand.Reader, iv); err != nil {
    +    panic(err)
    +}
    +
    +stream := cipher.NewOFB(block, iv)
    +stream.XORKeyStream(ciphertext[aes.BlockSize:], plaintext)
    +
    +// It's important to remember that ciphertexts must be authenticated
    +// (i.e. by using crypto/hmac) as well as being encrypted in order to
    +// be secure.
    +
    +// OFB mode is the same for both encryption and decryption, so we can
    +// also decrypt that ciphertext with NewOFB.
    +
    +plaintext2 := make([]byte, len(plaintext))
    +stream = cipher.NewOFB(block, iv)
    +stream.XORKeyStream(plaintext2, ciphertext[aes.BlockSize:])
    +
    +fmt.Printf("%s\n", plaintext2)
    +
    + +

    Output:

    +
    some plaintext
    +
    + + +
    +
    + + + + + + + + +

    type StreamReader

    +
    type StreamReader struct {
    +    S Stream
    +    R io.Reader
    +}
    +

    +StreamReader wraps a Stream into an io.Reader. It calls XORKeyStream +to process each slice of data which passes through. +

    + + + + + + +
    + +
    +

    Example

    + + + +

    Code:

    +
    +key := []byte("example key 1234")
    +
    +inFile, err := os.Open("encrypted-file")
    +if err != nil {
    +    panic(err)
    +}
    +defer inFile.Close()
    +
    +block, err := aes.NewCipher(key)
    +if err != nil {
    +    panic(err)
    +}
    +
    +// If the key is unique for each ciphertext, then it's ok to use a zero
    +// IV.
    +var iv [aes.BlockSize]byte
    +stream := cipher.NewOFB(block, iv[:])
    +
    +outFile, err := os.OpenFile("decrypted-file", os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0600)
    +if err != nil {
    +    panic(err)
    +}
    +defer outFile.Close()
    +
    +reader := &cipher.StreamReader{S: stream, R: inFile}
    +// Copy the input file to the output file, decrypting as we go.
    +if _, err := io.Copy(outFile, reader); err != nil {
    +    panic(err)
    +}
    +
    +// Note that this example is simplistic in that it omits any
    +// authentication of the encrypted data. If you were actually to use
    +// StreamReader in this manner, an attacker could flip arbitrary bits in
    +// the output.
    +
    + + +
    +
    + + + + + + + + +

    func (StreamReader) Read

    +
    func (r StreamReader) Read(dst []byte) (n int, err error)
    + + + + + + + + +

    type StreamWriter

    +
    type StreamWriter struct {
    +    S   Stream
    +    W   io.Writer
    +    Err error // unused
    +}
    +

    +StreamWriter wraps a Stream into an io.Writer. It calls XORKeyStream +to process each slice of data which passes through. If any Write call +returns short then the StreamWriter is out of sync and must be discarded. +A StreamWriter has no internal buffering; Close does not need +to be called to flush write data. +

    + + + + + + +
    + +
    +

    Example

    + + + +

    Code:

    +
    +key := []byte("example key 1234")
    +
    +inFile, err := os.Open("plaintext-file")
    +if err != nil {
    +    panic(err)
    +}
    +defer inFile.Close()
    +
    +block, err := aes.NewCipher(key)
    +if err != nil {
    +    panic(err)
    +}
    +
    +// If the key is unique for each ciphertext, then it's ok to use a zero
    +// IV.
    +var iv [aes.BlockSize]byte
    +stream := cipher.NewOFB(block, iv[:])
    +
    +outFile, err := os.OpenFile("encrypted-file", os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0600)
    +if err != nil {
    +    panic(err)
    +}
    +defer outFile.Close()
    +
    +writer := &cipher.StreamWriter{S: stream, W: outFile}
    +// Copy the input file to the output file, encrypting as we go.
    +if _, err := io.Copy(writer, inFile); err != nil {
    +    panic(err)
    +}
    +
    +// Note that this example is simplistic in that it omits any
    +// authentication of the encrypted data. If you were actually to use
    +// StreamReader in this manner, an attacker could flip arbitrary bits in
    +// the decrypted result.
    +
    + + +
    +
    + + + + + + + + +

    func (StreamWriter) Close

    +
    func (w StreamWriter) Close() error
    +

    +Close closes the underlying Writer and returns its Close return value, if the Writer +is also an io.Closer. Otherwise it returns nil. +

    + + + + + + +

    func (StreamWriter) Write

    +
    func (w StreamWriter) Write(src []byte) (n int, err error)
    + + + + + + + + + + + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/crypto/des/index.html b/pkg/crypto/des/index.html new file mode 100644 index 0000000..d51c922 --- /dev/null +++ b/pkg/crypto/des/index.html @@ -0,0 +1,328 @@ + + + + + + + + des - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Package des

    + + + + + + + + + + + + + + +
    +
    +
    import "crypto/des"
    +
    +
    +
    Overview
    +
    Index
    + +
    Examples
    + + +
    +
    + +
    + +
    +

    Overview ▾

    +

    +Package des implements the Data Encryption Standard (DES) and the +Triple Data Encryption Algorithm (TDEA) as defined +in U.S. Federal Information Processing Standards Publication 46-3. +

    + +
    +
    + + +
    + +
    +

    Index ▾

    + + + + + +
    +

    Examples

    +
    + +
    NewTripleDESCipher
    + +
    +
    + + + +

    Package files

    +

    + + + block.go + + cipher.go + + const.go + + +

    + +
    +
    + + + + +

    Constants

    + +
    const BlockSize = 8
    +

    +The DES block size in bytes. +

    + + + + + + + +

    func NewCipher

    +
    func NewCipher(key []byte) (cipher.Block, error)
    +

    +NewCipher creates and returns a new cipher.Block. +

    + + + + + + + +

    func NewTripleDESCipher

    +
    func NewTripleDESCipher(key []byte) (cipher.Block, error)
    +

    +NewTripleDESCipher creates and returns a new cipher.Block. +

    + +
    + +
    +

    Example

    + + + +

    Code:

    +
    +// NewTripleDESCipher can also be used when EDE2 is required by
    +// duplicating the first 8 bytes of the 16-byte key.
    +ede2Key := []byte("example key 1234")
    +
    +var tripleDESKey []byte
    +tripleDESKey = append(tripleDESKey, ede2Key[:16]...)
    +tripleDESKey = append(tripleDESKey, ede2Key[:8]...)
    +
    +_, err := des.NewTripleDESCipher(tripleDESKey)
    +if err != nil {
    +    panic(err)
    +}
    +
    +// See crypto/cipher for how to use a cipher.Block for encryption and
    +// decryption.
    +
    + + +
    +
    + + + + + + + +

    type KeySizeError

    +
    type KeySizeError int
    + + + + + + + + + + + + + + +

    func (KeySizeError) Error

    +
    func (k KeySizeError) Error() string
    + + + + + + + + + + + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/crypto/dsa/index.html b/pkg/crypto/dsa/index.html new file mode 100644 index 0000000..977fdbe --- /dev/null +++ b/pkg/crypto/dsa/index.html @@ -0,0 +1,417 @@ + + + + + + + + dsa - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Package dsa

    + + + + + + + + + + + + + + +
    +
    +
    import "crypto/dsa"
    +
    +
    +
    Overview
    +
    Index
    + + +
    +
    + +
    + +
    +

    Overview ▾

    +

    +Package dsa implements the Digital Signature Algorithm, as defined in FIPS 186-3. +

    + +
    +
    + + + + + + + + +

    Variables

    + +
    var ErrInvalidPublicKey = errors.New("crypto/dsa: invalid public key")
    +

    +ErrInvalidPublicKey results when a public key is not usable by this code. +FIPS is quite strict about the format of DSA keys, but other code may be +less so. Thus, when using keys which may have been generated by other code, +this error must be handled. +

    + + + + + + +

    func GenerateKey

    +
    func GenerateKey(priv *PrivateKey, rand io.Reader) error
    +

    +GenerateKey generates a public&private key pair. The Parameters of the +PrivateKey must already be valid (see GenerateParameters). +

    + + + + + + + +

    func GenerateParameters

    +
    func GenerateParameters(params *Parameters, rand io.Reader, sizes ParameterSizes) (err error)
    +

    +GenerateParameters puts a random, valid set of DSA parameters into params. +This function can take many seconds, even on fast machines. +

    + + + + + + + +

    func Sign

    +
    func Sign(rand io.Reader, priv *PrivateKey, hash []byte) (r, s *big.Int, err error)
    +

    +Sign signs an arbitrary length hash (which should be the result of hashing a +larger message) using the private key, priv. It returns the signature as a +pair of integers. The security of the private key depends on the entropy of +rand. +

    +

    +Note that FIPS 186-3 section 4.6 specifies that the hash should be truncated +to the byte-length of the subgroup. This function does not perform that +truncation itself. +

    + + + + + + + +

    func Verify

    +
    func Verify(pub *PublicKey, hash []byte, r, s *big.Int) bool
    +

    +Verify verifies the signature in r, s of hash using the public key, pub. It +reports whether the signature is valid. +

    +

    +Note that FIPS 186-3 section 4.6 specifies that the hash should be truncated +to the byte-length of the subgroup. This function does not perform that +truncation itself. +

    + + + + + + + + +

    type ParameterSizes

    +
    type ParameterSizes int
    +

    +ParameterSizes is a enumeration of the acceptable bit lengths of the primes +in a set of DSA parameters. See FIPS 186-3, section 4.2. +

    + + + +
    const (
    +    L1024N160 ParameterSizes = iota
    +    L2048N224
    +    L2048N256
    +    L3072N256
    +)
    + + + + + + + + + + + + + + + +

    type Parameters

    +
    type Parameters struct {
    +    P, Q, G *big.Int
    +}
    +

    +Parameters represents the domain parameters for a key. These parameters can +be shared across many keys. The bit length of Q must be a multiple of 8. +

    + + + + + + + + + + + + + + + + +

    type PrivateKey

    +
    type PrivateKey struct {
    +    PublicKey
    +    X *big.Int
    +}
    +

    +PrivateKey represents a DSA private key. +

    + + + + + + + + + + + + + + + + +

    type PublicKey

    +
    type PublicKey struct {
    +    Parameters
    +    Y *big.Int
    +}
    +

    +PublicKey represents a DSA public key. +

    + + + + + + + + + + + + + + + + + + + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/crypto/ecdsa/index.html b/pkg/crypto/ecdsa/index.html new file mode 100644 index 0000000..d54954a --- /dev/null +++ b/pkg/crypto/ecdsa/index.html @@ -0,0 +1,347 @@ + + + + + + + + ecdsa - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Package ecdsa

    + + + + + + + + + + + + + + +
    +
    +
    import "crypto/ecdsa"
    +
    +
    +
    Overview
    +
    Index
    + + +
    +
    + +
    + +
    +

    Overview ▾

    +

    +Package ecdsa implements the Elliptic Curve Digital Signature Algorithm, as +defined in FIPS 186-3. +

    +

    +This implementation derives the nonce from an AES-CTR CSPRNG keyed by +ChopMD(256, SHA2-512(priv.D || entropy || hash)). The CSPRNG key is IRO by +a result of Coron; the AES-CTR stream is IRO under standard assumptions. +

    + +
    +
    + + + + + + + + + + + +

    func Sign

    +
    func Sign(rand io.Reader, priv *PrivateKey, hash []byte) (r, s *big.Int, err error)
    +

    +Sign signs an arbitrary length hash (which should be the result of hashing a +larger message) using the private key, priv. It returns the signature as a +pair of integers. The security of the private key depends on the entropy of +rand. +

    + + + + + + + +

    func Verify

    +
    func Verify(pub *PublicKey, hash []byte, r, s *big.Int) bool
    +

    +Verify verifies the signature in r, s of hash using the public key, pub. Its +return value records whether the signature is valid. +

    + + + + + + + + +

    type PrivateKey

    +
    type PrivateKey struct {
    +    PublicKey
    +    D *big.Int
    +}
    +

    +PrivateKey represents a ECDSA private key. +

    + + + + + + + + + + + + +

    func GenerateKey

    +
    func GenerateKey(c elliptic.Curve, rand io.Reader) (priv *PrivateKey, err error)
    +

    +GenerateKey generates a public and private key pair. +

    + + + + + + + +

    func (*PrivateKey) Public

    +
    func (priv *PrivateKey) Public() crypto.PublicKey
    +

    +Public returns the public key corresponding to priv. +

    + + + + + + +

    func (*PrivateKey) Sign

    +
    func (priv *PrivateKey) Sign(rand io.Reader, msg []byte, opts crypto.SignerOpts) ([]byte, error)
    +

    +Sign signs msg with priv, reading randomness from rand. This method is +intended to support keys where the private part is kept in, for example, a +hardware module. Common uses should use the Sign function in this package +directly. +

    + + + + + + + + +

    type PublicKey

    +
    type PublicKey struct {
    +    elliptic.Curve
    +    X, Y *big.Int
    +}
    +

    +PublicKey represents an ECDSA public key. +

    + + + + + + + + + + + + + + + + + + + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/crypto/elliptic/index.html b/pkg/crypto/elliptic/index.html new file mode 100644 index 0000000..c667afe --- /dev/null +++ b/pkg/crypto/elliptic/index.html @@ -0,0 +1,450 @@ + + + + + + + + elliptic - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Package elliptic

    + + + + + + + + + + + + + + +
    +
    +
    import "crypto/elliptic"
    +
    +
    +
    Overview
    +
    Index
    + + +
    +
    + +
    + +
    +

    Overview ▾

    +

    +Package elliptic implements several standard elliptic curves over prime +fields. +

    + +
    +
    + + + + + + + + + + + +

    func GenerateKey

    +
    func GenerateKey(curve Curve, rand io.Reader) (priv []byte, x, y *big.Int, err error)
    +

    +GenerateKey returns a public/private key pair. The private key is +generated using the given reader, which must return random data. +

    + + + + + + + +

    func Marshal

    +
    func Marshal(curve Curve, x, y *big.Int) []byte
    +

    +Marshal converts a point into the form specified in section 4.3.6 of ANSI X9.62. +

    + + + + + + + +

    func Unmarshal

    +
    func Unmarshal(curve Curve, data []byte) (x, y *big.Int)
    +

    +Unmarshal converts a point, serialized by Marshal, into an x, y pair. +It is an error if the point is not on the curve. On error, x = nil. +

    + + + + + + + + +

    type Curve

    +
    type Curve interface {
    +    // Params returns the parameters for the curve.
    +    Params() *CurveParams
    +    // IsOnCurve reports whether the given (x,y) lies on the curve.
    +    IsOnCurve(x, y *big.Int) bool
    +    // Add returns the sum of (x1,y1) and (x2,y2)
    +    Add(x1, y1, x2, y2 *big.Int) (x, y *big.Int)
    +    // Double returns 2*(x,y)
    +    Double(x1, y1 *big.Int) (x, y *big.Int)
    +    // ScalarMult returns k*(Bx,By) where k is a number in big-endian form.
    +    ScalarMult(x1, y1 *big.Int, k []byte) (x, y *big.Int)
    +    // ScalarBaseMult returns k*G, where G is the base point of the group
    +    // and k is an integer in big-endian form.
    +    ScalarBaseMult(k []byte) (x, y *big.Int)
    +}
    +

    +A Curve represents a short-form Weierstrass curve with a=-3. +See http://www.hyperelliptic.org/EFD/g1p/auto-shortw.html +

    + + + + + + + + + + + + +

    func P224

    +
    func P224() Curve
    +

    +P224 returns a Curve which implements P-224 (see FIPS 186-3, section D.2.2) +

    + + + + + +

    func P256

    +
    func P256() Curve
    +

    +P256 returns a Curve which implements P-256 (see FIPS 186-3, section D.2.3) +

    + + + + + +

    func P384

    +
    func P384() Curve
    +

    +P384 returns a Curve which implements P-384 (see FIPS 186-3, section D.2.4) +

    + + + + + +

    func P521

    +
    func P521() Curve
    +

    +P521 returns a Curve which implements P-521 (see FIPS 186-3, section D.2.5) +

    + + + + + + + + + +

    type CurveParams

    +
    type CurveParams struct {
    +    P       *big.Int // the order of the underlying field
    +    N       *big.Int // the order of the base point
    +    B       *big.Int // the constant of the curve equation
    +    Gx, Gy  *big.Int // (x,y) of the base point
    +    BitSize int      // the size of the underlying field
    +    Name    string   // the canonical name of the curve
    +}
    +

    +CurveParams contains the parameters of an elliptic curve and also provides +a generic, non-constant time implementation of Curve. +

    + + + + + + + + + + + + + + +

    func (*CurveParams) Add

    +
    func (curve *CurveParams) Add(x1, y1, x2, y2 *big.Int) (*big.Int, *big.Int)
    + + + + + + +

    func (*CurveParams) Double

    +
    func (curve *CurveParams) Double(x1, y1 *big.Int) (*big.Int, *big.Int)
    + + + + + + +

    func (*CurveParams) IsOnCurve

    +
    func (curve *CurveParams) IsOnCurve(x, y *big.Int) bool
    + + + + + + +

    func (*CurveParams) Params

    +
    func (curve *CurveParams) Params() *CurveParams
    + + + + + + +

    func (*CurveParams) ScalarBaseMult

    +
    func (curve *CurveParams) ScalarBaseMult(k []byte) (*big.Int, *big.Int)
    + + + + + + +

    func (*CurveParams) ScalarMult

    +
    func (curve *CurveParams) ScalarMult(Bx, By *big.Int, k []byte) (*big.Int, *big.Int)
    + + + + + + + + + + + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/crypto/hmac/index.html b/pkg/crypto/hmac/index.html new file mode 100644 index 0000000..b723965 --- /dev/null +++ b/pkg/crypto/hmac/index.html @@ -0,0 +1,250 @@ + + + + + + + + hmac - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Package hmac

    + + + + + + + + + + + + + + +
    +
    +
    import "crypto/hmac"
    +
    +
    +
    Overview
    +
    Index
    + + +
    +
    + +
    + +
    +

    Overview ▾

    +

    +Package hmac implements the Keyed-Hash Message Authentication Code (HMAC) as +defined in U.S. Federal Information Processing Standards Publication 198. +An HMAC is a cryptographic hash that uses a key to sign a message. +The receiver verifies the hash by recomputing it using the same key. +

    +

    +Receivers should be careful to use Equal to compare MACs in order to avoid +timing side-channels: +

    +
    // CheckMAC reports whether messageMAC is a valid HMAC tag for message.
    +func CheckMAC(message, messageMAC, key []byte) bool {
    +	mac := hmac.New(sha256.New, key)
    +	mac.Write(message)
    +	expectedMAC := mac.Sum(nil)
    +	return hmac.Equal(messageMAC, expectedMAC)
    +}
    +
    + +
    +
    + + +
    + +
    +

    Index ▾

    + + + + + + + +

    Package files

    +

    + + + hmac.go + + +

    + +
    +
    + + + + + + + + +

    func Equal

    +
    func Equal(mac1, mac2 []byte) bool
    +

    +Equal compares two MACs for equality without leaking timing information. +

    + + + + + + + +

    func New

    +
    func New(h func() hash.Hash, key []byte) hash.Hash
    +

    +New returns a new HMAC hash using the given hash.Hash type and key. +

    + + + + + + + + + + + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/crypto/index.html b/pkg/crypto/index.html new file mode 100644 index 0000000..6d83dfd --- /dev/null +++ b/pkg/crypto/index.html @@ -0,0 +1,744 @@ + + + + + + + + crypto - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Package crypto

    + + + + + + + + + + + + + + +
    +
    +
    import "crypto"
    +
    +
    +
    Overview
    +
    Index
    + + +
    Subdirectories
    + +
    +
    + +
    + +
    +

    Overview ▾

    +

    +Package crypto collects common cryptographic constants. +

    + +
    +
    + + +
    + +
    +

    Index ▾

    + + + + + + + +

    Package files

    +

    + + + crypto.go + + +

    + +
    +
    + + + + + + + + +

    func RegisterHash

    +
    func RegisterHash(h Hash, f func() hash.Hash)
    +

    +RegisterHash registers a function that returns a new instance of the given +hash function. This is intended to be called from the init function in +packages that implement hash functions. +

    + + + + + + + + +

    type Decrypter

    +
    type Decrypter interface {
    +    // Public returns the public key corresponding to the opaque,
    +    // private key.
    +    Public() PublicKey
    +
    +    // Decrypt decrypts msg. The opts argument should be appropriate for
    +    // the primitive used. See the documentation in each implementation for
    +    // details.
    +    Decrypt(rand io.Reader, msg []byte, opts DecrypterOpts) (plaintext []byte, err error)
    +}
    +

    +Decrypter is an interface for an opaque private key that can be used for +asymmetric decryption operations. An example would be an RSA key +kept in a hardware module. +

    + + + + + + + + + + + + + + + + +

    type DecrypterOpts

    +
    type DecrypterOpts interface{}
    + + + + + + + + + + + + + + + + +

    type Hash

    +
    type Hash uint
    +

    +Hash identifies a cryptographic hash function that is implemented in another +package. +

    + + + +
    const (
    +    MD4        Hash = 1 + iota // import golang.org/x/crypto/md4
    +    MD5                        // import crypto/md5
    +    SHA1                       // import crypto/sha1
    +    SHA224                     // import crypto/sha256
    +    SHA256                     // import crypto/sha256
    +    SHA384                     // import crypto/sha512
    +    SHA512                     // import crypto/sha512
    +    MD5SHA1                    // no implementation; MD5+SHA1 used for TLS RSA
    +    RIPEMD160                  // import golang.org/x/crypto/ripemd160
    +    SHA3_224                   // import golang.org/x/crypto/sha3
    +    SHA3_256                   // import golang.org/x/crypto/sha3
    +    SHA3_384                   // import golang.org/x/crypto/sha3
    +    SHA3_512                   // import golang.org/x/crypto/sha3
    +    SHA512_224                 // import crypto/sha512
    +    SHA512_256                 // import crypto/sha512
    +
    +)
    + + + + + + + + + + + + + +

    func (Hash) Available

    +
    func (h Hash) Available() bool
    +

    +Available reports whether the given hash function is linked into the binary. +

    + + + + + + +

    func (Hash) HashFunc

    +
    func (h Hash) HashFunc() Hash
    +

    +HashFunc simply returns the value of h so that Hash implements SignerOpts. +

    + + + + + + +

    func (Hash) New

    +
    func (h Hash) New() hash.Hash
    +

    +New returns a new hash.Hash calculating the given hash function. New panics +if the hash function is not linked into the binary. +

    + + + + + + +

    func (Hash) Size

    +
    func (h Hash) Size() int
    +

    +Size returns the length, in bytes, of a digest resulting from the given hash +function. It doesn't require that the hash function in question be linked +into the program. +

    + + + + + + + + +

    type PrivateKey

    +
    type PrivateKey interface{}
    +

    +PrivateKey represents a private key using an unspecified algorithm. +

    + + + + + + + + + + + + + + + + +

    type PublicKey

    +
    type PublicKey interface{}
    +

    +PublicKey represents a public key using an unspecified algorithm. +

    + + + + + + + + + + + + + + + + +

    type Signer

    +
    type Signer interface {
    +    // Public returns the public key corresponding to the opaque,
    +    // private key.
    +    Public() PublicKey
    +
    +    // Sign signs digest with the private key, possibly using entropy from
    +    // rand. For an RSA key, the resulting signature should be either a
    +    // PKCS#1 v1.5 or PSS signature (as indicated by opts). For an (EC)DSA
    +    // key, it should be a DER-serialised, ASN.1 signature structure.
    +    //
    +    // Hash implements the SignerOpts interface and, in most cases, one can
    +    // simply pass in the hash function used as opts. Sign may also attempt
    +    // to type assert opts to other types in order to obtain algorithm
    +    // specific values. See the documentation in each package for details.
    +    //
    +    // Note that when a signature of a hash of a larger message is needed,
    +    // the caller is responsible for hashing the larger message and passing
    +    // the hash (as digest) and the hash function (as opts) to Sign.
    +    Sign(rand io.Reader, digest []byte, opts SignerOpts) (signature []byte, err error)
    +}
    +

    +Signer is an interface for an opaque private key that can be used for +signing operations. For example, an RSA key kept in a hardware module. +

    + + + + + + + + + + + + + + + + +

    type SignerOpts

    +
    type SignerOpts interface {
    +    // HashFunc returns an identifier for the hash function used to produce
    +    // the message passed to Signer.Sign, or else zero to indicate that no
    +    // hashing was done.
    +    HashFunc() Hash
    +}
    +

    +SignerOpts contains options for signing with a Signer. +

    + + + + + + + + + + + + + + + + + + + + + + + + +

    Subdirectories

    + + + + +
    +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    NameSynopsis
    ..
    + aes + + Package aes implements AES encryption (formerly Rijndael), as defined in U.S. Federal Information Processing Standards Publication 197. +
    + cipher + + Package cipher implements standard block cipher modes that can be wrapped around low-level block cipher implementations. +
    + des + + Package des implements the Data Encryption Standard (DES) and the Triple Data Encryption Algorithm (TDEA) as defined in U.S. Federal Information Processing Standards Publication 46-3. +
    + dsa + + Package dsa implements the Digital Signature Algorithm, as defined in FIPS 186-3. +
    + ecdsa + + Package ecdsa implements the Elliptic Curve Digital Signature Algorithm, as defined in FIPS 186-3. +
    + elliptic + + Package elliptic implements several standard elliptic curves over prime fields. +
    + hmac + + Package hmac implements the Keyed-Hash Message Authentication Code (HMAC) as defined in U.S. Federal Information Processing Standards Publication 198. +
    + md5 + + Package md5 implements the MD5 hash algorithm as defined in RFC 1321. +
    + rand + + Package rand implements a cryptographically secure pseudorandom number generator. +
    + rc4 + + Package rc4 implements RC4 encryption, as defined in Bruce Schneier's Applied Cryptography. +
    + rsa + + Package rsa implements RSA encryption as specified in PKCS#1. +
    + sha1 + + Package sha1 implements the SHA1 hash algorithm as defined in RFC 3174. +
    + sha256 + + Package sha256 implements the SHA224 and SHA256 hash algorithms as defined in FIPS 180-4. +
    + sha512 + + Package sha512 implements the SHA-384, SHA-512, SHA-512/224, and SHA-512/256 hash algorithms as defined in FIPS 180-4. +
    + subtle + + Package subtle implements functions that are often useful in cryptographic code but require careful thought to use correctly. +
    + tls + + Package tls partially implements TLS 1.2, as specified in RFC 5246. +
    + x509 + + Package x509 parses X.509-encoded keys and certificates. +
    + pkix + + Package pkix contains shared, low level structures used for ASN.1 parsing and serialization of X.509 certificates, CRL and OCSP. +
    + + + + + + + + + + + + + + + + + + + + + + + diff --git a/pkg/crypto/md5/index.html b/pkg/crypto/md5/index.html new file mode 100644 index 0000000..65b8ea6 --- /dev/null +++ b/pkg/crypto/md5/index.html @@ -0,0 +1,313 @@ + + + + + + + + md5 - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Package md5

    + + + + + + + + + + + + + + +
    +
    +
    import "crypto/md5"
    +
    +
    +
    Overview
    +
    Index
    + +
    Examples
    + + +
    +
    + +
    + +
    +

    Overview ▾

    +

    +Package md5 implements the MD5 hash algorithm as defined in RFC 1321. +

    + +
    +
    + + +
    + +
    +

    Index ▾

    + + + + + +
    +

    Examples

    +
    + +
    New
    + +
    Sum
    + +
    +
    + + + +

    Package files

    +

    + + + md5.go + + md5block.go + + md5block_decl.go + + +

    + +
    +
    + + + + +

    Constants

    + +
    const BlockSize = 64
    +

    +The blocksize of MD5 in bytes. +

    + + +
    const Size = 16
    +

    +The size of an MD5 checksum in bytes. +

    + + + + + + + +

    func New

    +
    func New() hash.Hash
    +

    +New returns a new hash.Hash computing the MD5 checksum. +

    + +
    + +
    +

    Example

    + + + +

    Code:

    +
    h := md5.New()
    +io.WriteString(h, "The fog is getting thicker!")
    +io.WriteString(h, "And Leon's getting laaarger!")
    +fmt.Printf("%x", h.Sum(nil))
    +
    + +

    Output:

    +
    e2c569be17396eca2a2e3c11578123ed
    +
    + + +
    +
    + + + + + + +

    func Sum

    +
    func Sum(data []byte) [Size]byte
    +

    +Sum returns the MD5 checksum of the data. +

    + +
    + +
    +

    Example

    + + + +

    Code:

    +
    data := []byte("These pretzels are making me thirsty.")
    +fmt.Printf("%x", md5.Sum(data))
    +
    + +

    Output:

    +
    b0804ec967f48520697662a204f5fe72
    +
    + + +
    +
    + + + + + + + + + + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/crypto/rand/index.html b/pkg/crypto/rand/index.html new file mode 100644 index 0000000..00fc59f --- /dev/null +++ b/pkg/crypto/rand/index.html @@ -0,0 +1,321 @@ + + + + + + + + rand - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Package rand

    + + + + + + + + + + + + + + +
    +
    +
    import "crypto/rand"
    +
    +
    +
    Overview
    +
    Index
    + +
    Examples
    + + +
    +
    + +
    + +
    +

    Overview ▾

    +

    +Package rand implements a cryptographically secure +pseudorandom number generator. +

    + +
    +
    + + +
    + +
    +

    Index ▾

    + + + + + +
    +

    Examples

    +
    + +
    Read
    + +
    +
    + + + +

    Package files

    +

    + + + eagain.go + + rand.go + + rand_linux.go + + rand_unix.go + + util.go + + +

    + +
    +
    + + + + + +

    Variables

    + +
    var Reader io.Reader
    +

    +Reader is a global, shared instance of a cryptographically +strong pseudo-random generator. +

    +

    +On Unix-like systems, Reader reads from /dev/urandom. +On Linux, Reader uses getrandom(2) if available, /dev/urandom otherwise. +On Windows systems, Reader uses the CryptGenRandom API. +

    + + + + + + +

    func Int

    +
    func Int(rand io.Reader, max *big.Int) (n *big.Int, err error)
    +

    +Int returns a uniform random value in [0, max). It panics if max <= 0. +

    + + + + + + + +

    func Prime

    +
    func Prime(rand io.Reader, bits int) (p *big.Int, err error)
    +

    +Prime returns a number, p, of the given size, such that p is prime +with high probability. +Prime will return error for any error returned by rand.Read or if bits < 2. +

    + + + + + + + +

    func Read

    +
    func Read(b []byte) (n int, err error)
    +

    +Read is a helper function that calls Reader.Read using io.ReadFull. +On return, n == len(b) if and only if err == nil. +

    + +
    + +
    +

    Example

    +

    This example reads 10 cryptographically secure pseudorandom numbers from +rand.Reader and writes them to a byte slice. +

    + + +

    Code:

    +
    c := 10
    +b := make([]byte, c)
    +_, err := rand.Read(b)
    +if err != nil {
    +    fmt.Println("error:", err)
    +    return
    +}
    +// The slice should now contain random bytes instead of only zeroes.
    +fmt.Println(bytes.Equal(b, make([]byte, c)))
    +
    +
    + +

    Output:

    +
    false
    +
    + + +
    +
    + + + + + + + + + + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/crypto/rc4/index.html b/pkg/crypto/rc4/index.html new file mode 100644 index 0000000..c194bd1 --- /dev/null +++ b/pkg/crypto/rc4/index.html @@ -0,0 +1,329 @@ + + + + + + + + rc4 - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Package rc4

    + + + + + + + + + + + + + + +
    +
    +
    import "crypto/rc4"
    +
    +
    +
    Overview
    +
    Index
    + + +
    +
    + +
    + +
    +

    Overview ▾

    +

    +Package rc4 implements RC4 encryption, as defined in Bruce Schneier's +Applied Cryptography. +

    + +
    +
    + + +
    + +
    +

    Index ▾

    + + + + + + + +

    Package files

    +

    + + + rc4.go + + rc4_asm.go + + +

    + +
    +
    + + + + + + + + + +

    type Cipher

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

    +A Cipher is an instance of RC4 using a particular key. +

    + + + + + + + + + + + + +

    func NewCipher

    +
    func NewCipher(key []byte) (*Cipher, error)
    +

    +NewCipher creates and returns a new Cipher. The key argument should be the +RC4 key, at least 1 byte and at most 256 bytes. +

    + + + + + + + +

    func (*Cipher) Reset

    +
    func (c *Cipher) Reset()
    +

    +Reset zeros the key data so that it will no longer appear in the +process's memory. +

    + + + + + + +

    func (*Cipher) XORKeyStream

    +
    func (c *Cipher) XORKeyStream(dst, src []byte)
    +

    +XORKeyStream sets dst to the result of XORing src with the key stream. +Dst and src may be the same slice but otherwise should not overlap. +

    + + + + + + + + +

    type KeySizeError

    +
    type KeySizeError int
    + + + + + + + + + + + + + + +

    func (KeySizeError) Error

    +
    func (k KeySizeError) Error() string
    + + + + + + + + + + +

    Bugs

    +
      + +
    • RC4 is in common use but has design weaknesses that make +it a poor choice for new protocols. +
    • + +
    + + + + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/crypto/rsa/index.html b/pkg/crypto/rsa/index.html new file mode 100644 index 0000000..627886d --- /dev/null +++ b/pkg/crypto/rsa/index.html @@ -0,0 +1,1088 @@ + + + + + + + + rsa - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Package rsa

    + + + + + + + + + + + + + + +
    +
    +
    import "crypto/rsa"
    +
    +
    +
    Overview
    +
    Index
    + +
    Examples
    + + +
    +
    + +
    + +
    +

    Overview ▾

    +

    +Package rsa implements RSA encryption as specified in PKCS#1. +

    +

    +RSA is a single, fundamental operation that is used in this package to +implement either public-key encryption or public-key signatures. +

    +

    +The original specification for encryption and signatures with RSA is PKCS#1 +and the terms "RSA encryption" and "RSA signatures" by default refer to +PKCS#1 version 1.5. However, that specification has flaws and new designs +should use version two, usually called by just OAEP and PSS, where +possible. +

    +

    +Two sets of interfaces are included in this package. When a more abstract +interface isn't neccessary, there are functions for encrypting/decrypting +with v1.5/OAEP and signing/verifying with v1.5/PSS. If one needs to abstract +over the public-key primitive, the PrivateKey struct implements the +Decrypter and Signer interfaces from the crypto package. +

    + +
    +
    + + +
    + +
    +

    Index ▾

    + + +
    +
    + +
    Constants
    + + +
    Variables
    + + + +
    func DecryptOAEP(hash hash.Hash, random io.Reader, priv *PrivateKey, ciphertext []byte, label []byte) (msg []byte, err error)
    + + +
    func DecryptPKCS1v15(rand io.Reader, priv *PrivateKey, ciphertext []byte) (out []byte, err error)
    + + +
    func DecryptPKCS1v15SessionKey(rand io.Reader, priv *PrivateKey, ciphertext []byte, key []byte) (err error)
    + + +
    func EncryptOAEP(hash hash.Hash, random io.Reader, pub *PublicKey, msg []byte, label []byte) (out []byte, err error)
    + + +
    func EncryptPKCS1v15(rand io.Reader, pub *PublicKey, msg []byte) (out []byte, err error)
    + + +
    func SignPKCS1v15(rand io.Reader, priv *PrivateKey, hash crypto.Hash, hashed []byte) (s []byte, err error)
    + + +
    func SignPSS(rand io.Reader, priv *PrivateKey, hash crypto.Hash, hashed []byte, opts *PSSOptions) (s []byte, err error)
    + + +
    func VerifyPKCS1v15(pub *PublicKey, hash crypto.Hash, hashed []byte, sig []byte) (err error)
    + + +
    func VerifyPSS(pub *PublicKey, hash crypto.Hash, hashed []byte, sig []byte, opts *PSSOptions) error
    + + + +
    type CRTValue
    + + + + +
    type OAEPOptions
    + + + + +
    type PKCS1v15DecryptOptions
    + + + + +
    type PSSOptions
    + + + +
        func (pssOpts *PSSOptions) HashFunc() crypto.Hash
    + + + +
    type PrecomputedValues
    + + + + +
    type PrivateKey
    + + +
        func GenerateKey(random io.Reader, bits int) (priv *PrivateKey, err error)
    + + +
        func GenerateMultiPrimeKey(random io.Reader, nprimes int, bits int) (priv *PrivateKey, err error)
    + + + +
        func (priv *PrivateKey) Decrypt(rand io.Reader, ciphertext []byte, opts crypto.DecrypterOpts) (plaintext []byte, err error)
    + + +
        func (priv *PrivateKey) Precompute()
    + + +
        func (priv *PrivateKey) Public() crypto.PublicKey
    + + +
        func (priv *PrivateKey) Sign(rand io.Reader, msg []byte, opts crypto.SignerOpts) ([]byte, error)
    + + +
        func (priv *PrivateKey) Validate() error
    + + + +
    type PublicKey
    + + + + +
    +
    + + + + + + +

    Package files

    +

    + + + pkcs1v15.go + + pss.go + + rsa.go + + +

    + +
    +
    + + + + +

    Constants

    + +
    const (
    +    // PSSSaltLengthAuto causes the salt in a PSS signature to be as large
    +    // as possible when signing, and to be auto-detected when verifying.
    +    PSSSaltLengthAuto = 0
    +    // PSSSaltLengthEqualsHash causes the salt length to equal the length
    +    // of the hash used in the signature.
    +    PSSSaltLengthEqualsHash = -1
    +)
    + + + + +

    Variables

    + +
    var ErrDecryption = errors.New("crypto/rsa: decryption error")
    +

    +ErrDecryption represents a failure to decrypt a message. +It is deliberately vague to avoid adaptive attacks. +

    + + +
    var ErrMessageTooLong = errors.New("crypto/rsa: message too long for RSA public key size")
    +

    +ErrMessageTooLong is returned when attempting to encrypt a message which is +too large for the size of the public key. +

    + + +
    var ErrVerification = errors.New("crypto/rsa: verification error")
    +

    +ErrVerification represents a failure to verify a signature. +It is deliberately vague to avoid adaptive attacks. +

    + + + + + + +

    func DecryptOAEP

    +
    func DecryptOAEP(hash hash.Hash, random io.Reader, priv *PrivateKey, ciphertext []byte, label []byte) (msg []byte, err error)
    +

    +OAEP is parameterised by a hash function that is used as a random oracle. +Encryption and decryption of a given message must use the same hash function +and sha256.New() is a reasonable choice. +

    +

    +The random parameter, if not nil, is used to blind the private-key operation +and avoid timing side-channel attacks. Blinding is purely internal to this +function – the random data need not match that used when encrypting. +

    +

    +The label parameter must match the value given when encrypting. See +EncryptOAEP for details. +

    + +
    + +
    +

    Example

    + + + +

    Code:

    +
    +ciphertext, _ := hex.DecodeString("4d1ee10e8f286390258c51a5e80802844c3e6358ad6690b7285218a7c7ed7fc3a4c7b950fbd04d4b0239cc060dcc7065ca6f84c1756deb71ca5685cadbb82be025e16449b905c568a19c088a1abfad54bf7ecc67a7df39943ec511091a34c0f2348d04e058fcff4d55644de3cd1d580791d4524b92f3e91695582e6e340a1c50b6c6d78e80b4e42c5b4d45e479b492de42bbd39cc642ebb80226bb5200020d501b24a37bcc2ec7f34e596b4fd6b063de4858dbf5a4e3dd18e262eda0ec2d19dbd8e890d672b63d368768360b20c0b6b8592a438fa275e5fa7f60bef0dd39673fd3989cc54d2cb80c08fcd19dacbc265ee1c6014616b0e04ea0328c2a04e73460")
    +label := []byte("orders")
    +
    +// crypto/rand.Reader is a good source of entropy for blinding the RSA
    +// operation.
    +rng := rand.Reader
    +
    +plaintext, err := DecryptOAEP(sha256.New(), rng, test2048Key, ciphertext, label)
    +if err != nil {
    +    fmt.Fprintf(os.Stderr, "Error from decryption: %s\n", err)
    +    return
    +}
    +
    +fmt.Printf("Plaintext: %s\n", string(plaintext))
    +
    +// Remember that encryption only provides confidentiality. The
    +// ciphertext should be signed before authenticity is assumed and, even
    +// then, consider that messages might be reordered.
    +
    + + +
    +
    + + + + + + +

    func DecryptPKCS1v15

    +
    func DecryptPKCS1v15(rand io.Reader, priv *PrivateKey, ciphertext []byte) (out []byte, err error)
    +

    +DecryptPKCS1v15 decrypts a plaintext using RSA and the padding scheme from PKCS#1 v1.5. +If rand != nil, it uses RSA blinding to avoid timing side-channel attacks. +

    +

    +Note that whether this function returns an error or not discloses secret +information. If an attacker can cause this function to run repeatedly and +learn whether each instance returned an error then they can decrypt and +forge signatures as if they had the private key. See +DecryptPKCS1v15SessionKey for a way of solving this problem. +

    + + + + + + + +

    func DecryptPKCS1v15SessionKey

    +
    func DecryptPKCS1v15SessionKey(rand io.Reader, priv *PrivateKey, ciphertext []byte, key []byte) (err error)
    +

    +DecryptPKCS1v15SessionKey decrypts a session key using RSA and the padding scheme from PKCS#1 v1.5. +If rand != nil, it uses RSA blinding to avoid timing side-channel attacks. +It returns an error if the ciphertext is the wrong length or if the +ciphertext is greater than the public modulus. Otherwise, no error is +returned. If the padding is valid, the resulting plaintext message is copied +into key. Otherwise, key is unchanged. These alternatives occur in constant +time. It is intended that the user of this function generate a random +session key beforehand and continue the protocol with the resulting value. +This will remove any possibility that an attacker can learn any information +about the plaintext. +See “Chosen Ciphertext Attacks Against Protocols Based on the RSA +Encryption Standard PKCS #1”, Daniel Bleichenbacher, Advances in Cryptology +(Crypto '98). +

    +

    +Note that if the session key is too small then it may be possible for an +attacker to brute-force it. If they can do that then they can learn whether +a random value was used (because it'll be different for the same ciphertext) +and thus whether the padding was correct. This defeats the point of this +function. Using at least a 16-byte key will protect against this attack. +

    + +
    + +
    +

    Example

    +

    RSA is able to encrypt only a very limited amount of data. In order +to encrypt reasonable amounts of data a hybrid scheme is commonly +used: RSA is used to encrypt a key for a symmetric primitive like +AES-GCM. + +Before encrypting, data is “padded” by embedding it in a known +structure. This is done for a number of reasons, but the most +obvious is to ensure that the value is large enough that the +exponentiation is larger than the modulus. (Otherwise it could be +decrypted with a square-root.) + +In these designs, when using PKCS#1 v1.5, it's vitally important to +avoid disclosing whether the received RSA message was well-formed +(that is, whether the result of decrypting is a correctly padded +message) because this leaks secret information. +DecryptPKCS1v15SessionKey is designed for this situation and copies +the decrypted, symmetric key (if well-formed) in constant-time over +a buffer that contains a random key. Thus, if the RSA result isn't +well-formed, the implementation uses a random key in constant time. +

    + + +

    Code:

    +
    +// crypto/rand.Reader is a good source of entropy for blinding the RSA
    +// operation.
    +rng := rand.Reader
    +
    +// The hybrid scheme should use at least a 16-byte symmetric key. Here
    +// we read the random key that will be used if the RSA decryption isn't
    +// well-formed.
    +key := make([]byte, 32)
    +if _, err := io.ReadFull(rng, key); err != nil {
    +    panic("RNG failure")
    +}
    +
    +rsaCiphertext, _ := hex.DecodeString("aabbccddeeff")
    +
    +if err := DecryptPKCS1v15SessionKey(rng, rsaPrivateKey, rsaCiphertext, key); err != nil {
    +    // Any errors that result will be “public” – meaning that they
    +    // can be determined without any secret information. (For
    +    // instance, if the length of key is impossible given the RSA
    +    // public key.)
    +    fmt.Fprintf(os.Stderr, "Error from RSA decryption: %s\n", err)
    +    return
    +}
    +
    +// Given the resulting key, a symmetric scheme can be used to decrypt a
    +// larger ciphertext.
    +block, err := aes.NewCipher(key)
    +if err != nil {
    +    panic("aes.NewCipher failed: " + err.Error())
    +}
    +
    +// Since the key is random, using a fixed nonce is acceptable as the
    +// (key, nonce) pair will still be unique, as required.
    +var zeroNonce [12]byte
    +aead, err := cipher.NewGCM(block)
    +if err != nil {
    +    panic("cipher.NewGCM failed: " + err.Error())
    +}
    +ciphertext, _ := hex.DecodeString("00112233445566")
    +plaintext, err := aead.Open(nil, zeroNonce[:], ciphertext, nil)
    +if err != nil {
    +    // The RSA ciphertext was badly formed; the decryption will
    +    // fail here because the AES-GCM key will be incorrect.
    +    fmt.Fprintf(os.Stderr, "Error decrypting: %s\n", err)
    +    return
    +}
    +
    +fmt.Printf("Plaintext: %s\n", string(plaintext))
    +
    + + +
    +
    + + + + + + +

    func EncryptOAEP

    +
    func EncryptOAEP(hash hash.Hash, random io.Reader, pub *PublicKey, msg []byte, label []byte) (out []byte, err error)
    +

    +EncryptOAEP encrypts the given message with RSA-OAEP. +

    +

    +OAEP is parameterised by a hash function that is used as a random oracle. +Encryption and decryption of a given message must use the same hash function +and sha256.New() is a reasonable choice. +

    +

    +The random parameter is used as a source of entropy to ensure that +encrypting the same message twice doesn't result in the same ciphertext. +

    +

    +The label parameter may contain arbitrary data that will not be encrypted, +but which gives important context to the message. For example, if a given +public key is used to decrypt two types of messages then distinct label +values could be used to ensure that a ciphertext for one purpose cannot be +used for another by an attacker. If not required it can be empty. +

    +

    +The message must be no longer than the length of the public modulus less +twice the hash length plus 2. +

    + +
    + +
    +

    Example

    + + + +

    Code:

    +
    +secretMessage := []byte("send reinforcements, we're going to advance")
    +label := []byte("orders")
    +
    +// crypto/rand.Reader is a good source of entropy for randomizing the
    +// encryption function.
    +rng := rand.Reader
    +
    +ciphertext, err := EncryptOAEP(sha256.New(), rng, &test2048Key.PublicKey, secretMessage, label)
    +if err != nil {
    +    fmt.Fprintf(os.Stderr, "Error from encryption: %s\n", err)
    +    return
    +}
    +
    +// Since encryption is a randomized function, ciphertext will be
    +// different each time.
    +fmt.Printf("Ciphertext: %x\n", ciphertext)
    +
    + + +
    +
    + + + + + + +

    func EncryptPKCS1v15

    +
    func EncryptPKCS1v15(rand io.Reader, pub *PublicKey, msg []byte) (out []byte, err error)
    +

    +EncryptPKCS1v15 encrypts the given message with RSA and the padding scheme from PKCS#1 v1.5. +The message must be no longer than the length of the public modulus minus 11 bytes. +

    +

    +The rand parameter is used as a source of entropy to ensure that encrypting +the same message twice doesn't result in the same ciphertext. +

    +

    +WARNING: use of this function to encrypt plaintexts other than session keys +is dangerous. Use RSA OAEP in new protocols. +

    + + + + + + + +

    func SignPKCS1v15

    +
    func SignPKCS1v15(rand io.Reader, priv *PrivateKey, hash crypto.Hash, hashed []byte) (s []byte, err error)
    +

    +SignPKCS1v15 calculates the signature of hashed using RSASSA-PKCS1-V1_5-SIGN from RSA PKCS#1 v1.5. +Note that hashed must be the result of hashing the input message using the +given hash function. If hash is zero, hashed is signed directly. This isn't +advisable except for interoperability. +

    +

    +If rand is not nil then RSA blinding will be used to avoid timing side-channel attacks. +

    +

    +This function is deterministic. Thus, if the set of possible messages is +small, an attacker may be able to build a map from messages to signatures +and identify the signed messages. As ever, signatures provide authenticity, +not confidentiality. +

    + +
    + +
    +

    Example

    + + + +

    Code:

    +
    +// crypto/rand.Reader is a good source of entropy for blinding the RSA
    +// operation.
    +rng := rand.Reader
    +
    +message := []byte("message to be signed")
    +
    +// Only small messages can be signed directly; thus the hash of a
    +// message, rather than the message itself, is signed. This requires
    +// that the hash function be collision resistant. SHA-256 is the
    +// least-strong hash function that should be used for this at the time
    +// of writing (2016).
    +hashed := sha256.Sum256(message)
    +
    +signature, err := SignPKCS1v15(rng, rsaPrivateKey, crypto.SHA256, hashed[:])
    +if err != nil {
    +    fmt.Fprintf(os.Stderr, "Error from signing: %s\n", err)
    +    return
    +}
    +
    +fmt.Printf("Signature: %x\n", signature)
    +
    + + +
    +
    + + + + + + +

    func SignPSS

    +
    func SignPSS(rand io.Reader, priv *PrivateKey, hash crypto.Hash, hashed []byte, opts *PSSOptions) (s []byte, err error)
    +

    +SignPSS calculates the signature of hashed using RSASSA-PSS [1]. +Note that hashed must be the result of hashing the input message using the +given hash function. The opts argument may be nil, in which case sensible +defaults are used. +

    + + + + + + + +

    func VerifyPKCS1v15

    +
    func VerifyPKCS1v15(pub *PublicKey, hash crypto.Hash, hashed []byte, sig []byte) (err error)
    +

    +VerifyPKCS1v15 verifies an RSA PKCS#1 v1.5 signature. +hashed is the result of hashing the input message using the given hash +function and sig is the signature. A valid signature is indicated by +returning a nil error. If hash is zero then hashed is used directly. This +isn't advisable except for interoperability. +

    + +
    + +
    +

    Example

    + + + +

    Code:

    +
    +message := []byte("message to be signed")
    +signature, _ := hex.DecodeString("ad2766728615cc7a746cc553916380ca7bfa4f8983b990913bc69eb0556539a350ff0f8fe65ddfd3ebe91fe1c299c2fac135bc8c61e26be44ee259f2f80c1530")
    +
    +// Only small messages can be signed directly; thus the hash of a
    +// message, rather than the message itself, is signed. This requires
    +// that the hash function be collision resistant. SHA-256 is the
    +// least-strong hash function that should be used for this at the time
    +// of writing (2016).
    +hashed := sha256.Sum256(message)
    +
    +err := VerifyPKCS1v15(&rsaPrivateKey.PublicKey, crypto.SHA256, hashed[:], signature)
    +if err != nil {
    +    fmt.Fprintf(os.Stderr, "Error from verification: %s\n", err)
    +    return
    +}
    +
    +// signature is a valid signature of message from the public key.
    +
    + + +
    +
    + + + + + + +

    func VerifyPSS

    +
    func VerifyPSS(pub *PublicKey, hash crypto.Hash, hashed []byte, sig []byte, opts *PSSOptions) error
    +

    +VerifyPSS verifies a PSS signature. +hashed is the result of hashing the input message using the given hash +function and sig is the signature. A valid signature is indicated by +returning a nil error. The opts argument may be nil, in which case sensible +defaults are used. +

    + + + + + + + + +

    type CRTValue

    +
    type CRTValue struct {
    +    Exp   *big.Int // D mod (prime-1).
    +    Coeff *big.Int // R·Coeff ≡ 1 mod Prime.
    +    R     *big.Int // product of primes prior to this (inc p and q).
    +}
    +

    +CRTValue contains the precomputed Chinese remainder theorem values. +

    + + + + + + + + + + + + + + + + +

    type OAEPOptions

    +
    type OAEPOptions struct {
    +    // Hash is the hash function that will be used when generating the mask.
    +    Hash crypto.Hash
    +    // Label is an arbitrary byte string that must be equal to the value
    +    // used when encrypting.
    +    Label []byte
    +}
    +

    +OAEPOptions is an interface for passing options to OAEP decryption using the +crypto.Decrypter interface. +

    + + + + + + + + + + + + + + + + +

    type PKCS1v15DecryptOptions

    +
    type PKCS1v15DecryptOptions struct {
    +    // SessionKeyLen is the length of the session key that is being
    +    // decrypted. If not zero, then a padding error during decryption will
    +    // cause a random plaintext of this length to be returned rather than
    +    // an error. These alternatives happen in constant time.
    +    SessionKeyLen int
    +}
    +

    +PKCS1v15DecrypterOpts is for passing options to PKCS#1 v1.5 decryption using +the crypto.Decrypter interface. +

    + + + + + + + + + + + + + + + + +

    type PSSOptions

    +
    type PSSOptions struct {
    +    // SaltLength controls the length of the salt used in the PSS
    +    // signature. It can either be a number of bytes, or one of the special
    +    // PSSSaltLength constants.
    +    SaltLength int
    +
    +    // Hash, if not zero, overrides the hash function passed to SignPSS.
    +    // This is the only way to specify the hash function when using the
    +    // crypto.Signer interface.
    +    Hash crypto.Hash
    +}
    +

    +PSSOptions contains options for creating and verifying PSS signatures. +

    + + + + + + + + + + + + + + +

    func (*PSSOptions) HashFunc

    +
    func (pssOpts *PSSOptions) HashFunc() crypto.Hash
    +

    +HashFunc returns pssOpts.Hash so that PSSOptions implements +crypto.SignerOpts. +

    + + + + + + + + +

    type PrecomputedValues

    +
    type PrecomputedValues struct {
    +    Dp, Dq *big.Int // D mod (P-1) (or mod Q-1)
    +    Qinv   *big.Int // Q^-1 mod P
    +
    +    // CRTValues is used for the 3rd and subsequent primes. Due to a
    +    // historical accident, the CRT for the first two primes is handled
    +    // differently in PKCS#1 and interoperability is sufficiently
    +    // important that we mirror this.
    +    CRTValues []CRTValue
    +}
    + + + + + + + + + + + + + + + + +

    type PrivateKey

    +
    type PrivateKey struct {
    +    PublicKey            // public part.
    +    D         *big.Int   // private exponent
    +    Primes    []*big.Int // prime factors of N, has >= 2 elements.
    +
    +    // Precomputed contains precomputed values that speed up private
    +    // operations, if available.
    +    Precomputed PrecomputedValues
    +}
    +

    +A PrivateKey represents an RSA key +

    + + + + + + + + + + + + +

    func GenerateKey

    +
    func GenerateKey(random io.Reader, bits int) (priv *PrivateKey, err error)
    +

    +GenerateKey generates an RSA keypair of the given bit size using the +random source random (for example, crypto/rand.Reader). +

    + + + + + +

    func GenerateMultiPrimeKey

    +
    func GenerateMultiPrimeKey(random io.Reader, nprimes int, bits int) (priv *PrivateKey, err error)
    +

    +GenerateMultiPrimeKey generates a multi-prime RSA keypair of the given bit +size and the given random source, as suggested in [1]. Although the public +keys are compatible (actually, indistinguishable) from the 2-prime case, +the private keys are not. Thus it may not be possible to export multi-prime +private keys in certain formats or to subsequently import them into other +code. +

    +

    +Table 1 in [2] suggests maximum numbers of primes for a given size. +

    +

    +[1] US patent 4405829 (1972, expired) +[2] http://www.cacr.math.uwaterloo.ca/techreports/2006/cacr2006-16.pdf +

    + + + + + + + +

    func (*PrivateKey) Decrypt

    +
    func (priv *PrivateKey) Decrypt(rand io.Reader, ciphertext []byte, opts crypto.DecrypterOpts) (plaintext []byte, err error)
    +

    +Decrypt decrypts ciphertext with priv. If opts is nil or of type +*PKCS1v15DecryptOptions then PKCS#1 v1.5 decryption is performed. Otherwise +opts must have type *OAEPOptions and OAEP decryption is done. +

    + + + + + + +

    func (*PrivateKey) Precompute

    +
    func (priv *PrivateKey) Precompute()
    +

    +Precompute performs some calculations that speed up private key operations +in the future. +

    + + + + + + +

    func (*PrivateKey) Public

    +
    func (priv *PrivateKey) Public() crypto.PublicKey
    +

    +Public returns the public key corresponding to priv. +

    + + + + + + +

    func (*PrivateKey) Sign

    +
    func (priv *PrivateKey) Sign(rand io.Reader, msg []byte, opts crypto.SignerOpts) ([]byte, error)
    +

    +Sign signs msg with priv, reading randomness from rand. If opts is a +*PSSOptions then the PSS algorithm will be used, otherwise PKCS#1 v1.5 will +be used. This method is intended to support keys where the private part is +kept in, for example, a hardware module. Common uses should use the Sign* +functions in this package. +

    + + + + + + +

    func (*PrivateKey) Validate

    +
    func (priv *PrivateKey) Validate() error
    +

    +Validate performs basic sanity checks on the key. +It returns nil if the key is valid, or else an error describing a problem. +

    + + + + + + + + +

    type PublicKey

    +
    type PublicKey struct {
    +    N *big.Int // modulus
    +    E int      // public exponent
    +}
    +

    +A PublicKey represents the public part of an RSA key. +

    + + + + + + + + + + + + + + + + + + + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/crypto/sha1/index.html b/pkg/crypto/sha1/index.html new file mode 100644 index 0000000..350f111 --- /dev/null +++ b/pkg/crypto/sha1/index.html @@ -0,0 +1,313 @@ + + + + + + + + sha1 - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Package sha1

    + + + + + + + + + + + + + + +
    +
    +
    import "crypto/sha1"
    +
    +
    +
    Overview
    +
    Index
    + +
    Examples
    + + +
    +
    + +
    + +
    +

    Overview ▾

    +

    +Package sha1 implements the SHA1 hash algorithm as defined in RFC 3174. +

    + +
    +
    + + +
    + +
    +

    Index ▾

    + + + + + +
    +

    Examples

    +
    + +
    New
    + +
    Sum
    + +
    +
    + + + +

    Package files

    +

    + + + sha1.go + + sha1block.go + + sha1block_decl.go + + +

    + +
    +
    + + + + +

    Constants

    + +
    const BlockSize = 64
    +

    +The blocksize of SHA1 in bytes. +

    + + +
    const Size = 20
    +

    +The size of a SHA1 checksum in bytes. +

    + + + + + + + +

    func New

    +
    func New() hash.Hash
    +

    +New returns a new hash.Hash computing the SHA1 checksum. +

    + +
    + +
    +

    Example

    + + + +

    Code:

    +
    h := sha1.New()
    +io.WriteString(h, "His money is twice tainted:")
    +io.WriteString(h, " 'taint yours and 'taint mine.")
    +fmt.Printf("% x", h.Sum(nil))
    +
    + +

    Output:

    +
    59 7f 6a 54 00 10 f9 4c 15 d7 18 06 a9 9a 2c 87 10 e7 47 bd
    +
    + + +
    +
    + + + + + + +

    func Sum

    +
    func Sum(data []byte) [Size]byte
    +

    +Sum returns the SHA1 checksum of the data. +

    + +
    + +
    +

    Example

    + + + +

    Code:

    +
    data := []byte("This page intentionally left blank.")
    +fmt.Printf("% x", sha1.Sum(data))
    +
    + +

    Output:

    +
    af 06 49 23 bb f2 30 15 96 aa c4 c2 73 ba 32 17 8e bc 4a 96
    +
    + + +
    +
    + + + + + + + + + + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/crypto/sha256/index.html b/pkg/crypto/sha256/index.html new file mode 100644 index 0000000..d505846 --- /dev/null +++ b/pkg/crypto/sha256/index.html @@ -0,0 +1,291 @@ + + + + + + + + sha256 - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Package sha256

    + + + + + + + + + + + + + + +
    +
    +
    import "crypto/sha256"
    +
    +
    +
    Overview
    +
    Index
    + + +
    +
    + +
    + +
    +

    Overview ▾

    +

    +Package sha256 implements the SHA224 and SHA256 hash algorithms as defined +in FIPS 180-4. +

    + +
    +
    + + +
    + +
    +

    Index ▾

    + + + + + + + +

    Package files

    +

    + + + sha256.go + + sha256block_decl.go + + +

    + +
    +
    + + + + +

    Constants

    + +
    const BlockSize = 64
    +

    +The blocksize of SHA256 and SHA224 in bytes. +

    + + +
    const Size = 32
    +

    +The size of a SHA256 checksum in bytes. +

    + + +
    const Size224 = 28
    +

    +The size of a SHA224 checksum in bytes. +

    + + + + + + + +

    func New

    +
    func New() hash.Hash
    +

    +New returns a new hash.Hash computing the SHA256 checksum. +

    + + + + + + + +

    func New224

    +
    func New224() hash.Hash
    +

    +New224 returns a new hash.Hash computing the SHA224 checksum. +

    + + + + + + + +

    func Sum224

    +
    func Sum224(data []byte) (sum224 [Size224]byte)
    +

    +Sum224 returns the SHA224 checksum of the data. +

    + + + + + + + +

    func Sum256

    +
    func Sum256(data []byte) [Size]byte
    +

    +Sum256 returns the SHA256 checksum of the data. +

    + + + + + + + + + + + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/crypto/sha512/index.html b/pkg/crypto/sha512/index.html new file mode 100644 index 0000000..b6ef769 --- /dev/null +++ b/pkg/crypto/sha512/index.html @@ -0,0 +1,352 @@ + + + + + + + + sha512 - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Package sha512

    + + + + + + + + + + + + + + +
    +
    +
    import "crypto/sha512"
    +
    +
    +
    Overview
    +
    Index
    + + +
    +
    + +
    + +
    +

    Overview ▾

    +

    +Package sha512 implements the SHA-384, SHA-512, SHA-512/224, and SHA-512/256 +hash algorithms as defined in FIPS 180-4. +

    + +
    +
    + + + + + + + +

    Constants

    + +
    const (
    +    // Size is the size, in bytes, of a SHA-512 checksum.
    +    Size = 64
    +
    +    // Size224 is the size, in bytes, of a SHA-512/224 checksum.
    +    Size224 = 28
    +
    +    // Size256 is the size, in bytes, of a SHA-512/256 checksum.
    +    Size256 = 32
    +
    +    // Size384 is the size, in bytes, of a SHA-384 checksum.
    +    Size384 = 48
    +
    +    // BlockSize is the block size, in bytes, of the SHA-512/224,
    +    // SHA-512/256, SHA-384 and SHA-512 hash functions.
    +    BlockSize = 128
    +)
    + + + + + + + +

    func New

    +
    func New() hash.Hash
    +

    +New returns a new hash.Hash computing the SHA-512 checksum. +

    + + + + + + + +

    func New384

    +
    func New384() hash.Hash
    +

    +New384 returns a new hash.Hash computing the SHA-384 checksum. +

    + + + + + + + +

    func New512_224

    +
    func New512_224() hash.Hash
    +

    +New512_224 returns a new hash.Hash computing the SHA-512/224 checksum. +

    + + + + + + + +

    func New512_256

    +
    func New512_256() hash.Hash
    +

    +New512_256 returns a new hash.Hash computing the SHA-512/256 checksum. +

    + + + + + + + +

    func Sum384

    +
    func Sum384(data []byte) (sum384 [Size384]byte)
    +

    +Sum384 returns the SHA384 checksum of the data. +

    + + + + + + + +

    func Sum512

    +
    func Sum512(data []byte) [Size]byte
    +

    +Sum512 returns the SHA512 checksum of the data. +

    + + + + + + + +

    func Sum512_224

    +
    func Sum512_224(data []byte) (sum224 [Size224]byte)
    +

    +Sum512_224 returns the Sum512/224 checksum of the data. +

    + + + + + + + +

    func Sum512_256

    +
    func Sum512_256(data []byte) (sum256 [Size256]byte)
    +

    +Sum512_256 returns the Sum512/256 checksum of the data. +

    + + + + + + + + + + + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/crypto/subtle/index.html b/pkg/crypto/subtle/index.html new file mode 100644 index 0000000..d1f80f5 --- /dev/null +++ b/pkg/crypto/subtle/index.html @@ -0,0 +1,302 @@ + + + + + + + + subtle - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Package subtle

    + + + + + + + + + + + + + + +
    +
    +
    import "crypto/subtle"
    +
    +
    +
    Overview
    +
    Index
    + + +
    +
    + +
    + +
    +

    Overview ▾

    +

    +Package subtle implements functions that are often useful in cryptographic +code but require careful thought to use correctly. +

    + +
    +
    + + + + + + + + + + + +

    func ConstantTimeByteEq

    +
    func ConstantTimeByteEq(x, y uint8) int
    +

    +ConstantTimeByteEq returns 1 if x == y and 0 otherwise. +

    + + + + + + + +

    func ConstantTimeCompare

    +
    func ConstantTimeCompare(x, y []byte) int
    +

    +ConstantTimeCompare returns 1 iff the two slices, x +and y, have equal contents. The time taken is a function of the length of +the slices and is independent of the contents. +

    + + + + + + + +

    func ConstantTimeCopy

    +
    func ConstantTimeCopy(v int, x, y []byte)
    +

    +ConstantTimeCopy copies the contents of y into x (a slice of equal length) +if v == 1. If v == 0, x is left unchanged. Its behavior is undefined if v +takes any other value. +

    + + + + + + + +

    func ConstantTimeEq

    +
    func ConstantTimeEq(x, y int32) int
    +

    +ConstantTimeEq returns 1 if x == y and 0 otherwise. +

    + + + + + + + +

    func ConstantTimeLessOrEq

    +
    func ConstantTimeLessOrEq(x, y int) int
    +

    +ConstantTimeLessOrEq returns 1 if x <= y and 0 otherwise. +Its behavior is undefined if x or y are negative or > 2**31 - 1. +

    + + + + + + + +

    func ConstantTimeSelect

    +
    func ConstantTimeSelect(v, x, y int) int
    +

    +ConstantTimeSelect returns x if v is 1 and y if v is 0. +Its behavior is undefined if v takes any other value. +

    + + + + + + + + + + + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/crypto/tls/index.html b/pkg/crypto/tls/index.html new file mode 100644 index 0000000..3352674 --- /dev/null +++ b/pkg/crypto/tls/index.html @@ -0,0 +1,1205 @@ + + + + + + + + tls - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Package tls

    + + + + + + + + + + + + + + +
    +
    +
    import "crypto/tls"
    +
    +
    +
    Overview
    +
    Index
    + +
    Examples
    + + +
    +
    + +
    + +
    +

    Overview ▾

    +

    +Package tls partially implements TLS 1.2, as specified in RFC 5246. +

    + +
    +
    + + +
    + +
    +

    Index ▾

    + + +
    +
    + +
    Constants
    + + + + +
    func Listen(network, laddr string, config *Config) (net.Listener, error)
    + + +
    func NewListener(inner net.Listener, config *Config) net.Listener
    + + + +
    type Certificate
    + + +
        func LoadX509KeyPair(certFile, keyFile string) (Certificate, error)
    + + +
        func X509KeyPair(certPEMBlock, keyPEMBlock []byte) (Certificate, error)
    + + + + +
    type ClientAuthType
    + + + + +
    type ClientHelloInfo
    + + + + +
    type ClientSessionCache
    + + +
        func NewLRUClientSessionCache(capacity int) ClientSessionCache
    + + + + +
    type ClientSessionState
    + + + + +
    type Config
    + + + +
        func (c *Config) BuildNameToCertificate()
    + + +
        func (c *Config) SetSessionTicketKeys(keys [][32]byte)
    + + + +
    type Conn
    + + +
        func Client(conn net.Conn, config *Config) *Conn
    + + +
        func Dial(network, addr string, config *Config) (*Conn, error)
    + + +
        func DialWithDialer(dialer *net.Dialer, network, addr string, config *Config) (*Conn, error)
    + + +
        func Server(conn net.Conn, config *Config) *Conn
    + + + +
        func (c *Conn) Close() error
    + + +
        func (c *Conn) ConnectionState() ConnectionState
    + + +
        func (c *Conn) Handshake() error
    + + +
        func (c *Conn) LocalAddr() net.Addr
    + + +
        func (c *Conn) OCSPResponse() []byte
    + + +
        func (c *Conn) Read(b []byte) (n int, err error)
    + + +
        func (c *Conn) RemoteAddr() net.Addr
    + + +
        func (c *Conn) SetDeadline(t time.Time) error
    + + +
        func (c *Conn) SetReadDeadline(t time.Time) error
    + + +
        func (c *Conn) SetWriteDeadline(t time.Time) error
    + + +
        func (c *Conn) VerifyHostname(host string) error
    + + +
        func (c *Conn) Write(b []byte) (int, error)
    + + + +
    type ConnectionState
    + + + + +
    type CurveID
    + + + + +
    type RecordHeaderError
    + + + +
        func (e RecordHeaderError) Error() string
    + + + + +
    Bugs
    + + +
    +
    + + +
    +

    Examples

    +
    + +
    Dial
    + +
    +
    + + + +

    Package files

    +

    + + + alert.go + + cipher_suites.go + + common.go + + conn.go + + handshake_client.go + + handshake_messages.go + + handshake_server.go + + key_agreement.go + + prf.go + + ticket.go + + tls.go + + +

    + +
    +
    + + + + +

    Constants

    + +
    const (
    +    TLS_RSA_WITH_RC4_128_SHA                uint16 = 0x0005
    +    TLS_RSA_WITH_3DES_EDE_CBC_SHA           uint16 = 0x000a
    +    TLS_RSA_WITH_AES_128_CBC_SHA            uint16 = 0x002f
    +    TLS_RSA_WITH_AES_256_CBC_SHA            uint16 = 0x0035
    +    TLS_RSA_WITH_AES_128_GCM_SHA256         uint16 = 0x009c
    +    TLS_RSA_WITH_AES_256_GCM_SHA384         uint16 = 0x009d
    +    TLS_ECDHE_ECDSA_WITH_RC4_128_SHA        uint16 = 0xc007
    +    TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA    uint16 = 0xc009
    +    TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA    uint16 = 0xc00a
    +    TLS_ECDHE_RSA_WITH_RC4_128_SHA          uint16 = 0xc011
    +    TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA     uint16 = 0xc012
    +    TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA      uint16 = 0xc013
    +    TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA      uint16 = 0xc014
    +    TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256   uint16 = 0xc02f
    +    TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 uint16 = 0xc02b
    +    TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384   uint16 = 0xc030
    +    TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384 uint16 = 0xc02c
    +
    +    // TLS_FALLBACK_SCSV isn't a standard cipher suite but an indicator
    +    // that the client is doing version fallback. See
    +    // https://tools.ietf.org/html/draft-ietf-tls-downgrade-scsv-00.
    +    TLS_FALLBACK_SCSV uint16 = 0x5600
    +)
    +

    +A list of the possible cipher suite ids. Taken from +http://www.iana.org/assignments/tls-parameters/tls-parameters.xml +

    + + +
    const (
    +    VersionSSL30 = 0x0300
    +    VersionTLS10 = 0x0301
    +    VersionTLS11 = 0x0302
    +    VersionTLS12 = 0x0303
    +)
    + + + + + + + +

    func Listen

    +
    func Listen(network, laddr string, config *Config) (net.Listener, error)
    +

    +Listen creates a TLS listener accepting connections on the +given network address using net.Listen. +The configuration config must be non-nil and must include +at least one certificate or else set GetCertificate. +

    + + + + + + + +

    func NewListener

    +
    func NewListener(inner net.Listener, config *Config) net.Listener
    +

    +NewListener creates a Listener which accepts connections from an inner +Listener and wraps each connection with Server. +The configuration config must be non-nil and must include +at least one certificate or else set GetCertificate. +

    + + + + + + + + +

    type Certificate

    +
    type Certificate struct {
    +    Certificate [][]byte
    +    // PrivateKey contains the private key corresponding to the public key
    +    // in Leaf. For a server, this must implement crypto.Signer and/or
    +    // crypto.Decrypter, with an RSA or ECDSA PublicKey. For a client
    +    // (performing client authentication), this must be a crypto.Signer
    +    // with an RSA or ECDSA PublicKey.
    +    PrivateKey crypto.PrivateKey
    +    // OCSPStaple contains an optional OCSP response which will be served
    +    // to clients that request it.
    +    OCSPStaple []byte
    +    // SignedCertificateTimestamps contains an optional list of Signed
    +    // Certificate Timestamps which will be served to clients that request it.
    +    SignedCertificateTimestamps [][]byte
    +    // Leaf is the parsed form of the leaf certificate, which may be
    +    // initialized using x509.ParseCertificate to reduce per-handshake
    +    // processing for TLS clients doing client authentication. If nil, the
    +    // leaf certificate will be parsed as needed.
    +    Leaf *x509.Certificate
    +}
    +

    +A Certificate is a chain of one or more certificates, leaf first. +

    + + + + + + + + + + + + +

    func LoadX509KeyPair

    +
    func LoadX509KeyPair(certFile, keyFile string) (Certificate, error)
    +

    +LoadX509KeyPair reads and parses a public/private key pair from a pair of +files. The files must contain PEM encoded data. On successful return, +Certificate.Leaf will be nil because the parsed form of the certificate is +not retained. +

    + + + + + +

    func X509KeyPair

    +
    func X509KeyPair(certPEMBlock, keyPEMBlock []byte) (Certificate, error)
    +

    +X509KeyPair parses a public/private key pair from a pair of +PEM encoded data. On successful return, Certificate.Leaf will be nil because +the parsed form of the certificate is not retained. +

    + + + + + + + + + +

    type ClientAuthType

    +
    type ClientAuthType int
    +

    +ClientAuthType declares the policy the server will follow for +TLS Client Authentication. +

    + + + +
    const (
    +    NoClientCert ClientAuthType = iota
    +    RequestClientCert
    +    RequireAnyClientCert
    +    VerifyClientCertIfGiven
    +    RequireAndVerifyClientCert
    +)
    + + + + + + + + + + + + + + + +

    type ClientHelloInfo

    +
    type ClientHelloInfo struct {
    +    // CipherSuites lists the CipherSuites supported by the client (e.g.
    +    // TLS_RSA_WITH_RC4_128_SHA).
    +    CipherSuites []uint16
    +
    +    // ServerName indicates the name of the server requested by the client
    +    // in order to support virtual hosting. ServerName is only set if the
    +    // client is using SNI (see
    +    // http://tools.ietf.org/html/rfc4366#section-3.1).
    +    ServerName string
    +
    +    // SupportedCurves lists the elliptic curves supported by the client.
    +    // SupportedCurves is set only if the Supported Elliptic Curves
    +    // Extension is being used (see
    +    // http://tools.ietf.org/html/rfc4492#section-5.1.1).
    +    SupportedCurves []CurveID
    +
    +    // SupportedPoints lists the point formats supported by the client.
    +    // SupportedPoints is set only if the Supported Point Formats Extension
    +    // is being used (see
    +    // http://tools.ietf.org/html/rfc4492#section-5.1.2).
    +    SupportedPoints []uint8
    +}
    +

    +ClientHelloInfo contains information from a ClientHello message in order to +guide certificate selection in the GetCertificate callback. +

    + + + + + + + + + + + + + + + + +

    type ClientSessionCache

    +
    type ClientSessionCache interface {
    +    // Get searches for a ClientSessionState associated with the given key.
    +    // On return, ok is true if one was found.
    +    Get(sessionKey string) (session *ClientSessionState, ok bool)
    +
    +    // Put adds the ClientSessionState to the cache with the given key.
    +    Put(sessionKey string, cs *ClientSessionState)
    +}
    +

    +ClientSessionCache is a cache of ClientSessionState objects that can be used +by a client to resume a TLS session with a given server. ClientSessionCache +implementations should expect to be called concurrently from different +goroutines. +

    + + + + + + + + + + + + +

    func NewLRUClientSessionCache

    +
    func NewLRUClientSessionCache(capacity int) ClientSessionCache
    +

    +NewLRUClientSessionCache returns a ClientSessionCache with the given +capacity that uses an LRU strategy. If capacity is < 1, a default capacity +is used instead. +

    + + + + + + + + + +

    type ClientSessionState

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

    +ClientSessionState contains the state needed by clients to resume TLS +sessions. +

    + + + + + + + + + + + + + + + + +

    type Config

    +
    type Config struct {
    +    // Rand provides the source of entropy for nonces and RSA blinding.
    +    // If Rand is nil, TLS uses the cryptographic random reader in package
    +    // crypto/rand.
    +    // The Reader must be safe for use by multiple goroutines.
    +    Rand io.Reader
    +
    +    // Time returns the current time as the number of seconds since the epoch.
    +    // If Time is nil, TLS uses time.Now.
    +    Time func() time.Time
    +
    +    // Certificates contains one or more certificate chains
    +    // to present to the other side of the connection.
    +    // Server configurations must include at least one certificate
    +    // or else set GetCertificate.
    +    Certificates []Certificate
    +
    +    // NameToCertificate maps from a certificate name to an element of
    +    // Certificates. Note that a certificate name can be of the form
    +    // '*.example.com' and so doesn't have to be a domain name as such.
    +    // See Config.BuildNameToCertificate
    +    // The nil value causes the first element of Certificates to be used
    +    // for all connections.
    +    NameToCertificate map[string]*Certificate
    +
    +    // GetCertificate returns a Certificate based on the given
    +    // ClientHelloInfo. It will only be called if the client supplies SNI
    +    // information or if Certificates is empty.
    +    //
    +    // If GetCertificate is nil or returns nil, then the certificate is
    +    // retrieved from NameToCertificate. If NameToCertificate is nil, the
    +    // first element of Certificates will be used.
    +    GetCertificate func(clientHello *ClientHelloInfo) (*Certificate, error)
    +
    +    // RootCAs defines the set of root certificate authorities
    +    // that clients use when verifying server certificates.
    +    // If RootCAs is nil, TLS uses the host's root CA set.
    +    RootCAs *x509.CertPool
    +
    +    // NextProtos is a list of supported, application level protocols.
    +    NextProtos []string
    +
    +    // ServerName is used to verify the hostname on the returned
    +    // certificates unless InsecureSkipVerify is given. It is also included
    +    // in the client's handshake to support virtual hosting unless it is
    +    // an IP address.
    +    ServerName string
    +
    +    // ClientAuth determines the server's policy for
    +    // TLS Client Authentication. The default is NoClientCert.
    +    ClientAuth ClientAuthType
    +
    +    // ClientCAs defines the set of root certificate authorities
    +    // that servers use if required to verify a client certificate
    +    // by the policy in ClientAuth.
    +    ClientCAs *x509.CertPool
    +
    +    // InsecureSkipVerify controls whether a client verifies the
    +    // server's certificate chain and host name.
    +    // If InsecureSkipVerify is true, TLS accepts any certificate
    +    // presented by the server and any host name in that certificate.
    +    // In this mode, TLS is susceptible to man-in-the-middle attacks.
    +    // This should be used only for testing.
    +    InsecureSkipVerify bool
    +
    +    // CipherSuites is a list of supported cipher suites. If CipherSuites
    +    // is nil, TLS uses a list of suites supported by the implementation.
    +    CipherSuites []uint16
    +
    +    // PreferServerCipherSuites controls whether the server selects the
    +    // client's most preferred ciphersuite, or the server's most preferred
    +    // ciphersuite. If true then the server's preference, as expressed in
    +    // the order of elements in CipherSuites, is used.
    +    PreferServerCipherSuites bool
    +
    +    // SessionTicketsDisabled may be set to true to disable session ticket
    +    // (resumption) support.
    +    SessionTicketsDisabled bool
    +
    +    // SessionTicketKey is used by TLS servers to provide session
    +    // resumption. See RFC 5077. If zero, it will be filled with
    +    // random data before the first server handshake.
    +    //
    +    // If multiple servers are terminating connections for the same host
    +    // they should all have the same SessionTicketKey. If the
    +    // SessionTicketKey leaks, previously recorded and future TLS
    +    // connections using that key are compromised.
    +    SessionTicketKey [32]byte
    +
    +    // SessionCache is a cache of ClientSessionState entries for TLS session
    +    // resumption.
    +    ClientSessionCache ClientSessionCache
    +
    +    // MinVersion contains the minimum SSL/TLS version that is acceptable.
    +    // If zero, then TLS 1.0 is taken as the minimum.
    +    MinVersion uint16
    +
    +    // MaxVersion contains the maximum SSL/TLS version that is acceptable.
    +    // If zero, then the maximum version supported by this package is used,
    +    // which is currently TLS 1.2.
    +    MaxVersion uint16
    +
    +    // CurvePreferences contains the elliptic curves that will be used in
    +    // an ECDHE handshake, in preference order. If empty, the default will
    +    // be used.
    +    CurvePreferences []CurveID
    +    // contains filtered or unexported fields
    +}
    +

    +A Config structure is used to configure a TLS client or server. +After one has been passed to a TLS function it must not be +modified. A Config may be reused; the tls package will also not +modify it. +

    + + + + + + + + + + + + + + +

    func (*Config) BuildNameToCertificate

    +
    func (c *Config) BuildNameToCertificate()
    +

    +BuildNameToCertificate parses c.Certificates and builds c.NameToCertificate +from the CommonName and SubjectAlternateName fields of each of the leaf +certificates. +

    + + + + + + +

    func (*Config) SetSessionTicketKeys

    +
    func (c *Config) SetSessionTicketKeys(keys [][32]byte)
    +

    +SetSessionTicketKeys updates the session ticket keys for a server. The first +key will be used when creating new tickets, while all keys can be used for +decrypting tickets. It is safe to call this function while the server is +running in order to rotate the session ticket keys. The function will panic +if keys is empty. +

    + + + + + + + + +

    type Conn

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

    +A Conn represents a secured connection. +It implements the net.Conn interface. +

    + + + + + + + + + + + + +

    func Client

    +
    func Client(conn net.Conn, config *Config) *Conn
    +

    +Client returns a new TLS client side connection +using conn as the underlying transport. +The config cannot be nil: users must set either ServerName or +InsecureSkipVerify in the config. +

    + + + + + +

    func Dial

    +
    func Dial(network, addr string, config *Config) (*Conn, error)
    +

    +Dial connects to the given network address using net.Dial +and then initiates a TLS handshake, returning the resulting +TLS connection. +Dial interprets a nil configuration as equivalent to +the zero configuration; see the documentation of Config +for the defaults. +

    + +
    + +
    +

    Example

    + + + +

    Code:

    +
    +// Connecting with a custom root-certificate set.
    +
    +const rootPEM = `
    +-----BEGIN CERTIFICATE-----
    +MIIEBDCCAuygAwIBAgIDAjppMA0GCSqGSIb3DQEBBQUAMEIxCzAJBgNVBAYTAlVT
    +MRYwFAYDVQQKEw1HZW9UcnVzdCBJbmMuMRswGQYDVQQDExJHZW9UcnVzdCBHbG9i
    +YWwgQ0EwHhcNMTMwNDA1MTUxNTU1WhcNMTUwNDA0MTUxNTU1WjBJMQswCQYDVQQG
    +EwJVUzETMBEGA1UEChMKR29vZ2xlIEluYzElMCMGA1UEAxMcR29vZ2xlIEludGVy
    +bmV0IEF1dGhvcml0eSBHMjCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEB
    +AJwqBHdc2FCROgajguDYUEi8iT/xGXAaiEZ+4I/F8YnOIe5a/mENtzJEiaB0C1NP
    +VaTOgmKV7utZX8bhBYASxF6UP7xbSDj0U/ck5vuR6RXEz/RTDfRK/J9U3n2+oGtv
    +h8DQUB8oMANA2ghzUWx//zo8pzcGjr1LEQTrfSTe5vn8MXH7lNVg8y5Kr0LSy+rE
    +ahqyzFPdFUuLH8gZYR/Nnag+YyuENWllhMgZxUYi+FOVvuOAShDGKuy6lyARxzmZ
    +EASg8GF6lSWMTlJ14rbtCMoU/M4iarNOz0YDl5cDfsCx3nuvRTPPuj5xt970JSXC
    +DTWJnZ37DhF5iR43xa+OcmkCAwEAAaOB+zCB+DAfBgNVHSMEGDAWgBTAephojYn7
    +qwVkDBF9qn1luMrMTjAdBgNVHQ4EFgQUSt0GFhu89mi1dvWBtrtiGrpagS8wEgYD
    +VR0TAQH/BAgwBgEB/wIBADAOBgNVHQ8BAf8EBAMCAQYwOgYDVR0fBDMwMTAvoC2g
    +K4YpaHR0cDovL2NybC5nZW90cnVzdC5jb20vY3Jscy9ndGdsb2JhbC5jcmwwPQYI
    +KwYBBQUHAQEEMTAvMC0GCCsGAQUFBzABhiFodHRwOi8vZ3RnbG9iYWwtb2NzcC5n
    +ZW90cnVzdC5jb20wFwYDVR0gBBAwDjAMBgorBgEEAdZ5AgUBMA0GCSqGSIb3DQEB
    +BQUAA4IBAQA21waAESetKhSbOHezI6B1WLuxfoNCunLaHtiONgaX4PCVOzf9G0JY
    +/iLIa704XtE7JW4S615ndkZAkNoUyHgN7ZVm2o6Gb4ChulYylYbc3GrKBIxbf/a/
    +zG+FA1jDaFETzf3I93k9mTXwVqO94FntT0QJo544evZG0R0SnU++0ED8Vf4GXjza
    +HFa9llF7b1cq26KqltyMdMKVvvBulRP/F/A8rLIQjcxz++iPAsbw+zOzlTvjwsto
    +WHPbqCRiOwY1nQ2pM714A5AuTHhdUDqB1O6gyHA43LL5Z/qHQF1hwFGPa4NrzQU6
    +yuGnBXj8ytqU0CwIPX4WecigUCAkVDNx
    +-----END CERTIFICATE-----`
    +
    +// First, create the set of root certificates. For this example we only
    +// have one. It's also possible to omit this in order to use the
    +// default root set of the current operating system.
    +roots := x509.NewCertPool()
    +ok := roots.AppendCertsFromPEM([]byte(rootPEM))
    +if !ok {
    +    panic("failed to parse root certificate")
    +}
    +
    +conn, err := tls.Dial("tcp", "mail.google.com:443", &tls.Config{
    +    RootCAs: roots,
    +})
    +if err != nil {
    +    panic("failed to connect: " + err.Error())
    +}
    +conn.Close()
    +
    + + +
    +
    + + + + +

    func DialWithDialer

    +
    func DialWithDialer(dialer *net.Dialer, network, addr string, config *Config) (*Conn, error)
    +

    +DialWithDialer connects to the given network address using dialer.Dial and +then initiates a TLS handshake, returning the resulting TLS connection. Any +timeout or deadline given in the dialer apply to connection and TLS +handshake as a whole. +

    +

    +DialWithDialer interprets a nil configuration as equivalent to the zero +configuration; see the documentation of Config for the defaults. +

    + + + + + +

    func Server

    +
    func Server(conn net.Conn, config *Config) *Conn
    +

    +Server returns a new TLS server side connection +using conn as the underlying transport. +The configuration config must be non-nil and must include +at least one certificate or else set GetCertificate. +

    + + + + + + + +

    func (*Conn) Close

    +
    func (c *Conn) Close() error
    +

    +Close closes the connection. +

    + + + + + + +

    func (*Conn) ConnectionState

    +
    func (c *Conn) ConnectionState() ConnectionState
    +

    +ConnectionState returns basic TLS details about the connection. +

    + + + + + + +

    func (*Conn) Handshake

    +
    func (c *Conn) Handshake() error
    +

    +Handshake runs the client or server handshake +protocol if it has not yet been run. +Most uses of this package need not call Handshake +explicitly: the first Read or Write will call it automatically. +

    + + + + + + +

    func (*Conn) LocalAddr

    +
    func (c *Conn) LocalAddr() net.Addr
    +

    +LocalAddr returns the local network address. +

    + + + + + + +

    func (*Conn) OCSPResponse

    +
    func (c *Conn) OCSPResponse() []byte
    +

    +OCSPResponse returns the stapled OCSP response from the TLS server, if +any. (Only valid for client connections.) +

    + + + + + + +

    func (*Conn) Read

    +
    func (c *Conn) Read(b []byte) (n int, err error)
    +

    +Read can be made to time out and return a net.Error with Timeout() == true +after a fixed time limit; see SetDeadline and SetReadDeadline. +

    + + + + + + +

    func (*Conn) RemoteAddr

    +
    func (c *Conn) RemoteAddr() net.Addr
    +

    +RemoteAddr returns the remote network address. +

    + + + + + + +

    func (*Conn) SetDeadline

    +
    func (c *Conn) SetDeadline(t time.Time) error
    +

    +SetDeadline sets the read and write deadlines associated with the connection. +A zero value for t means Read and Write will not time out. +After a Write has timed out, the TLS state is corrupt and all future writes will return the same error. +

    + + + + + + +

    func (*Conn) SetReadDeadline

    +
    func (c *Conn) SetReadDeadline(t time.Time) error
    +

    +SetReadDeadline sets the read deadline on the underlying connection. +A zero value for t means Read will not time out. +

    + + + + + + +

    func (*Conn) SetWriteDeadline

    +
    func (c *Conn) SetWriteDeadline(t time.Time) error
    +

    +SetWriteDeadline sets the write deadline on the underlying connection. +A zero value for t means Write will not time out. +After a Write has timed out, the TLS state is corrupt and all future writes will return the same error. +

    + + + + + + +

    func (*Conn) VerifyHostname

    +
    func (c *Conn) VerifyHostname(host string) error
    +

    +VerifyHostname checks that the peer certificate chain is valid for +connecting to host. If so, it returns nil; if not, it returns an error +describing the problem. +

    + + + + + + +

    func (*Conn) Write

    +
    func (c *Conn) Write(b []byte) (int, error)
    +

    +Write writes data to the connection. +

    + + + + + + + + +

    type ConnectionState

    +
    type ConnectionState struct {
    +    Version                     uint16                // TLS version used by the connection (e.g. VersionTLS12)
    +    HandshakeComplete           bool                  // TLS handshake is complete
    +    DidResume                   bool                  // connection resumes a previous TLS connection
    +    CipherSuite                 uint16                // cipher suite in use (TLS_RSA_WITH_RC4_128_SHA, ...)
    +    NegotiatedProtocol          string                // negotiated next protocol (from Config.NextProtos)
    +    NegotiatedProtocolIsMutual  bool                  // negotiated protocol was advertised by server
    +    ServerName                  string                // server name requested by client, if any (server side only)
    +    PeerCertificates            []*x509.Certificate   // certificate chain presented by remote peer
    +    VerifiedChains              [][]*x509.Certificate // verified chains built from PeerCertificates
    +    SignedCertificateTimestamps [][]byte              // SCTs from the server, if any
    +    OCSPResponse                []byte                // stapled OCSP response from server, if any
    +
    +    // TLSUnique contains the "tls-unique" channel binding value (see RFC
    +    // 5929, section 3). For resumed sessions this value will be nil
    +    // because resumption does not include enough context (see
    +    // https://secure-resumption.com/#channelbindings). This will change in
    +    // future versions of Go once the TLS master-secret fix has been
    +    // standardized and implemented.
    +    TLSUnique []byte
    +}
    +

    +ConnectionState records basic TLS details about the connection. +

    + + + + + + + + + + + + + + + + +

    type CurveID

    +
    type CurveID uint16
    +

    +CurveID is the type of a TLS identifier for an elliptic curve. See +http://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-8 +

    + + + +
    const (
    +    CurveP256 CurveID = 23
    +    CurveP384 CurveID = 24
    +    CurveP521 CurveID = 25
    +)
    + + + + + + + + + + + + + + + +

    type RecordHeaderError

    +
    type RecordHeaderError struct {
    +    // Msg contains a human readable string that describes the error.
    +    Msg string
    +    // RecordHeader contains the five bytes of TLS record header that
    +    // triggered the error.
    +    RecordHeader [5]byte
    +}
    +

    +RecordHeaderError results when a TLS record header is invalid. +

    + + + + + + + + + + + + + + +

    func (RecordHeaderError) Error

    +
    func (e RecordHeaderError) Error() string
    + + + + + + + + + + +

    Bugs

    +
      + +
    • The crypto/tls package does not implement countermeasures +against Lucky13 attacks on CBC-mode encryption. See +http://www.isg.rhul.ac.uk/tls/TLStiming.pdf and +https://www.imperialviolet.org/2013/02/04/luckythirteen.html. +
    • + +
    + + + + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/crypto/x509/index.html b/pkg/crypto/x509/index.html new file mode 100644 index 0000000..6f86750 --- /dev/null +++ b/pkg/crypto/x509/index.html @@ -0,0 +1,1602 @@ + + + + + + + + x509 - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Package x509

    + + + + + + + + + + + + + + +
    +
    +
    import "crypto/x509"
    +
    +
    +
    Overview
    +
    Index
    + +
    Examples
    + + +
    Subdirectories
    + +
    +
    + +
    + +
    +

    Overview ▾

    +

    +Package x509 parses X.509-encoded keys and certificates. +

    + +
    +
    + + +
    + +
    +

    Index ▾

    + + +
    +
    + + +
    Variables
    + + + +
    func CreateCertificate(rand io.Reader, template, parent *Certificate, pub, priv interface{}) (cert []byte, err error)
    + + +
    func CreateCertificateRequest(rand io.Reader, template *CertificateRequest, priv interface{}) (csr []byte, err error)
    + + +
    func DecryptPEMBlock(b *pem.Block, password []byte) ([]byte, error)
    + + +
    func EncryptPEMBlock(rand io.Reader, blockType string, data, password []byte, alg PEMCipher) (*pem.Block, error)
    + + +
    func IsEncryptedPEMBlock(b *pem.Block) bool
    + + +
    func MarshalECPrivateKey(key *ecdsa.PrivateKey) ([]byte, error)
    + + +
    func MarshalPKCS1PrivateKey(key *rsa.PrivateKey) []byte
    + + +
    func MarshalPKIXPublicKey(pub interface{}) ([]byte, error)
    + + +
    func ParseCRL(crlBytes []byte) (certList *pkix.CertificateList, err error)
    + + +
    func ParseCertificates(asn1Data []byte) ([]*Certificate, error)
    + + +
    func ParseDERCRL(derBytes []byte) (certList *pkix.CertificateList, err error)
    + + +
    func ParseECPrivateKey(der []byte) (key *ecdsa.PrivateKey, err error)
    + + +
    func ParsePKCS1PrivateKey(der []byte) (key *rsa.PrivateKey, err error)
    + + +
    func ParsePKCS8PrivateKey(der []byte) (key interface{}, err error)
    + + +
    func ParsePKIXPublicKey(derBytes []byte) (pub interface{}, err error)
    + + + +
    type CertPool
    + + +
        func NewCertPool() *CertPool
    + + + +
        func (s *CertPool) AddCert(cert *Certificate)
    + + +
        func (s *CertPool) AppendCertsFromPEM(pemCerts []byte) (ok bool)
    + + +
        func (s *CertPool) Subjects() (res [][]byte)
    + + + +
    type Certificate
    + + +
        func ParseCertificate(asn1Data []byte) (*Certificate, error)
    + + + +
        func (c *Certificate) CheckCRLSignature(crl *pkix.CertificateList) (err error)
    + + +
        func (c *Certificate) CheckSignature(algo SignatureAlgorithm, signed, signature []byte) (err error)
    + + +
        func (c *Certificate) CheckSignatureFrom(parent *Certificate) (err error)
    + + +
        func (c *Certificate) CreateCRL(rand io.Reader, priv interface{}, revokedCerts []pkix.RevokedCertificate, now, expiry time.Time) (crlBytes []byte, err error)
    + + +
        func (c *Certificate) Equal(other *Certificate) bool
    + + +
        func (c *Certificate) Verify(opts VerifyOptions) (chains [][]*Certificate, err error)
    + + +
        func (c *Certificate) VerifyHostname(h string) error
    + + + +
    type CertificateInvalidError
    + + + +
        func (e CertificateInvalidError) Error() string
    + + + +
    type CertificateRequest
    + + +
        func ParseCertificateRequest(asn1Data []byte) (*CertificateRequest, error)
    + + + +
        func (c *CertificateRequest) CheckSignature() (err error)
    + + + +
    type ConstraintViolationError
    + + + +
        func (ConstraintViolationError) Error() string
    + + + +
    type ExtKeyUsage
    + + + + +
    type HostnameError
    + + + +
        func (h HostnameError) Error() string
    + + + +
    type InsecureAlgorithmError
    + + + +
        func (e InsecureAlgorithmError) Error() string
    + + + +
    type InvalidReason
    + + + + +
    type KeyUsage
    + + + + +
    type PEMCipher
    + + + + +
    type PublicKeyAlgorithm
    + + + + +
    type SignatureAlgorithm
    + + + +
        func (algo SignatureAlgorithm) String() string
    + + + +
    type SystemRootsError
    + + + +
        func (SystemRootsError) Error() string
    + + + +
    type UnhandledCriticalExtension
    + + + +
        func (h UnhandledCriticalExtension) Error() string
    + + + +
    type UnknownAuthorityError
    + + + +
        func (e UnknownAuthorityError) Error() string
    + + + +
    type VerifyOptions
    + + + + +
    +
    + + +
    +

    Examples

    +
    + +
    Certificate.Verify
    + +
    +
    + + + +

    Package files

    +

    + + + cert_pool.go + + pem_decrypt.go + + pkcs1.go + + pkcs8.go + + root.go + + root_linux.go + + root_unix.go + + sec1.go + + verify.go + + x509.go + + +

    + +
    +
    + + + + + +

    Variables

    + +
    var ErrUnsupportedAlgorithm = errors.New("x509: cannot verify signature: algorithm unimplemented")
    +

    +ErrUnsupportedAlgorithm results from attempting to perform an operation that +involves algorithms that are not currently implemented. +

    + + +
    var IncorrectPasswordError = errors.New("x509: decryption password incorrect")
    +

    +IncorrectPasswordError is returned when an incorrect password is detected. +

    + + + + + + +

    func CreateCertificate

    +
    func CreateCertificate(rand io.Reader, template, parent *Certificate, pub, priv interface{}) (cert []byte, err error)
    +

    +CreateCertificate creates a new certificate based on a template. The +following members of template are used: SerialNumber, Subject, NotBefore, +NotAfter, KeyUsage, ExtKeyUsage, UnknownExtKeyUsage, BasicConstraintsValid, +IsCA, MaxPathLen, SubjectKeyId, DNSNames, PermittedDNSDomainsCritical, +PermittedDNSDomains, SignatureAlgorithm. +

    +

    +The certificate is signed by parent. If parent is equal to template then the +certificate is self-signed. The parameter pub is the public key of the +signee and priv is the private key of the signer. +

    +

    +The returned slice is the certificate in DER encoding. +

    +

    +All keys types that are implemented via crypto.Signer are supported (This +includes *rsa.PublicKey and *ecdsa.PublicKey.) +

    + + + + + + + +

    func CreateCertificateRequest

    +
    func CreateCertificateRequest(rand io.Reader, template *CertificateRequest, priv interface{}) (csr []byte, err error)
    +

    +CreateCertificateRequest creates a new certificate based on a template. The +following members of template are used: Subject, Attributes, +SignatureAlgorithm, Extensions, DNSNames, EmailAddresses, and IPAddresses. +The private key is the private key of the signer. +

    +

    +The returned slice is the certificate request in DER encoding. +

    +

    +All keys types that are implemented via crypto.Signer are supported (This +includes *rsa.PublicKey and *ecdsa.PublicKey.) +

    + + + + + + + +

    func DecryptPEMBlock

    +
    func DecryptPEMBlock(b *pem.Block, password []byte) ([]byte, error)
    +

    +DecryptPEMBlock takes a password encrypted PEM block and the password used to +encrypt it and returns a slice of decrypted DER encoded bytes. It inspects +the DEK-Info header to determine the algorithm used for decryption. If no +DEK-Info header is present, an error is returned. If an incorrect password +is detected an IncorrectPasswordError is returned. Because of deficiencies +in the encrypted-PEM format, it's not always possible to detect an incorrect +password. In these cases no error will be returned but the decrypted DER +bytes will be random noise. +

    + + + + + + + +

    func EncryptPEMBlock

    +
    func EncryptPEMBlock(rand io.Reader, blockType string, data, password []byte, alg PEMCipher) (*pem.Block, error)
    +

    +EncryptPEMBlock returns a PEM block of the specified type holding the +given DER-encoded data encrypted with the specified algorithm and +password. +

    + + + + + + + +

    func IsEncryptedPEMBlock

    +
    func IsEncryptedPEMBlock(b *pem.Block) bool
    +

    +IsEncryptedPEMBlock returns if the PEM block is password encrypted. +

    + + + + + + + +

    func MarshalECPrivateKey

    +
    func MarshalECPrivateKey(key *ecdsa.PrivateKey) ([]byte, error)
    +

    +MarshalECPrivateKey marshals an EC private key into ASN.1, DER format. +

    + + + + + + + +

    func MarshalPKCS1PrivateKey

    +
    func MarshalPKCS1PrivateKey(key *rsa.PrivateKey) []byte
    +

    +MarshalPKCS1PrivateKey converts a private key to ASN.1 DER encoded form. +

    + + + + + + + +

    func MarshalPKIXPublicKey

    +
    func MarshalPKIXPublicKey(pub interface{}) ([]byte, error)
    +

    +MarshalPKIXPublicKey serialises a public key to DER-encoded PKIX format. +

    + + + + + + + +

    func ParseCRL

    +
    func ParseCRL(crlBytes []byte) (certList *pkix.CertificateList, err error)
    +

    +ParseCRL parses a CRL from the given bytes. It's often the case that PEM +encoded CRLs will appear where they should be DER encoded, so this function +will transparently handle PEM encoding as long as there isn't any leading +garbage. +

    + + + + + + + +

    func ParseCertificates

    +
    func ParseCertificates(asn1Data []byte) ([]*Certificate, error)
    +

    +ParseCertificates parses one or more certificates from the given ASN.1 DER +data. The certificates must be concatenated with no intermediate padding. +

    + + + + + + + +

    func ParseDERCRL

    +
    func ParseDERCRL(derBytes []byte) (certList *pkix.CertificateList, err error)
    +

    +ParseDERCRL parses a DER encoded CRL from the given bytes. +

    + + + + + + + +

    func ParseECPrivateKey

    +
    func ParseECPrivateKey(der []byte) (key *ecdsa.PrivateKey, err error)
    +

    +ParseECPrivateKey parses an ASN.1 Elliptic Curve Private Key Structure. +

    + + + + + + + +

    func ParsePKCS1PrivateKey

    +
    func ParsePKCS1PrivateKey(der []byte) (key *rsa.PrivateKey, err error)
    +

    +ParsePKCS1PrivateKey returns an RSA private key from its ASN.1 PKCS#1 DER encoded form. +

    + + + + + + + +

    func ParsePKCS8PrivateKey

    +
    func ParsePKCS8PrivateKey(der []byte) (key interface{}, err error)
    +

    +ParsePKCS8PrivateKey parses an unencrypted, PKCS#8 private key. See +http://www.rsa.com/rsalabs/node.asp?id=2130 and RFC5208. +

    + + + + + + + +

    func ParsePKIXPublicKey

    +
    func ParsePKIXPublicKey(derBytes []byte) (pub interface{}, err error)
    +

    +ParsePKIXPublicKey parses a DER encoded public key. These values are +typically found in PEM blocks with "BEGIN PUBLIC KEY". +

    + + + + + + + + +

    type CertPool

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

    +CertPool is a set of certificates. +

    + + + + + + + + + + + + +

    func NewCertPool

    +
    func NewCertPool() *CertPool
    +

    +NewCertPool returns a new, empty CertPool. +

    + + + + + + + +

    func (*CertPool) AddCert

    +
    func (s *CertPool) AddCert(cert *Certificate)
    +

    +AddCert adds a certificate to a pool. +

    + + + + + + +

    func (*CertPool) AppendCertsFromPEM

    +
    func (s *CertPool) AppendCertsFromPEM(pemCerts []byte) (ok bool)
    +

    +AppendCertsFromPEM attempts to parse a series of PEM encoded certificates. +It appends any certificates found to s and reports whether any certificates +were successfully parsed. +

    +

    +On many Linux systems, /etc/ssl/cert.pem will contain the system wide set +of root CAs in a format suitable for this function. +

    + + + + + + +

    func (*CertPool) Subjects

    +
    func (s *CertPool) Subjects() (res [][]byte)
    +

    +Subjects returns a list of the DER-encoded subjects of +all of the certificates in the pool. +

    + + + + + + + + +

    type Certificate

    +
    type Certificate struct {
    +    Raw                     []byte // Complete ASN.1 DER content (certificate, signature algorithm and signature).
    +    RawTBSCertificate       []byte // Certificate part of raw ASN.1 DER content.
    +    RawSubjectPublicKeyInfo []byte // DER encoded SubjectPublicKeyInfo.
    +    RawSubject              []byte // DER encoded Subject
    +    RawIssuer               []byte // DER encoded Issuer
    +
    +    Signature          []byte
    +    SignatureAlgorithm SignatureAlgorithm
    +
    +    PublicKeyAlgorithm PublicKeyAlgorithm
    +    PublicKey          interface{}
    +
    +    Version             int
    +    SerialNumber        *big.Int
    +    Issuer              pkix.Name
    +    Subject             pkix.Name
    +    NotBefore, NotAfter time.Time // Validity bounds.
    +    KeyUsage            KeyUsage
    +
    +    // Extensions contains raw X.509 extensions. When parsing certificates,
    +    // this can be used to extract non-critical extensions that are not
    +    // parsed by this package. When marshaling certificates, the Extensions
    +    // field is ignored, see ExtraExtensions.
    +    Extensions []pkix.Extension
    +
    +    // ExtraExtensions contains extensions to be copied, raw, into any
    +    // marshaled certificates. Values override any extensions that would
    +    // otherwise be produced based on the other fields. The ExtraExtensions
    +    // field is not populated when parsing certificates, see Extensions.
    +    ExtraExtensions []pkix.Extension
    +
    +    // UnhandledCriticalExtensions contains a list of extension IDs that
    +    // were not (fully) processed when parsing. Verify will fail if this
    +    // slice is non-empty, unless verification is delegated to an OS
    +    // library which understands all the critical extensions.
    +    //
    +    // Users can access these extensions using Extensions and can remove
    +    // elements from this slice if they believe that they have been
    +    // handled.
    +    UnhandledCriticalExtensions []asn1.ObjectIdentifier
    +
    +    ExtKeyUsage        []ExtKeyUsage           // Sequence of extended key usages.
    +    UnknownExtKeyUsage []asn1.ObjectIdentifier // Encountered extended key usages unknown to this package.
    +
    +    BasicConstraintsValid bool // if true then the next two fields are valid.
    +    IsCA                  bool
    +    MaxPathLen            int
    +    // MaxPathLenZero indicates that BasicConstraintsValid==true and
    +    // MaxPathLen==0 should be interpreted as an actual maximum path length
    +    // of zero. Otherwise, that combination is interpreted as MaxPathLen
    +    // not being set.
    +    MaxPathLenZero bool
    +
    +    SubjectKeyId   []byte
    +    AuthorityKeyId []byte
    +
    +    // RFC 5280, 4.2.2.1 (Authority Information Access)
    +    OCSPServer            []string
    +    IssuingCertificateURL []string
    +
    +    // Subject Alternate Name values
    +    DNSNames       []string
    +    EmailAddresses []string
    +    IPAddresses    []net.IP
    +
    +    // Name constraints
    +    PermittedDNSDomainsCritical bool // if true then the name constraints are marked critical.
    +    PermittedDNSDomains         []string
    +
    +    // CRL Distribution Points
    +    CRLDistributionPoints []string
    +
    +    PolicyIdentifiers []asn1.ObjectIdentifier
    +}
    +

    +A Certificate represents an X.509 certificate. +

    + + + + + + + + + + + + +

    func ParseCertificate

    +
    func ParseCertificate(asn1Data []byte) (*Certificate, error)
    +

    +ParseCertificate parses a single certificate from the given ASN.1 DER data. +

    + + + + + + + +

    func (*Certificate) CheckCRLSignature

    +
    func (c *Certificate) CheckCRLSignature(crl *pkix.CertificateList) (err error)
    +

    +CheckCRLSignature checks that the signature in crl is from c. +

    + + + + + + +

    func (*Certificate) CheckSignature

    +
    func (c *Certificate) CheckSignature(algo SignatureAlgorithm, signed, signature []byte) (err error)
    +

    +CheckSignature verifies that signature is a valid signature over signed from +c's public key. +

    + + + + + + +

    func (*Certificate) CheckSignatureFrom

    +
    func (c *Certificate) CheckSignatureFrom(parent *Certificate) (err error)
    +

    +CheckSignatureFrom verifies that the signature on c is a valid signature +from parent. +

    + + + + + + +

    func (*Certificate) CreateCRL

    +
    func (c *Certificate) CreateCRL(rand io.Reader, priv interface{}, revokedCerts []pkix.RevokedCertificate, now, expiry time.Time) (crlBytes []byte, err error)
    +

    +CreateCRL returns a DER encoded CRL, signed by this Certificate, that +contains the given list of revoked certificates. +

    + + + + + + +

    func (*Certificate) Equal

    +
    func (c *Certificate) Equal(other *Certificate) bool
    + + + + + + +

    func (*Certificate) Verify

    +
    func (c *Certificate) Verify(opts VerifyOptions) (chains [][]*Certificate, err error)
    +

    +Verify attempts to verify c by building one or more chains from c to a +certificate in opts.Roots, using certificates in opts.Intermediates if +needed. If successful, it returns one or more chains where the first +element of the chain is c and the last element is from opts.Roots. +

    +

    +If opts.Roots is nil and system roots are unavailable the returned error +will be of type SystemRootsError. +

    +

    +WARNING: this doesn't do any revocation checking. +

    + + +
    + +
    +

    Example

    + + + +

    Code:

    +
    +// Verifying with a custom list of root certificates.
    +
    +const rootPEM = `
    +-----BEGIN CERTIFICATE-----
    +MIIEBDCCAuygAwIBAgIDAjppMA0GCSqGSIb3DQEBBQUAMEIxCzAJBgNVBAYTAlVT
    +MRYwFAYDVQQKEw1HZW9UcnVzdCBJbmMuMRswGQYDVQQDExJHZW9UcnVzdCBHbG9i
    +YWwgQ0EwHhcNMTMwNDA1MTUxNTU1WhcNMTUwNDA0MTUxNTU1WjBJMQswCQYDVQQG
    +EwJVUzETMBEGA1UEChMKR29vZ2xlIEluYzElMCMGA1UEAxMcR29vZ2xlIEludGVy
    +bmV0IEF1dGhvcml0eSBHMjCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEB
    +AJwqBHdc2FCROgajguDYUEi8iT/xGXAaiEZ+4I/F8YnOIe5a/mENtzJEiaB0C1NP
    +VaTOgmKV7utZX8bhBYASxF6UP7xbSDj0U/ck5vuR6RXEz/RTDfRK/J9U3n2+oGtv
    +h8DQUB8oMANA2ghzUWx//zo8pzcGjr1LEQTrfSTe5vn8MXH7lNVg8y5Kr0LSy+rE
    +ahqyzFPdFUuLH8gZYR/Nnag+YyuENWllhMgZxUYi+FOVvuOAShDGKuy6lyARxzmZ
    +EASg8GF6lSWMTlJ14rbtCMoU/M4iarNOz0YDl5cDfsCx3nuvRTPPuj5xt970JSXC
    +DTWJnZ37DhF5iR43xa+OcmkCAwEAAaOB+zCB+DAfBgNVHSMEGDAWgBTAephojYn7
    +qwVkDBF9qn1luMrMTjAdBgNVHQ4EFgQUSt0GFhu89mi1dvWBtrtiGrpagS8wEgYD
    +VR0TAQH/BAgwBgEB/wIBADAOBgNVHQ8BAf8EBAMCAQYwOgYDVR0fBDMwMTAvoC2g
    +K4YpaHR0cDovL2NybC5nZW90cnVzdC5jb20vY3Jscy9ndGdsb2JhbC5jcmwwPQYI
    +KwYBBQUHAQEEMTAvMC0GCCsGAQUFBzABhiFodHRwOi8vZ3RnbG9iYWwtb2NzcC5n
    +ZW90cnVzdC5jb20wFwYDVR0gBBAwDjAMBgorBgEEAdZ5AgUBMA0GCSqGSIb3DQEB
    +BQUAA4IBAQA21waAESetKhSbOHezI6B1WLuxfoNCunLaHtiONgaX4PCVOzf9G0JY
    +/iLIa704XtE7JW4S615ndkZAkNoUyHgN7ZVm2o6Gb4ChulYylYbc3GrKBIxbf/a/
    +zG+FA1jDaFETzf3I93k9mTXwVqO94FntT0QJo544evZG0R0SnU++0ED8Vf4GXjza
    +HFa9llF7b1cq26KqltyMdMKVvvBulRP/F/A8rLIQjcxz++iPAsbw+zOzlTvjwsto
    +WHPbqCRiOwY1nQ2pM714A5AuTHhdUDqB1O6gyHA43LL5Z/qHQF1hwFGPa4NrzQU6
    +yuGnBXj8ytqU0CwIPX4WecigUCAkVDNx
    +-----END CERTIFICATE-----`
    +
    +const certPEM = `
    +-----BEGIN CERTIFICATE-----
    +MIIDujCCAqKgAwIBAgIIE31FZVaPXTUwDQYJKoZIhvcNAQEFBQAwSTELMAkGA1UE
    +BhMCVVMxEzARBgNVBAoTCkdvb2dsZSBJbmMxJTAjBgNVBAMTHEdvb2dsZSBJbnRl
    +cm5ldCBBdXRob3JpdHkgRzIwHhcNMTQwMTI5MTMyNzQzWhcNMTQwNTI5MDAwMDAw
    +WjBpMQswCQYDVQQGEwJVUzETMBEGA1UECAwKQ2FsaWZvcm5pYTEWMBQGA1UEBwwN
    +TW91bnRhaW4gVmlldzETMBEGA1UECgwKR29vZ2xlIEluYzEYMBYGA1UEAwwPbWFp
    +bC5nb29nbGUuY29tMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEfRrObuSW5T7q
    +5CnSEqefEmtH4CCv6+5EckuriNr1CjfVvqzwfAhopXkLrq45EQm8vkmf7W96XJhC
    +7ZM0dYi1/qOCAU8wggFLMB0GA1UdJQQWMBQGCCsGAQUFBwMBBggrBgEFBQcDAjAa
    +BgNVHREEEzARgg9tYWlsLmdvb2dsZS5jb20wCwYDVR0PBAQDAgeAMGgGCCsGAQUF
    +BwEBBFwwWjArBggrBgEFBQcwAoYfaHR0cDovL3BraS5nb29nbGUuY29tL0dJQUcy
    +LmNydDArBggrBgEFBQcwAYYfaHR0cDovL2NsaWVudHMxLmdvb2dsZS5jb20vb2Nz
    +cDAdBgNVHQ4EFgQUiJxtimAuTfwb+aUtBn5UYKreKvMwDAYDVR0TAQH/BAIwADAf
    +BgNVHSMEGDAWgBRK3QYWG7z2aLV29YG2u2IaulqBLzAXBgNVHSAEEDAOMAwGCisG
    +AQQB1nkCBQEwMAYDVR0fBCkwJzAloCOgIYYfaHR0cDovL3BraS5nb29nbGUuY29t
    +L0dJQUcyLmNybDANBgkqhkiG9w0BAQUFAAOCAQEAH6RYHxHdcGpMpFE3oxDoFnP+
    +gtuBCHan2yE2GRbJ2Cw8Lw0MmuKqHlf9RSeYfd3BXeKkj1qO6TVKwCh+0HdZk283
    +TZZyzmEOyclm3UGFYe82P/iDFt+CeQ3NpmBg+GoaVCuWAARJN/KfglbLyyYygcQq
    +0SgeDh8dRKUiaW3HQSoYvTvdTuqzwK4CXsr3b5/dAOY8uMuG/IAR3FgwTbZ1dtoW
    +RvOTa8hYiU6A475WuZKyEHcwnGYe57u2I2KbMgcKjPniocj4QzgYsVAVKW3IwaOh
    +yE+vPxsiUkvQHdO2fojCkY8jg70jxM+gu59tPDNbw3Uh/2Ij310FgTHsnGQMyA==
    +-----END CERTIFICATE-----`
    +
    +// First, create the set of root certificates. For this example we only
    +// have one. It's also possible to omit this in order to use the
    +// default root set of the current operating system.
    +roots := x509.NewCertPool()
    +ok := roots.AppendCertsFromPEM([]byte(rootPEM))
    +if !ok {
    +    panic("failed to parse root certificate")
    +}
    +
    +block, _ := pem.Decode([]byte(certPEM))
    +if block == nil {
    +    panic("failed to parse certificate PEM")
    +}
    +cert, err := x509.ParseCertificate(block.Bytes)
    +if err != nil {
    +    panic("failed to parse certificate: " + err.Error())
    +}
    +
    +opts := x509.VerifyOptions{
    +    DNSName: "mail.google.com",
    +    Roots:   roots,
    +}
    +
    +if _, err := cert.Verify(opts); err != nil {
    +    panic("failed to verify certificate: " + err.Error())
    +}
    +
    + + +
    +
    + + + + +

    func (*Certificate) VerifyHostname

    +
    func (c *Certificate) VerifyHostname(h string) error
    +

    +VerifyHostname returns nil if c is a valid certificate for the named host. +Otherwise it returns an error describing the mismatch. +

    + + + + + + + + +

    type CertificateInvalidError

    +
    type CertificateInvalidError struct {
    +    Cert   *Certificate
    +    Reason InvalidReason
    +}
    +

    +CertificateInvalidError results when an odd error occurs. Users of this +library probably want to handle all these errors uniformly. +

    + + + + + + + + + + + + + + +

    func (CertificateInvalidError) Error

    +
    func (e CertificateInvalidError) Error() string
    + + + + + + + + +

    type CertificateRequest

    +
    type CertificateRequest struct {
    +    Raw                      []byte // Complete ASN.1 DER content (CSR, signature algorithm and signature).
    +    RawTBSCertificateRequest []byte // Certificate request info part of raw ASN.1 DER content.
    +    RawSubjectPublicKeyInfo  []byte // DER encoded SubjectPublicKeyInfo.
    +    RawSubject               []byte // DER encoded Subject.
    +
    +    Version            int
    +    Signature          []byte
    +    SignatureAlgorithm SignatureAlgorithm
    +
    +    PublicKeyAlgorithm PublicKeyAlgorithm
    +    PublicKey          interface{}
    +
    +    Subject pkix.Name
    +
    +    // Attributes is the dried husk of a bug and shouldn't be used.
    +    Attributes []pkix.AttributeTypeAndValueSET
    +
    +    // Extensions contains raw X.509 extensions. When parsing CSRs, this
    +    // can be used to extract extensions that are not parsed by this
    +    // package.
    +    Extensions []pkix.Extension
    +
    +    // ExtraExtensions contains extensions to be copied, raw, into any
    +    // marshaled CSR. Values override any extensions that would otherwise
    +    // be produced based on the other fields but are overridden by any
    +    // extensions specified in Attributes.
    +    //
    +    // The ExtraExtensions field is not populated when parsing CSRs, see
    +    // Extensions.
    +    ExtraExtensions []pkix.Extension
    +
    +    // Subject Alternate Name values.
    +    DNSNames       []string
    +    EmailAddresses []string
    +    IPAddresses    []net.IP
    +}
    +

    +CertificateRequest represents a PKCS #10, certificate signature request. +

    + + + + + + + + + + + + +

    func ParseCertificateRequest

    +
    func ParseCertificateRequest(asn1Data []byte) (*CertificateRequest, error)
    +

    +ParseCertificateRequest parses a single certificate request from the +given ASN.1 DER data. +

    + + + + + + + +

    func (*CertificateRequest) CheckSignature

    +
    func (c *CertificateRequest) CheckSignature() (err error)
    +

    +CheckSignature verifies that the signature on c is a valid signature +

    + + + + + + + + +

    type ConstraintViolationError

    +
    type ConstraintViolationError struct{}
    +

    +ConstraintViolationError results when a requested usage is not permitted by +a certificate. For example: checking a signature when the public key isn't a +certificate signing key. +

    + + + + + + + + + + + + + + +

    func (ConstraintViolationError) Error

    +
    func (ConstraintViolationError) Error() string
    + + + + + + + + +

    type ExtKeyUsage

    +
    type ExtKeyUsage int
    +

    +ExtKeyUsage represents an extended set of actions that are valid for a given key. +Each of the ExtKeyUsage* constants define a unique action. +

    + + + +
    const (
    +    ExtKeyUsageAny ExtKeyUsage = iota
    +    ExtKeyUsageServerAuth
    +    ExtKeyUsageClientAuth
    +    ExtKeyUsageCodeSigning
    +    ExtKeyUsageEmailProtection
    +    ExtKeyUsageIPSECEndSystem
    +    ExtKeyUsageIPSECTunnel
    +    ExtKeyUsageIPSECUser
    +    ExtKeyUsageTimeStamping
    +    ExtKeyUsageOCSPSigning
    +    ExtKeyUsageMicrosoftServerGatedCrypto
    +    ExtKeyUsageNetscapeServerGatedCrypto
    +)
    + + + + + + + + + + + + + + + +

    type HostnameError

    +
    type HostnameError struct {
    +    Certificate *Certificate
    +    Host        string
    +}
    +

    +HostnameError results when the set of authorized names doesn't match the +requested name. +

    + + + + + + + + + + + + + + +

    func (HostnameError) Error

    +
    func (h HostnameError) Error() string
    + + + + + + + + +

    type InsecureAlgorithmError

    +
    type InsecureAlgorithmError SignatureAlgorithm
    +

    +An InsecureAlgorithmError +

    + + + + + + + + + + + + + + +

    func (InsecureAlgorithmError) Error

    +
    func (e InsecureAlgorithmError) Error() string
    + + + + + + + + +

    type InvalidReason

    +
    type InvalidReason int
    + + + +
    const (
    +    // NotAuthorizedToSign results when a certificate is signed by another
    +    // which isn't marked as a CA certificate.
    +    NotAuthorizedToSign InvalidReason = iota
    +    // Expired results when a certificate has expired, based on the time
    +    // given in the VerifyOptions.
    +    Expired
    +    // CANotAuthorizedForThisName results when an intermediate or root
    +    // certificate has a name constraint which doesn't include the name
    +    // being checked.
    +    CANotAuthorizedForThisName
    +    // TooManyIntermediates results when a path length constraint is
    +    // violated.
    +    TooManyIntermediates
    +    // IncompatibleUsage results when the certificate's key usage indicates
    +    // that it may only be used for a different purpose.
    +    IncompatibleUsage
    +)
    + + + + + + + + + + + + + + + +

    type KeyUsage

    +
    type KeyUsage int
    +

    +KeyUsage represents the set of actions that are valid for a given key. It's +a bitmap of the KeyUsage* constants. +

    + + + +
    const (
    +    KeyUsageDigitalSignature KeyUsage = 1 << iota
    +    KeyUsageContentCommitment
    +    KeyUsageKeyEncipherment
    +    KeyUsageDataEncipherment
    +    KeyUsageKeyAgreement
    +    KeyUsageCertSign
    +    KeyUsageCRLSign
    +    KeyUsageEncipherOnly
    +    KeyUsageDecipherOnly
    +)
    + + + + + + + + + + + + + + + +

    type PEMCipher

    +
    type PEMCipher int
    + + + +
    const (
    +    PEMCipherDES PEMCipher
    +    PEMCipher3DES
    +    PEMCipherAES128
    +    PEMCipherAES192
    +    PEMCipherAES256
    +)
    +

    +Possible values for the EncryptPEMBlock encryption algorithm. +

    + + + + + + + + + + + + + + + +

    type PublicKeyAlgorithm

    +
    type PublicKeyAlgorithm int
    + + + +
    const (
    +    UnknownPublicKeyAlgorithm PublicKeyAlgorithm = iota
    +    RSA
    +    DSA
    +    ECDSA
    +)
    + + + + + + + + + + + + + + + +

    type SignatureAlgorithm

    +
    type SignatureAlgorithm int
    + + + +
    const (
    +    UnknownSignatureAlgorithm SignatureAlgorithm = iota
    +    MD2WithRSA
    +    MD5WithRSA
    +    SHA1WithRSA
    +    SHA256WithRSA
    +    SHA384WithRSA
    +    SHA512WithRSA
    +    DSAWithSHA1
    +    DSAWithSHA256
    +    ECDSAWithSHA1
    +    ECDSAWithSHA256
    +    ECDSAWithSHA384
    +    ECDSAWithSHA512
    +)
    + + + + + + + + + + + + + +

    func (SignatureAlgorithm) String

    +
    func (algo SignatureAlgorithm) String() string
    + + + + + + + + +

    type SystemRootsError

    +
    type SystemRootsError struct{}
    +

    +SystemRootsError results when we fail to load the system root certificates. +

    + + + + + + + + + + + + + + +

    func (SystemRootsError) Error

    +
    func (SystemRootsError) Error() string
    + + + + + + + + +

    type UnhandledCriticalExtension

    +
    type UnhandledCriticalExtension struct{}
    + + + + + + + + + + + + + + +

    func (UnhandledCriticalExtension) Error

    +
    func (h UnhandledCriticalExtension) Error() string
    + + + + + + + + +

    type UnknownAuthorityError

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

    +UnknownAuthorityError results when the certificate issuer is unknown +

    + + + + + + + + + + + + + + +

    func (UnknownAuthorityError) Error

    +
    func (e UnknownAuthorityError) Error() string
    + + + + + + + + +

    type VerifyOptions

    +
    type VerifyOptions struct {
    +    DNSName       string
    +    Intermediates *CertPool
    +    Roots         *CertPool // if nil, the system roots are used
    +    CurrentTime   time.Time // if zero, the current time is used
    +    // KeyUsage specifies which Extended Key Usage values are acceptable.
    +    // An empty list means ExtKeyUsageServerAuth. Key usage is considered a
    +    // constraint down the chain which mirrors Windows CryptoAPI behaviour,
    +    // but not the spec. To accept any key usage, include ExtKeyUsageAny.
    +    KeyUsages []ExtKeyUsage
    +}
    +

    +VerifyOptions contains parameters for Certificate.Verify. It's a structure +because other PKIX verification APIs have ended up needing many options. +

    + + + + + + + + + + + + + + + + + + + + + + + + +

    Subdirectories

    + + + + +
    + + + + + + + + + + + + + + + + + + + + +
    NameSynopsis
    ..
    + pkix + + Package pkix contains shared, low level structures used for ASN.1 parsing and serialization of X.509 certificates, CRL and OCSP. +
    +
    + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/crypto/x509/pkix/index.html b/pkg/crypto/x509/pkix/index.html new file mode 100644 index 0000000..e0f90ea --- /dev/null +++ b/pkg/crypto/x509/pkix/index.html @@ -0,0 +1,545 @@ + + + + + + + + pkix - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Package pkix

    + + + + + + + + + + + + + + +
    +
    +
    import "crypto/x509/pkix"
    +
    +
    +
    Overview
    +
    Index
    + + +
    +
    + +
    + +
    +

    Overview ▾

    +

    +Package pkix contains shared, low level structures used for ASN.1 parsing +and serialization of X.509 certificates, CRL and OCSP. +

    + +
    +
    + + + + + + + + + + + + +

    type AlgorithmIdentifier

    +
    type AlgorithmIdentifier struct {
    +    Algorithm  asn1.ObjectIdentifier
    +    Parameters asn1.RawValue `asn1:"optional"`
    +}
    +

    +AlgorithmIdentifier represents the ASN.1 structure of the same name. See RFC +5280, section 4.1.1.2. +

    + + + + + + + + + + + + + + + + +

    type AttributeTypeAndValue

    +
    type AttributeTypeAndValue struct {
    +    Type  asn1.ObjectIdentifier
    +    Value interface{}
    +}
    +

    +AttributeTypeAndValue mirrors the ASN.1 structure of the same name in +http://tools.ietf.org/html/rfc5280#section-4.1.2.4 +

    + + + + + + + + + + + + + + + + +

    type AttributeTypeAndValueSET

    +
    type AttributeTypeAndValueSET struct {
    +    Type  asn1.ObjectIdentifier
    +    Value [][]AttributeTypeAndValue `asn1:"set"`
    +}
    +

    +AttributeTypeAndValueSET represents a set of ASN.1 sequences of +AttributeTypeAndValue sequences from RFC 2986 (PKCS #10). +

    + + + + + + + + + + + + + + + + +

    type CertificateList

    +
    type CertificateList struct {
    +    TBSCertList        TBSCertificateList
    +    SignatureAlgorithm AlgorithmIdentifier
    +    SignatureValue     asn1.BitString
    +}
    +

    +CertificateList represents the ASN.1 structure of the same name. See RFC +5280, section 5.1. Use Certificate.CheckCRLSignature to verify the +signature. +

    + + + + + + + + + + + + + + +

    func (*CertificateList) HasExpired

    +
    func (certList *CertificateList) HasExpired(now time.Time) bool
    +

    +HasExpired reports whether now is past the expiry time of certList. +

    + + + + + + + + +

    type Extension

    +
    type Extension struct {
    +    Id       asn1.ObjectIdentifier
    +    Critical bool `asn1:"optional"`
    +    Value    []byte
    +}
    +

    +Extension represents the ASN.1 structure of the same name. See RFC +5280, section 4.2. +

    + + + + + + + + + + + + + + + + +

    type Name

    +
    type Name struct {
    +    Country, Organization, OrganizationalUnit []string
    +    Locality, Province                        []string
    +    StreetAddress, PostalCode                 []string
    +    SerialNumber, CommonName                  string
    +
    +    Names      []AttributeTypeAndValue
    +    ExtraNames []AttributeTypeAndValue
    +}
    +

    +Name represents an X.509 distinguished name. This only includes the common +elements of a DN. When parsing, all elements are stored in Names and +non-standard elements can be extracted from there. When marshaling, elements +in ExtraNames are appended and override other values with the same OID. +

    + + + + + + + + + + + + + + +

    func (*Name) FillFromRDNSequence

    +
    func (n *Name) FillFromRDNSequence(rdns *RDNSequence)
    + + + + + + +

    func (Name) ToRDNSequence

    +
    func (n Name) ToRDNSequence() (ret RDNSequence)
    + + + + + + + + +

    type RDNSequence

    +
    type RDNSequence []RelativeDistinguishedNameSET
    + + + + + + + + + + + + + + + + +

    type RelativeDistinguishedNameSET

    +
    type RelativeDistinguishedNameSET []AttributeTypeAndValue
    + + + + + + + + + + + + + + + + +

    type RevokedCertificate

    +
    type RevokedCertificate struct {
    +    SerialNumber   *big.Int
    +    RevocationTime time.Time
    +    Extensions     []Extension `asn1:"optional"`
    +}
    +

    +RevokedCertificate represents the ASN.1 structure of the same name. See RFC +5280, section 5.1. +

    + + + + + + + + + + + + + + + + +

    type TBSCertificateList

    +
    type TBSCertificateList struct {
    +    Raw                 asn1.RawContent
    +    Version             int `asn1:"optional,default:1"`
    +    Signature           AlgorithmIdentifier
    +    Issuer              RDNSequence
    +    ThisUpdate          time.Time
    +    NextUpdate          time.Time            `asn1:"optional"`
    +    RevokedCertificates []RevokedCertificate `asn1:"optional"`
    +    Extensions          []Extension          `asn1:"tag:0,optional,explicit"`
    +}
    +

    +TBSCertificateList represents the ASN.1 structure of the same name. See RFC +5280, section 5.1. +

    + + + + + + + + + + + + + + + + + + + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/database/index.html b/pkg/database/index.html new file mode 100644 index 0000000..1cc70ce --- /dev/null +++ b/pkg/database/index.html @@ -0,0 +1,141 @@ + + + + + + + + /src/database - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Directory /src/database

    + + + + + + + + + + + + + + + + + + + +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    NameSynopsis
    ..
    + sql + + Package sql provides a generic interface around SQL (or SQL-like) databases. +
    + driver + + Package driver defines interfaces to be implemented by database drivers as used by package sql. +
    +
    + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/database/sql/driver/index.html b/pkg/database/sql/driver/index.html new file mode 100644 index 0000000..f4809a8 --- /dev/null +++ b/pkg/database/sql/driver/index.html @@ -0,0 +1,926 @@ + + + + + + + + driver - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Package driver

    + + + + + + + + + + + + + + +
    +
    +
    import "database/sql/driver"
    +
    +
    +
    Overview
    +
    Index
    + + +
    +
    + +
    + +
    +

    Overview ▾

    +

    +Package driver defines interfaces to be implemented by database +drivers as used by package sql. +

    +

    +Most code should use package sql. +

    + +
    +
    + + +
    + + +
    + + + + + +

    Variables

    + +
    var Bool boolType
    +

    +Bool is a ValueConverter that converts input values to bools. +

    +

    +The conversion rules are: +

    +
    - booleans are returned unchanged
    +- for integer types,
    +     1 is true
    +     0 is false,
    +     other integers are an error
    +- for strings and []byte, same rules as strconv.ParseBool
    +- all other types are an error
    +
    + + +
    var DefaultParameterConverter defaultConverter
    +

    +DefaultParameterConverter is the default implementation of +ValueConverter that's used when a Stmt doesn't implement +ColumnConverter. +

    +

    +DefaultParameterConverter returns its argument directly if +IsValue(arg). Otherwise, if the argument implements Valuer, its +Value method is used to return a Value. As a fallback, the provided +argument's underlying type is used to convert it to a Value: +underlying integer types are converted to int64, floats to float64, +and strings to []byte. If the argument is a nil pointer, +ConvertValue returns a nil Value. If the argument is a non-nil +pointer, it is dereferenced and ConvertValue is called +recursively. Other types are an error. +

    + + +
    var ErrBadConn = errors.New("driver: bad connection")
    +

    +ErrBadConn should be returned by a driver to signal to the sql +package that a driver.Conn is in a bad state (such as the server +having earlier closed the connection) and the sql package should +retry on a new connection. +

    +

    +To prevent duplicate operations, ErrBadConn should NOT be returned +if there's a possibility that the database server might have +performed the operation. Even if the server sends back an error, +you shouldn't return ErrBadConn. +

    + + +
    var ErrSkip = errors.New("driver: skip fast-path; continue as if unimplemented")
    +

    +ErrSkip may be returned by some optional interfaces' methods to +indicate at runtime that the fast path is unavailable and the sql +package should continue as if the optional interface was not +implemented. ErrSkip is only supported where explicitly +documented. +

    + + +
    var Int32 int32Type
    +

    +Int32 is a ValueConverter that converts input values to int64, +respecting the limits of an int32 value. +

    + + +
    var ResultNoRows noRows
    +

    +ResultNoRows is a pre-defined Result for drivers to return when a DDL +command (such as a CREATE TABLE) succeeds. It returns an error for both +LastInsertId and RowsAffected. +

    + + +
    var String stringType
    +

    +String is a ValueConverter that converts its input to a string. +If the value is already a string or []byte, it's unchanged. +If the value is of another type, conversion to string is done +with fmt.Sprintf("%v", v). +

    + + + + + + +

    func IsScanValue

    +
    func IsScanValue(v interface{}) bool
    +

    +IsScanValue reports whether v is a valid Value scan type. +Unlike IsValue, IsScanValue does not permit the string type. +

    + + + + + + + +

    func IsValue

    +
    func IsValue(v interface{}) bool
    +

    +IsValue reports whether v is a valid Value parameter type. +Unlike IsScanValue, IsValue permits the string type. +

    + + + + + + + + +

    type ColumnConverter

    +
    type ColumnConverter interface {
    +    // ColumnConverter returns a ValueConverter for the provided
    +    // column index.  If the type of a specific column isn't known
    +    // or shouldn't be handled specially, DefaultValueConverter
    +    // can be returned.
    +    ColumnConverter(idx int) ValueConverter
    +}
    +

    +ColumnConverter may be optionally implemented by Stmt if the +statement is aware of its own columns' types and can convert from +any type to a driver Value. +

    + + + + + + + + + + + + + + + + +

    type Conn

    +
    type Conn interface {
    +    // Prepare returns a prepared statement, bound to this connection.
    +    Prepare(query string) (Stmt, error)
    +
    +    // Close invalidates and potentially stops any current
    +    // prepared statements and transactions, marking this
    +    // connection as no longer in use.
    +    //
    +    // Because the sql package maintains a free pool of
    +    // connections and only calls Close when there's a surplus of
    +    // idle connections, it shouldn't be necessary for drivers to
    +    // do their own connection caching.
    +    Close() error
    +
    +    // Begin starts and returns a new transaction.
    +    Begin() (Tx, error)
    +}
    +

    +Conn is a connection to a database. It is not used concurrently +by multiple goroutines. +

    +

    +Conn is assumed to be stateful. +

    + + + + + + + + + + + + + + + + +

    type Driver

    +
    type Driver interface {
    +    // Open returns a new connection to the database.
    +    // The name is a string in a driver-specific format.
    +    //
    +    // Open may return a cached connection (one previously
    +    // closed), but doing so is unnecessary; the sql package
    +    // maintains a pool of idle connections for efficient re-use.
    +    //
    +    // The returned connection is only used by one goroutine at a
    +    // time.
    +    Open(name string) (Conn, error)
    +}
    +

    +Driver is the interface that must be implemented by a database +driver. +

    + + + + + + + + + + + + + + + + +

    type Execer

    +
    type Execer interface {
    +    Exec(query string, args []Value) (Result, error)
    +}
    +

    +Execer is an optional interface that may be implemented by a Conn. +

    +

    +If a Conn does not implement Execer, the sql package's DB.Exec will +first prepare a query, execute the statement, and then close the +statement. +

    +

    +Exec may return ErrSkip. +

    + + + + + + + + + + + + + + + + +

    type NotNull

    +
    type NotNull struct {
    +    Converter ValueConverter
    +}
    +

    +NotNull is a type that implements ValueConverter by disallowing nil +values but otherwise delegating to another ValueConverter. +

    + + + + + + + + + + + + + + +

    func (NotNull) ConvertValue

    +
    func (n NotNull) ConvertValue(v interface{}) (Value, error)
    + + + + + + + + +

    type Null

    +
    type Null struct {
    +    Converter ValueConverter
    +}
    +

    +Null is a type that implements ValueConverter by allowing nil +values but otherwise delegating to another ValueConverter. +

    + + + + + + + + + + + + + + +

    func (Null) ConvertValue

    +
    func (n Null) ConvertValue(v interface{}) (Value, error)
    + + + + + + + + +

    type Queryer

    +
    type Queryer interface {
    +    Query(query string, args []Value) (Rows, error)
    +}
    +

    +Queryer is an optional interface that may be implemented by a Conn. +

    +

    +If a Conn does not implement Queryer, the sql package's DB.Query will +first prepare a query, execute the statement, and then close the +statement. +

    +

    +Query may return ErrSkip. +

    + + + + + + + + + + + + + + + + +

    type Result

    +
    type Result interface {
    +    // LastInsertId returns the database's auto-generated ID
    +    // after, for example, an INSERT into a table with primary
    +    // key.
    +    LastInsertId() (int64, error)
    +
    +    // RowsAffected returns the number of rows affected by the
    +    // query.
    +    RowsAffected() (int64, error)
    +}
    +

    +Result is the result of a query execution. +

    + + + + + + + + + + + + + + + + +

    type Rows

    +
    type Rows interface {
    +    // Columns returns the names of the columns. The number of
    +    // columns of the result is inferred from the length of the
    +    // slice.  If a particular column name isn't known, an empty
    +    // string should be returned for that entry.
    +    Columns() []string
    +
    +    // Close closes the rows iterator.
    +    Close() error
    +
    +    // Next is called to populate the next row of data into
    +    // the provided slice. The provided slice will be the same
    +    // size as the Columns() are wide.
    +    //
    +    // The dest slice may be populated only with
    +    // a driver Value type, but excluding string.
    +    // All string values must be converted to []byte.
    +    //
    +    // Next should return io.EOF when there are no more rows.
    +    Next(dest []Value) error
    +}
    +

    +Rows is an iterator over an executed query's results. +

    + + + + + + + + + + + + + + + + +

    type RowsAffected

    +
    type RowsAffected int64
    +

    +RowsAffected implements Result for an INSERT or UPDATE operation +which mutates a number of rows. +

    + + + + + + + + + + + + + + +

    func (RowsAffected) LastInsertId

    +
    func (RowsAffected) LastInsertId() (int64, error)
    + + + + + + +

    func (RowsAffected) RowsAffected

    +
    func (v RowsAffected) RowsAffected() (int64, error)
    + + + + + + + + +

    type Stmt

    +
    type Stmt interface {
    +    // Close closes the statement.
    +    //
    +    // As of Go 1.1, a Stmt will not be closed if it's in use
    +    // by any queries.
    +    Close() error
    +
    +    // NumInput returns the number of placeholder parameters.
    +    //
    +    // If NumInput returns >= 0, the sql package will sanity check
    +    // argument counts from callers and return errors to the caller
    +    // before the statement's Exec or Query methods are called.
    +    //
    +    // NumInput may also return -1, if the driver doesn't know
    +    // its number of placeholders. In that case, the sql package
    +    // will not sanity check Exec or Query argument counts.
    +    NumInput() int
    +
    +    // Exec executes a query that doesn't return rows, such
    +    // as an INSERT or UPDATE.
    +    Exec(args []Value) (Result, error)
    +
    +    // Query executes a query that may return rows, such as a
    +    // SELECT.
    +    Query(args []Value) (Rows, error)
    +}
    +

    +Stmt is a prepared statement. It is bound to a Conn and not +used by multiple goroutines concurrently. +

    + + + + + + + + + + + + + + + + +

    type Tx

    +
    type Tx interface {
    +    Commit() error
    +    Rollback() error
    +}
    +

    +Tx is a transaction. +

    + + + + + + + + + + + + + + + + +

    type Value

    +
    type Value interface{}
    +

    +Value is a value that drivers must be able to handle. +It is either nil or an instance of one of these types: +

    +
    int64
    +float64
    +bool
    +[]byte
    +string   [*] everywhere except from Rows.Next.
    +time.Time
    +
    + + + + + + + + + + + + + + + + +

    type ValueConverter

    +
    type ValueConverter interface {
    +    // ConvertValue converts a value to a driver Value.
    +    ConvertValue(v interface{}) (Value, error)
    +}
    +

    +ValueConverter is the interface providing the ConvertValue method. +

    +

    +Various implementations of ValueConverter are provided by the +driver package to provide consistent implementations of conversions +between drivers. The ValueConverters have several uses: +

    +
    * converting from the Value types as provided by the sql package
    +  into a database table's specific column type and making sure it
    +  fits, such as making sure a particular int64 fits in a
    +  table's uint16 column.
    +
    +* converting a value as given from the database into one of the
    +  driver Value types.
    +
    +* by the sql package, for converting from a driver's Value type
    +  to a user's type in a scan.
    +
    + + + + + + + + + + + + + + + + +

    type Valuer

    +
    type Valuer interface {
    +    // Value returns a driver Value.
    +    Value() (Value, error)
    +}
    +

    +Valuer is the interface providing the Value method. +

    +

    +Types implementing Valuer interface are able to convert +themselves to a driver Value. +

    + + + + + + + + + + + + + + + + + + + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/database/sql/index.html b/pkg/database/sql/index.html new file mode 100644 index 0000000..4d566b7 --- /dev/null +++ b/pkg/database/sql/index.html @@ -0,0 +1,1521 @@ + + + + + + + + sql - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Package sql

    + + + + + + + + + + + + + + +
    +
    +
    import "database/sql"
    +
    +
    +
    Overview
    +
    Index
    + +
    Examples
    + + +
    Subdirectories
    + +
    +
    + +
    + +
    +

    Overview ▾

    +

    +Package sql provides a generic interface around SQL (or SQL-like) +databases. +

    +

    +The sql package must be used in conjunction with a database driver. +See https://golang.org/s/sqldrivers for a list of drivers. +

    +

    +For more usage examples, see the wiki page at +https://golang.org/s/sqlwiki. +

    + +
    +
    + + +
    + +
    +

    Index ▾

    + + +
    +
    + + +
    Variables
    + + + +
    func Drivers() []string
    + + +
    func Register(name string, driver driver.Driver)
    + + + +
    type DB
    + + +
        func Open(driverName, dataSourceName string) (*DB, error)
    + + + +
        func (db *DB) Begin() (*Tx, error)
    + + +
        func (db *DB) Close() error
    + + +
        func (db *DB) Driver() driver.Driver
    + + +
        func (db *DB) Exec(query string, args ...interface{}) (Result, error)
    + + +
        func (db *DB) Ping() error
    + + +
        func (db *DB) Prepare(query string) (*Stmt, error)
    + + +
        func (db *DB) Query(query string, args ...interface{}) (*Rows, error)
    + + +
        func (db *DB) QueryRow(query string, args ...interface{}) *Row
    + + +
        func (db *DB) SetConnMaxLifetime(d time.Duration)
    + + +
        func (db *DB) SetMaxIdleConns(n int)
    + + +
        func (db *DB) SetMaxOpenConns(n int)
    + + +
        func (db *DB) Stats() DBStats
    + + + +
    type DBStats
    + + + + +
    type NullBool
    + + + +
        func (n *NullBool) Scan(value interface{}) error
    + + +
        func (n NullBool) Value() (driver.Value, error)
    + + + +
    type NullFloat64
    + + + +
        func (n *NullFloat64) Scan(value interface{}) error
    + + +
        func (n NullFloat64) Value() (driver.Value, error)
    + + + +
    type NullInt64
    + + + +
        func (n *NullInt64) Scan(value interface{}) error
    + + +
        func (n NullInt64) Value() (driver.Value, error)
    + + + +
    type NullString
    + + + +
        func (ns *NullString) Scan(value interface{}) error
    + + +
        func (ns NullString) Value() (driver.Value, error)
    + + + +
    type RawBytes
    + + + + +
    type Result
    + + + + +
    type Row
    + + + +
        func (r *Row) Scan(dest ...interface{}) error
    + + + +
    type Rows
    + + + +
        func (rs *Rows) Close() error
    + + +
        func (rs *Rows) Columns() ([]string, error)
    + + +
        func (rs *Rows) Err() error
    + + +
        func (rs *Rows) Next() bool
    + + +
        func (rs *Rows) Scan(dest ...interface{}) error
    + + + +
    type Scanner
    + + + + +
    type Stmt
    + + + +
        func (s *Stmt) Close() error
    + + +
        func (s *Stmt) Exec(args ...interface{}) (Result, error)
    + + +
        func (s *Stmt) Query(args ...interface{}) (*Rows, error)
    + + +
        func (s *Stmt) QueryRow(args ...interface{}) *Row
    + + + +
    type Tx
    + + + +
        func (tx *Tx) Commit() error
    + + +
        func (tx *Tx) Exec(query string, args ...interface{}) (Result, error)
    + + +
        func (tx *Tx) Prepare(query string) (*Stmt, error)
    + + +
        func (tx *Tx) Query(query string, args ...interface{}) (*Rows, error)
    + + +
        func (tx *Tx) QueryRow(query string, args ...interface{}) *Row
    + + +
        func (tx *Tx) Rollback() error
    + + +
        func (tx *Tx) Stmt(stmt *Stmt) *Stmt
    + + + +
    +
    + + +
    +

    Examples

    +
    + +
    DB.Query
    + +
    DB.QueryRow
    + +
    +
    + + + +

    Package files

    +

    + + + convert.go + + sql.go + + +

    + +
    +
    + + + + + +

    Variables

    + +
    var ErrNoRows = errors.New("sql: no rows in result set")
    +

    +ErrNoRows is returned by Scan when QueryRow doesn't return a +row. In such a case, QueryRow returns a placeholder *Row value that +defers this error until a Scan. +

    + + +
    var ErrTxDone = errors.New("sql: Transaction has already been committed or rolled back")
    + + + + + + +

    func Drivers

    +
    func Drivers() []string
    +

    +Drivers returns a sorted list of the names of the registered drivers. +

    + + + + + + + +

    func Register

    +
    func Register(name string, driver driver.Driver)
    +

    +Register makes a database driver available by the provided name. +If Register is called twice with the same name or if driver is nil, +it panics. +

    + + + + + + + + +

    type DB

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

    +DB is a database handle representing a pool of zero or more +underlying connections. It's safe for concurrent use by multiple +goroutines. +

    +

    +The sql package creates and frees connections automatically; it +also maintains a free pool of idle connections. If the database has +a concept of per-connection state, such state can only be reliably +observed within a transaction. Once DB.Begin is called, the +returned Tx is bound to a single connection. Once Commit or +Rollback is called on the transaction, that transaction's +connection is returned to DB's idle connection pool. The pool size +can be controlled with SetMaxIdleConns. +

    + + + + + + + + + + + + +

    func Open

    +
    func Open(driverName, dataSourceName string) (*DB, error)
    +

    +Open opens a database specified by its database driver name and a +driver-specific data source name, usually consisting of at least a +database name and connection information. +

    +

    +Most users will open a database via a driver-specific connection +helper function that returns a *DB. No database drivers are included +in the Go standard library. See https://golang.org/s/sqldrivers for +a list of third-party drivers. +

    +

    +Open may just validate its arguments without creating a connection +to the database. To verify that the data source name is valid, call +Ping. +

    +

    +The returned DB is safe for concurrent use by multiple goroutines +and maintains its own pool of idle connections. Thus, the Open +function should be called just once. It is rarely necessary to +close a DB. +

    + + + + + + + +

    func (*DB) Begin

    +
    func (db *DB) Begin() (*Tx, error)
    +

    +Begin starts a transaction. The isolation level is dependent on +the driver. +

    + + + + + + +

    func (*DB) Close

    +
    func (db *DB) Close() error
    +

    +Close closes the database, releasing any open resources. +

    +

    +It is rare to Close a DB, as the DB handle is meant to be +long-lived and shared between many goroutines. +

    + + + + + + +

    func (*DB) Driver

    +
    func (db *DB) Driver() driver.Driver
    +

    +Driver returns the database's underlying driver. +

    + + + + + + +

    func (*DB) Exec

    +
    func (db *DB) Exec(query string, args ...interface{}) (Result, error)
    +

    +Exec executes a query without returning any rows. +The args are for any placeholder parameters in the query. +

    + + + + + + +

    func (*DB) Ping

    +
    func (db *DB) Ping() error
    +

    +Ping verifies a connection to the database is still alive, +establishing a connection if necessary. +

    + + + + + + +

    func (*DB) Prepare

    +
    func (db *DB) Prepare(query string) (*Stmt, error)
    +

    +Prepare creates a prepared statement for later queries or executions. +Multiple queries or executions may be run concurrently from the +returned statement. +The caller must call the statement's Close method +when the statement is no longer needed. +

    + + + + + + +

    func (*DB) Query

    +
    func (db *DB) Query(query string, args ...interface{}) (*Rows, error)
    +

    +Query executes a query that returns rows, typically a SELECT. +The args are for any placeholder parameters in the query. +

    + + +
    + +
    +

    Example

    + + + +

    Code:

    +
    +age := 27
    +rows, err := db.Query("SELECT name FROM users WHERE age=?", age)
    +if err != nil {
    +    log.Fatal(err)
    +}
    +defer rows.Close()
    +for rows.Next() {
    +    var name string
    +    if err := rows.Scan(&name); err != nil {
    +        log.Fatal(err)
    +    }
    +    fmt.Printf("%s is %d\n", name, age)
    +}
    +if err := rows.Err(); err != nil {
    +    log.Fatal(err)
    +}
    +
    + + +
    +
    + + + + +

    func (*DB) QueryRow

    +
    func (db *DB) QueryRow(query string, args ...interface{}) *Row
    +

    +QueryRow executes a query that is expected to return at most one row. +QueryRow always returns a non-nil value. Errors are deferred until +Row's Scan method is called. +

    + + +
    + +
    +

    Example

    + + + +

    Code:

    +
    +id := 123
    +var username string
    +err := db.QueryRow("SELECT username FROM users WHERE id=?", id).Scan(&username)
    +switch {
    +case err == sql.ErrNoRows:
    +    log.Printf("No user with that ID.")
    +case err != nil:
    +    log.Fatal(err)
    +default:
    +    fmt.Printf("Username is %s\n", username)
    +}
    +
    + + +
    +
    + + + + +

    func (*DB) SetConnMaxLifetime

    +
    func (db *DB) SetConnMaxLifetime(d time.Duration)
    +

    +SetConnMaxLifetime sets the maximum amount of time a connection may be reused. +

    +

    +Expired connections may be closed lazily before reuse. +

    +

    +If d <= 0, connections are reused forever. +

    + + + + + + +

    func (*DB) SetMaxIdleConns

    +
    func (db *DB) SetMaxIdleConns(n int)
    +

    +SetMaxIdleConns sets the maximum number of connections in the idle +connection pool. +

    +

    +If MaxOpenConns is greater than 0 but less than the new MaxIdleConns +then the new MaxIdleConns will be reduced to match the MaxOpenConns limit +

    +

    +If n <= 0, no idle connections are retained. +

    + + + + + + +

    func (*DB) SetMaxOpenConns

    +
    func (db *DB) SetMaxOpenConns(n int)
    +

    +SetMaxOpenConns sets the maximum number of open connections to the database. +

    +

    +If MaxIdleConns is greater than 0 and the new MaxOpenConns is less than +MaxIdleConns, then MaxIdleConns will be reduced to match the new +MaxOpenConns limit +

    +

    +If n <= 0, then there is no limit on the number of open connections. +The default is 0 (unlimited). +

    + + + + + + +

    func (*DB) Stats

    +
    func (db *DB) Stats() DBStats
    +

    +Stats returns database statistics. +

    + + + + + + + + +

    type DBStats

    +
    type DBStats struct {
    +    // OpenConnections is the number of open connections to the database.
    +    OpenConnections int
    +}
    +

    +DBStats contains database statistics. +

    + + + + + + + + + + + + + + + + +

    type NullBool

    +
    type NullBool struct {
    +    Bool  bool
    +    Valid bool // Valid is true if Bool is not NULL
    +}
    +

    +NullBool represents a bool that may be null. +NullBool implements the Scanner interface so +it can be used as a scan destination, similar to NullString. +

    + + + + + + + + + + + + + + +

    func (*NullBool) Scan

    +
    func (n *NullBool) Scan(value interface{}) error
    +

    +Scan implements the Scanner interface. +

    + + + + + + +

    func (NullBool) Value

    +
    func (n NullBool) Value() (driver.Value, error)
    +

    +Value implements the driver Valuer interface. +

    + + + + + + + + +

    type NullFloat64

    +
    type NullFloat64 struct {
    +    Float64 float64
    +    Valid   bool // Valid is true if Float64 is not NULL
    +}
    +

    +NullFloat64 represents a float64 that may be null. +NullFloat64 implements the Scanner interface so +it can be used as a scan destination, similar to NullString. +

    + + + + + + + + + + + + + + +

    func (*NullFloat64) Scan

    +
    func (n *NullFloat64) Scan(value interface{}) error
    +

    +Scan implements the Scanner interface. +

    + + + + + + +

    func (NullFloat64) Value

    +
    func (n NullFloat64) Value() (driver.Value, error)
    +

    +Value implements the driver Valuer interface. +

    + + + + + + + + +

    type NullInt64

    +
    type NullInt64 struct {
    +    Int64 int64
    +    Valid bool // Valid is true if Int64 is not NULL
    +}
    +

    +NullInt64 represents an int64 that may be null. +NullInt64 implements the Scanner interface so +it can be used as a scan destination, similar to NullString. +

    + + + + + + + + + + + + + + +

    func (*NullInt64) Scan

    +
    func (n *NullInt64) Scan(value interface{}) error
    +

    +Scan implements the Scanner interface. +

    + + + + + + +

    func (NullInt64) Value

    +
    func (n NullInt64) Value() (driver.Value, error)
    +

    +Value implements the driver Valuer interface. +

    + + + + + + + + +

    type NullString

    +
    type NullString struct {
    +    String string
    +    Valid  bool // Valid is true if String is not NULL
    +}
    +

    +NullString represents a string that may be null. +NullString implements the Scanner interface so +it can be used as a scan destination: +

    +
    var s NullString
    +err := db.QueryRow("SELECT name FROM foo WHERE id=?", id).Scan(&s)
    +...
    +if s.Valid {
    +   // use s.String
    +} else {
    +   // NULL value
    +}
    +
    + + + + + + + + + + + + + + +

    func (*NullString) Scan

    +
    func (ns *NullString) Scan(value interface{}) error
    +

    +Scan implements the Scanner interface. +

    + + + + + + +

    func (NullString) Value

    +
    func (ns NullString) Value() (driver.Value, error)
    +

    +Value implements the driver Valuer interface. +

    + + + + + + + + +

    type RawBytes

    +
    type RawBytes []byte
    +

    +RawBytes is a byte slice that holds a reference to memory owned by +the database itself. After a Scan into a RawBytes, the slice is only +valid until the next call to Next, Scan, or Close. +

    + + + + + + + + + + + + + + + + +

    type Result

    +
    type Result interface {
    +    // LastInsertId returns the integer generated by the database
    +    // in response to a command. Typically this will be from an
    +    // "auto increment" column when inserting a new row. Not all
    +    // databases support this feature, and the syntax of such
    +    // statements varies.
    +    LastInsertId() (int64, error)
    +
    +    // RowsAffected returns the number of rows affected by an
    +    // update, insert, or delete. Not every database or database
    +    // driver may support this.
    +    RowsAffected() (int64, error)
    +}
    +

    +A Result summarizes an executed SQL command. +

    + + + + + + + + + + + + + + + + +

    type Row

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

    +Row is the result of calling QueryRow to select a single row. +

    + + + + + + + + + + + + + + +

    func (*Row) Scan

    +
    func (r *Row) Scan(dest ...interface{}) error
    +

    +Scan copies the columns from the matched row into the values +pointed at by dest. See the documentation on Rows.Scan for details. +If more than one row matches the query, +Scan uses the first row and discards the rest. If no row matches +the query, Scan returns ErrNoRows. +

    + + + + + + + + +

    type Rows

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

    +Rows is the result of a query. Its cursor starts before the first row +of the result set. Use Next to advance through the rows: +

    +
    rows, err := db.Query("SELECT ...")
    +...
    +defer rows.Close()
    +for rows.Next() {
    +    var id int
    +    var name string
    +    err = rows.Scan(&id, &name)
    +    ...
    +}
    +err = rows.Err() // get any error encountered during iteration
    +...
    +
    + + + + + + + + + + + + + + +

    func (*Rows) Close

    +
    func (rs *Rows) Close() error
    +

    +Close closes the Rows, preventing further enumeration. If Next returns +false, the Rows are closed automatically and it will suffice to check the +result of Err. Close is idempotent and does not affect the result of Err. +

    + + + + + + +

    func (*Rows) Columns

    +
    func (rs *Rows) Columns() ([]string, error)
    +

    +Columns returns the column names. +Columns returns an error if the rows are closed, or if the rows +are from QueryRow and there was a deferred error. +

    + + + + + + +

    func (*Rows) Err

    +
    func (rs *Rows) Err() error
    +

    +Err returns the error, if any, that was encountered during iteration. +Err may be called after an explicit or implicit Close. +

    + + + + + + +

    func (*Rows) Next

    +
    func (rs *Rows) Next() bool
    +

    +Next prepares the next result row for reading with the Scan method. It +returns true on success, or false if there is no next result row or an error +happened while preparing it. Err should be consulted to distinguish between +the two cases. +

    +

    +Every call to Scan, even the first one, must be preceded by a call to Next. +

    + + + + + + +

    func (*Rows) Scan

    +
    func (rs *Rows) Scan(dest ...interface{}) error
    +

    +Scan copies the columns in the current row into the values pointed +at by dest. The number of values in dest must be the same as the +number of columns in Rows. +

    +

    +Scan converts columns read from the database into the following +common Go types and special types provided by the sql package: +

    +
    *string
    +*[]byte
    +*int, *int8, *int16, *int32, *int64
    +*uint, *uint8, *uint16, *uint32, *uint64
    +*bool
    +*float32, *float64
    +*interface{}
    +*RawBytes
    +any type implementing Scanner (see Scanner docs)
    +
    +

    +In the most simple case, if the type of the value from the source +column is an integer, bool or string type T and dest is of type *T, +Scan simply assigns the value through the pointer. +

    +

    +Scan also converts between string and numeric types, as long as no +information would be lost. While Scan stringifies all numbers +scanned from numeric database columns into *string, scans into +numeric types are checked for overflow. For example, a float64 with +value 300 or a string with value "300" can scan into a uint16, but +not into a uint8, though float64(255) or "255" can scan into a +uint8. One exception is that scans of some float64 numbers to +strings may lose information when stringifying. In general, scan +floating point columns into *float64. +

    +

    +If a dest argument has type *[]byte, Scan saves in that argument a +copy of the corresponding data. The copy is owned by the caller and +can be modified and held indefinitely. The copy can be avoided by +using an argument of type *RawBytes instead; see the documentation +for RawBytes for restrictions on its use. +

    +

    +If an argument has type *interface{}, Scan copies the value +provided by the underlying driver without conversion. When scanning +from a source value of type []byte to *interface{}, a copy of the +slice is made and the caller owns the result. +

    +

    +Source values of type time.Time may be scanned into values of type +*time.Time, *interface{}, *string, or *[]byte. When converting to +the latter two, time.Format3339Nano is used. +

    +

    +Source values of type bool may be scanned into types *bool, +*interface{}, *string, *[]byte, or *RawBytes. +

    +

    +For scanning into *bool, the source may be true, false, 1, 0, or +string inputs parseable by strconv.ParseBool. +

    + + + + + + + + +

    type Scanner

    +
    type Scanner interface {
    +    // Scan assigns a value from a database driver.
    +    //
    +    // The src value will be of one of the following types:
    +    //
    +    //    int64
    +    //    float64
    +    //    bool
    +    //    []byte
    +    //    string
    +    //    time.Time
    +    //    nil - for NULL values
    +    //
    +    // An error should be returned if the value can not be stored
    +    // without loss of information.
    +    Scan(src interface{}) error
    +}
    +

    +Scanner is an interface used by Scan. +

    + + + + + + + + + + + + + + + + +

    type Stmt

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

    +Stmt is a prepared statement. +A Stmt is safe for concurrent use by multiple goroutines. +

    + + + + + + + + + + + + + + +

    func (*Stmt) Close

    +
    func (s *Stmt) Close() error
    +

    +Close closes the statement. +

    + + + + + + +

    func (*Stmt) Exec

    +
    func (s *Stmt) Exec(args ...interface{}) (Result, error)
    +

    +Exec executes a prepared statement with the given arguments and +returns a Result summarizing the effect of the statement. +

    + + + + + + +

    func (*Stmt) Query

    +
    func (s *Stmt) Query(args ...interface{}) (*Rows, error)
    +

    +Query executes a prepared query statement with the given arguments +and returns the query results as a *Rows. +

    + + + + + + +

    func (*Stmt) QueryRow

    +
    func (s *Stmt) QueryRow(args ...interface{}) *Row
    +

    +QueryRow executes a prepared query statement with the given arguments. +If an error occurs during the execution of the statement, that error will +be returned by a call to Scan on the returned *Row, which is always non-nil. +If the query selects no rows, the *Row's Scan will return ErrNoRows. +Otherwise, the *Row's Scan scans the first selected row and discards +the rest. +

    +

    +Example usage: +

    +
    var name string
    +err := nameByUseridStmt.QueryRow(id).Scan(&name)
    +
    + + + + + + + + +

    type Tx

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

    +Tx is an in-progress database transaction. +

    +

    +A transaction must end with a call to Commit or Rollback. +

    +

    +After a call to Commit or Rollback, all operations on the +transaction fail with ErrTxDone. +

    +

    +The statements prepared for a transaction by calling +the transaction's Prepare or Stmt methods are closed +by the call to Commit or Rollback. +

    + + + + + + + + + + + + + + +

    func (*Tx) Commit

    +
    func (tx *Tx) Commit() error
    +

    +Commit commits the transaction. +

    + + + + + + +

    func (*Tx) Exec

    +
    func (tx *Tx) Exec(query string, args ...interface{}) (Result, error)
    +

    +Exec executes a query that doesn't return rows. +For example: an INSERT and UPDATE. +

    + + + + + + +

    func (*Tx) Prepare

    +
    func (tx *Tx) Prepare(query string) (*Stmt, error)
    +

    +Prepare creates a prepared statement for use within a transaction. +

    +

    +The returned statement operates within the transaction and can no longer +be used once the transaction has been committed or rolled back. +

    +

    +To use an existing prepared statement on this transaction, see Tx.Stmt. +

    + + + + + + +

    func (*Tx) Query

    +
    func (tx *Tx) Query(query string, args ...interface{}) (*Rows, error)
    +

    +Query executes a query that returns rows, typically a SELECT. +

    + + + + + + +

    func (*Tx) QueryRow

    +
    func (tx *Tx) QueryRow(query string, args ...interface{}) *Row
    +

    +QueryRow executes a query that is expected to return at most one row. +QueryRow always returns a non-nil value. Errors are deferred until +Row's Scan method is called. +

    + + + + + + +

    func (*Tx) Rollback

    +
    func (tx *Tx) Rollback() error
    +

    +Rollback aborts the transaction. +

    + + + + + + +

    func (*Tx) Stmt

    +
    func (tx *Tx) Stmt(stmt *Stmt) *Stmt
    +

    +Stmt returns a transaction-specific prepared statement from +an existing statement. +

    +

    +Example: +

    +
    updateMoney, err := db.Prepare("UPDATE balance SET money=money+? WHERE id=?")
    +...
    +tx, err := db.Begin()
    +...
    +res, err := tx.Stmt(updateMoney).Exec(123.45, 98293203)
    +
    +

    +The returned statement operates within the transaction and can no longer +be used once the transaction has been committed or rolled back. +

    + + + + + + + + + + + + + + + + +

    Subdirectories

    + + + + +
    + + + + + + + + + + + + + + + + + + + + +
    NameSynopsis
    ..
    + driver + + Package driver defines interfaces to be implemented by database drivers as used by package sql. +
    +
    + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/encoding/asn1/index.html b/pkg/encoding/asn1/index.html new file mode 100644 index 0000000..9f59e82 --- /dev/null +++ b/pkg/encoding/asn1/index.html @@ -0,0 +1,674 @@ + + + + + + + + asn1 - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Package asn1

    + + + + + + + + + + + + + + +
    +
    +
    import "encoding/asn1"
    +
    +
    +
    Overview
    +
    Index
    + + +
    +
    + +
    + +
    +

    Overview ▾

    +

    +Package asn1 implements parsing of DER-encoded ASN.1 data structures, +as defined in ITU-T Rec X.690. +

    +

    +See also “A Layman's Guide to a Subset of ASN.1, BER, and DER,” +http://luca.ntop.org/Teaching/Appunti/asn1.html. +

    + +
    +
    + + + + + + + +

    Constants

    + +
    const (
    +    TagBoolean         = 1
    +    TagInteger         = 2
    +    TagBitString       = 3
    +    TagOctetString     = 4
    +    TagOID             = 6
    +    TagEnum            = 10
    +    TagUTF8String      = 12
    +    TagSequence        = 16
    +    TagSet             = 17
    +    TagPrintableString = 19
    +    TagT61String       = 20
    +    TagIA5String       = 22
    +    TagUTCTime         = 23
    +    TagGeneralizedTime = 24
    +    TagGeneralString   = 27
    +)
    +

    +ASN.1 tags represent the type of the following object. +

    + + +
    const (
    +    ClassUniversal       = 0
    +    ClassApplication     = 1
    +    ClassContextSpecific = 2
    +    ClassPrivate         = 3
    +)
    +

    +ASN.1 class types represent the namespace of the tag. +

    + + + + + + + +

    func Marshal

    +
    func Marshal(val interface{}) ([]byte, error)
    +

    +Marshal returns the ASN.1 encoding of val. +

    +

    +In addition to the struct tags recognised by Unmarshal, the following can be +used: +

    +
    ia5:		causes strings to be marshaled as ASN.1, IA5 strings
    +omitempty:	causes empty slices to be skipped
    +printable:	causes strings to be marshaled as ASN.1, PrintableString strings.
    +utf8:		causes strings to be marshaled as ASN.1, UTF8 strings
    +
    + + + + + + + +

    func Unmarshal

    +
    func Unmarshal(b []byte, val interface{}) (rest []byte, err error)
    +

    +Unmarshal parses the DER-encoded ASN.1 data structure b +and uses the reflect package to fill in an arbitrary value pointed at by val. +Because Unmarshal uses the reflect package, the structs +being written to must use upper case field names. +

    +

    +An ASN.1 INTEGER can be written to an int, int32, int64, +or *big.Int (from the math/big package). +If the encoded value does not fit in the Go type, +Unmarshal returns a parse error. +

    +

    +An ASN.1 BIT STRING can be written to a BitString. +

    +

    +An ASN.1 OCTET STRING can be written to a []byte. +

    +

    +An ASN.1 OBJECT IDENTIFIER can be written to an +ObjectIdentifier. +

    +

    +An ASN.1 ENUMERATED can be written to an Enumerated. +

    +

    +An ASN.1 UTCTIME or GENERALIZEDTIME can be written to a time.Time. +

    +

    +An ASN.1 PrintableString or IA5String can be written to a string. +

    +

    +Any of the above ASN.1 values can be written to an interface{}. +The value stored in the interface has the corresponding Go type. +For integers, that type is int64. +

    +

    +An ASN.1 SEQUENCE OF x or SET OF x can be written +to a slice if an x can be written to the slice's element type. +

    +

    +An ASN.1 SEQUENCE or SET can be written to a struct +if each of the elements in the sequence can be +written to the corresponding element in the struct. +

    +

    +The following tags on struct fields have special meaning to Unmarshal: +

    +
    application	specifies that a APPLICATION tag is used
    +default:x	sets the default value for optional integer fields
    +explicit	specifies that an additional, explicit tag wraps the implicit one
    +optional	marks the field as ASN.1 OPTIONAL
    +set		causes a SET, rather than a SEQUENCE type to be expected
    +tag:x		specifies the ASN.1 tag number; implies ASN.1 CONTEXT SPECIFIC
    +
    +

    +If the type of the first field of a structure is RawContent then the raw +ASN1 contents of the struct will be stored in it. +

    +

    +If the type name of a slice element ends with "SET" then it's treated as if +the "set" tag was set on it. This can be used with nested slices where a +struct tag cannot be given. +

    +

    +Other ASN.1 types are not supported; if it encounters them, +Unmarshal returns a parse error. +

    + + + + + + + +

    func UnmarshalWithParams

    +
    func UnmarshalWithParams(b []byte, val interface{}, params string) (rest []byte, err error)
    +

    +UnmarshalWithParams allows field parameters to be specified for the +top-level element. The form of the params is the same as the field tags. +

    + + + + + + + + +

    type BitString

    +
    type BitString struct {
    +    Bytes     []byte // bits packed into bytes.
    +    BitLength int    // length in bits.
    +}
    +

    +BitString is the structure to use when you want an ASN.1 BIT STRING type. A +bit string is padded up to the nearest byte in memory and the number of +valid bits is recorded. Padding bits will be zero. +

    + + + + + + + + + + + + + + +

    func (BitString) At

    +
    func (b BitString) At(i int) int
    +

    +At returns the bit at the given index. If the index is out of range it +returns false. +

    + + + + + + +

    func (BitString) RightAlign

    +
    func (b BitString) RightAlign() []byte
    +

    +RightAlign returns a slice where the padding bits are at the beginning. The +slice may share memory with the BitString. +

    + + + + + + + + +

    type Enumerated

    +
    type Enumerated int
    +

    +An Enumerated is represented as a plain int. +

    + + + + + + + + + + + + + + + + +

    type Flag

    +
    type Flag bool
    +

    +A Flag accepts any data and is set to true if present. +

    + + + + + + + + + + + + + + + + +

    type ObjectIdentifier

    +
    type ObjectIdentifier []int
    +

    +An ObjectIdentifier represents an ASN.1 OBJECT IDENTIFIER. +

    + + + + + + + + + + + + + + +

    func (ObjectIdentifier) Equal

    +
    func (oi ObjectIdentifier) Equal(other ObjectIdentifier) bool
    +

    +Equal reports whether oi and other represent the same identifier. +

    + + + + + + +

    func (ObjectIdentifier) String

    +
    func (oi ObjectIdentifier) String() string
    + + + + + + + + +

    type RawContent

    +
    type RawContent []byte
    +

    +RawContent is used to signal that the undecoded, DER data needs to be +preserved for a struct. To use it, the first field of the struct must have +this type. It's an error for any of the other fields to have this type. +

    + + + + + + + + + + + + + + + + +

    type RawValue

    +
    type RawValue struct {
    +    Class, Tag int
    +    IsCompound bool
    +    Bytes      []byte
    +    FullBytes  []byte // includes the tag and length
    +}
    +

    +A RawValue represents an undecoded ASN.1 object. +

    + + + + + + + + + + + + + + + + +

    type StructuralError

    +
    type StructuralError struct {
    +    Msg string
    +}
    +

    +A StructuralError suggests that the ASN.1 data is valid, but the Go type +which is receiving it doesn't match. +

    + + + + + + + + + + + + + + +

    func (StructuralError) Error

    +
    func (e StructuralError) Error() string
    + + + + + + + + +

    type SyntaxError

    +
    type SyntaxError struct {
    +    Msg string
    +}
    +

    +A SyntaxError suggests that the ASN.1 data is invalid. +

    + + + + + + + + + + + + + + +

    func (SyntaxError) Error

    +
    func (e SyntaxError) Error() string
    + + + + + + + + + + + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/encoding/json/index.html b/pkg/encoding/json/index.html new file mode 100644 index 0000000..c4e786b --- /dev/null +++ b/pkg/encoding/json/index.html @@ -0,0 +1,1655 @@ + + + + + + + + json - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Package json

    + + + + + + + + + + + + + + +
    +
    +
    import "encoding/json"
    +
    +
    +
    Overview
    +
    Index
    + +
    Examples
    + + +
    +
    + +
    + +
    +

    Overview ▾

    +

    +Package json implements encoding and decoding of JSON objects as defined in +RFC 4627. The mapping between JSON objects and Go values is described +in the documentation for the Marshal and Unmarshal functions. +

    +

    +See "JSON and Go" for an introduction to this package: +https://golang.org/doc/articles/json_and_go.html +

    + +
    +
    + + +
    + +
    +

    Index ▾

    + + +
    +
    + + + + +
    func Compact(dst *bytes.Buffer, src []byte) error
    + + +
    func HTMLEscape(dst *bytes.Buffer, src []byte)
    + + +
    func Indent(dst *bytes.Buffer, src []byte, prefix, indent string) error
    + + +
    func Marshal(v interface{}) ([]byte, error)
    + + +
    func MarshalIndent(v interface{}, prefix, indent string) ([]byte, error)
    + + +
    func Unmarshal(data []byte, v interface{}) error
    + + + +
    type Decoder
    + + +
        func NewDecoder(r io.Reader) *Decoder
    + + + +
        func (dec *Decoder) Buffered() io.Reader
    + + +
        func (dec *Decoder) Decode(v interface{}) error
    + + +
        func (dec *Decoder) More() bool
    + + +
        func (dec *Decoder) Token() (Token, error)
    + + +
        func (dec *Decoder) UseNumber()
    + + + +
    type Delim
    + + + +
        func (d Delim) String() string
    + + + +
    type Encoder
    + + +
        func NewEncoder(w io.Writer) *Encoder
    + + + +
        func (enc *Encoder) Encode(v interface{}) error
    + + + +
    type InvalidUTF8Error
    + + + +
        func (e *InvalidUTF8Error) Error() string
    + + + +
    type InvalidUnmarshalError
    + + + +
        func (e *InvalidUnmarshalError) Error() string
    + + + +
    type Marshaler
    + + + + +
    type MarshalerError
    + + + +
        func (e *MarshalerError) Error() string
    + + + +
    type Number
    + + + +
        func (n Number) Float64() (float64, error)
    + + +
        func (n Number) Int64() (int64, error)
    + + +
        func (n Number) String() string
    + + + +
    type RawMessage
    + + + +
        func (m *RawMessage) MarshalJSON() ([]byte, error)
    + + +
        func (m *RawMessage) UnmarshalJSON(data []byte) error
    + + + +
    type SyntaxError
    + + + +
        func (e *SyntaxError) Error() string
    + + + +
    type Token
    + + + + +
    type UnmarshalFieldError
    + + + +
        func (e *UnmarshalFieldError) Error() string
    + + + +
    type UnmarshalTypeError
    + + + +
        func (e *UnmarshalTypeError) Error() string
    + + + +
    type Unmarshaler
    + + + + +
    type UnsupportedTypeError
    + + + +
        func (e *UnsupportedTypeError) Error() string
    + + + +
    type UnsupportedValueError
    + + + +
        func (e *UnsupportedValueError) Error() string
    + + + +
    +
    + + +
    +

    Examples

    +
    + +
    Decoder
    + +
    Decoder.Decode (Stream)
    + +
    Decoder.Token
    + +
    Indent
    + +
    Marshal
    + +
    RawMessage
    + +
    Unmarshal
    + +
    +
    + + + +

    Package files

    +

    + + + decode.go + + encode.go + + fold.go + + indent.go + + scanner.go + + stream.go + + tags.go + + +

    + +
    +
    + + + + + + + + +

    func Compact

    +
    func Compact(dst *bytes.Buffer, src []byte) error
    +

    +Compact appends to dst the JSON-encoded src with +insignificant space characters elided. +

    + + + + + + + +

    func HTMLEscape

    +
    func HTMLEscape(dst *bytes.Buffer, src []byte)
    +

    +HTMLEscape appends to dst the JSON-encoded src with <, >, &, U+2028 and U+2029 +characters inside string literals changed to \u003c, \u003e, \u0026, \u2028, \u2029 +so that the JSON will be safe to embed inside HTML <script> tags. +For historical reasons, web browsers don't honor standard HTML +escaping within <script> tags, so an alternative JSON encoding must +be used. +

    + + + + + + + +

    func Indent

    +
    func Indent(dst *bytes.Buffer, src []byte, prefix, indent string) error
    +

    +Indent appends to dst an indented form of the JSON-encoded src. +Each element in a JSON object or array begins on a new, +indented line beginning with prefix followed by one or more +copies of indent according to the indentation nesting. +The data appended to dst does not begin with the prefix nor +any indentation, to make it easier to embed inside other formatted JSON data. +Although leading space characters (space, tab, carriage return, newline) +at the beginning of src are dropped, trailing space characters +at the end of src are preserved and copied to dst. +For example, if src has no trailing spaces, neither will dst; +if src ends in a trailing newline, so will dst. +

    + +
    + +
    +

    Example

    + + + +

    Code:

    +
    type Road struct {
    +    Name   string
    +    Number int
    +}
    +roads := []Road{
    +    {"Diamond Fork", 29},
    +    {"Sheep Creek", 51},
    +}
    +
    +b, err := json.Marshal(roads)
    +if err != nil {
    +    log.Fatal(err)
    +}
    +
    +var out bytes.Buffer
    +json.Indent(&out, b, "=", "\t")
    +out.WriteTo(os.Stdout)
    +
    + +

    Output:

    +
    [
    +=	{
    +=		"Name": "Diamond Fork",
    +=		"Number": 29
    +=	},
    +=	{
    +=		"Name": "Sheep Creek",
    +=		"Number": 51
    +=	}
    +=]
    +
    + + +
    +
    + + + + + + +

    func Marshal

    +
    func Marshal(v interface{}) ([]byte, error)
    +

    +Marshal returns the JSON encoding of v. +

    +

    +Marshal traverses the value v recursively. +If an encountered value implements the Marshaler interface +and is not a nil pointer, Marshal calls its MarshalJSON method +to produce JSON. If no MarshalJSON method is present but the +value implements encoding.TextMarshaler instead, Marshal calls +its MarshalText method. +The nil pointer exception is not strictly necessary +but mimics a similar, necessary exception in the behavior of +UnmarshalJSON. +

    +

    +Otherwise, Marshal uses the following type-dependent default encodings: +

    +

    +Boolean values encode as JSON booleans. +

    +

    +Floating point, integer, and Number values encode as JSON numbers. +

    +

    +String values encode as JSON strings coerced to valid UTF-8, +replacing invalid bytes with the Unicode replacement rune. +The angle brackets "<" and ">" are escaped to "\u003c" and "\u003e" +to keep some browsers from misinterpreting JSON output as HTML. +Ampersand "&" is also escaped to "\u0026" for the same reason. +

    +

    +Array and slice values encode as JSON arrays, except that +[]byte encodes as a base64-encoded string, and a nil slice +encodes as the null JSON object. +

    +

    +Struct values encode as JSON objects. Each exported struct field +becomes a member of the object unless +

    +
    - the field's tag is "-", or
    +- the field is empty and its tag specifies the "omitempty" option.
    +
    +

    +The empty values are false, 0, any +nil pointer or interface value, and any array, slice, map, or string of +length zero. The object's default key string is the struct field name +but can be specified in the struct field's tag value. The "json" key in +the struct field's tag value is the key name, followed by an optional comma +and options. Examples: +

    +
    // Field is ignored by this package.
    +Field int `json:"-"`
    +
    +// Field appears in JSON as key "myName".
    +Field int `json:"myName"`
    +
    +// Field appears in JSON as key "myName" and
    +// the field is omitted from the object if its value is empty,
    +// as defined above.
    +Field int `json:"myName,omitempty"`
    +
    +// Field appears in JSON as key "Field" (the default), but
    +// the field is skipped if empty.
    +// Note the leading comma.
    +Field int `json:",omitempty"`
    +
    +

    +The "string" option signals that a field is stored as JSON inside a +JSON-encoded string. It applies only to fields of string, floating point, +integer, or boolean types. This extra level of encoding is sometimes used +when communicating with JavaScript programs: +

    +
    Int64String int64 `json:",string"`
    +
    +

    +The key name will be used if it's a non-empty string consisting of +only Unicode letters, digits, dollar signs, percent signs, hyphens, +underscores and slashes. +

    +

    +Anonymous struct fields are usually marshaled as if their inner exported fields +were fields in the outer struct, subject to the usual Go visibility rules amended +as described in the next paragraph. +An anonymous struct field with a name given in its JSON tag is treated as +having that name, rather than being anonymous. +An anonymous struct field of interface type is treated the same as having +that type as its name, rather than being anonymous. +

    +

    +The Go visibility rules for struct fields are amended for JSON when +deciding which field to marshal or unmarshal. If there are +multiple fields at the same level, and that level is the least +nested (and would therefore be the nesting level selected by the +usual Go rules), the following extra rules apply: +

    +

    +1) Of those fields, if any are JSON-tagged, only tagged fields are considered, +even if there are multiple untagged fields that would otherwise conflict. +2) If there is exactly one field (tagged or not according to the first rule), that is selected. +3) Otherwise there are multiple fields, and all are ignored; no error occurs. +

    +

    +Handling of anonymous struct fields is new in Go 1.1. +Prior to Go 1.1, anonymous struct fields were ignored. To force ignoring of +an anonymous struct field in both current and earlier versions, give the field +a JSON tag of "-". +

    +

    +Map values encode as JSON objects. +The map's key type must be string; the map keys are used as JSON object +keys, subject to the UTF-8 coercion described for string values above. +

    +

    +Pointer values encode as the value pointed to. +A nil pointer encodes as the null JSON object. +

    +

    +Interface values encode as the value contained in the interface. +A nil interface value encodes as the null JSON object. +

    +

    +Channel, complex, and function values cannot be encoded in JSON. +Attempting to encode such a value causes Marshal to return +an UnsupportedTypeError. +

    +

    +JSON cannot represent cyclic data structures and Marshal does not +handle them. Passing cyclic structures to Marshal will result in +an infinite recursion. +

    + +
    + +
    +

    Example

    + + + +

    Code:

    +
    type ColorGroup struct {
    +    ID     int
    +    Name   string
    +    Colors []string
    +}
    +group := ColorGroup{
    +    ID:     1,
    +    Name:   "Reds",
    +    Colors: []string{"Crimson", "Red", "Ruby", "Maroon"},
    +}
    +b, err := json.Marshal(group)
    +if err != nil {
    +    fmt.Println("error:", err)
    +}
    +os.Stdout.Write(b)
    +
    + +

    Output:

    +
    {"ID":1,"Name":"Reds","Colors":["Crimson","Red","Ruby","Maroon"]}
    +
    + + +
    +
    + + + + + + +

    func MarshalIndent

    +
    func MarshalIndent(v interface{}, prefix, indent string) ([]byte, error)
    +

    +MarshalIndent is like Marshal but applies Indent to format the output. +

    + + + + + + + +

    func Unmarshal

    +
    func Unmarshal(data []byte, v interface{}) error
    +

    +Unmarshal parses the JSON-encoded data and stores the result +in the value pointed to by v. +

    +

    +Unmarshal uses the inverse of the encodings that +Marshal uses, allocating maps, slices, and pointers as necessary, +with the following additional rules: +

    +

    +To unmarshal JSON into a pointer, Unmarshal first handles the case of +the JSON being the JSON literal null. In that case, Unmarshal sets +the pointer to nil. Otherwise, Unmarshal unmarshals the JSON into +the value pointed at by the pointer. If the pointer is nil, Unmarshal +allocates a new value for it to point to. +

    +

    +To unmarshal JSON into a struct, Unmarshal matches incoming object +keys to the keys used by Marshal (either the struct field name or its tag), +preferring an exact match but also accepting a case-insensitive match. +Unmarshal will only set exported fields of the struct. +

    +

    +To unmarshal JSON into an interface value, +Unmarshal stores one of these in the interface value: +

    +
    bool, for JSON booleans
    +float64, for JSON numbers
    +string, for JSON strings
    +[]interface{}, for JSON arrays
    +map[string]interface{}, for JSON objects
    +nil for JSON null
    +
    +

    +To unmarshal a JSON array into a slice, Unmarshal resets the slice length +to zero and then appends each element to the slice. +As a special case, to unmarshal an empty JSON array into a slice, +Unmarshal replaces the slice with a new empty slice. +

    +

    +To unmarshal a JSON array into a Go array, Unmarshal decodes +JSON array elements into corresponding Go array elements. +If the Go array is smaller than the JSON array, +the additional JSON array elements are discarded. +If the JSON array is smaller than the Go array, +the additional Go array elements are set to zero values. +

    +

    +To unmarshal a JSON object into a string-keyed map, Unmarshal first +establishes a map to use, If the map is nil, Unmarshal allocates a new map. +Otherwise Unmarshal reuses the existing map, keeping existing entries. +Unmarshal then stores key-value pairs from the JSON object into the map. +

    +

    +If a JSON value is not appropriate for a given target type, +or if a JSON number overflows the target type, Unmarshal +skips that field and completes the unmarshaling as best it can. +If no more serious errors are encountered, Unmarshal returns +an UnmarshalTypeError describing the earliest such error. +

    +

    +The JSON null value unmarshals into an interface, map, pointer, or slice +by setting that Go value to nil. Because null is often used in JSON to mean +“not present,” unmarshaling a JSON null into any other Go type has no effect +on the value and produces no error. +

    +

    +When unmarshaling quoted strings, invalid UTF-8 or +invalid UTF-16 surrogate pairs are not treated as an error. +Instead, they are replaced by the Unicode replacement +character U+FFFD. +

    + +
    + +
    +

    Example

    + + + +

    Code:

    +
    var jsonBlob = []byte(`[
    +    {"Name": "Platypus", "Order": "Monotremata"},
    +    {"Name": "Quoll",    "Order": "Dasyuromorphia"}
    +]`)
    +type Animal struct {
    +    Name  string
    +    Order string
    +}
    +var animals []Animal
    +err := json.Unmarshal(jsonBlob, &animals)
    +if err != nil {
    +    fmt.Println("error:", err)
    +}
    +fmt.Printf("%+v", animals)
    +
    + +

    Output:

    +
    [{Name:Platypus Order:Monotremata} {Name:Quoll Order:Dasyuromorphia}]
    +
    + + +
    +
    + + + + + + + +

    type Decoder

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

    +A Decoder reads and decodes JSON objects from an input stream. +

    + + + + + + +
    + +
    +

    Example

    +

    This example uses a Decoder to decode a stream of distinct JSON values. +

    + + +

    Code:

    +
    const jsonStream = `
    +    {"Name": "Ed", "Text": "Knock knock."}
    +    {"Name": "Sam", "Text": "Who's there?"}
    +    {"Name": "Ed", "Text": "Go fmt."}
    +    {"Name": "Sam", "Text": "Go fmt who?"}
    +    {"Name": "Ed", "Text": "Go fmt yourself!"}
    +`
    +type Message struct {
    +    Name, Text string
    +}
    +dec := json.NewDecoder(strings.NewReader(jsonStream))
    +for {
    +    var m Message
    +    if err := dec.Decode(&m); err == io.EOF {
    +        break
    +    } else if err != nil {
    +        log.Fatal(err)
    +    }
    +    fmt.Printf("%s: %s\n", m.Name, m.Text)
    +}
    +
    + +

    Output:

    +
    Ed: Knock knock.
    +Sam: Who's there?
    +Ed: Go fmt.
    +Sam: Go fmt who?
    +Ed: Go fmt yourself!
    +
    + + +
    +
    + + + + + + +

    func NewDecoder

    +
    func NewDecoder(r io.Reader) *Decoder
    +

    +NewDecoder returns a new decoder that reads from r. +

    +

    +The decoder introduces its own buffering and may +read data from r beyond the JSON values requested. +

    + + + + + + + +

    func (*Decoder) Buffered

    +
    func (dec *Decoder) Buffered() io.Reader
    +

    +Buffered returns a reader of the data remaining in the Decoder's +buffer. The reader is valid until the next call to Decode. +

    + + + + + + +

    func (*Decoder) Decode

    +
    func (dec *Decoder) Decode(v interface{}) error
    +

    +Decode reads the next JSON-encoded value from its +input and stores it in the value pointed to by v. +

    +

    +See the documentation for Unmarshal for details about +the conversion of JSON into a Go value. +

    + + +
    + +
    +

    Example (Stream)

    +

    This example uses a Decoder to decode a streaming array of JSON objects. +

    + + +

    Code:

    +
    const jsonStream = `
    +    [
    +        {"Name": "Ed", "Text": "Knock knock."},
    +        {"Name": "Sam", "Text": "Who's there?"},
    +        {"Name": "Ed", "Text": "Go fmt."},
    +        {"Name": "Sam", "Text": "Go fmt who?"},
    +        {"Name": "Ed", "Text": "Go fmt yourself!"}
    +    ]
    +`
    +type Message struct {
    +    Name, Text string
    +}
    +dec := json.NewDecoder(strings.NewReader(jsonStream))
    +
    +// read open bracket
    +t, err := dec.Token()
    +if err != nil {
    +    log.Fatal(err)
    +}
    +fmt.Printf("%T: %v\n", t, t)
    +
    +var m Message
    +// while the array contains values
    +for dec.More() {
    +
    +    // decode an array value (Message)
    +    err := dec.Decode(&m)
    +    if err != nil {
    +        log.Fatal(err)
    +    }
    +
    +    fmt.Printf("%v: %v\n", m.Name, m.Text)
    +}
    +
    +// read closing bracket
    +t, err = dec.Token()
    +if err != nil {
    +    log.Fatal(err)
    +}
    +fmt.Printf("%T: %v\n", t, t)
    +
    +
    + +

    Output:

    +
    json.Delim: [
    +Ed: Knock knock.
    +Sam: Who's there?
    +Ed: Go fmt.
    +Sam: Go fmt who?
    +Ed: Go fmt yourself!
    +json.Delim: ]
    +
    + + +
    +
    + + + + +

    func (*Decoder) More

    +
    func (dec *Decoder) More() bool
    +

    +More reports whether there is another element in the +current array or object being parsed. +

    + + + + + + +

    func (*Decoder) Token

    +
    func (dec *Decoder) Token() (Token, error)
    +

    +Token returns the next JSON token in the input stream. +At the end of the input stream, Token returns nil, io.EOF. +

    +

    +Token guarantees that the delimiters [ ] { } it returns are +properly nested and matched: if Token encounters an unexpected +delimiter in the input, it will return an error. +

    +

    +The input stream consists of basic JSON values—bool, string, +number, and null—along with delimiters [ ] { } of type Delim +to mark the start and end of arrays and objects. +Commas and colons are elided. +

    + + +
    + +
    +

    Example

    +

    This example uses a Decoder to decode a stream of distinct JSON values. +

    + + +

    Code:

    +
    const jsonStream = `
    +    {"Message": "Hello", "Array": [1, 2, 3], "Null": null, "Number": 1.234}
    +`
    +dec := json.NewDecoder(strings.NewReader(jsonStream))
    +for {
    +    t, err := dec.Token()
    +    if err == io.EOF {
    +        break
    +    }
    +    if err != nil {
    +        log.Fatal(err)
    +    }
    +    fmt.Printf("%T: %v", t, t)
    +    if dec.More() {
    +        fmt.Printf(" (more)")
    +    }
    +    fmt.Printf("\n")
    +}
    +
    + +

    Output:

    +
    json.Delim: { (more)
    +string: Message (more)
    +string: Hello (more)
    +string: Array (more)
    +json.Delim: [ (more)
    +float64: 1 (more)
    +float64: 2 (more)
    +float64: 3
    +json.Delim: ] (more)
    +string: Null (more)
    +<nil>: <nil> (more)
    +string: Number (more)
    +float64: 1.234
    +json.Delim: }
    +
    + + +
    +
    + + + + +

    func (*Decoder) UseNumber

    +
    func (dec *Decoder) UseNumber()
    +

    +UseNumber causes the Decoder to unmarshal a number into an interface{} as a +Number instead of as a float64. +

    + + + + + + + + +

    type Delim

    +
    type Delim rune
    +

    +A Delim is a JSON array or object delimiter, one of [ ] { or }. +

    + + + + + + + + + + + + + + +

    func (Delim) String

    +
    func (d Delim) String() string
    + + + + + + + + +

    type Encoder

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

    +An Encoder writes JSON objects to an output stream. +

    + + + + + + + + + + + + +

    func NewEncoder

    +
    func NewEncoder(w io.Writer) *Encoder
    +

    +NewEncoder returns a new encoder that writes to w. +

    + + + + + + + +

    func (*Encoder) Encode

    +
    func (enc *Encoder) Encode(v interface{}) error
    +

    +Encode writes the JSON encoding of v to the stream, +followed by a newline character. +

    +

    +See the documentation for Marshal for details about the +conversion of Go values to JSON. +

    + + + + + + + + +

    type InvalidUTF8Error

    +
    type InvalidUTF8Error struct {
    +    S string // the whole string value that caused the error
    +}
    +

    +Before Go 1.2, an InvalidUTF8Error was returned by Marshal when +attempting to encode a string value with invalid UTF-8 sequences. +As of Go 1.2, Marshal instead coerces the string to valid UTF-8 by +replacing invalid bytes with the Unicode replacement rune U+FFFD. +This error is no longer generated but is kept for backwards compatibility +with programs that might mention it. +

    + + + + + + + + + + + + + + +

    func (*InvalidUTF8Error) Error

    +
    func (e *InvalidUTF8Error) Error() string
    + + + + + + + + +

    type InvalidUnmarshalError

    +
    type InvalidUnmarshalError struct {
    +    Type reflect.Type
    +}
    +

    +An InvalidUnmarshalError describes an invalid argument passed to Unmarshal. +(The argument to Unmarshal must be a non-nil pointer.) +

    + + + + + + + + + + + + + + +

    func (*InvalidUnmarshalError) Error

    +
    func (e *InvalidUnmarshalError) Error() string
    + + + + + + + + +

    type Marshaler

    +
    type Marshaler interface {
    +    MarshalJSON() ([]byte, error)
    +}
    +

    +Marshaler is the interface implemented by objects that +can marshal themselves into valid JSON. +

    + + + + + + + + + + + + + + + + +

    type MarshalerError

    +
    type MarshalerError struct {
    +    Type reflect.Type
    +    Err  error
    +}
    + + + + + + + + + + + + + + +

    func (*MarshalerError) Error

    +
    func (e *MarshalerError) Error() string
    + + + + + + + + +

    type Number

    +
    type Number string
    +

    +A Number represents a JSON number literal. +

    + + + + + + + + + + + + + + +

    func (Number) Float64

    +
    func (n Number) Float64() (float64, error)
    +

    +Float64 returns the number as a float64. +

    + + + + + + +

    func (Number) Int64

    +
    func (n Number) Int64() (int64, error)
    +

    +Int64 returns the number as an int64. +

    + + + + + + +

    func (Number) String

    +
    func (n Number) String() string
    +

    +String returns the literal text of the number. +

    + + + + + + + + +

    type RawMessage

    +
    type RawMessage []byte
    +

    +RawMessage is a raw encoded JSON object. +It implements Marshaler and Unmarshaler and can +be used to delay JSON decoding or precompute a JSON encoding. +

    + + + + + + +
    + +
    +

    Example

    +

    This example uses RawMessage to delay parsing part of a JSON message. +

    + + +

    Code:

    +
    type Color struct {
    +    Space string
    +    Point json.RawMessage // delay parsing until we know the color space
    +}
    +type RGB struct {
    +    R uint8
    +    G uint8
    +    B uint8
    +}
    +type YCbCr struct {
    +    Y  uint8
    +    Cb int8
    +    Cr int8
    +}
    +
    +var j = []byte(`[
    +    {"Space": "YCbCr", "Point": {"Y": 255, "Cb": 0, "Cr": -10}},
    +    {"Space": "RGB",   "Point": {"R": 98, "G": 218, "B": 255}}
    +]`)
    +var colors []Color
    +err := json.Unmarshal(j, &colors)
    +if err != nil {
    +    log.Fatalln("error:", err)
    +}
    +
    +for _, c := range colors {
    +    var dst interface{}
    +    switch c.Space {
    +    case "RGB":
    +        dst = new(RGB)
    +    case "YCbCr":
    +        dst = new(YCbCr)
    +    }
    +    err := json.Unmarshal(c.Point, dst)
    +    if err != nil {
    +        log.Fatalln("error:", err)
    +    }
    +    fmt.Println(c.Space, dst)
    +}
    +
    + +

    Output:

    +
    YCbCr &{255 0 -10}
    +RGB &{98 218 255}
    +
    + + +
    +
    + + + + + + + + +

    func (*RawMessage) MarshalJSON

    +
    func (m *RawMessage) MarshalJSON() ([]byte, error)
    +

    +MarshalJSON returns *m as the JSON encoding of m. +

    + + + + + + +

    func (*RawMessage) UnmarshalJSON

    +
    func (m *RawMessage) UnmarshalJSON(data []byte) error
    +

    +UnmarshalJSON sets *m to a copy of data. +

    + + + + + + + + +

    type SyntaxError

    +
    type SyntaxError struct {
    +    Offset int64 // error occurred after reading Offset bytes
    +    // contains filtered or unexported fields
    +}
    +

    +A SyntaxError is a description of a JSON syntax error. +

    + + + + + + + + + + + + + + +

    func (*SyntaxError) Error

    +
    func (e *SyntaxError) Error() string
    + + + + + + + + +

    type Token

    +
    type Token interface{}
    +

    +A Token holds a value of one of these types: +

    +
    Delim, for the four JSON delimiters [ ] { }
    +bool, for JSON booleans
    +float64, for JSON numbers
    +Number, for JSON numbers
    +string, for JSON string literals
    +nil, for JSON null
    +
    + + + + + + + + + + + + + + + + +

    type UnmarshalFieldError

    +
    type UnmarshalFieldError struct {
    +    Key   string
    +    Type  reflect.Type
    +    Field reflect.StructField
    +}
    +

    +An UnmarshalFieldError describes a JSON object key that +led to an unexported (and therefore unwritable) struct field. +(No longer used; kept for compatibility.) +

    + + + + + + + + + + + + + + +

    func (*UnmarshalFieldError) Error

    +
    func (e *UnmarshalFieldError) Error() string
    + + + + + + + + +

    type UnmarshalTypeError

    +
    type UnmarshalTypeError struct {
    +    Value  string       // description of JSON value - "bool", "array", "number -5"
    +    Type   reflect.Type // type of Go value it could not be assigned to
    +    Offset int64        // error occurred after reading Offset bytes
    +}
    +

    +An UnmarshalTypeError describes a JSON value that was +not appropriate for a value of a specific Go type. +

    + + + + + + + + + + + + + + +

    func (*UnmarshalTypeError) Error

    +
    func (e *UnmarshalTypeError) Error() string
    + + + + + + + + +

    type Unmarshaler

    +
    type Unmarshaler interface {
    +    UnmarshalJSON([]byte) error
    +}
    +

    +Unmarshaler is the interface implemented by objects +that can unmarshal a JSON description of themselves. +The input can be assumed to be a valid encoding of +a JSON value. UnmarshalJSON must copy the JSON data +if it wishes to retain the data after returning. +

    + + + + + + + + + + + + + + + + +

    type UnsupportedTypeError

    +
    type UnsupportedTypeError struct {
    +    Type reflect.Type
    +}
    +

    +An UnsupportedTypeError is returned by Marshal when attempting +to encode an unsupported value type. +

    + + + + + + + + + + + + + + +

    func (*UnsupportedTypeError) Error

    +
    func (e *UnsupportedTypeError) Error() string
    + + + + + + + + +

    type UnsupportedValueError

    +
    type UnsupportedValueError struct {
    +    Value reflect.Value
    +    Str   string
    +}
    + + + + + + + + + + + + + + +

    func (*UnsupportedValueError) Error

    +
    func (e *UnsupportedValueError) Error() string
    + + + + + + + + + + + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/encoding/pem/index.html b/pkg/encoding/pem/index.html new file mode 100644 index 0000000..9df5863 --- /dev/null +++ b/pkg/encoding/pem/index.html @@ -0,0 +1,288 @@ + + + + + + + + pem - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Package pem

    + + + + + + + + + + + + + + +
    +
    +
    import "encoding/pem"
    +
    +
    +
    Overview
    +
    Index
    + + +
    +
    + +
    + +
    +

    Overview ▾

    +

    +Package pem implements the PEM data encoding, which originated in Privacy +Enhanced Mail. The most common use of PEM encoding today is in TLS keys and +certificates. See RFC 1421. +

    + +
    +
    + + +
    + +
    +

    Index ▾

    + + + + + + + +

    Package files

    +

    + + + pem.go + + +

    + +
    +
    + + + + + + + + +

    func Encode

    +
    func Encode(out io.Writer, b *Block) error
    + + + + + + + +

    func EncodeToMemory

    +
    func EncodeToMemory(b *Block) []byte
    + + + + + + + + +

    type Block

    +
    type Block struct {
    +    Type    string            // The type, taken from the preamble (i.e. "RSA PRIVATE KEY").
    +    Headers map[string]string // Optional headers.
    +    Bytes   []byte            // The decoded bytes of the contents. Typically a DER encoded ASN.1 structure.
    +}
    +

    +A Block represents a PEM encoded structure. +

    +

    +The encoded form is: +

    +
    -----BEGIN Type-----
    +Headers
    +base64-encoded Bytes
    +-----END Type-----
    +
    +

    +where Headers is a possibly empty sequence of Key: Value lines. +

    + + + + + + + + + + + + +

    func Decode

    +
    func Decode(data []byte) (p *Block, rest []byte)
    +

    +Decode will find the next PEM formatted block (certificate, private key +etc) in the input. It returns that block and the remainder of the input. If +no PEM data is found, p is nil and the whole of the input is returned in +rest. +

    + + + + + + + + + + + + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/encoding/xml/index.html b/pkg/encoding/xml/index.html new file mode 100644 index 0000000..fb251a2 --- /dev/null +++ b/pkg/encoding/xml/index.html @@ -0,0 +1,1709 @@ + + + + + + + + xml - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Package xml

    + + + + + + + + + + + + + + +
    +
    +
    import "encoding/xml"
    +
    +
    +
    Overview
    +
    Index
    + +
    Examples
    + + +
    +
    + +
    + +
    +

    Overview ▾

    +

    +Package xml implements a simple XML 1.0 parser that +understands XML name spaces. +

    + +
    +
    + + +
    + +
    +

    Index ▾

    + + +
    +
    + +
    Constants
    + + +
    Variables
    + + + +
    func Escape(w io.Writer, s []byte)
    + + +
    func EscapeText(w io.Writer, s []byte) error
    + + +
    func Marshal(v interface{}) ([]byte, error)
    + + +
    func MarshalIndent(v interface{}, prefix, indent string) ([]byte, error)
    + + +
    func Unmarshal(data []byte, v interface{}) error
    + + + +
    type Attr
    + + + + +
    type CharData
    + + + +
        func (c CharData) Copy() CharData
    + + + +
    type Comment
    + + + +
        func (c Comment) Copy() Comment
    + + + +
    type Decoder
    + + +
        func NewDecoder(r io.Reader) *Decoder
    + + + +
        func (d *Decoder) Decode(v interface{}) error
    + + +
        func (d *Decoder) DecodeElement(v interface{}, start *StartElement) error
    + + +
        func (d *Decoder) InputOffset() int64
    + + +
        func (d *Decoder) RawToken() (Token, error)
    + + +
        func (d *Decoder) Skip() error
    + + +
        func (d *Decoder) Token() (t Token, err error)
    + + + +
    type Directive
    + + + +
        func (d Directive) Copy() Directive
    + + + +
    type Encoder
    + + +
        func NewEncoder(w io.Writer) *Encoder
    + + + +
        func (enc *Encoder) Encode(v interface{}) error
    + + +
        func (enc *Encoder) EncodeElement(v interface{}, start StartElement) error
    + + +
        func (enc *Encoder) EncodeToken(t Token) error
    + + +
        func (enc *Encoder) Flush() error
    + + +
        func (enc *Encoder) Indent(prefix, indent string)
    + + + +
    type EndElement
    + + + + +
    type Marshaler
    + + + + +
    type MarshalerAttr
    + + + + +
    type Name
    + + + + +
    type ProcInst
    + + + +
        func (p ProcInst) Copy() ProcInst
    + + + +
    type StartElement
    + + + +
        func (e StartElement) Copy() StartElement
    + + +
        func (e StartElement) End() EndElement
    + + + +
    type SyntaxError
    + + + +
        func (e *SyntaxError) Error() string
    + + + +
    type TagPathError
    + + + +
        func (e *TagPathError) Error() string
    + + + +
    type Token
    + + +
        func CopyToken(t Token) Token
    + + + + +
    type UnmarshalError
    + + + +
        func (e UnmarshalError) Error() string
    + + + +
    type Unmarshaler
    + + + + +
    type UnmarshalerAttr
    + + + + +
    type UnsupportedTypeError
    + + + +
        func (e *UnsupportedTypeError) Error() string
    + + + + +
    Bugs
    + + +
    +
    + + +
    +

    Examples

    +
    + +
    Encoder
    + +
    MarshalIndent
    + +
    Unmarshal
    + +
    +
    + + + +

    Package files

    +

    + + + marshal.go + + read.go + + typeinfo.go + + xml.go + + +

    + +
    +
    + + + + +

    Constants

    + +
    const (
    +    // A generic XML header suitable for use with the output of Marshal.
    +    // This is not automatically added to any output of this package,
    +    // it is provided as a convenience.
    +    Header = `<?xml version="1.0" encoding="UTF-8"?>` + "\n"
    +)
    + + + + +

    Variables

    + +
    var HTMLAutoClose = htmlAutoClose
    +

    +HTMLAutoClose is the set of HTML elements that +should be considered to close automatically. +

    + + +
    var HTMLEntity = htmlEntity
    +

    +HTMLEntity is an entity map containing translations for the +standard HTML entity characters. +

    + + + + + + +

    func Escape

    +
    func Escape(w io.Writer, s []byte)
    +

    +Escape is like EscapeText but omits the error return value. +It is provided for backwards compatibility with Go 1.0. +Code targeting Go 1.1 or later should use EscapeText. +

    + + + + + + + +

    func EscapeText

    +
    func EscapeText(w io.Writer, s []byte) error
    +

    +EscapeText writes to w the properly escaped XML equivalent +of the plain text data s. +

    + + + + + + + +

    func Marshal

    +
    func Marshal(v interface{}) ([]byte, error)
    +

    +Marshal returns the XML encoding of v. +

    +

    +Marshal handles an array or slice by marshalling each of the elements. +Marshal handles a pointer by marshalling the value it points at or, if the +pointer is nil, by writing nothing. Marshal handles an interface value by +marshalling the value it contains or, if the interface value is nil, by +writing nothing. Marshal handles all other data by writing one or more XML +elements containing the data. +

    +

    +The name for the XML elements is taken from, in order of preference: +

    +
    - the tag on the XMLName field, if the data is a struct
    +- the value of the XMLName field of type xml.Name
    +- the tag of the struct field used to obtain the data
    +- the name of the struct field used to obtain the data
    +- the name of the marshalled type
    +
    +

    +The XML element for a struct contains marshalled elements for each of the +exported fields of the struct, with these exceptions: +

    +
    - the XMLName field, described above, is omitted.
    +- a field with tag "-" is omitted.
    +- a field with tag "name,attr" becomes an attribute with
    +  the given name in the XML element.
    +- a field with tag ",attr" becomes an attribute with the
    +  field name in the XML element.
    +- a field with tag ",chardata" is written as character data,
    +  not as an XML element.
    +- a field with tag ",cdata" is written as character data
    +  wrapped in one or more <![CDATA[ ... ]]> tags, not as an XML element.
    +- a field with tag ",innerxml" is written verbatim, not subject
    +  to the usual marshalling procedure.
    +- a field with tag ",comment" is written as an XML comment, not
    +  subject to the usual marshalling procedure. It must not contain
    +  the "--" string within it.
    +- a field with a tag including the "omitempty" option is omitted
    +  if the field value is empty. The empty values are false, 0, any
    +  nil pointer or interface value, and any array, slice, map, or
    +  string of length zero.
    +- an anonymous struct field is handled as if the fields of its
    +  value were part of the outer struct.
    +
    +

    +If a field uses a tag "a>b>c", then the element c will be nested inside +parent elements a and b. Fields that appear next to each other that name +the same parent will be enclosed in one XML element. +

    +

    +See MarshalIndent for an example. +

    +

    +Marshal will return an error if asked to marshal a channel, function, or map. +

    + + + + + + + +

    func MarshalIndent

    +
    func MarshalIndent(v interface{}, prefix, indent string) ([]byte, error)
    +

    +MarshalIndent works like Marshal, but each XML element begins on a new +indented line that starts with prefix and is followed by one or more +copies of indent according to the nesting depth. +

    + +
    + +
    +

    Example

    + + + +

    Code:

    +
    type Address struct {
    +    City, State string
    +}
    +type Person struct {
    +    XMLName   xml.Name `xml:"person"`
    +    Id        int      `xml:"id,attr"`
    +    FirstName string   `xml:"name>first"`
    +    LastName  string   `xml:"name>last"`
    +    Age       int      `xml:"age"`
    +    Height    float32  `xml:"height,omitempty"`
    +    Married   bool
    +    Address
    +    Comment string `xml:",comment"`
    +}
    +
    +v := &Person{Id: 13, FirstName: "John", LastName: "Doe", Age: 42}
    +v.Comment = " Need more details. "
    +v.Address = Address{"Hanga Roa", "Easter Island"}
    +
    +output, err := xml.MarshalIndent(v, "  ", "    ")
    +if err != nil {
    +    fmt.Printf("error: %v\n", err)
    +}
    +
    +os.Stdout.Write(output)
    +
    + +

    Output:

    +
      <person id="13">
    +      <name>
    +          <first>John</first>
    +          <last>Doe</last>
    +      </name>
    +      <age>42</age>
    +      <Married>false</Married>
    +      <City>Hanga Roa</City>
    +      <State>Easter Island</State>
    +      <!-- Need more details. -->
    +  </person>
    +
    + + +
    +
    + + + + + + +

    func Unmarshal

    +
    func Unmarshal(data []byte, v interface{}) error
    +

    +Unmarshal parses the XML-encoded data and stores the result in +the value pointed to by v, which must be an arbitrary struct, +slice, or string. Well-formed data that does not fit into v is +discarded. +

    +

    +Because Unmarshal uses the reflect package, it can only assign +to exported (upper case) fields. Unmarshal uses a case-sensitive +comparison to match XML element names to tag values and struct +field names. +

    +

    +Unmarshal maps an XML element to a struct using the following rules. +In the rules, the tag of a field refers to the value associated with the +key 'xml' in the struct field's tag (see the example above). +

    +
    * If the struct has a field of type []byte or string with tag
    +   ",innerxml", Unmarshal accumulates the raw XML nested inside the
    +   element in that field.  The rest of the rules still apply.
    +
    +* If the struct has a field named XMLName of type xml.Name,
    +   Unmarshal records the element name in that field.
    +
    +* If the XMLName field has an associated tag of the form
    +   "name" or "namespace-URL name", the XML element must have
    +   the given name (and, optionally, name space) or else Unmarshal
    +   returns an error.
    +
    +* If the XML element has an attribute whose name matches a
    +   struct field name with an associated tag containing ",attr" or
    +   the explicit name in a struct field tag of the form "name,attr",
    +   Unmarshal records the attribute value in that field.
    +
    +* If the XML element contains character data, that data is
    +   accumulated in the first struct field that has tag ",chardata".
    +   The struct field may have type []byte or string.
    +   If there is no such field, the character data is discarded.
    +
    +* If the XML element contains comments, they are accumulated in
    +   the first struct field that has tag ",comment".  The struct
    +   field may have type []byte or string.  If there is no such
    +   field, the comments are discarded.
    +
    +* If the XML element contains a sub-element whose name matches
    +   the prefix of a tag formatted as "a" or "a>b>c", unmarshal
    +   will descend into the XML structure looking for elements with the
    +   given names, and will map the innermost elements to that struct
    +   field. A tag starting with ">" is equivalent to one starting
    +   with the field name followed by ">".
    +
    +* If the XML element contains a sub-element whose name matches
    +   a struct field's XMLName tag and the struct field has no
    +   explicit name tag as per the previous rule, unmarshal maps
    +   the sub-element to that struct field.
    +
    +* If the XML element contains a sub-element whose name matches a
    +   field without any mode flags (",attr", ",chardata", etc), Unmarshal
    +   maps the sub-element to that struct field.
    +
    +* If the XML element contains a sub-element that hasn't matched any
    +   of the above rules and the struct has a field with tag ",any",
    +   unmarshal maps the sub-element to that struct field.
    +
    +* An anonymous struct field is handled as if the fields of its
    +   value were part of the outer struct.
    +
    +* A struct field with tag "-" is never unmarshalled into.
    +
    +

    +Unmarshal maps an XML element to a string or []byte by saving the +concatenation of that element's character data in the string or +[]byte. The saved []byte is never nil. +

    +

    +Unmarshal maps an attribute value to a string or []byte by saving +the value in the string or slice. +

    +

    +Unmarshal maps an XML element to a slice by extending the length of +the slice and mapping the element to the newly created value. +

    +

    +Unmarshal maps an XML element or attribute value to a bool by +setting it to the boolean value represented by the string. +

    +

    +Unmarshal maps an XML element or attribute value to an integer or +floating-point field by setting the field to the result of +interpreting the string value in decimal. There is no check for +overflow. +

    +

    +Unmarshal maps an XML element to an xml.Name by recording the +element name. +

    +

    +Unmarshal maps an XML element to a pointer by setting the pointer +to a freshly allocated value and then mapping the element to that value. +

    + +
    + +
    +

    Example

    +

    This example demonstrates unmarshaling an XML excerpt into a value with +some preset fields. Note that the Phone field isn't modified and that +the XML <Company> element is ignored. Also, the Groups field is assigned +considering the element path provided in its tag. +

    + + +

    Code:

    +
    type Email struct {
    +    Where string `xml:"where,attr"`
    +    Addr  string
    +}
    +type Address struct {
    +    City, State string
    +}
    +type Result struct {
    +    XMLName xml.Name `xml:"Person"`
    +    Name    string   `xml:"FullName"`
    +    Phone   string
    +    Email   []Email
    +    Groups  []string `xml:"Group>Value"`
    +    Address
    +}
    +v := Result{Name: "none", Phone: "none"}
    +
    +data := `
    +    <Person>
    +        <FullName>Grace R. Emlin</FullName>
    +        <Company>Example Inc.</Company>
    +        <Email where="home">
    +            <Addr>gre@example.com</Addr>
    +        </Email>
    +        <Email where='work'>
    +            <Addr>gre@work.com</Addr>
    +        </Email>
    +        <Group>
    +            <Value>Friends</Value>
    +            <Value>Squash</Value>
    +        </Group>
    +        <City>Hanga Roa</City>
    +        <State>Easter Island</State>
    +    </Person>
    +`
    +err := xml.Unmarshal([]byte(data), &v)
    +if err != nil {
    +    fmt.Printf("error: %v", err)
    +    return
    +}
    +fmt.Printf("XMLName: %#v\n", v.XMLName)
    +fmt.Printf("Name: %q\n", v.Name)
    +fmt.Printf("Phone: %q\n", v.Phone)
    +fmt.Printf("Email: %v\n", v.Email)
    +fmt.Printf("Groups: %v\n", v.Groups)
    +fmt.Printf("Address: %v\n", v.Address)
    +
    + +

    Output:

    +
    XMLName: xml.Name{Space:"", Local:"Person"}
    +Name: "Grace R. Emlin"
    +Phone: "none"
    +Email: [{home gre@example.com} {work gre@work.com}]
    +Groups: [Friends Squash]
    +Address: {Hanga Roa Easter Island}
    +
    + + +
    +
    + + + + + + + +

    type Attr

    +
    type Attr struct {
    +    Name  Name
    +    Value string
    +}
    +

    +An Attr represents an attribute in an XML element (Name=Value). +

    + + + + + + + + + + + + + + + + +

    type CharData

    +
    type CharData []byte
    +

    +A CharData represents XML character data (raw text), +in which XML escape sequences have been replaced by +the characters they represent. +

    + + + + + + + + + + + + + + +

    func (CharData) Copy

    +
    func (c CharData) Copy() CharData
    + + + + + + + + +

    type Comment

    +
    type Comment []byte
    +

    +A Comment represents an XML comment of the form <!--comment-->. +The bytes do not include the <!-- and --> comment markers. +

    + + + + + + + + + + + + + + +

    func (Comment) Copy

    +
    func (c Comment) Copy() Comment
    + + + + + + + + +

    type Decoder

    +
    type Decoder struct {
    +    // Strict defaults to true, enforcing the requirements
    +    // of the XML specification.
    +    // If set to false, the parser allows input containing common
    +    // mistakes:
    +    //	* If an element is missing an end tag, the parser invents
    +    //	  end tags as necessary to keep the return values from Token
    +    //	  properly balanced.
    +    //	* In attribute values and character data, unknown or malformed
    +    //	  character entities (sequences beginning with &) are left alone.
    +    //
    +    // Setting:
    +    //
    +    //	d.Strict = false;
    +    //	d.AutoClose = HTMLAutoClose;
    +    //	d.Entity = HTMLEntity
    +    //
    +    // creates a parser that can handle typical HTML.
    +    //
    +    // Strict mode does not enforce the requirements of the XML name spaces TR.
    +    // In particular it does not reject name space tags using undefined prefixes.
    +    // Such tags are recorded with the unknown prefix as the name space URL.
    +    Strict bool
    +
    +    // When Strict == false, AutoClose indicates a set of elements to
    +    // consider closed immediately after they are opened, regardless
    +    // of whether an end element is present.
    +    AutoClose []string
    +
    +    // Entity can be used to map non-standard entity names to string replacements.
    +    // The parser behaves as if these standard mappings are present in the map,
    +    // regardless of the actual map content:
    +    //
    +    //	"lt": "<",
    +    //	"gt": ">",
    +    //	"amp": "&",
    +    //	"apos": "'",
    +    //	"quot": `"`,
    +    Entity map[string]string
    +
    +    // CharsetReader, if non-nil, defines a function to generate
    +    // charset-conversion readers, converting from the provided
    +    // non-UTF-8 charset into UTF-8. If CharsetReader is nil or
    +    // returns an error, parsing stops with an error. One of the
    +    // the CharsetReader's result values must be non-nil.
    +    CharsetReader func(charset string, input io.Reader) (io.Reader, error)
    +
    +    // DefaultSpace sets the default name space used for unadorned tags,
    +    // as if the entire XML stream were wrapped in an element containing
    +    // the attribute xmlns="DefaultSpace".
    +    DefaultSpace string
    +    // contains filtered or unexported fields
    +}
    +

    +A Decoder represents an XML parser reading a particular input stream. +The parser assumes that its input is encoded in UTF-8. +

    + + + + + + + + + + + + +

    func NewDecoder

    +
    func NewDecoder(r io.Reader) *Decoder
    +

    +NewDecoder creates a new XML parser reading from r. +If r does not implement io.ByteReader, NewDecoder will +do its own buffering. +

    + + + + + + + +

    func (*Decoder) Decode

    +
    func (d *Decoder) Decode(v interface{}) error
    +

    +Decode works like xml.Unmarshal, except it reads the decoder +stream to find the start element. +

    + + + + + + +

    func (*Decoder) DecodeElement

    +
    func (d *Decoder) DecodeElement(v interface{}, start *StartElement) error
    +

    +DecodeElement works like xml.Unmarshal except that it takes +a pointer to the start XML element to decode into v. +It is useful when a client reads some raw XML tokens itself +but also wants to defer to Unmarshal for some elements. +

    + + + + + + +

    func (*Decoder) InputOffset

    +
    func (d *Decoder) InputOffset() int64
    +

    +InputOffset returns the input stream byte offset of the current decoder position. +The offset gives the location of the end of the most recently returned token +and the beginning of the next token. +

    + + + + + + +

    func (*Decoder) RawToken

    +
    func (d *Decoder) RawToken() (Token, error)
    +

    +RawToken is like Token but does not verify that +start and end elements match and does not translate +name space prefixes to their corresponding URLs. +

    + + + + + + +

    func (*Decoder) Skip

    +
    func (d *Decoder) Skip() error
    +

    +Skip reads tokens until it has consumed the end element +matching the most recent start element already consumed. +It recurs if it encounters a start element, so it can be used to +skip nested structures. +It returns nil if it finds an end element matching the start +element; otherwise it returns an error describing the problem. +

    + + + + + + +

    func (*Decoder) Token

    +
    func (d *Decoder) Token() (t Token, err error)
    +

    +Token returns the next XML token in the input stream. +At the end of the input stream, Token returns nil, io.EOF. +

    +

    +Slices of bytes in the returned token data refer to the +parser's internal buffer and remain valid only until the next +call to Token. To acquire a copy of the bytes, call CopyToken +or the token's Copy method. +

    +

    +Token expands self-closing elements such as <br/> +into separate start and end elements returned by successive calls. +

    +

    +Token guarantees that the StartElement and EndElement +tokens it returns are properly nested and matched: +if Token encounters an unexpected end element +or EOF before all expected end elements, +it will return an error. +

    +

    +Token implements XML name spaces as described by +http://www.w3.org/TR/REC-xml-names/. Each of the +Name structures contained in the Token has the Space +set to the URL identifying its name space when known. +If Token encounters an unrecognized name space prefix, +it uses the prefix as the Space rather than report an error. +

    + + + + + + + + +

    type Directive

    +
    type Directive []byte
    +

    +A Directive represents an XML directive of the form <!text>. +The bytes do not include the <! and > markers. +

    + + + + + + + + + + + + + + +

    func (Directive) Copy

    +
    func (d Directive) Copy() Directive
    + + + + + + + + +

    type Encoder

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

    +An Encoder writes XML data to an output stream. +

    + + + + + + +
    + +
    +

    Example

    + + + +

    Code:

    +
    type Address struct {
    +    City, State string
    +}
    +type Person struct {
    +    XMLName   xml.Name `xml:"person"`
    +    Id        int      `xml:"id,attr"`
    +    FirstName string   `xml:"name>first"`
    +    LastName  string   `xml:"name>last"`
    +    Age       int      `xml:"age"`
    +    Height    float32  `xml:"height,omitempty"`
    +    Married   bool
    +    Address
    +    Comment string `xml:",comment"`
    +}
    +
    +v := &Person{Id: 13, FirstName: "John", LastName: "Doe", Age: 42}
    +v.Comment = " Need more details. "
    +v.Address = Address{"Hanga Roa", "Easter Island"}
    +
    +enc := xml.NewEncoder(os.Stdout)
    +enc.Indent("  ", "    ")
    +if err := enc.Encode(v); err != nil {
    +    fmt.Printf("error: %v\n", err)
    +}
    +
    +
    + +

    Output:

    +
      <person id="13">
    +      <name>
    +          <first>John</first>
    +          <last>Doe</last>
    +      </name>
    +      <age>42</age>
    +      <Married>false</Married>
    +      <City>Hanga Roa</City>
    +      <State>Easter Island</State>
    +      <!-- Need more details. -->
    +  </person>
    +
    + + +
    +
    + + + + + + +

    func NewEncoder

    +
    func NewEncoder(w io.Writer) *Encoder
    +

    +NewEncoder returns a new encoder that writes to w. +

    + + + + + + + +

    func (*Encoder) Encode

    +
    func (enc *Encoder) Encode(v interface{}) error
    +

    +Encode writes the XML encoding of v to the stream. +

    +

    +See the documentation for Marshal for details about the conversion +of Go values to XML. +

    +

    +Encode calls Flush before returning. +

    + + + + + + +

    func (*Encoder) EncodeElement

    +
    func (enc *Encoder) EncodeElement(v interface{}, start StartElement) error
    +

    +EncodeElement writes the XML encoding of v to the stream, +using start as the outermost tag in the encoding. +

    +

    +See the documentation for Marshal for details about the conversion +of Go values to XML. +

    +

    +EncodeElement calls Flush before returning. +

    + + + + + + +

    func (*Encoder) EncodeToken

    +
    func (enc *Encoder) EncodeToken(t Token) error
    +

    +EncodeToken writes the given XML token to the stream. +It returns an error if StartElement and EndElement tokens are not properly matched. +

    +

    +EncodeToken does not call Flush, because usually it is part of a larger operation +such as Encode or EncodeElement (or a custom Marshaler's MarshalXML invoked +during those), and those will call Flush when finished. +Callers that create an Encoder and then invoke EncodeToken directly, without +using Encode or EncodeElement, need to call Flush when finished to ensure +that the XML is written to the underlying writer. +

    +

    +EncodeToken allows writing a ProcInst with Target set to "xml" only as the first token +in the stream. +

    + + + + + + +

    func (*Encoder) Flush

    +
    func (enc *Encoder) Flush() error
    +

    +Flush flushes any buffered XML to the underlying writer. +See the EncodeToken documentation for details about when it is necessary. +

    + + + + + + +

    func (*Encoder) Indent

    +
    func (enc *Encoder) Indent(prefix, indent string)
    +

    +Indent sets the encoder to generate XML in which each element +begins on a new indented line that starts with prefix and is followed by +one or more copies of indent according to the nesting depth. +

    + + + + + + + + +

    type EndElement

    +
    type EndElement struct {
    +    Name Name
    +}
    +

    +An EndElement represents an XML end element. +

    + + + + + + + + + + + + + + + + +

    type Marshaler

    +
    type Marshaler interface {
    +    MarshalXML(e *Encoder, start StartElement) error
    +}
    +

    +Marshaler is the interface implemented by objects that can marshal +themselves into valid XML elements. +

    +

    +MarshalXML encodes the receiver as zero or more XML elements. +By convention, arrays or slices are typically encoded as a sequence +of elements, one per entry. +Using start as the element tag is not required, but doing so +will enable Unmarshal to match the XML elements to the correct +struct field. +One common implementation strategy is to construct a separate +value with a layout corresponding to the desired XML and then +to encode it using e.EncodeElement. +Another common strategy is to use repeated calls to e.EncodeToken +to generate the XML output one token at a time. +The sequence of encoded tokens must make up zero or more valid +XML elements. +

    + + + + + + + + + + + + + + + + +

    type MarshalerAttr

    +
    type MarshalerAttr interface {
    +    MarshalXMLAttr(name Name) (Attr, error)
    +}
    +

    +MarshalerAttr is the interface implemented by objects that can marshal +themselves into valid XML attributes. +

    +

    +MarshalXMLAttr returns an XML attribute with the encoded value of the receiver. +Using name as the attribute name is not required, but doing so +will enable Unmarshal to match the attribute to the correct +struct field. +If MarshalXMLAttr returns the zero attribute Attr{}, no attribute +will be generated in the output. +MarshalXMLAttr is used only for struct fields with the +"attr" option in the field tag. +

    + + + + + + + + + + + + + + + + +

    type Name

    +
    type Name struct {
    +    Space, Local string
    +}
    +

    +A Name represents an XML name (Local) annotated +with a name space identifier (Space). +In tokens returned by Decoder.Token, the Space identifier +is given as a canonical URL, not the short prefix used +in the document being parsed. +

    + + + + + + + + + + + + + + + + +

    type ProcInst

    +
    type ProcInst struct {
    +    Target string
    +    Inst   []byte
    +}
    +

    +A ProcInst represents an XML processing instruction of the form <?target inst?> +

    + + + + + + + + + + + + + + +

    func (ProcInst) Copy

    +
    func (p ProcInst) Copy() ProcInst
    + + + + + + + + +

    type StartElement

    +
    type StartElement struct {
    +    Name Name
    +    Attr []Attr
    +}
    +

    +A StartElement represents an XML start element. +

    + + + + + + + + + + + + + + +

    func (StartElement) Copy

    +
    func (e StartElement) Copy() StartElement
    + + + + + + +

    func (StartElement) End

    +
    func (e StartElement) End() EndElement
    +

    +End returns the corresponding XML end element. +

    + + + + + + + + +

    type SyntaxError

    +
    type SyntaxError struct {
    +    Msg  string
    +    Line int
    +}
    +

    +A SyntaxError represents a syntax error in the XML input stream. +

    + + + + + + + + + + + + + + +

    func (*SyntaxError) Error

    +
    func (e *SyntaxError) Error() string
    + + + + + + + + +

    type TagPathError

    +
    type TagPathError struct {
    +    Struct       reflect.Type
    +    Field1, Tag1 string
    +    Field2, Tag2 string
    +}
    +

    +A TagPathError represents an error in the unmarshalling process +caused by the use of field tags with conflicting paths. +

    + + + + + + + + + + + + + + +

    func (*TagPathError) Error

    +
    func (e *TagPathError) Error() string
    + + + + + + + + +

    type Token

    +
    type Token interface{}
    +

    +A Token is an interface holding one of the token types: +StartElement, EndElement, CharData, Comment, ProcInst, or Directive. +

    + + + + + + + + + + + + +

    func CopyToken

    +
    func CopyToken(t Token) Token
    +

    +CopyToken returns a copy of a Token. +

    + + + + + + + + + +

    type UnmarshalError

    +
    type UnmarshalError string
    +

    +An UnmarshalError represents an error in the unmarshalling process. +

    + + + + + + + + + + + + + + +

    func (UnmarshalError) Error

    +
    func (e UnmarshalError) Error() string
    + + + + + + + + +

    type Unmarshaler

    +
    type Unmarshaler interface {
    +    UnmarshalXML(d *Decoder, start StartElement) error
    +}
    +

    +Unmarshaler is the interface implemented by objects that can unmarshal +an XML element description of themselves. +

    +

    +UnmarshalXML decodes a single XML element +beginning with the given start element. +If it returns an error, the outer call to Unmarshal stops and +returns that error. +UnmarshalXML must consume exactly one XML element. +One common implementation strategy is to unmarshal into +a separate value with a layout matching the expected XML +using d.DecodeElement, and then to copy the data from +that value into the receiver. +Another common strategy is to use d.Token to process the +XML object one token at a time. +UnmarshalXML may not use d.RawToken. +

    + + + + + + + + + + + + + + + + +

    type UnmarshalerAttr

    +
    type UnmarshalerAttr interface {
    +    UnmarshalXMLAttr(attr Attr) error
    +}
    +

    +UnmarshalerAttr is the interface implemented by objects that can unmarshal +an XML attribute description of themselves. +

    +

    +UnmarshalXMLAttr decodes a single XML attribute. +If it returns an error, the outer call to Unmarshal stops and +returns that error. +UnmarshalXMLAttr is used only for struct fields with the +"attr" option in the field tag. +

    + + + + + + + + + + + + + + + + +

    type UnsupportedTypeError

    +
    type UnsupportedTypeError struct {
    +    Type reflect.Type
    +}
    +

    +A MarshalXMLError is returned when Marshal encounters a type +that cannot be converted into XML. +

    + + + + + + + + + + + + + + +

    func (*UnsupportedTypeError) Error

    +
    func (e *UnsupportedTypeError) Error() string
    + + + + + + + + + + +

    Bugs

    +
      + +
    • Mapping between XML elements and data structures is inherently flawed: +an XML element is an order-dependent collection of anonymous +values, while a data structure is an order-independent collection +of named values. +See package json for a textual representation more suitable +to data structures. +
    • + +
    + + + + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/errors/index.html b/pkg/errors/index.html new file mode 100644 index 0000000..5159400 --- /dev/null +++ b/pkg/errors/index.html @@ -0,0 +1,329 @@ + + + + + + + + errors - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Package errors

    + + + + + + + + + + + + + + +
    +
    +
    import "errors"
    +
    +
    +
    Overview
    +
    Index
    + +
    Examples
    + + +
    +
    + +
    + +
    +

    Overview ▾

    +

    +Package errors implements functions to manipulate errors. +

    + +
    +
    +
    + +
    +

    Example

    + + + +

    Code:

    +
    package errors_test
    +
    +import (
    +    "fmt"
    +    "time"
    +)
    +
    +// MyError is an error implementation that includes a time and message.
    +type MyError struct {
    +    When time.Time
    +    What string
    +}
    +
    +func (e MyError) Error() string {
    +    return fmt.Sprintf("%v: %v", e.When, e.What)
    +}
    +
    +func oops() error {
    +    return MyError{
    +        time.Date(1989, 3, 15, 22, 30, 0, 0, time.UTC),
    +        "the file system has gone away",
    +    }
    +}
    +
    +func Example() {
    +    if err := oops(); err != nil {
    +        fmt.Println(err)
    +    }
    +    // Output: 1989-03-15 22:30:00 +0000 UTC: the file system has gone away
    +}
    +
    + + +
    +
    + + +
    + +
    +

    Index ▾

    + + +
    +
    + + + + +
    func New(text string) error
    + + + +
    +
    + + +
    +

    Examples

    +
    + +
    Package
    + +
    New
    + +
    New (Errorf)
    + +
    +
    + + + +

    Package files

    +

    + + + errors.go + + +

    + +
    +
    + + + + + + + + +

    func New

    +
    func New(text string) error
    +

    +New returns an error that formats as the given text. +

    + +
    + +
    +

    Example

    + + + +

    Code:

    +
    err := errors.New("emit macho dwarf: elf header corrupted")
    +if err != nil {
    +    fmt.Print(err)
    +}
    +
    + +

    Output:

    +
    emit macho dwarf: elf header corrupted
    +
    + + +
    +
    +
    + +
    +

    Example (Errorf)

    +

    The fmt package's Errorf function lets us use the package's formatting +features to create descriptive error messages. +

    + + +

    Code:

    +
    const name, id = "bimmler", 17
    +err := fmt.Errorf("user %q (id %d) not found", name, id)
    +if err != nil {
    +    fmt.Print(err)
    +}
    +
    + +

    Output:

    +
    user "bimmler" (id 17) not found
    +
    + + +
    +
    + + + + + + + + + + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/flag/index.html b/pkg/flag/index.html new file mode 100644 index 0000000..4f40682 --- /dev/null +++ b/pkg/flag/index.html @@ -0,0 +1,1561 @@ + + + + + + + + flag - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Package flag

    + + + + + + + + + + + + + + +
    +
    +
    import "flag"
    +
    +
    +
    Overview
    +
    Index
    + +
    Examples
    + + +
    +
    + +
    + +
    +

    Overview ▾

    +

    +Package flag implements command-line flag parsing. +

    +

    +Usage: +

    +

    +Define flags using flag.String(), Bool(), Int(), etc. +

    +

    +This declares an integer flag, -flagname, stored in the pointer ip, with type *int. +

    +
    import "flag"
    +var ip = flag.Int("flagname", 1234, "help message for flagname")
    +
    +

    +If you like, you can bind the flag to a variable using the Var() functions. +

    +
    var flagvar int
    +func init() {
    +	flag.IntVar(&flagvar, "flagname", 1234, "help message for flagname")
    +}
    +
    +

    +Or you can create custom flags that satisfy the Value interface (with +pointer receivers) and couple them to flag parsing by +

    +
    flag.Var(&flagVal, "name", "help message for flagname")
    +
    +

    +For such flags, the default value is just the initial value of the variable. +

    +

    +After all flags are defined, call +

    +
    flag.Parse()
    +
    +

    +to parse the command line into the defined flags. +

    +

    +Flags may then be used directly. If you're using the flags themselves, +they are all pointers; if you bind to variables, they're values. +

    +
    fmt.Println("ip has value ", *ip)
    +fmt.Println("flagvar has value ", flagvar)
    +
    +

    +After parsing, the arguments following the flags are available as the +slice flag.Args() or individually as flag.Arg(i). +The arguments are indexed from 0 through flag.NArg()-1. +

    +

    +Command line flag syntax: +

    +
    -flag
    +-flag=x
    +-flag x  // non-boolean flags only
    +
    +

    +One or two minus signs may be used; they are equivalent. +The last form is not permitted for boolean flags because the +meaning of the command +

    +
    cmd -x *
    +
    +

    +will change if there is a file called 0, false, etc. You must +use the -flag=false form to turn off a boolean flag. +

    +

    +Flag parsing stops just before the first non-flag argument +("-" is a non-flag argument) or after the terminator "--". +

    +

    +Integer flags accept 1234, 0664, 0x1234 and may be negative. +Boolean flags may be: +

    +
    1, 0, t, f, T, F, true, false, TRUE, FALSE, True, False
    +
    +

    +Duration flags accept any input valid for time.ParseDuration. +

    +

    +The default set of command-line flags is controlled by +top-level functions. The FlagSet type allows one to define +independent sets of flags, such as to implement subcommands +in a command-line interface. The methods of FlagSet are +analogous to the top-level functions for the command-line +flag set. +

    + +
    +
    +
    + +
    +

    Example

    + + + +

    Code:

    +
    // These examples demonstrate more intricate uses of the flag package.
    +package flag_test
    +
    +import (
    +    "errors"
    +    "flag"
    +    "fmt"
    +    "strings"
    +    "time"
    +)
    +
    +// Example 1: A single string flag called "species" with default value "gopher".
    +var species = flag.String("species", "gopher", "the species we are studying")
    +
    +// Example 2: Two flags sharing a variable, so we can have a shorthand.
    +// The order of initialization is undefined, so make sure both use the
    +// same default value. They must be set up with an init function.
    +var gopherType string
    +
    +func init() {
    +    const (
    +        defaultGopher = "pocket"
    +        usage         = "the variety of gopher"
    +    )
    +    flag.StringVar(&gopherType, "gopher_type", defaultGopher, usage)
    +    flag.StringVar(&gopherType, "g", defaultGopher, usage+" (shorthand)")
    +}
    +
    +// Example 3: A user-defined flag type, a slice of durations.
    +type interval []time.Duration
    +
    +// String is the method to format the flag's value, part of the flag.Value interface.
    +// The String method's output will be used in diagnostics.
    +func (i *interval) String() string {
    +    return fmt.Sprint(*i)
    +}
    +
    +// Set is the method to set the flag value, part of the flag.Value interface.
    +// Set's argument is a string to be parsed to set the flag.
    +// It's a comma-separated list, so we split it.
    +func (i *interval) Set(value string) error {
    +    // If we wanted to allow the flag to be set multiple times,
    +    // accumulating values, we would delete this if statement.
    +    // That would permit usages such as
    +    //	-deltaT 10s -deltaT 15s
    +    // and other combinations.
    +    if len(*i) > 0 {
    +        return errors.New("interval flag already set")
    +    }
    +    for _, dt := range strings.Split(value, ",") {
    +        duration, err := time.ParseDuration(dt)
    +        if err != nil {
    +            return err
    +        }
    +        *i = append(*i, duration)
    +    }
    +    return nil
    +}
    +
    +// Define a flag to accumulate durations. Because it has a special type,
    +// we need to use the Var function and therefore create the flag during
    +// init.
    +
    +var intervalFlag interval
    +
    +func init() {
    +    // Tie the command-line flag to the intervalFlag variable and
    +    // set a usage message.
    +    flag.Var(&intervalFlag, "deltaT", "comma-separated list of intervals to use between events")
    +}
    +
    +func Example() {
    +    // All the interesting pieces are with the variables declared above, but
    +    // to enable the flag package to see the flags defined there, one must
    +    // execute, typically at the start of main (not init!):
    +    //	flag.Parse()
    +    // We don't run it here because this is not a main function and
    +    // the testing suite has already parsed the flags.
    +}
    +
    + + +
    +
    + + +
    + +
    +

    Index ▾

    + + +
    +
    + + +
    Variables
    + + + +
    func Arg(i int) string
    + + +
    func Args() []string
    + + +
    func Bool(name string, value bool, usage string) *bool
    + + +
    func BoolVar(p *bool, name string, value bool, usage string)
    + + +
    func Duration(name string, value time.Duration, usage string) *time.Duration
    + + +
    func DurationVar(p *time.Duration, name string, value time.Duration, usage string)
    + + +
    func Float64(name string, value float64, usage string) *float64
    + + +
    func Float64Var(p *float64, name string, value float64, usage string)
    + + +
    func Int(name string, value int, usage string) *int
    + + +
    func Int64(name string, value int64, usage string) *int64
    + + +
    func Int64Var(p *int64, name string, value int64, usage string)
    + + +
    func IntVar(p *int, name string, value int, usage string)
    + + +
    func NArg() int
    + + +
    func NFlag() int
    + + +
    func Parse()
    + + +
    func Parsed() bool
    + + +
    func PrintDefaults()
    + + +
    func Set(name, value string) error
    + + +
    func String(name string, value string, usage string) *string
    + + +
    func StringVar(p *string, name string, value string, usage string)
    + + +
    func Uint(name string, value uint, usage string) *uint
    + + +
    func Uint64(name string, value uint64, usage string) *uint64
    + + +
    func Uint64Var(p *uint64, name string, value uint64, usage string)
    + + +
    func UintVar(p *uint, name string, value uint, usage string)
    + + +
    func UnquoteUsage(flag *Flag) (name string, usage string)
    + + +
    func Var(value Value, name string, usage string)
    + + +
    func Visit(fn func(*Flag))
    + + +
    func VisitAll(fn func(*Flag))
    + + + +
    type ErrorHandling
    + + + + +
    type Flag
    + + +
        func Lookup(name string) *Flag
    + + + + +
    type FlagSet
    + + +
        func NewFlagSet(name string, errorHandling ErrorHandling) *FlagSet
    + + + +
        func (f *FlagSet) Arg(i int) string
    + + +
        func (f *FlagSet) Args() []string
    + + +
        func (f *FlagSet) Bool(name string, value bool, usage string) *bool
    + + +
        func (f *FlagSet) BoolVar(p *bool, name string, value bool, usage string)
    + + +
        func (f *FlagSet) Duration(name string, value time.Duration, usage string) *time.Duration
    + + +
        func (f *FlagSet) DurationVar(p *time.Duration, name string, value time.Duration, usage string)
    + + +
        func (f *FlagSet) Float64(name string, value float64, usage string) *float64
    + + +
        func (f *FlagSet) Float64Var(p *float64, name string, value float64, usage string)
    + + +
        func (f *FlagSet) Init(name string, errorHandling ErrorHandling)
    + + +
        func (f *FlagSet) Int(name string, value int, usage string) *int
    + + +
        func (f *FlagSet) Int64(name string, value int64, usage string) *int64
    + + +
        func (f *FlagSet) Int64Var(p *int64, name string, value int64, usage string)
    + + +
        func (f *FlagSet) IntVar(p *int, name string, value int, usage string)
    + + +
        func (f *FlagSet) Lookup(name string) *Flag
    + + +
        func (f *FlagSet) NArg() int
    + + +
        func (f *FlagSet) NFlag() int
    + + +
        func (f *FlagSet) Parse(arguments []string) error
    + + +
        func (f *FlagSet) Parsed() bool
    + + +
        func (f *FlagSet) PrintDefaults()
    + + +
        func (f *FlagSet) Set(name, value string) error
    + + +
        func (f *FlagSet) SetOutput(output io.Writer)
    + + +
        func (f *FlagSet) String(name string, value string, usage string) *string
    + + +
        func (f *FlagSet) StringVar(p *string, name string, value string, usage string)
    + + +
        func (f *FlagSet) Uint(name string, value uint, usage string) *uint
    + + +
        func (f *FlagSet) Uint64(name string, value uint64, usage string) *uint64
    + + +
        func (f *FlagSet) Uint64Var(p *uint64, name string, value uint64, usage string)
    + + +
        func (f *FlagSet) UintVar(p *uint, name string, value uint, usage string)
    + + +
        func (f *FlagSet) Var(value Value, name string, usage string)
    + + +
        func (f *FlagSet) Visit(fn func(*Flag))
    + + +
        func (f *FlagSet) VisitAll(fn func(*Flag))
    + + + +
    type Getter
    + + + + +
    type Value
    + + + + +
    +
    + + +
    +

    Examples

    +
    + +
    Package
    + +
    +
    + + + +

    Package files

    +

    + + + flag.go + + +

    + +
    +
    + + + + + +

    Variables

    + +
    var CommandLine = NewFlagSet(os.Args[0], ExitOnError)
    +

    +CommandLine is the default set of command-line flags, parsed from os.Args. +The top-level functions such as BoolVar, Arg, and so on are wrappers for the +methods of CommandLine. +

    + + +
    var ErrHelp = errors.New("flag: help requested")
    +

    +ErrHelp is the error returned if the -help or -h flag is invoked +but no such flag is defined. +

    + + +
    var Usage = func() {
    +    fmt.Fprintf(os.Stderr, "Usage of %s:\n", os.Args[0])
    +    PrintDefaults()
    +}
    +

    +Usage prints to standard error a usage message documenting all defined command-line flags. +It is called when an error occurs while parsing flags. +The function is a variable that may be changed to point to a custom function. +By default it prints a simple header and calls PrintDefaults; for details about the +format of the output and how to control it, see the documentation for PrintDefaults. +

    + + + + + + +

    func Arg

    +
    func Arg(i int) string
    +

    +Arg returns the i'th command-line argument. Arg(0) is the first remaining argument +after flags have been processed. Arg returns an empty string if the +requested element does not exist. +

    + + + + + + + +

    func Args

    +
    func Args() []string
    +

    +Args returns the non-flag command-line arguments. +

    + + + + + + + +

    func Bool

    +
    func Bool(name string, value bool, usage string) *bool
    +

    +Bool defines a bool flag with specified name, default value, and usage string. +The return value is the address of a bool variable that stores the value of the flag. +

    + + + + + + + +

    func BoolVar

    +
    func BoolVar(p *bool, name string, value bool, usage string)
    +

    +BoolVar defines a bool flag with specified name, default value, and usage string. +The argument p points to a bool variable in which to store the value of the flag. +

    + + + + + + + +

    func Duration

    +
    func Duration(name string, value time.Duration, usage string) *time.Duration
    +

    +Duration defines a time.Duration flag with specified name, default value, and usage string. +The return value is the address of a time.Duration variable that stores the value of the flag. +The flag accepts a value acceptable to time.ParseDuration. +

    + + + + + + + +

    func DurationVar

    +
    func DurationVar(p *time.Duration, name string, value time.Duration, usage string)
    +

    +DurationVar defines a time.Duration flag with specified name, default value, and usage string. +The argument p points to a time.Duration variable in which to store the value of the flag. +The flag accepts a value acceptable to time.ParseDuration. +

    + + + + + + + +

    func Float64

    +
    func Float64(name string, value float64, usage string) *float64
    +

    +Float64 defines a float64 flag with specified name, default value, and usage string. +The return value is the address of a float64 variable that stores the value of the flag. +

    + + + + + + + +

    func Float64Var

    +
    func Float64Var(p *float64, name string, value float64, usage string)
    +

    +Float64Var defines a float64 flag with specified name, default value, and usage string. +The argument p points to a float64 variable in which to store the value of the flag. +

    + + + + + + + +

    func Int

    +
    func Int(name string, value int, usage string) *int
    +

    +Int defines an int flag with specified name, default value, and usage string. +The return value is the address of an int variable that stores the value of the flag. +

    + + + + + + + +

    func Int64

    +
    func Int64(name string, value int64, usage string) *int64
    +

    +Int64 defines an int64 flag with specified name, default value, and usage string. +The return value is the address of an int64 variable that stores the value of the flag. +

    + + + + + + + +

    func Int64Var

    +
    func Int64Var(p *int64, name string, value int64, usage string)
    +

    +Int64Var defines an int64 flag with specified name, default value, and usage string. +The argument p points to an int64 variable in which to store the value of the flag. +

    + + + + + + + +

    func IntVar

    +
    func IntVar(p *int, name string, value int, usage string)
    +

    +IntVar defines an int flag with specified name, default value, and usage string. +The argument p points to an int variable in which to store the value of the flag. +

    + + + + + + + +

    func NArg

    +
    func NArg() int
    +

    +NArg is the number of arguments remaining after flags have been processed. +

    + + + + + + + +

    func NFlag

    +
    func NFlag() int
    +

    +NFlag returns the number of command-line flags that have been set. +

    + + + + + + + +

    func Parse

    +
    func Parse()
    +

    +Parse parses the command-line flags from os.Args[1:]. Must be called +after all flags are defined and before flags are accessed by the program. +

    + + + + + + + +

    func Parsed

    +
    func Parsed() bool
    +

    +Parsed reports whether the command-line flags have been parsed. +

    + + + + + + + +

    func PrintDefaults

    +
    func PrintDefaults()
    +

    +PrintDefaults prints, to standard error unless configured otherwise, +a usage message showing the default settings of all defined +command-line flags. +For an integer valued flag x, the default output has the form +

    +
    -x int
    +	usage-message-for-x (default 7)
    +
    +

    +The usage message will appear on a separate line for anything but +a bool flag with a one-byte name. For bool flags, the type is +omitted and if the flag name is one byte the usage message appears +on the same line. The parenthetical default is omitted if the +default is the zero value for the type. The listed type, here int, +can be changed by placing a back-quoted name in the flag's usage +string; the first such item in the message is taken to be a parameter +name to show in the message and the back quotes are stripped from +the message when displayed. For instance, given +

    +
    flag.String("I", "", "search `directory` for include files")
    +
    +

    +the output will be +

    +
    -I directory
    +	search directory for include files.
    +
    + + + + + + + +

    func Set

    +
    func Set(name, value string) error
    +

    +Set sets the value of the named command-line flag. +

    + + + + + + + +

    func String

    +
    func String(name string, value string, usage string) *string
    +

    +String defines a string flag with specified name, default value, and usage string. +The return value is the address of a string variable that stores the value of the flag. +

    + + + + + + + +

    func StringVar

    +
    func StringVar(p *string, name string, value string, usage string)
    +

    +StringVar defines a string flag with specified name, default value, and usage string. +The argument p points to a string variable in which to store the value of the flag. +

    + + + + + + + +

    func Uint

    +
    func Uint(name string, value uint, usage string) *uint
    +

    +Uint defines a uint flag with specified name, default value, and usage string. +The return value is the address of a uint variable that stores the value of the flag. +

    + + + + + + + +

    func Uint64

    +
    func Uint64(name string, value uint64, usage string) *uint64
    +

    +Uint64 defines a uint64 flag with specified name, default value, and usage string. +The return value is the address of a uint64 variable that stores the value of the flag. +

    + + + + + + + +

    func Uint64Var

    +
    func Uint64Var(p *uint64, name string, value uint64, usage string)
    +

    +Uint64Var defines a uint64 flag with specified name, default value, and usage string. +The argument p points to a uint64 variable in which to store the value of the flag. +

    + + + + + + + +

    func UintVar

    +
    func UintVar(p *uint, name string, value uint, usage string)
    +

    +UintVar defines a uint flag with specified name, default value, and usage string. +The argument p points to a uint variable in which to store the value of the flag. +

    + + + + + + + +

    func UnquoteUsage

    +
    func UnquoteUsage(flag *Flag) (name string, usage string)
    +

    +UnquoteUsage extracts a back-quoted name from the usage +string for a flag and returns it and the un-quoted usage. +Given "a `name` to show" it returns ("name", "a name to show"). +If there are no back quotes, the name is an educated guess of the +type of the flag's value, or the empty string if the flag is boolean. +

    + + + + + + + +

    func Var

    +
    func Var(value Value, name string, usage string)
    +

    +Var defines a flag with the specified name and usage string. The type and +value of the flag are represented by the first argument, of type Value, which +typically holds a user-defined implementation of Value. For instance, the +caller could create a flag that turns a comma-separated string into a slice +of strings by giving the slice the methods of Value; in particular, Set would +decompose the comma-separated string into the slice. +

    + + + + + + + +

    func Visit

    +
    func Visit(fn func(*Flag))
    +

    +Visit visits the command-line flags in lexicographical order, calling fn +for each. It visits only those flags that have been set. +

    + + + + + + + +

    func VisitAll

    +
    func VisitAll(fn func(*Flag))
    +

    +VisitAll visits the command-line flags in lexicographical order, calling +fn for each. It visits all flags, even those not set. +

    + + + + + + + + +

    type ErrorHandling

    +
    type ErrorHandling int
    +

    +ErrorHandling defines how FlagSet.Parse behaves if the parse fails. +

    + + + +
    const (
    +    ContinueOnError ErrorHandling = iota // Return a descriptive error.
    +    ExitOnError                          // Call os.Exit(2).
    +    PanicOnError                         // Call panic with a descriptive error.
    +)
    +

    +These constants cause FlagSet.Parse to behave as described if the parse fails. +

    + + + + + + + + + + + + + + + +

    type Flag

    +
    type Flag struct {
    +    Name     string // name as it appears on command line
    +    Usage    string // help message
    +    Value    Value  // value as set
    +    DefValue string // default value (as text); for usage message
    +}
    +

    +A Flag represents the state of a flag. +

    + + + + + + + + + + + + +

    func Lookup

    +
    func Lookup(name string) *Flag
    +

    +Lookup returns the Flag structure of the named command-line flag, +returning nil if none exists. +

    + + + + + + + + + +

    type FlagSet

    +
    type FlagSet struct {
    +    // Usage is the function called when an error occurs while parsing flags.
    +    // The field is a function (not a method) that may be changed to point to
    +    // a custom error handler.
    +    Usage func()
    +    // contains filtered or unexported fields
    +}
    +

    +A FlagSet represents a set of defined flags. The zero value of a FlagSet +has no name and has ContinueOnError error handling. +

    + + + + + + + + + + + + +

    func NewFlagSet

    +
    func NewFlagSet(name string, errorHandling ErrorHandling) *FlagSet
    +

    +NewFlagSet returns a new, empty flag set with the specified name and +error handling property. +

    + + + + + + + +

    func (*FlagSet) Arg

    +
    func (f *FlagSet) Arg(i int) string
    +

    +Arg returns the i'th argument. Arg(0) is the first remaining argument +after flags have been processed. Arg returns an empty string if the +requested element does not exist. +

    + + + + + + +

    func (*FlagSet) Args

    +
    func (f *FlagSet) Args() []string
    +

    +Args returns the non-flag arguments. +

    + + + + + + +

    func (*FlagSet) Bool

    +
    func (f *FlagSet) Bool(name string, value bool, usage string) *bool
    +

    +Bool defines a bool flag with specified name, default value, and usage string. +The return value is the address of a bool variable that stores the value of the flag. +

    + + + + + + +

    func (*FlagSet) BoolVar

    +
    func (f *FlagSet) BoolVar(p *bool, name string, value bool, usage string)
    +

    +BoolVar defines a bool flag with specified name, default value, and usage string. +The argument p points to a bool variable in which to store the value of the flag. +

    + + + + + + +

    func (*FlagSet) Duration

    +
    func (f *FlagSet) Duration(name string, value time.Duration, usage string) *time.Duration
    +

    +Duration defines a time.Duration flag with specified name, default value, and usage string. +The return value is the address of a time.Duration variable that stores the value of the flag. +The flag accepts a value acceptable to time.ParseDuration. +

    + + + + + + +

    func (*FlagSet) DurationVar

    +
    func (f *FlagSet) DurationVar(p *time.Duration, name string, value time.Duration, usage string)
    +

    +DurationVar defines a time.Duration flag with specified name, default value, and usage string. +The argument p points to a time.Duration variable in which to store the value of the flag. +The flag accepts a value acceptable to time.ParseDuration. +

    + + + + + + +

    func (*FlagSet) Float64

    +
    func (f *FlagSet) Float64(name string, value float64, usage string) *float64
    +

    +Float64 defines a float64 flag with specified name, default value, and usage string. +The return value is the address of a float64 variable that stores the value of the flag. +

    + + + + + + +

    func (*FlagSet) Float64Var

    +
    func (f *FlagSet) Float64Var(p *float64, name string, value float64, usage string)
    +

    +Float64Var defines a float64 flag with specified name, default value, and usage string. +The argument p points to a float64 variable in which to store the value of the flag. +

    + + + + + + +

    func (*FlagSet) Init

    +
    func (f *FlagSet) Init(name string, errorHandling ErrorHandling)
    +

    +Init sets the name and error handling property for a flag set. +By default, the zero FlagSet uses an empty name and the +ContinueOnError error handling policy. +

    + + + + + + +

    func (*FlagSet) Int

    +
    func (f *FlagSet) Int(name string, value int, usage string) *int
    +

    +Int defines an int flag with specified name, default value, and usage string. +The return value is the address of an int variable that stores the value of the flag. +

    + + + + + + +

    func (*FlagSet) Int64

    +
    func (f *FlagSet) Int64(name string, value int64, usage string) *int64
    +

    +Int64 defines an int64 flag with specified name, default value, and usage string. +The return value is the address of an int64 variable that stores the value of the flag. +

    + + + + + + +

    func (*FlagSet) Int64Var

    +
    func (f *FlagSet) Int64Var(p *int64, name string, value int64, usage string)
    +

    +Int64Var defines an int64 flag with specified name, default value, and usage string. +The argument p points to an int64 variable in which to store the value of the flag. +

    + + + + + + +

    func (*FlagSet) IntVar

    +
    func (f *FlagSet) IntVar(p *int, name string, value int, usage string)
    +

    +IntVar defines an int flag with specified name, default value, and usage string. +The argument p points to an int variable in which to store the value of the flag. +

    + + + + + + +

    func (*FlagSet) Lookup

    +
    func (f *FlagSet) Lookup(name string) *Flag
    +

    +Lookup returns the Flag structure of the named flag, returning nil if none exists. +

    + + + + + + +

    func (*FlagSet) NArg

    +
    func (f *FlagSet) NArg() int
    +

    +NArg is the number of arguments remaining after flags have been processed. +

    + + + + + + +

    func (*FlagSet) NFlag

    +
    func (f *FlagSet) NFlag() int
    +

    +NFlag returns the number of flags that have been set. +

    + + + + + + +

    func (*FlagSet) Parse

    +
    func (f *FlagSet) Parse(arguments []string) error
    +

    +Parse parses flag definitions from the argument list, which should not +include the command name. Must be called after all flags in the FlagSet +are defined and before flags are accessed by the program. +The return value will be ErrHelp if -help or -h were set but not defined. +

    + + + + + + +

    func (*FlagSet) Parsed

    +
    func (f *FlagSet) Parsed() bool
    +

    +Parsed reports whether f.Parse has been called. +

    + + + + + + +

    func (*FlagSet) PrintDefaults

    +
    func (f *FlagSet) PrintDefaults()
    +

    +PrintDefaults prints to standard error the default values of all +defined command-line flags in the set. See the documentation for +the global function PrintDefaults for more information. +

    + + + + + + +

    func (*FlagSet) Set

    +
    func (f *FlagSet) Set(name, value string) error
    +

    +Set sets the value of the named flag. +

    + + + + + + +

    func (*FlagSet) SetOutput

    +
    func (f *FlagSet) SetOutput(output io.Writer)
    +

    +SetOutput sets the destination for usage and error messages. +If output is nil, os.Stderr is used. +

    + + + + + + +

    func (*FlagSet) String

    +
    func (f *FlagSet) String(name string, value string, usage string) *string
    +

    +String defines a string flag with specified name, default value, and usage string. +The return value is the address of a string variable that stores the value of the flag. +

    + + + + + + +

    func (*FlagSet) StringVar

    +
    func (f *FlagSet) StringVar(p *string, name string, value string, usage string)
    +

    +StringVar defines a string flag with specified name, default value, and usage string. +The argument p points to a string variable in which to store the value of the flag. +

    + + + + + + +

    func (*FlagSet) Uint

    +
    func (f *FlagSet) Uint(name string, value uint, usage string) *uint
    +

    +Uint defines a uint flag with specified name, default value, and usage string. +The return value is the address of a uint variable that stores the value of the flag. +

    + + + + + + +

    func (*FlagSet) Uint64

    +
    func (f *FlagSet) Uint64(name string, value uint64, usage string) *uint64
    +

    +Uint64 defines a uint64 flag with specified name, default value, and usage string. +The return value is the address of a uint64 variable that stores the value of the flag. +

    + + + + + + +

    func (*FlagSet) Uint64Var

    +
    func (f *FlagSet) Uint64Var(p *uint64, name string, value uint64, usage string)
    +

    +Uint64Var defines a uint64 flag with specified name, default value, and usage string. +The argument p points to a uint64 variable in which to store the value of the flag. +

    + + + + + + +

    func (*FlagSet) UintVar

    +
    func (f *FlagSet) UintVar(p *uint, name string, value uint, usage string)
    +

    +UintVar defines a uint flag with specified name, default value, and usage string. +The argument p points to a uint variable in which to store the value of the flag. +

    + + + + + + +

    func (*FlagSet) Var

    +
    func (f *FlagSet) Var(value Value, name string, usage string)
    +

    +Var defines a flag with the specified name and usage string. The type and +value of the flag are represented by the first argument, of type Value, which +typically holds a user-defined implementation of Value. For instance, the +caller could create a flag that turns a comma-separated string into a slice +of strings by giving the slice the methods of Value; in particular, Set would +decompose the comma-separated string into the slice. +

    + + + + + + +

    func (*FlagSet) Visit

    +
    func (f *FlagSet) Visit(fn func(*Flag))
    +

    +Visit visits the flags in lexicographical order, calling fn for each. +It visits only those flags that have been set. +

    + + + + + + +

    func (*FlagSet) VisitAll

    +
    func (f *FlagSet) VisitAll(fn func(*Flag))
    +

    +VisitAll visits the flags in lexicographical order, calling fn for each. +It visits all flags, even those not set. +

    + + + + + + + + +

    type Getter

    +
    type Getter interface {
    +    Value
    +    Get() interface{}
    +}
    +

    +Getter is an interface that allows the contents of a Value to be retrieved. +It wraps the Value interface, rather than being part of it, because it +appeared after Go 1 and its compatibility rules. All Value types provided +by this package satisfy the Getter interface. +

    + + + + + + + + + + + + + + + + +

    type Value

    +
    type Value interface {
    +    String() string
    +    Set(string) error
    +}
    +

    +Value is the interface to the dynamic value stored in a flag. +(The default value is represented as a string.) +

    +

    +If a Value has an IsBoolFlag() bool method returning true, +the command-line parser makes -name equivalent to -name=true +rather than using the next command-line argument. +

    +

    +Set is called once, in command line order, for each flag present. +

    + + + + + + + + + + + + + + + + + + + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/fmt/index.html b/pkg/fmt/index.html new file mode 100644 index 0000000..43ae29d --- /dev/null +++ b/pkg/fmt/index.html @@ -0,0 +1,1148 @@ + + + + + + + + fmt - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Package fmt

    + + + + + + + + + + + + + + +
    +
    +
    import "fmt"
    +
    +
    +
    Overview
    +
    Index
    + + +
    +
    + +
    + +
    +

    Overview ▾

    +

    +Package fmt implements formatted I/O with functions analogous +to C's printf and scanf. The format 'verbs' are derived from C's but +are simpler. +

    +

    Printing

    +

    +The verbs: +

    +

    +General: +

    +
    %v	the value in a default format
    +	when printing structs, the plus flag (%+v) adds field names
    +%#v	a Go-syntax representation of the value
    +%T	a Go-syntax representation of the type of the value
    +%%	a literal percent sign; consumes no value
    +
    +

    +Boolean: +

    +
    %t	the word true or false
    +
    +

    +Integer: +

    +
    %b	base 2
    +%c	the character represented by the corresponding Unicode code point
    +%d	base 10
    +%o	base 8
    +%q	a single-quoted character literal safely escaped with Go syntax.
    +%x	base 16, with lower-case letters for a-f
    +%X	base 16, with upper-case letters for A-F
    +%U	Unicode format: U+1234; same as "U+%04X"
    +
    +

    +Floating-point and complex constituents: +

    +
    %b	decimalless scientific notation with exponent a power of two,
    +	in the manner of strconv.FormatFloat with the 'b' format,
    +	e.g. -123456p-78
    +%e	scientific notation, e.g. -1.234456e+78
    +%E	scientific notation, e.g. -1.234456E+78
    +%f	decimal point but no exponent, e.g. 123.456
    +%F	synonym for %f
    +%g	%e for large exponents, %f otherwise
    +%G	%E for large exponents, %F otherwise
    +
    +

    +String and slice of bytes (treated equivalently with these verbs): +

    +
    %s	the uninterpreted bytes of the string or slice
    +%q	a double-quoted string safely escaped with Go syntax
    +%x	base 16, lower-case, two characters per byte
    +%X	base 16, upper-case, two characters per byte
    +
    +

    +Pointer: +

    +
    %p	base 16 notation, with leading 0x
    +
    +

    +There is no 'u' flag. Integers are printed unsigned if they have unsigned type. +Similarly, there is no need to specify the size of the operand (int8, int64). +

    +

    +The default format for %v is: +

    +
    bool:                    %t
    +int, int8 etc.:          %d
    +uint, uint8 etc.:        %d, %x if printed with %#v
    +float32, complex64, etc: %g
    +string:                  %s
    +chan:                    %p
    +pointer:                 %p
    +
    +

    +For compound objects, the elements are printed using these rules, recursively, +laid out like this: +

    +
    struct:             {field0 field1 ...}
    +array, slice:       [elem0  elem1 ...]
    +maps:               map[key1:value1 key2:value2]
    +pointer to above:   &{}, &[], &map[]
    +
    +

    +Width is specified by an optional decimal number immediately preceding the verb. +If absent, the width is whatever is necessary to represent the value. +Precision is specified after the (optional) width by a period followed by a +decimal number. If no period is present, a default precision is used. +A period with no following number specifies a precision of zero. +Examples: +

    +
    %f     default width, default precision
    +%9f    width 9, default precision
    +%.2f   default width, precision 2
    +%9.2f  width 9, precision 2
    +%9.f   width 9, precision 0
    +
    +

    +Width and precision are measured in units of Unicode code points, +that is, runes. (This differs from C's printf where the +units are always measured in bytes.) Either or both of the flags +may be replaced with the character '*', causing their values to be +obtained from the next operand, which must be of type int. +

    +

    +For most values, width is the minimum number of runes to output, +padding the formatted form with spaces if necessary. +

    +

    +For strings, byte slices and byte arrays, however, precision +limits the length of the input to be formatted (not the size of +the output), truncating if necessary. Normally it is measured in +runes, but for these types when formatted with the %x or %X format +it is measured in bytes. +

    +

    +For floating-point values, width sets the minimum width of the field and +precision sets the number of places after the decimal, if appropriate, +except that for %g/%G it sets the total number of digits. For example, +given 123.45 the format %6.2f prints 123.45 while %.4g prints 123.5. +The default precision for %e and %f is 6; for %g it is the smallest +number of digits necessary to identify the value uniquely. +

    +

    +For complex numbers, the width and precision apply to the two +components independently and the result is parenthesized, so %f applied +to 1.2+3.4i produces (1.200000+3.400000i). +

    +

    +Other flags: +

    +
    +	always print a sign for numeric values;
    +	guarantee ASCII-only output for %q (%+q)
    +-	pad with spaces on the right rather than the left (left-justify the field)
    +#	alternate format: add leading 0 for octal (%#o), 0x for hex (%#x);
    +	0X for hex (%#X); suppress 0x for %p (%#p);
    +	for %q, print a raw (backquoted) string if strconv.CanBackquote
    +	returns true;
    +	write e.g. U+0078 'x' if the character is printable for %U (%#U).
    +' '	(space) leave a space for elided sign in numbers (% d);
    +	put spaces between bytes printing strings or slices in hex (% x, % X)
    +0	pad with leading zeros rather than spaces;
    +	for numbers, this moves the padding after the sign
    +
    +

    +Flags are ignored by verbs that do not expect them. +For example there is no alternate decimal format, so %#d and %d +behave identically. +

    +

    +For each Printf-like function, there is also a Print function +that takes no format and is equivalent to saying %v for every +operand. Another variant Println inserts blanks between +operands and appends a newline. +

    +

    +Regardless of the verb, if an operand is an interface value, +the internal concrete value is used, not the interface itself. +Thus: +

    +
    var i interface{} = 23
    +fmt.Printf("%v\n", i)
    +
    +

    +will print 23. +

    +

    +Except when printed using the verbs %T and %p, special +formatting considerations apply for operands that implement +certain interfaces. In order of application: +

    +

    +1. If the operand is a reflect.Value, the operand is replaced by the +concrete value that it holds, and printing continues with the next rule. +

    +

    +2. If an operand implements the Formatter interface, it will +be invoked. Formatter provides fine control of formatting. +

    +

    +3. If the %v verb is used with the # flag (%#v) and the operand +implements the GoStringer interface, that will be invoked. +

    +

    +If the format (which is implicitly %v for Println etc.) is valid +for a string (%s %q %v %x %X), the following two rules apply: +

    +

    +4. If an operand implements the error interface, the Error method +will be invoked to convert the object to a string, which will then +be formatted as required by the verb (if any). +

    +

    +5. If an operand implements method String() string, that method +will be invoked to convert the object to a string, which will then +be formatted as required by the verb (if any). +

    +

    +For compound operands such as slices and structs, the format +applies to the elements of each operand, recursively, not to the +operand as a whole. Thus %q will quote each element of a slice +of strings, and %6.2f will control formatting for each element +of a floating-point array. +

    +

    +However, when printing a byte slice with a string-like verb +(%s %q %x %X), it is treated identically to a string, as a single item. +

    +

    +To avoid recursion in cases such as +

    +
    type X string
    +func (x X) String() string { return Sprintf("<%s>", x) }
    +
    +

    +convert the value before recurring: +

    +
    func (x X) String() string { return Sprintf("<%s>", string(x)) }
    +
    +

    +Infinite recursion can also be triggered by self-referential data +structures, such as a slice that contains itself as an element, if +that type has a String method. Such pathologies are rare, however, +and the package does not protect against them. +

    +

    +Explicit argument indexes: +

    +

    +In Printf, Sprintf, and Fprintf, the default behavior is for each +formatting verb to format successive arguments passed in the call. +However, the notation [n] immediately before the verb indicates that the +nth one-indexed argument is to be formatted instead. The same notation +before a '*' for a width or precision selects the argument index holding +the value. After processing a bracketed expression [n], subsequent verbs +will use arguments n+1, n+2, etc. unless otherwise directed. +

    +

    +For example, +

    +
    fmt.Sprintf("%[2]d %[1]d\n", 11, 22)
    +
    +

    +will yield "22 11", while +

    +
    fmt.Sprintf("%[3]*.[2]*[1]f", 12.0, 2, 6),
    +
    +

    +equivalent to +

    +
    fmt.Sprintf("%6.2f", 12.0),
    +
    +

    +will yield " 12.00". Because an explicit index affects subsequent verbs, +this notation can be used to print the same values multiple times +by resetting the index for the first argument to be repeated: +

    +
    fmt.Sprintf("%d %d %#[1]x %#x", 16, 17)
    +
    +

    +will yield "16 17 0x10 0x11". +

    +

    +Format errors: +

    +

    +If an invalid argument is given for a verb, such as providing +a string to %d, the generated string will contain a +description of the problem, as in these examples: +

    +
    Wrong type or unknown verb: %!verb(type=value)
    +	Printf("%d", hi):          %!d(string=hi)
    +Too many arguments: %!(EXTRA type=value)
    +	Printf("hi", "guys"):      hi%!(EXTRA string=guys)
    +Too few arguments: %!verb(MISSING)
    +	Printf("hi%d"):            hi %!d(MISSING)
    +Non-int for width or precision: %!(BADWIDTH) or %!(BADPREC)
    +	Printf("%*s", 4.5, "hi"):  %!(BADWIDTH)hi
    +	Printf("%.*s", 4.5, "hi"): %!(BADPREC)hi
    +Invalid or invalid use of argument index: %!(BADINDEX)
    +	Printf("%*[2]d", 7):       %!d(BADINDEX)
    +	Printf("%.[2]d", 7):       %!d(BADINDEX)
    +
    +

    +All errors begin with the string "%!" followed sometimes +by a single character (the verb) and end with a parenthesized +description. +

    +

    +If an Error or String method triggers a panic when called by a +print routine, the fmt package reformats the error message +from the panic, decorating it with an indication that it came +through the fmt package. For example, if a String method +calls panic("bad"), the resulting formatted message will look +like +

    +
    %!s(PANIC=bad)
    +
    +

    +The %!s just shows the print verb in use when the failure +occurred. If the panic is caused by a nil receiver to an Error +or String method, however, the output is the undecorated +string, "<nil>". +

    +

    Scanning

    +

    +An analogous set of functions scans formatted text to yield +values. Scan, Scanf and Scanln read from os.Stdin; Fscan, +Fscanf and Fscanln read from a specified io.Reader; Sscan, +Sscanf and Sscanln read from an argument string. +

    +

    +Scan, Fscan, Sscan treat newlines in the input as spaces. +

    +

    +Scanln, Fscanln and Sscanln stop scanning at a newline and +require that the items be followed by a newline or EOF. +

    +

    +Scanf, Fscanf and Sscanf require that (after skipping spaces) +newlines in the format are matched by newlines in the input +and vice versa. This behavior differs from the corresponding +routines in C, which uniformly treat newlines as spaces. +

    +

    +When scanning with Scanf, Fscanf, and Sscanf, all non-empty +runs of space characters (except newline) are equivalent +to a single space in both the format and the input. With +that proviso, text in the format string must match the input +text; scanning stops if it does not, with the return value +of the function indicating the number of arguments scanned. +

    +

    +Scanf, Fscanf, and Sscanf parse the arguments according to a +format string, analogous to that of Printf. For example, %x +will scan an integer as a hexadecimal number, and %v will scan +the default representation format for the value. +

    +

    +The formats behave analogously to those of Printf with the +following exceptions: +

    +
    %p is not implemented
    +%T is not implemented
    +%e %E %f %F %g %G are all equivalent and scan any floating point or complex value
    +%s and %v on strings scan a space-delimited token
    +Flags # and + are not implemented.
    +
    +

    +The familiar base-setting prefixes 0 (octal) and 0x +(hexadecimal) are accepted when scanning integers without +a format or with the %v verb. +

    +

    +Width is interpreted in the input text but there is no +syntax for scanning with a precision (no %5.2f, just %5f). +If width is provided, it applies after leading spaces are +trimmed and specifies the maximum number of runes to read +to satisfy the verb. For example, +

    +
    Sscanf(" 1234567 ", "%5s%d", &s, &i)
    +
    +

    +will set s to "12345" and i to 67 while +

    +
    Sscanf(" 12 34 567 ", "%5s%d", &s, &i)
    +
    +

    +will set s to "12" and i to 34. +

    +

    +In all the scanning functions, a carriage return followed +immediately by a newline is treated as a plain newline +(\r\n means the same as \n). +

    +

    +In all the scanning functions, if an operand implements method +Scan (that is, it implements the Scanner interface) that +method will be used to scan the text for that operand. Also, +if the number of arguments scanned is less than the number of +arguments provided, an error is returned. +

    +

    +All arguments to be scanned must be either pointers to basic +types or implementations of the Scanner interface. +

    +

    +Note: Fscan etc. can read one character (rune) past the input +they return, which means that a loop calling a scan routine +may skip some of the input. This is usually a problem only +when there is no space between input values. If the reader +provided to Fscan implements ReadRune, that method will be used +to read characters. If the reader also implements UnreadRune, +that method will be used to save the character and successive +calls will not lose data. To attach ReadRune and UnreadRune +methods to a reader without that capability, use +bufio.NewReader. +

    + +
    +
    + + +
    + + +
    + + + + + + + + +

    func Errorf

    +
    func Errorf(format string, a ...interface{}) error
    +

    +Errorf formats according to a format specifier and returns the string +as a value that satisfies error. +

    + + + + + + + +

    func Fprint

    +
    func Fprint(w io.Writer, a ...interface{}) (n int, err error)
    +

    +Fprint formats using the default formats for its operands and writes to w. +Spaces are added between operands when neither is a string. +It returns the number of bytes written and any write error encountered. +

    + + + + + + + +

    func Fprintf

    +
    func Fprintf(w io.Writer, format string, a ...interface{}) (n int, err error)
    +

    +Fprintf formats according to a format specifier and writes to w. +It returns the number of bytes written and any write error encountered. +

    + + + + + + + +

    func Fprintln

    +
    func Fprintln(w io.Writer, a ...interface{}) (n int, err error)
    +

    +Fprintln formats using the default formats for its operands and writes to w. +Spaces are always added between operands and a newline is appended. +It returns the number of bytes written and any write error encountered. +

    + + + + + + + +

    func Fscan

    +
    func Fscan(r io.Reader, a ...interface{}) (n int, err error)
    +

    +Fscan scans text read from r, storing successive space-separated +values into successive arguments. Newlines count as space. It +returns the number of items successfully scanned. If that is less +than the number of arguments, err will report why. +

    + + + + + + + +

    func Fscanf

    +
    func Fscanf(r io.Reader, format string, a ...interface{}) (n int, err error)
    +

    +Fscanf scans text read from r, storing successive space-separated +values into successive arguments as determined by the format. It +returns the number of items successfully parsed. +Newlines in the input must match newlines in the format. +

    + + + + + + + +

    func Fscanln

    +
    func Fscanln(r io.Reader, a ...interface{}) (n int, err error)
    +

    +Fscanln is similar to Fscan, but stops scanning at a newline and +after the final item there must be a newline or EOF. +

    + + + + + + + +

    func Print

    +
    func Print(a ...interface{}) (n int, err error)
    +

    +Print formats using the default formats for its operands and writes to standard output. +Spaces are added between operands when neither is a string. +It returns the number of bytes written and any write error encountered. +

    + + + + + + + +

    func Printf

    +
    func Printf(format string, a ...interface{}) (n int, err error)
    +

    +Printf formats according to a format specifier and writes to standard output. +It returns the number of bytes written and any write error encountered. +

    + + + + + + + +

    func Println

    +
    func Println(a ...interface{}) (n int, err error)
    +

    +Println formats using the default formats for its operands and writes to standard output. +Spaces are always added between operands and a newline is appended. +It returns the number of bytes written and any write error encountered. +

    + + + + + + + +

    func Scan

    +
    func Scan(a ...interface{}) (n int, err error)
    +

    +Scan scans text read from standard input, storing successive +space-separated values into successive arguments. Newlines count +as space. It returns the number of items successfully scanned. +If that is less than the number of arguments, err will report why. +

    + + + + + + + +

    func Scanf

    +
    func Scanf(format string, a ...interface{}) (n int, err error)
    +

    +Scanf scans text read from standard input, storing successive +space-separated values into successive arguments as determined by +the format. It returns the number of items successfully scanned. +If that is less than the number of arguments, err will report why. +Newlines in the input must match newlines in the format. +The one exception: the verb %c always scans the next rune in the +input, even if it is a space (or tab etc.) or newline. +

    + + + + + + + +

    func Scanln

    +
    func Scanln(a ...interface{}) (n int, err error)
    +

    +Scanln is similar to Scan, but stops scanning at a newline and +after the final item there must be a newline or EOF. +

    + + + + + + + +

    func Sprint

    +
    func Sprint(a ...interface{}) string
    +

    +Sprint formats using the default formats for its operands and returns the resulting string. +Spaces are added between operands when neither is a string. +

    + + + + + + + +

    func Sprintf

    +
    func Sprintf(format string, a ...interface{}) string
    +

    +Sprintf formats according to a format specifier and returns the resulting string. +

    + + + + + + + +

    func Sprintln

    +
    func Sprintln(a ...interface{}) string
    +

    +Sprintln formats using the default formats for its operands and returns the resulting string. +Spaces are always added between operands and a newline is appended. +

    + + + + + + + +

    func Sscan

    +
    func Sscan(str string, a ...interface{}) (n int, err error)
    +

    +Sscan scans the argument string, storing successive space-separated +values into successive arguments. Newlines count as space. It +returns the number of items successfully scanned. If that is less +than the number of arguments, err will report why. +

    + + + + + + + +

    func Sscanf

    +
    func Sscanf(str string, format string, a ...interface{}) (n int, err error)
    +

    +Sscanf scans the argument string, storing successive space-separated +values into successive arguments as determined by the format. It +returns the number of items successfully parsed. +Newlines in the input must match newlines in the format. +

    + + + + + + + +

    func Sscanln

    +
    func Sscanln(str string, a ...interface{}) (n int, err error)
    +

    +Sscanln is similar to Sscan, but stops scanning at a newline and +after the final item there must be a newline or EOF. +

    + + + + + + + + +

    type Formatter

    +
    type Formatter interface {
    +    Format(f State, c rune)
    +}
    +

    +Formatter is the interface implemented by values with a custom formatter. +The implementation of Format may call Sprint(f) or Fprint(f) etc. +to generate its output. +

    + + + + + + + + + + + + + + + + +

    type GoStringer

    +
    type GoStringer interface {
    +    GoString() string
    +}
    +

    +GoStringer is implemented by any value that has a GoString method, +which defines the Go syntax for that value. +The GoString method is used to print values passed as an operand +to a %#v format. +

    + + + + + + + + + + + + + + + + +

    type ScanState

    +
    type ScanState interface {
    +    // ReadRune reads the next rune (Unicode code point) from the input.
    +    // If invoked during Scanln, Fscanln, or Sscanln, ReadRune() will
    +    // return EOF after returning the first '\n' or when reading beyond
    +    // the specified width.
    +    ReadRune() (r rune, size int, err error)
    +    // UnreadRune causes the next call to ReadRune to return the same rune.
    +    UnreadRune() error
    +    // SkipSpace skips space in the input. Newlines are treated appropriately
    +    // for the operation being performed; see the package documentation
    +    // for more information.
    +    SkipSpace()
    +    // Token skips space in the input if skipSpace is true, then returns the
    +    // run of Unicode code points c satisfying f(c).  If f is nil,
    +    // !unicode.IsSpace(c) is used; that is, the token will hold non-space
    +    // characters.  Newlines are treated appropriately for the operation being
    +    // performed; see the package documentation for more information.
    +    // The returned slice points to shared data that may be overwritten
    +    // by the next call to Token, a call to a Scan function using the ScanState
    +    // as input, or when the calling Scan method returns.
    +    Token(skipSpace bool, f func(rune) bool) (token []byte, err error)
    +    // Width returns the value of the width option and whether it has been set.
    +    // The unit is Unicode code points.
    +    Width() (wid int, ok bool)
    +    // Because ReadRune is implemented by the interface, Read should never be
    +    // called by the scanning routines and a valid implementation of
    +    // ScanState may choose always to return an error from Read.
    +    Read(buf []byte) (n int, err error)
    +}
    +

    +ScanState represents the scanner state passed to custom scanners. +Scanners may do rune-at-a-time scanning or ask the ScanState +to discover the next space-delimited token. +

    + + + + + + + + + + + + + + + + +

    type Scanner

    +
    type Scanner interface {
    +    Scan(state ScanState, verb rune) error
    +}
    +

    +Scanner is implemented by any value that has a Scan method, which scans +the input for the representation of a value and stores the result in the +receiver, which must be a pointer to be useful. The Scan method is called +for any argument to Scan, Scanf, or Scanln that implements it. +

    + + + + + + + + + + + + + + + + +

    type State

    +
    type State interface {
    +    // Write is the function to call to emit formatted output to be printed.
    +    Write(b []byte) (ret int, err error)
    +    // Width returns the value of the width option and whether it has been set.
    +    Width() (wid int, ok bool)
    +    // Precision returns the value of the precision option and whether it has been set.
    +    Precision() (prec int, ok bool)
    +
    +    // Flag reports whether the flag c, a character, has been set.
    +    Flag(c int) bool
    +}
    +

    +State represents the printer state passed to custom formatters. +It provides access to the io.Writer interface plus information about +the flags and options for the operand's format specifier. +

    + + + + + + + + + + + + + + + + +

    type Stringer

    +
    type Stringer interface {
    +    String() string
    +}
    +

    +Stringer is implemented by any value that has a String method, +which defines the “native” format for that value. +The String method is used to print values passed as an operand +to any format that accepts a string or to an unformatted printer +such as Print. +

    + + + + + + + + + + + + + + + + + + + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/github.com/PuerkitoBio/goquery/index.html b/pkg/github.com/PuerkitoBio/goquery/index.html new file mode 100644 index 0000000..0031f91 --- /dev/null +++ b/pkg/github.com/PuerkitoBio/goquery/index.html @@ -0,0 +1,3288 @@ + + + + + + + + goquery - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Package goquery

    + + + + + + + + + + + + + + +
    +
    +
    import "github.com/PuerkitoBio/goquery"
    +
    +
    +
    Overview
    +
    Index
    + +
    Examples
    + + +
    +
    + +
    + +
    +

    Overview ▾

    +

    +Package goquery implements features similar to jQuery, including the chainable +syntax, to manipulate and query an HTML document. +

    +

    +It brings a syntax and a set of features similar to jQuery to the Go language. +It is based on Go's net/html package and the CSS Selector library cascadia. +Since the net/html parser returns nodes, and not a full-featured DOM +tree, jQuery's stateful manipulation functions (like height(), css(), detach()) +have been left off. +

    +

    +Also, because the net/html parser requires UTF-8 encoding, so does goquery: it is +the caller's responsibility to ensure that the source document provides UTF-8 encoded HTML. +See the repository's wiki for various options on how to do this. +

    +

    +Syntax-wise, it is as close as possible to jQuery, with the same method names when +possible, and that warm and fuzzy chainable interface. jQuery being the +ultra-popular library that it is, writing a similar HTML-manipulating +library was better to follow its API than to start anew (in the same spirit as +Go's fmt package), even though some of its methods are less than intuitive (looking +at you, index()...). +

    +

    +It is hosted on GitHub, along with additional documentation in the README.md +file: https://github.com/puerkitobio/goquery +

    +

    +Please note that because of the net/html dependency, goquery requires Go1.1+. +

    +

    +The various methods are split into files based on the category of behavior. +The three dots (...) indicate that various "overloads" are available. +

    +

    +* array.go : array-like positional manipulation of the selection. +

    +
    - Eq()
    +- First()
    +- Get()
    +- Index...()
    +- Last()
    +- Slice()
    +
    +

    +* expand.go : methods that expand or augment the selection's set. +

    +
    - Add...()
    +- AndSelf()
    +- Union(), which is an alias for AddSelection()
    +
    +

    +* filter.go : filtering methods, that reduce the selection's set. +

    +
    - End()
    +- Filter...()
    +- Has...()
    +- Intersection(), which is an alias of FilterSelection()
    +- Not...()
    +
    +

    +* iteration.go : methods to loop over the selection's nodes. +

    +
    - Each()
    +- EachWithBreak()
    +- Map()
    +
    +

    +* manipulation.go : methods for modifying the document +

    +
    - After...()
    +- Append...()
    +- Before...()
    +- Clone()
    +- Empty()
    +- Prepend...()
    +- Remove...()
    +- ReplaceWith...()
    +- Unwrap()
    +- Wrap...()
    +- WrapAll...()
    +- WrapInner...()
    +
    +

    +* property.go : methods that inspect and get the node's properties values. +

    +
    - Attr*(), RemoveAttr(), SetAttr()
    +- AddClass(), HasClass(), RemoveClass(), ToggleClass()
    +- Html()
    +- Length()
    +- Size(), which is an alias for Length()
    +- Text()
    +
    +

    +* query.go : methods that query, or reflect, a node's identity. +

    +
    - Contains()
    +- Is...()
    +
    +

    +* traversal.go : methods to traverse the HTML document tree. +

    +
    - Children...()
    +- Contents()
    +- Find...()
    +- Next...()
    +- Parent[s]...()
    +- Prev...()
    +- Siblings...()
    +
    +

    +* type.go : definition of the types exposed by goquery. +

    +
    - Document
    +- Selection
    +- Matcher
    +
    +

    +* utilities.go : definition of helper functions (and not methods on a *Selection) +that are not part of jQuery, but are useful to goquery. +

    +
    - NodeName
    +- OuterHtml
    +
    + +
    +
    +
    + +
    +

    Example

    +

    This example scrapes the reviews shown on the home page of metalsucks.net. +

    + + +

    Code:

    +
    +// Load the HTML document
    +doc, err := goquery.NewDocument("http://metalsucks.net")
    +if err != nil {
    +    log.Fatal(err)
    +}
    +
    +// Find the review items
    +doc.Find(".sidebar-reviews article .content-block").Each(func(i int, s *goquery.Selection) {
    +    // For each item found, get the band and title
    +    band := s.Find("a").Text()
    +    title := s.Find("i").Text()
    +    fmt.Printf("Review %d: %s - %s\n", i, band, title)
    +})
    +// To see the output of the Example while running the test suite (go test), simply
    +// remove the leading "x" before Output on the next line. This will cause the
    +// example to fail (all the "real" tests should pass).
    +
    +// xOutput: voluntarily fail the Example output.
    +
    + + +
    +
    + + +
    + +
    +

    Index ▾

    + + +
    +
    + + + + +
    func NodeName(s *Selection) string
    + + +
    func OuterHtml(s *Selection) (string, error)
    + + + +
    type Document
    + + +
        func CloneDocument(doc *Document) *Document
    + + +
        func NewDocument(url string) (*Document, error)
    + + +
        func NewDocumentFromNode(root *html.Node) *Document
    + + +
        func NewDocumentFromReader(r io.Reader) (*Document, error)
    + + +
        func NewDocumentFromResponse(res *http.Response) (*Document, error)
    + + + + +
    type Matcher
    + + + + +
    type Selection
    + + + +
        func (s *Selection) Add(selector string) *Selection
    + + +
        func (s *Selection) AddClass(class ...string) *Selection
    + + +
        func (s *Selection) AddMatcher(m Matcher) *Selection
    + + +
        func (s *Selection) AddNodes(nodes ...*html.Node) *Selection
    + + +
        func (s *Selection) AddSelection(sel *Selection) *Selection
    + + +
        func (s *Selection) After(selector string) *Selection
    + + +
        func (s *Selection) AfterHtml(html string) *Selection
    + + +
        func (s *Selection) AfterMatcher(m Matcher) *Selection
    + + +
        func (s *Selection) AfterNodes(ns ...*html.Node) *Selection
    + + +
        func (s *Selection) AfterSelection(sel *Selection) *Selection
    + + +
        func (s *Selection) AndSelf() *Selection
    + + +
        func (s *Selection) Append(selector string) *Selection
    + + +
        func (s *Selection) AppendHtml(html string) *Selection
    + + +
        func (s *Selection) AppendMatcher(m Matcher) *Selection
    + + +
        func (s *Selection) AppendNodes(ns ...*html.Node) *Selection
    + + +
        func (s *Selection) AppendSelection(sel *Selection) *Selection
    + + +
        func (s *Selection) Attr(attrName string) (val string, exists bool)
    + + +
        func (s *Selection) AttrOr(attrName, defaultValue string) string
    + + +
        func (s *Selection) Before(selector string) *Selection
    + + +
        func (s *Selection) BeforeHtml(html string) *Selection
    + + +
        func (s *Selection) BeforeMatcher(m Matcher) *Selection
    + + +
        func (s *Selection) BeforeNodes(ns ...*html.Node) *Selection
    + + +
        func (s *Selection) BeforeSelection(sel *Selection) *Selection
    + + +
        func (s *Selection) Children() *Selection
    + + +
        func (s *Selection) ChildrenFiltered(selector string) *Selection
    + + +
        func (s *Selection) ChildrenMatcher(m Matcher) *Selection
    + + +
        func (s *Selection) Clone() *Selection
    + + +
        func (s *Selection) Closest(selector string) *Selection
    + + +
        func (s *Selection) ClosestMatcher(m Matcher) *Selection
    + + +
        func (s *Selection) ClosestNodes(nodes ...*html.Node) *Selection
    + + +
        func (s *Selection) ClosestSelection(sel *Selection) *Selection
    + + +
        func (s *Selection) Contains(n *html.Node) bool
    + + +
        func (s *Selection) Contents() *Selection
    + + +
        func (s *Selection) ContentsFiltered(selector string) *Selection
    + + +
        func (s *Selection) ContentsMatcher(m Matcher) *Selection
    + + +
        func (s *Selection) Each(f func(int, *Selection)) *Selection
    + + +
        func (s *Selection) EachWithBreak(f func(int, *Selection) bool) *Selection
    + + +
        func (s *Selection) Empty() *Selection
    + + +
        func (s *Selection) End() *Selection
    + + +
        func (s *Selection) Eq(index int) *Selection
    + + +
        func (s *Selection) Filter(selector string) *Selection
    + + +
        func (s *Selection) FilterFunction(f func(int, *Selection) bool) *Selection
    + + +
        func (s *Selection) FilterMatcher(m Matcher) *Selection
    + + +
        func (s *Selection) FilterNodes(nodes ...*html.Node) *Selection
    + + +
        func (s *Selection) FilterSelection(sel *Selection) *Selection
    + + +
        func (s *Selection) Find(selector string) *Selection
    + + +
        func (s *Selection) FindMatcher(m Matcher) *Selection
    + + +
        func (s *Selection) FindNodes(nodes ...*html.Node) *Selection
    + + +
        func (s *Selection) FindSelection(sel *Selection) *Selection
    + + +
        func (s *Selection) First() *Selection
    + + +
        func (s *Selection) Get(index int) *html.Node
    + + +
        func (s *Selection) Has(selector string) *Selection
    + + +
        func (s *Selection) HasClass(class string) bool
    + + +
        func (s *Selection) HasMatcher(m Matcher) *Selection
    + + +
        func (s *Selection) HasNodes(nodes ...*html.Node) *Selection
    + + +
        func (s *Selection) HasSelection(sel *Selection) *Selection
    + + +
        func (s *Selection) Html() (ret string, e error)
    + + +
        func (s *Selection) Index() int
    + + +
        func (s *Selection) IndexMatcher(m Matcher) int
    + + +
        func (s *Selection) IndexOfNode(node *html.Node) int
    + + +
        func (s *Selection) IndexOfSelection(sel *Selection) int
    + + +
        func (s *Selection) IndexSelector(selector string) int
    + + +
        func (s *Selection) Intersection(sel *Selection) *Selection
    + + +
        func (s *Selection) Is(selector string) bool
    + + +
        func (s *Selection) IsFunction(f func(int, *Selection) bool) bool
    + + +
        func (s *Selection) IsMatcher(m Matcher) bool
    + + +
        func (s *Selection) IsNodes(nodes ...*html.Node) bool
    + + +
        func (s *Selection) IsSelection(sel *Selection) bool
    + + +
        func (s *Selection) Last() *Selection
    + + +
        func (s *Selection) Length() int
    + + +
        func (s *Selection) Map(f func(int, *Selection) string) (result []string)
    + + +
        func (s *Selection) Next() *Selection
    + + +
        func (s *Selection) NextAll() *Selection
    + + +
        func (s *Selection) NextAllFiltered(selector string) *Selection
    + + +
        func (s *Selection) NextAllMatcher(m Matcher) *Selection
    + + +
        func (s *Selection) NextFiltered(selector string) *Selection
    + + +
        func (s *Selection) NextFilteredUntil(filterSelector, untilSelector string) *Selection
    + + +
        func (s *Selection) NextFilteredUntilMatcher(filter, until Matcher) *Selection
    + + +
        func (s *Selection) NextFilteredUntilNodes(filterSelector string, nodes ...*html.Node) *Selection
    + + +
        func (s *Selection) NextFilteredUntilSelection(filterSelector string, sel *Selection) *Selection
    + + +
        func (s *Selection) NextMatcher(m Matcher) *Selection
    + + +
        func (s *Selection) NextMatcherUntilNodes(filter Matcher, nodes ...*html.Node) *Selection
    + + +
        func (s *Selection) NextMatcherUntilSelection(filter Matcher, sel *Selection) *Selection
    + + +
        func (s *Selection) NextUntil(selector string) *Selection
    + + +
        func (s *Selection) NextUntilMatcher(m Matcher) *Selection
    + + +
        func (s *Selection) NextUntilNodes(nodes ...*html.Node) *Selection
    + + +
        func (s *Selection) NextUntilSelection(sel *Selection) *Selection
    + + +
        func (s *Selection) Not(selector string) *Selection
    + + +
        func (s *Selection) NotFunction(f func(int, *Selection) bool) *Selection
    + + +
        func (s *Selection) NotMatcher(m Matcher) *Selection
    + + +
        func (s *Selection) NotNodes(nodes ...*html.Node) *Selection
    + + +
        func (s *Selection) NotSelection(sel *Selection) *Selection
    + + +
        func (s *Selection) Parent() *Selection
    + + +
        func (s *Selection) ParentFiltered(selector string) *Selection
    + + +
        func (s *Selection) ParentMatcher(m Matcher) *Selection
    + + +
        func (s *Selection) Parents() *Selection
    + + +
        func (s *Selection) ParentsFiltered(selector string) *Selection
    + + +
        func (s *Selection) ParentsFilteredUntil(filterSelector, untilSelector string) *Selection
    + + +
        func (s *Selection) ParentsFilteredUntilMatcher(filter, until Matcher) *Selection
    + + +
        func (s *Selection) ParentsFilteredUntilNodes(filterSelector string, nodes ...*html.Node) *Selection
    + + +
        func (s *Selection) ParentsFilteredUntilSelection(filterSelector string, sel *Selection) *Selection
    + + +
        func (s *Selection) ParentsMatcher(m Matcher) *Selection
    + + +
        func (s *Selection) ParentsMatcherUntilNodes(filter Matcher, nodes ...*html.Node) *Selection
    + + +
        func (s *Selection) ParentsMatcherUntilSelection(filter Matcher, sel *Selection) *Selection
    + + +
        func (s *Selection) ParentsUntil(selector string) *Selection
    + + +
        func (s *Selection) ParentsUntilMatcher(m Matcher) *Selection
    + + +
        func (s *Selection) ParentsUntilNodes(nodes ...*html.Node) *Selection
    + + +
        func (s *Selection) ParentsUntilSelection(sel *Selection) *Selection
    + + +
        func (s *Selection) Prepend(selector string) *Selection
    + + +
        func (s *Selection) PrependHtml(html string) *Selection
    + + +
        func (s *Selection) PrependMatcher(m Matcher) *Selection
    + + +
        func (s *Selection) PrependNodes(ns ...*html.Node) *Selection
    + + +
        func (s *Selection) PrependSelection(sel *Selection) *Selection
    + + +
        func (s *Selection) Prev() *Selection
    + + +
        func (s *Selection) PrevAll() *Selection
    + + +
        func (s *Selection) PrevAllFiltered(selector string) *Selection
    + + +
        func (s *Selection) PrevAllMatcher(m Matcher) *Selection
    + + +
        func (s *Selection) PrevFiltered(selector string) *Selection
    + + +
        func (s *Selection) PrevFilteredUntil(filterSelector, untilSelector string) *Selection
    + + +
        func (s *Selection) PrevFilteredUntilMatcher(filter, until Matcher) *Selection
    + + +
        func (s *Selection) PrevFilteredUntilNodes(filterSelector string, nodes ...*html.Node) *Selection
    + + +
        func (s *Selection) PrevFilteredUntilSelection(filterSelector string, sel *Selection) *Selection
    + + +
        func (s *Selection) PrevMatcher(m Matcher) *Selection
    + + +
        func (s *Selection) PrevMatcherUntilNodes(filter Matcher, nodes ...*html.Node) *Selection
    + + +
        func (s *Selection) PrevMatcherUntilSelection(filter Matcher, sel *Selection) *Selection
    + + +
        func (s *Selection) PrevUntil(selector string) *Selection
    + + +
        func (s *Selection) PrevUntilMatcher(m Matcher) *Selection
    + + +
        func (s *Selection) PrevUntilNodes(nodes ...*html.Node) *Selection
    + + +
        func (s *Selection) PrevUntilSelection(sel *Selection) *Selection
    + + +
        func (s *Selection) Remove() *Selection
    + + +
        func (s *Selection) RemoveAttr(attrName string) *Selection
    + + +
        func (s *Selection) RemoveClass(class ...string) *Selection
    + + +
        func (s *Selection) RemoveFiltered(selector string) *Selection
    + + +
        func (s *Selection) RemoveMatcher(m Matcher) *Selection
    + + +
        func (s *Selection) ReplaceWith(selector string) *Selection
    + + +
        func (s *Selection) ReplaceWithHtml(html string) *Selection
    + + +
        func (s *Selection) ReplaceWithMatcher(m Matcher) *Selection
    + + +
        func (s *Selection) ReplaceWithNodes(ns ...*html.Node) *Selection
    + + +
        func (s *Selection) ReplaceWithSelection(sel *Selection) *Selection
    + + +
        func (s *Selection) SetAttr(attrName, val string) *Selection
    + + +
        func (s *Selection) Siblings() *Selection
    + + +
        func (s *Selection) SiblingsFiltered(selector string) *Selection
    + + +
        func (s *Selection) SiblingsMatcher(m Matcher) *Selection
    + + +
        func (s *Selection) Size() int
    + + +
        func (s *Selection) Slice(start, end int) *Selection
    + + +
        func (s *Selection) Text() string
    + + +
        func (s *Selection) ToggleClass(class ...string) *Selection
    + + +
        func (s *Selection) Union(sel *Selection) *Selection
    + + +
        func (s *Selection) Unwrap() *Selection
    + + +
        func (s *Selection) Wrap(selector string) *Selection
    + + +
        func (s *Selection) WrapAll(selector string) *Selection
    + + +
        func (s *Selection) WrapAllHtml(html string) *Selection
    + + +
        func (s *Selection) WrapAllMatcher(m Matcher) *Selection
    + + +
        func (s *Selection) WrapAllNode(n *html.Node) *Selection
    + + +
        func (s *Selection) WrapAllSelection(sel *Selection) *Selection
    + + +
        func (s *Selection) WrapHtml(html string) *Selection
    + + +
        func (s *Selection) WrapInner(selector string) *Selection
    + + +
        func (s *Selection) WrapInnerHtml(html string) *Selection
    + + +
        func (s *Selection) WrapInnerMatcher(m Matcher) *Selection
    + + +
        func (s *Selection) WrapInnerNode(n *html.Node) *Selection
    + + +
        func (s *Selection) WrapInnerSelection(sel *Selection) *Selection
    + + +
        func (s *Selection) WrapMatcher(m Matcher) *Selection
    + + +
        func (s *Selection) WrapNode(n *html.Node) *Selection
    + + +
        func (s *Selection) WrapSelection(sel *Selection) *Selection
    + + + +
    +
    + + +
    +

    Examples

    +
    + +
    Package
    + +
    +
    + + + +

    Package files

    +

    + + + array.go + + doc.go + + expand.go + + filter.go + + iteration.go + + manipulation.go + + property.go + + query.go + + traversal.go + + type.go + + utilities.go + + +

    + +
    +
    + + + + + + + + +

    func NodeName

    +
    func NodeName(s *Selection) string
    +

    +NodeName returns the node name of the first element in the selection. +It tries to behave in a similar way as the DOM's nodeName property +(https://developer.mozilla.org/en-US/docs/Web/API/Node/nodeName). +

    +

    +Go's net/html package defines the following node types, listed with +the corresponding returned value from this function: +

    +
    ErrorNode : #error
    +TextNode : #text
    +DocumentNode : #document
    +ElementNode : the element's tag name
    +CommentNode : #comment
    +DoctypeNode : the name of the document type
    +
    + + + + + + + +

    func OuterHtml

    +
    func OuterHtml(s *Selection) (string, error)
    +

    +OuterHtml returns the outer HTML rendering of the first item in +the selection - that is, the HTML including the first element's +tag and attributes. +

    +

    +Unlike InnerHtml, this is a function and not a method on the Selection, +because this is not a jQuery method (in javascript-land, this is +a property provided by the DOM). +

    + + + + + + + + +

    type Document

    +
    type Document struct {
    +    *Selection
    +    Url *url.URL
    +    // contains filtered or unexported fields
    +}
    +

    +Document represents an HTML document to be manipulated. Unlike jQuery, which +is loaded as part of a DOM document, and thus acts upon its containing +document, GoQuery doesn't know which HTML document to act upon. So it needs +to be told, and that's what the Document class is for. It holds the root +document node to manipulate, and can make selections on this document. +

    + + + + + + + + + + + + +

    func CloneDocument

    +
    func CloneDocument(doc *Document) *Document
    +

    +CloneDocument creates a deep-clone of a document. +

    + + + + + +

    func NewDocument

    +
    func NewDocument(url string) (*Document, error)
    +

    +NewDocument is a Document constructor that takes a string URL as argument. +It loads the specified document, parses it, and stores the root Document +node, ready to be manipulated. +

    + + + + + +

    func NewDocumentFromNode

    +
    func NewDocumentFromNode(root *html.Node) *Document
    +

    +NewDocumentFromNode is a Document constructor that takes a root html Node +as argument. +

    + + + + + +

    func NewDocumentFromReader

    +
    func NewDocumentFromReader(r io.Reader) (*Document, error)
    +

    +NewDocumentFromReader returns a Document from a generic reader. +It returns an error as second value if the reader's data cannot be parsed +as html. It does *not* check if the reader is also an io.Closer, so the +provided reader is never closed by this call, it is the responsibility +of the caller to close it if required. +

    + + + + + +

    func NewDocumentFromResponse

    +
    func NewDocumentFromResponse(res *http.Response) (*Document, error)
    +

    +NewDocumentFromResponse is another Document constructor that takes an http response as argument. +It loads the specified response's document, parses it, and stores the root Document +node, ready to be manipulated. The response's body is closed on return. +

    + + + + + + + + + +

    type Matcher

    +
    type Matcher interface {
    +    Match(*html.Node) bool
    +    MatchAll(*html.Node) []*html.Node
    +    Filter([]*html.Node) []*html.Node
    +}
    +

    +Matcher is an interface that defines the methods to match +HTML nodes against a compiled selector string. Cascadia's +Selector implements this interface. +

    + + + + + + + + + + + + + + + + +

    type Selection

    +
    type Selection struct {
    +    Nodes []*html.Node
    +    // contains filtered or unexported fields
    +}
    +

    +Selection represents a collection of nodes matching some criteria. The +initial Selection can be created by using Document.Find, and then +manipulated using the jQuery-like chainable syntax and methods. +

    + + + + + + + + + + + + + + +

    func (*Selection) Add

    +
    func (s *Selection) Add(selector string) *Selection
    +

    +Add adds the selector string's matching nodes to those in the current +selection and returns a new Selection object. +The selector string is run in the context of the document of the current +Selection object. +

    + + + + + + +

    func (*Selection) AddClass

    +
    func (s *Selection) AddClass(class ...string) *Selection
    +

    +AddClass adds the given class(es) to each element in the set of matched elements. +Multiple class names can be specified, separated by a space or via multiple arguments. +

    + + + + + + +

    func (*Selection) AddMatcher

    +
    func (s *Selection) AddMatcher(m Matcher) *Selection
    +

    +AddMatcher adds the matcher's matching nodes to those in the current +selection and returns a new Selection object. +The matcher is run in the context of the document of the current +Selection object. +

    + + + + + + +

    func (*Selection) AddNodes

    +
    func (s *Selection) AddNodes(nodes ...*html.Node) *Selection
    +

    +AddNodes adds the specified nodes to those in the +current selection and returns a new Selection object. +

    + + + + + + +

    func (*Selection) AddSelection

    +
    func (s *Selection) AddSelection(sel *Selection) *Selection
    +

    +AddSelection adds the specified Selection object's nodes to those in the +current selection and returns a new Selection object. +

    + + + + + + +

    func (*Selection) After

    +
    func (s *Selection) After(selector string) *Selection
    +

    +After applies the selector from the root document and inserts the matched elements +after the elements in the set of matched elements. +

    +

    +If one of the matched elements in the selection is not currently in the +document, it's impossible to insert nodes after it, so it will be ignored. +

    +

    +This follows the same rules as Selection.Append. +

    + + + + + + +

    func (*Selection) AfterHtml

    +
    func (s *Selection) AfterHtml(html string) *Selection
    +

    +AfterHtml parses the html and inserts it after the set of matched elements. +

    +

    +This follows the same rules as Selection.Append. +

    + + + + + + +

    func (*Selection) AfterMatcher

    +
    func (s *Selection) AfterMatcher(m Matcher) *Selection
    +

    +AfterMatcher applies the matcher from the root document and inserts the matched elements +after the elements in the set of matched elements. +

    +

    +If one of the matched elements in the selection is not currently in the +document, it's impossible to insert nodes after it, so it will be ignored. +

    +

    +This follows the same rules as Selection.Append. +

    + + + + + + +

    func (*Selection) AfterNodes

    +
    func (s *Selection) AfterNodes(ns ...*html.Node) *Selection
    +

    +AfterNodes inserts the nodes after each element in the set of matched elements. +

    +

    +This follows the same rules as Selection.Append. +

    + + + + + + +

    func (*Selection) AfterSelection

    +
    func (s *Selection) AfterSelection(sel *Selection) *Selection
    +

    +AfterSelection inserts the elements in the selection after each element in the set of matched +elements. +

    +

    +This follows the same rules as Selection.Append. +

    + + + + + + +

    func (*Selection) AndSelf

    +
    func (s *Selection) AndSelf() *Selection
    +

    +AndSelf adds the previous set of elements on the stack to the current set. +It returns a new Selection object containing the current Selection combined +with the previous one. +

    + + + + + + +

    func (*Selection) Append

    +
    func (s *Selection) Append(selector string) *Selection
    +

    +Append appends the elements specified by the selector to the end of each element +in the set of matched elements, following those rules: +

    +

    +1) The selector is applied to the root document. +

    +

    +2) Elements that are part of the document will be moved to the new location. +

    +

    +3) If there are multiple locations to append to, cloned nodes will be +appended to all target locations except the last one, which will be moved +as noted in (2). +

    + + + + + + +

    func (*Selection) AppendHtml

    +
    func (s *Selection) AppendHtml(html string) *Selection
    +

    +AppendHtml parses the html and appends it to the set of matched elements. +

    + + + + + + +

    func (*Selection) AppendMatcher

    +
    func (s *Selection) AppendMatcher(m Matcher) *Selection
    +

    +AppendMatcher appends the elements specified by the matcher to the end of each element +in the set of matched elements. +

    +

    +This follows the same rules as Selection.Append. +

    + + + + + + +

    func (*Selection) AppendNodes

    +
    func (s *Selection) AppendNodes(ns ...*html.Node) *Selection
    +

    +AppendNodes appends the specified nodes to each node in the set of matched elements. +

    +

    +This follows the same rules as Selection.Append. +

    + + + + + + +

    func (*Selection) AppendSelection

    +
    func (s *Selection) AppendSelection(sel *Selection) *Selection
    +

    +AppendSelection appends the elements in the selection to the end of each element +in the set of matched elements. +

    +

    +This follows the same rules as Selection.Append. +

    + + + + + + +

    func (*Selection) Attr

    +
    func (s *Selection) Attr(attrName string) (val string, exists bool)
    +

    +Attr gets the specified attribute's value for the first element in the +Selection. To get the value for each element individually, use a looping +construct such as Each or Map method. +

    + + + + + + +

    func (*Selection) AttrOr

    +
    func (s *Selection) AttrOr(attrName, defaultValue string) string
    +

    +AttrOr works like Attr but returns default value if attribute is not present. +

    + + + + + + +

    func (*Selection) Before

    +
    func (s *Selection) Before(selector string) *Selection
    +

    +Before inserts the matched elements before each element in the set of matched elements. +

    +

    +This follows the same rules as Selection.Append. +

    + + + + + + +

    func (*Selection) BeforeHtml

    +
    func (s *Selection) BeforeHtml(html string) *Selection
    +

    +BeforeHtml parses the html and inserts it before the set of matched elements. +

    +

    +This follows the same rules as Selection.Append. +

    + + + + + + +

    func (*Selection) BeforeMatcher

    +
    func (s *Selection) BeforeMatcher(m Matcher) *Selection
    +

    +BeforeMatcher inserts the matched elements before each element in the set of matched elements. +

    +

    +This follows the same rules as Selection.Append. +

    + + + + + + +

    func (*Selection) BeforeNodes

    +
    func (s *Selection) BeforeNodes(ns ...*html.Node) *Selection
    +

    +BeforeNodes inserts the nodes before each element in the set of matched elements. +

    +

    +This follows the same rules as Selection.Append. +

    + + + + + + +

    func (*Selection) BeforeSelection

    +
    func (s *Selection) BeforeSelection(sel *Selection) *Selection
    +

    +BeforeSelection inserts the elements in the selection before each element in the set of matched +elements. +

    +

    +This follows the same rules as Selection.Append. +

    + + + + + + +

    func (*Selection) Children

    +
    func (s *Selection) Children() *Selection
    +

    +Children gets the child elements of each element in the Selection. +It returns a new Selection object containing these elements. +

    + + + + + + +

    func (*Selection) ChildrenFiltered

    +
    func (s *Selection) ChildrenFiltered(selector string) *Selection
    +

    +ChildrenFiltered gets the child elements of each element in the Selection, +filtered by the specified selector. It returns a new +Selection object containing these elements. +

    + + + + + + +

    func (*Selection) ChildrenMatcher

    +
    func (s *Selection) ChildrenMatcher(m Matcher) *Selection
    +

    +ChildrenMatcher gets the child elements of each element in the Selection, +filtered by the specified matcher. It returns a new +Selection object containing these elements. +

    + + + + + + +

    func (*Selection) Clone

    +
    func (s *Selection) Clone() *Selection
    +

    +Clone creates a deep copy of the set of matched nodes. The new nodes will not be +attached to the document. +

    + + + + + + +

    func (*Selection) Closest

    +
    func (s *Selection) Closest(selector string) *Selection
    +

    +Closest gets the first element that matches the selector by testing the +element itself and traversing up through its ancestors in the DOM tree. +

    + + + + + + +

    func (*Selection) ClosestMatcher

    +
    func (s *Selection) ClosestMatcher(m Matcher) *Selection
    +

    +ClosestMatcher gets the first element that matches the matcher by testing the +element itself and traversing up through its ancestors in the DOM tree. +

    + + + + + + +

    func (*Selection) ClosestNodes

    +
    func (s *Selection) ClosestNodes(nodes ...*html.Node) *Selection
    +

    +ClosestNodes gets the first element that matches one of the nodes by testing the +element itself and traversing up through its ancestors in the DOM tree. +

    + + + + + + +

    func (*Selection) ClosestSelection

    +
    func (s *Selection) ClosestSelection(sel *Selection) *Selection
    +

    +ClosestSelection gets the first element that matches one of the nodes in the +Selection by testing the element itself and traversing up through its ancestors +in the DOM tree. +

    + + + + + + +

    func (*Selection) Contains

    +
    func (s *Selection) Contains(n *html.Node) bool
    +

    +Contains returns true if the specified Node is within, +at any depth, one of the nodes in the Selection object. +It is NOT inclusive, to behave like jQuery's implementation, and +unlike Javascript's .contains, so if the contained +node is itself in the selection, it returns false. +

    + + + + + + +

    func (*Selection) Contents

    +
    func (s *Selection) Contents() *Selection
    +

    +Contents gets the children of each element in the Selection, +including text and comment nodes. It returns a new Selection object +containing these elements. +

    + + + + + + +

    func (*Selection) ContentsFiltered

    +
    func (s *Selection) ContentsFiltered(selector string) *Selection
    +

    +ContentsFiltered gets the children of each element in the Selection, +filtered by the specified selector. It returns a new Selection +object containing these elements. Since selectors only act on Element nodes, +this function is an alias to ChildrenFiltered unless the selector is empty, +in which case it is an alias to Contents. +

    + + + + + + +

    func (*Selection) ContentsMatcher

    +
    func (s *Selection) ContentsMatcher(m Matcher) *Selection
    +

    +ContentsMatcher gets the children of each element in the Selection, +filtered by the specified matcher. It returns a new Selection +object containing these elements. Since matchers only act on Element nodes, +this function is an alias to ChildrenMatcher. +

    + + + + + + +

    func (*Selection) Each

    +
    func (s *Selection) Each(f func(int, *Selection)) *Selection
    +

    +Each iterates over a Selection object, executing a function for each +matched element. It returns the current Selection object. The function +f is called for each element in the selection with the index of the +element in that selection starting at 0, and a *Selection that contains +only that element. +

    + + + + + + +

    func (*Selection) EachWithBreak

    +
    func (s *Selection) EachWithBreak(f func(int, *Selection) bool) *Selection
    +

    +EachWithBreak iterates over a Selection object, executing a function for each +matched element. It is identical to Each except that it is possible to break +out of the loop by returning false in the callback function. It returns the +current Selection object. +

    + + + + + + +

    func (*Selection) Empty

    +
    func (s *Selection) Empty() *Selection
    +

    +Empty removes all children nodes from the set of matched elements. +It returns the children nodes in a new Selection. +

    + + + + + + +

    func (*Selection) End

    +
    func (s *Selection) End() *Selection
    +

    +End ends the most recent filtering operation in the current chain and +returns the set of matched elements to its previous state. +

    + + + + + + +

    func (*Selection) Eq

    +
    func (s *Selection) Eq(index int) *Selection
    +

    +Eq reduces the set of matched elements to the one at the specified index. +If a negative index is given, it counts backwards starting at the end of the +set. It returns a new Selection object, and an empty Selection object if the +index is invalid. +

    + + + + + + +

    func (*Selection) Filter

    +
    func (s *Selection) Filter(selector string) *Selection
    +

    +Filter reduces the set of matched elements to those that match the selector string. +It returns a new Selection object for this subset of matching elements. +

    + + + + + + +

    func (*Selection) FilterFunction

    +
    func (s *Selection) FilterFunction(f func(int, *Selection) bool) *Selection
    +

    +FilterFunction reduces the set of matched elements to those that pass the function's test. +It returns a new Selection object for this subset of elements. +

    + + + + + + +

    func (*Selection) FilterMatcher

    +
    func (s *Selection) FilterMatcher(m Matcher) *Selection
    +

    +FilterMatcher reduces the set of matched elements to those that match +the given matcher. It returns a new Selection object for this subset +of matching elements. +

    + + + + + + +

    func (*Selection) FilterNodes

    +
    func (s *Selection) FilterNodes(nodes ...*html.Node) *Selection
    +

    +FilterNodes reduces the set of matched elements to those that match the specified nodes. +It returns a new Selection object for this subset of elements. +

    + + + + + + +

    func (*Selection) FilterSelection

    +
    func (s *Selection) FilterSelection(sel *Selection) *Selection
    +

    +FilterSelection reduces the set of matched elements to those that match a +node in the specified Selection object. +It returns a new Selection object for this subset of elements. +

    + + + + + + +

    func (*Selection) Find

    +
    func (s *Selection) Find(selector string) *Selection
    +

    +Find gets the descendants of each element in the current set of matched +elements, filtered by a selector. It returns a new Selection object +containing these matched elements. +

    + + + + + + +

    func (*Selection) FindMatcher

    +
    func (s *Selection) FindMatcher(m Matcher) *Selection
    +

    +FindMatcher gets the descendants of each element in the current set of matched +elements, filtered by the matcher. It returns a new Selection object +containing these matched elements. +

    + + + + + + +

    func (*Selection) FindNodes

    +
    func (s *Selection) FindNodes(nodes ...*html.Node) *Selection
    +

    +FindNodes gets the descendants of each element in the current +Selection, filtered by some nodes. It returns a new Selection object +containing these matched elements. +

    + + + + + + +

    func (*Selection) FindSelection

    +
    func (s *Selection) FindSelection(sel *Selection) *Selection
    +

    +FindSelection gets the descendants of each element in the current +Selection, filtered by a Selection. It returns a new Selection object +containing these matched elements. +

    + + + + + + +

    func (*Selection) First

    +
    func (s *Selection) First() *Selection
    +

    +First reduces the set of matched elements to the first in the set. +It returns a new Selection object, and an empty Selection object if the +the selection is empty. +

    + + + + + + +

    func (*Selection) Get

    +
    func (s *Selection) Get(index int) *html.Node
    +

    +Get retrieves the underlying node at the specified index. +Get without parameter is not implemented, since the node array is available +on the Selection object. +

    + + + + + + +

    func (*Selection) Has

    +
    func (s *Selection) Has(selector string) *Selection
    +

    +Has reduces the set of matched elements to those that have a descendant +that matches the selector. +It returns a new Selection object with the matching elements. +

    + + + + + + +

    func (*Selection) HasClass

    +
    func (s *Selection) HasClass(class string) bool
    +

    +HasClass determines whether any of the matched elements are assigned the +given class. +

    + + + + + + +

    func (*Selection) HasMatcher

    +
    func (s *Selection) HasMatcher(m Matcher) *Selection
    +

    +HasMatcher reduces the set of matched elements to those that have a descendant +that matches the matcher. +It returns a new Selection object with the matching elements. +

    + + + + + + +

    func (*Selection) HasNodes

    +
    func (s *Selection) HasNodes(nodes ...*html.Node) *Selection
    +

    +HasNodes reduces the set of matched elements to those that have a +descendant that matches one of the nodes. +It returns a new Selection object with the matching elements. +

    + + + + + + +

    func (*Selection) HasSelection

    +
    func (s *Selection) HasSelection(sel *Selection) *Selection
    +

    +HasSelection reduces the set of matched elements to those that have a +descendant that matches one of the nodes of the specified Selection object. +It returns a new Selection object with the matching elements. +

    + + + + + + +

    func (*Selection) Html

    +
    func (s *Selection) Html() (ret string, e error)
    +

    +Html gets the HTML contents of the first element in the set of matched +elements. It includes text and comment nodes. +

    + + + + + + +

    func (*Selection) Index

    +
    func (s *Selection) Index() int
    +

    +Index returns the position of the first element within the Selection object +relative to its sibling elements. +

    + + + + + + +

    func (*Selection) IndexMatcher

    +
    func (s *Selection) IndexMatcher(m Matcher) int
    +

    +IndexMatcher returns the position of the first element within the +Selection object relative to the elements matched by the matcher, or -1 if +not found. +

    + + + + + + +

    func (*Selection) IndexOfNode

    +
    func (s *Selection) IndexOfNode(node *html.Node) int
    +

    +IndexOfNode returns the position of the specified node within the Selection +object, or -1 if not found. +

    + + + + + + +

    func (*Selection) IndexOfSelection

    +
    func (s *Selection) IndexOfSelection(sel *Selection) int
    +

    +IndexOfSelection returns the position of the first node in the specified +Selection object within this Selection object, or -1 if not found. +

    + + + + + + +

    func (*Selection) IndexSelector

    +
    func (s *Selection) IndexSelector(selector string) int
    +

    +IndexSelector returns the position of the first element within the +Selection object relative to the elements matched by the selector, or -1 if +not found. +

    + + + + + + +

    func (*Selection) Intersection

    +
    func (s *Selection) Intersection(sel *Selection) *Selection
    +

    +Intersection is an alias for FilterSelection. +

    + + + + + + +

    func (*Selection) Is

    +
    func (s *Selection) Is(selector string) bool
    +

    +Is checks the current matched set of elements against a selector and +returns true if at least one of these elements matches. +

    + + + + + + +

    func (*Selection) IsFunction

    +
    func (s *Selection) IsFunction(f func(int, *Selection) bool) bool
    +

    +IsFunction checks the current matched set of elements against a predicate and +returns true if at least one of these elements matches. +

    + + + + + + +

    func (*Selection) IsMatcher

    +
    func (s *Selection) IsMatcher(m Matcher) bool
    +

    +IsMatcher checks the current matched set of elements against a matcher and +returns true if at least one of these elements matches. +

    + + + + + + +

    func (*Selection) IsNodes

    +
    func (s *Selection) IsNodes(nodes ...*html.Node) bool
    +

    +IsNodes checks the current matched set of elements against the specified nodes +and returns true if at least one of these elements matches. +

    + + + + + + +

    func (*Selection) IsSelection

    +
    func (s *Selection) IsSelection(sel *Selection) bool
    +

    +IsSelection checks the current matched set of elements against a Selection object +and returns true if at least one of these elements matches. +

    + + + + + + +

    func (*Selection) Last

    +
    func (s *Selection) Last() *Selection
    +

    +Last reduces the set of matched elements to the last in the set. +It returns a new Selection object, and an empty Selection object if +the selection is empty. +

    + + + + + + +

    func (*Selection) Length

    +
    func (s *Selection) Length() int
    +

    +Length returns the number of elements in the Selection object. +

    + + + + + + +

    func (*Selection) Map

    +
    func (s *Selection) Map(f func(int, *Selection) string) (result []string)
    +

    +Map passes each element in the current matched set through a function, +producing a slice of string holding the returned values. The function +f is called for each element in the selection with the index of the +element in that selection starting at 0, and a *Selection that contains +only that element. +

    + + + + + + +

    func (*Selection) Next

    +
    func (s *Selection) Next() *Selection
    +

    +Next gets the immediately following sibling of each element in the +Selection. It returns a new Selection object containing the matched elements. +

    + + + + + + +

    func (*Selection) NextAll

    +
    func (s *Selection) NextAll() *Selection
    +

    +NextAll gets all the following siblings of each element in the +Selection. It returns a new Selection object containing the matched elements. +

    + + + + + + +

    func (*Selection) NextAllFiltered

    +
    func (s *Selection) NextAllFiltered(selector string) *Selection
    +

    +NextAllFiltered gets all the following siblings of each element in the +Selection filtered by a selector. It returns a new Selection object +containing the matched elements. +

    + + + + + + +

    func (*Selection) NextAllMatcher

    +
    func (s *Selection) NextAllMatcher(m Matcher) *Selection
    +

    +NextAllMatcher gets all the following siblings of each element in the +Selection filtered by a matcher. It returns a new Selection object +containing the matched elements. +

    + + + + + + +

    func (*Selection) NextFiltered

    +
    func (s *Selection) NextFiltered(selector string) *Selection
    +

    +NextFiltered gets the immediately following sibling of each element in the +Selection filtered by a selector. It returns a new Selection object +containing the matched elements. +

    + + + + + + +

    func (*Selection) NextFilteredUntil

    +
    func (s *Selection) NextFilteredUntil(filterSelector, untilSelector string) *Selection
    +

    +NextFilteredUntil is like NextUntil, with the option to filter +the results based on a selector string. +It returns a new Selection object containing the matched elements. +

    + + + + + + +

    func (*Selection) NextFilteredUntilMatcher

    +
    func (s *Selection) NextFilteredUntilMatcher(filter, until Matcher) *Selection
    +

    +NextFilteredUntilMatcher is like NextUntilMatcher, with the option to filter +the results based on a matcher. +It returns a new Selection object containing the matched elements. +

    + + + + + + +

    func (*Selection) NextFilteredUntilNodes

    +
    func (s *Selection) NextFilteredUntilNodes(filterSelector string, nodes ...*html.Node) *Selection
    +

    +NextFilteredUntilNodes is like NextUntilNodes, with the +option to filter the results based on a selector string. It returns a new +Selection object containing the matched elements. +

    + + + + + + +

    func (*Selection) NextFilteredUntilSelection

    +
    func (s *Selection) NextFilteredUntilSelection(filterSelector string, sel *Selection) *Selection
    +

    +NextFilteredUntilSelection is like NextUntilSelection, with the +option to filter the results based on a selector string. It returns a new +Selection object containing the matched elements. +

    + + + + + + +

    func (*Selection) NextMatcher

    +
    func (s *Selection) NextMatcher(m Matcher) *Selection
    +

    +NextMatcher gets the immediately following sibling of each element in the +Selection filtered by a matcher. It returns a new Selection object +containing the matched elements. +

    + + + + + + +

    func (*Selection) NextMatcherUntilNodes

    +
    func (s *Selection) NextMatcherUntilNodes(filter Matcher, nodes ...*html.Node) *Selection
    +

    +NextMatcherUntilNodes is like NextUntilNodes, with the +option to filter the results based on a matcher. It returns a new +Selection object containing the matched elements. +

    + + + + + + +

    func (*Selection) NextMatcherUntilSelection

    +
    func (s *Selection) NextMatcherUntilSelection(filter Matcher, sel *Selection) *Selection
    +

    +NextMatcherUntilSelection is like NextUntilSelection, with the +option to filter the results based on a matcher. It returns a new +Selection object containing the matched elements. +

    + + + + + + +

    func (*Selection) NextUntil

    +
    func (s *Selection) NextUntil(selector string) *Selection
    +

    +NextUntil gets all following siblings of each element up to but not +including the element matched by the selector. It returns a new Selection +object containing the matched elements. +

    + + + + + + +

    func (*Selection) NextUntilMatcher

    +
    func (s *Selection) NextUntilMatcher(m Matcher) *Selection
    +

    +NextUntilMatcher gets all following siblings of each element up to but not +including the element matched by the matcher. It returns a new Selection +object containing the matched elements. +

    + + + + + + +

    func (*Selection) NextUntilNodes

    +
    func (s *Selection) NextUntilNodes(nodes ...*html.Node) *Selection
    +

    +NextUntilNodes gets all following siblings of each element up to but not +including the element matched by the nodes. It returns a new Selection +object containing the matched elements. +

    + + + + + + +

    func (*Selection) NextUntilSelection

    +
    func (s *Selection) NextUntilSelection(sel *Selection) *Selection
    +

    +NextUntilSelection gets all following siblings of each element up to but not +including the element matched by the Selection. It returns a new Selection +object containing the matched elements. +

    + + + + + + +

    func (*Selection) Not

    +
    func (s *Selection) Not(selector string) *Selection
    +

    +Not removes elements from the Selection that match the selector string. +It returns a new Selection object with the matching elements removed. +

    + + + + + + +

    func (*Selection) NotFunction

    +
    func (s *Selection) NotFunction(f func(int, *Selection) bool) *Selection
    +

    +NotFunction removes elements from the Selection that pass the function's test. +It returns a new Selection object with the matching elements removed. +

    + + + + + + +

    func (*Selection) NotMatcher

    +
    func (s *Selection) NotMatcher(m Matcher) *Selection
    +

    +NotMatcher removes elements from the Selection that match the given matcher. +It returns a new Selection object with the matching elements removed. +

    + + + + + + +

    func (*Selection) NotNodes

    +
    func (s *Selection) NotNodes(nodes ...*html.Node) *Selection
    +

    +NotNodes removes elements from the Selection that match the specified nodes. +It returns a new Selection object with the matching elements removed. +

    + + + + + + +

    func (*Selection) NotSelection

    +
    func (s *Selection) NotSelection(sel *Selection) *Selection
    +

    +NotSelection removes elements from the Selection that match a node in the specified +Selection object. It returns a new Selection object with the matching elements removed. +

    + + + + + + +

    func (*Selection) Parent

    +
    func (s *Selection) Parent() *Selection
    +

    +Parent gets the parent of each element in the Selection. It returns a +new Selection object containing the matched elements. +

    + + + + + + +

    func (*Selection) ParentFiltered

    +
    func (s *Selection) ParentFiltered(selector string) *Selection
    +

    +ParentFiltered gets the parent of each element in the Selection filtered by a +selector. It returns a new Selection object containing the matched elements. +

    + + + + + + +

    func (*Selection) ParentMatcher

    +
    func (s *Selection) ParentMatcher(m Matcher) *Selection
    +

    +ParentMatcher gets the parent of each element in the Selection filtered by a +matcher. It returns a new Selection object containing the matched elements. +

    + + + + + + +

    func (*Selection) Parents

    +
    func (s *Selection) Parents() *Selection
    +

    +Parents gets the ancestors of each element in the current Selection. It +returns a new Selection object with the matched elements. +

    + + + + + + +

    func (*Selection) ParentsFiltered

    +
    func (s *Selection) ParentsFiltered(selector string) *Selection
    +

    +ParentsFiltered gets the ancestors of each element in the current +Selection. It returns a new Selection object with the matched elements. +

    + + + + + + +

    func (*Selection) ParentsFilteredUntil

    +
    func (s *Selection) ParentsFilteredUntil(filterSelector, untilSelector string) *Selection
    +

    +ParentsFilteredUntil is like ParentsUntil, with the option to filter the +results based on a selector string. It returns a new Selection +object containing the matched elements. +

    + + + + + + +

    func (*Selection) ParentsFilteredUntilMatcher

    +
    func (s *Selection) ParentsFilteredUntilMatcher(filter, until Matcher) *Selection
    +

    +ParentsFilteredUntilMatcher is like ParentsUntilMatcher, with the option to filter the +results based on a matcher. It returns a new Selection object containing the matched elements. +

    + + + + + + +

    func (*Selection) ParentsFilteredUntilNodes

    +
    func (s *Selection) ParentsFilteredUntilNodes(filterSelector string, nodes ...*html.Node) *Selection
    +

    +ParentsFilteredUntilNodes is like ParentsUntilNodes, with the +option to filter the results based on a selector string. It returns a new +Selection object containing the matched elements. +

    + + + + + + +

    func (*Selection) ParentsFilteredUntilSelection

    +
    func (s *Selection) ParentsFilteredUntilSelection(filterSelector string, sel *Selection) *Selection
    +

    +ParentsFilteredUntilSelection is like ParentsUntilSelection, with the +option to filter the results based on a selector string. It returns a new +Selection object containing the matched elements. +

    + + + + + + +

    func (*Selection) ParentsMatcher

    +
    func (s *Selection) ParentsMatcher(m Matcher) *Selection
    +

    +ParentsMatcher gets the ancestors of each element in the current +Selection. It returns a new Selection object with the matched elements. +

    + + + + + + +

    func (*Selection) ParentsMatcherUntilNodes

    +
    func (s *Selection) ParentsMatcherUntilNodes(filter Matcher, nodes ...*html.Node) *Selection
    +

    +ParentsMatcherUntilNodes is like ParentsUntilNodes, with the +option to filter the results based on a matcher. It returns a new +Selection object containing the matched elements. +

    + + + + + + +

    func (*Selection) ParentsMatcherUntilSelection

    +
    func (s *Selection) ParentsMatcherUntilSelection(filter Matcher, sel *Selection) *Selection
    +

    +ParentsMatcherUntilSelection is like ParentsUntilSelection, with the +option to filter the results based on a matcher. It returns a new +Selection object containing the matched elements. +

    + + + + + + +

    func (*Selection) ParentsUntil

    +
    func (s *Selection) ParentsUntil(selector string) *Selection
    +

    +ParentsUntil gets the ancestors of each element in the Selection, up to but +not including the element matched by the selector. It returns a new Selection +object containing the matched elements. +

    + + + + + + +

    func (*Selection) ParentsUntilMatcher

    +
    func (s *Selection) ParentsUntilMatcher(m Matcher) *Selection
    +

    +ParentsUntilMatcher gets the ancestors of each element in the Selection, up to but +not including the element matched by the matcher. It returns a new Selection +object containing the matched elements. +

    + + + + + + +

    func (*Selection) ParentsUntilNodes

    +
    func (s *Selection) ParentsUntilNodes(nodes ...*html.Node) *Selection
    +

    +ParentsUntilNodes gets the ancestors of each element in the Selection, +up to but not including the specified nodes. It returns a +new Selection object containing the matched elements. +

    + + + + + + +

    func (*Selection) ParentsUntilSelection

    +
    func (s *Selection) ParentsUntilSelection(sel *Selection) *Selection
    +

    +ParentsUntilSelection gets the ancestors of each element in the Selection, +up to but not including the elements in the specified Selection. It returns a +new Selection object containing the matched elements. +

    + + + + + + +

    func (*Selection) Prepend

    +
    func (s *Selection) Prepend(selector string) *Selection
    +

    +Prepend prepends the elements specified by the selector to each element in +the set of matched elements, following the same rules as Append. +

    + + + + + + +

    func (*Selection) PrependHtml

    +
    func (s *Selection) PrependHtml(html string) *Selection
    +

    +PrependHtml parses the html and prepends it to the set of matched elements. +

    + + + + + + +

    func (*Selection) PrependMatcher

    +
    func (s *Selection) PrependMatcher(m Matcher) *Selection
    +

    +PrependMatcher prepends the elements specified by the matcher to each +element in the set of matched elements. +

    +

    +This follows the same rules as Selection.Append. +

    + + + + + + +

    func (*Selection) PrependNodes

    +
    func (s *Selection) PrependNodes(ns ...*html.Node) *Selection
    +

    +PrependNodes prepends the specified nodes to each node in the set of +matched elements. +

    +

    +This follows the same rules as Selection.Append. +

    + + + + + + +

    func (*Selection) PrependSelection

    +
    func (s *Selection) PrependSelection(sel *Selection) *Selection
    +

    +PrependSelection prepends the elements in the selection to each element in +the set of matched elements. +

    +

    +This follows the same rules as Selection.Append. +

    + + + + + + +

    func (*Selection) Prev

    +
    func (s *Selection) Prev() *Selection
    +

    +Prev gets the immediately preceding sibling of each element in the +Selection. It returns a new Selection object containing the matched elements. +

    + + + + + + +

    func (*Selection) PrevAll

    +
    func (s *Selection) PrevAll() *Selection
    +

    +PrevAll gets all the preceding siblings of each element in the +Selection. It returns a new Selection object containing the matched elements. +

    + + + + + + +

    func (*Selection) PrevAllFiltered

    +
    func (s *Selection) PrevAllFiltered(selector string) *Selection
    +

    +PrevAllFiltered gets all the preceding siblings of each element in the +Selection filtered by a selector. It returns a new Selection object +containing the matched elements. +

    + + + + + + +

    func (*Selection) PrevAllMatcher

    +
    func (s *Selection) PrevAllMatcher(m Matcher) *Selection
    +

    +PrevAllMatcher gets all the preceding siblings of each element in the +Selection filtered by a matcher. It returns a new Selection object +containing the matched elements. +

    + + + + + + +

    func (*Selection) PrevFiltered

    +
    func (s *Selection) PrevFiltered(selector string) *Selection
    +

    +PrevFiltered gets the immediately preceding sibling of each element in the +Selection filtered by a selector. It returns a new Selection object +containing the matched elements. +

    + + + + + + +

    func (*Selection) PrevFilteredUntil

    +
    func (s *Selection) PrevFilteredUntil(filterSelector, untilSelector string) *Selection
    +

    +PrevFilteredUntil is like PrevUntil, with the option to filter +the results based on a selector string. +It returns a new Selection object containing the matched elements. +

    + + + + + + +

    func (*Selection) PrevFilteredUntilMatcher

    +
    func (s *Selection) PrevFilteredUntilMatcher(filter, until Matcher) *Selection
    +

    +PrevFilteredUntilMatcher is like PrevUntilMatcher, with the option to filter +the results based on a matcher. +It returns a new Selection object containing the matched elements. +

    + + + + + + +

    func (*Selection) PrevFilteredUntilNodes

    +
    func (s *Selection) PrevFilteredUntilNodes(filterSelector string, nodes ...*html.Node) *Selection
    +

    +PrevFilteredUntilNodes is like PrevUntilNodes, with the +option to filter the results based on a selector string. It returns a new +Selection object containing the matched elements. +

    + + + + + + +

    func (*Selection) PrevFilteredUntilSelection

    +
    func (s *Selection) PrevFilteredUntilSelection(filterSelector string, sel *Selection) *Selection
    +

    +PrevFilteredUntilSelection is like PrevUntilSelection, with the +option to filter the results based on a selector string. It returns a new +Selection object containing the matched elements. +

    + + + + + + +

    func (*Selection) PrevMatcher

    +
    func (s *Selection) PrevMatcher(m Matcher) *Selection
    +

    +PrevMatcher gets the immediately preceding sibling of each element in the +Selection filtered by a matcher. It returns a new Selection object +containing the matched elements. +

    + + + + + + +

    func (*Selection) PrevMatcherUntilNodes

    +
    func (s *Selection) PrevMatcherUntilNodes(filter Matcher, nodes ...*html.Node) *Selection
    +

    +PrevMatcherUntilNodes is like PrevUntilNodes, with the +option to filter the results based on a matcher. It returns a new +Selection object containing the matched elements. +

    + + + + + + +

    func (*Selection) PrevMatcherUntilSelection

    +
    func (s *Selection) PrevMatcherUntilSelection(filter Matcher, sel *Selection) *Selection
    +

    +PrevMatcherUntilSelection is like PrevUntilSelection, with the +option to filter the results based on a matcher. It returns a new +Selection object containing the matched elements. +

    + + + + + + +

    func (*Selection) PrevUntil

    +
    func (s *Selection) PrevUntil(selector string) *Selection
    +

    +PrevUntil gets all preceding siblings of each element up to but not +including the element matched by the selector. It returns a new Selection +object containing the matched elements. +

    + + + + + + +

    func (*Selection) PrevUntilMatcher

    +
    func (s *Selection) PrevUntilMatcher(m Matcher) *Selection
    +

    +PrevUntilMatcher gets all preceding siblings of each element up to but not +including the element matched by the matcher. It returns a new Selection +object containing the matched elements. +

    + + + + + + +

    func (*Selection) PrevUntilNodes

    +
    func (s *Selection) PrevUntilNodes(nodes ...*html.Node) *Selection
    +

    +PrevUntilNodes gets all preceding siblings of each element up to but not +including the element matched by the nodes. It returns a new Selection +object containing the matched elements. +

    + + + + + + +

    func (*Selection) PrevUntilSelection

    +
    func (s *Selection) PrevUntilSelection(sel *Selection) *Selection
    +

    +PrevUntilSelection gets all preceding siblings of each element up to but not +including the element matched by the Selection. It returns a new Selection +object containing the matched elements. +

    + + + + + + +

    func (*Selection) Remove

    +
    func (s *Selection) Remove() *Selection
    +

    +Remove removes the set of matched elements from the document. +It returns the same selection, now consisting of nodes not in the document. +

    + + + + + + +

    func (*Selection) RemoveAttr

    +
    func (s *Selection) RemoveAttr(attrName string) *Selection
    +

    +RemoveAttr removes the named attribute from each element in the set of matched elements. +

    + + + + + + +

    func (*Selection) RemoveClass

    +
    func (s *Selection) RemoveClass(class ...string) *Selection
    +

    +RemoveClass removes the given class(es) from each element in the set of matched elements. +Multiple class names can be specified, separated by a space or via multiple arguments. +If no class name is provided, all classes are removed. +

    + + + + + + +

    func (*Selection) RemoveFiltered

    +
    func (s *Selection) RemoveFiltered(selector string) *Selection
    +

    +RemoveFiltered removes the set of matched elements by selector. +It returns the Selection of removed nodes. +

    + + + + + + +

    func (*Selection) RemoveMatcher

    +
    func (s *Selection) RemoveMatcher(m Matcher) *Selection
    +

    +RemoveMatcher removes the set of matched elements. +It returns the Selection of removed nodes. +

    + + + + + + +

    func (*Selection) ReplaceWith

    +
    func (s *Selection) ReplaceWith(selector string) *Selection
    +

    +ReplaceWith replaces each element in the set of matched elements with the +nodes matched by the given selector. +It returns the removed elements. +

    +

    +This follows the same rules as Selection.Append. +

    + + + + + + +

    func (*Selection) ReplaceWithHtml

    +
    func (s *Selection) ReplaceWithHtml(html string) *Selection
    +

    +ReplaceWithHtml replaces each element in the set of matched elements with +the parsed HTML. +It returns the removed elements. +

    +

    +This follows the same rules as Selection.Append. +

    + + + + + + +

    func (*Selection) ReplaceWithMatcher

    +
    func (s *Selection) ReplaceWithMatcher(m Matcher) *Selection
    +

    +ReplaceWithMatcher replaces each element in the set of matched elements with +the nodes matched by the given Matcher. +It returns the removed elements. +

    +

    +This follows the same rules as Selection.Append. +

    + + + + + + +

    func (*Selection) ReplaceWithNodes

    +
    func (s *Selection) ReplaceWithNodes(ns ...*html.Node) *Selection
    +

    +ReplaceWithNodes replaces each element in the set of matched elements with +the given nodes. +It returns the removed elements. +

    +

    +This follows the same rules as Selection.Append. +

    + + + + + + +

    func (*Selection) ReplaceWithSelection

    +
    func (s *Selection) ReplaceWithSelection(sel *Selection) *Selection
    +

    +ReplaceWithSelection replaces each element in the set of matched elements with +the nodes from the given Selection. +It returns the removed elements. +

    +

    +This follows the same rules as Selection.Append. +

    + + + + + + +

    func (*Selection) SetAttr

    +
    func (s *Selection) SetAttr(attrName, val string) *Selection
    +

    +SetAttr sets the given attribute on each element in the set of matched elements. +

    + + + + + + +

    func (*Selection) Siblings

    +
    func (s *Selection) Siblings() *Selection
    +

    +Siblings gets the siblings of each element in the Selection. It returns +a new Selection object containing the matched elements. +

    + + + + + + +

    func (*Selection) SiblingsFiltered

    +
    func (s *Selection) SiblingsFiltered(selector string) *Selection
    +

    +SiblingsFiltered gets the siblings of each element in the Selection +filtered by a selector. It returns a new Selection object containing the +matched elements. +

    + + + + + + +

    func (*Selection) SiblingsMatcher

    +
    func (s *Selection) SiblingsMatcher(m Matcher) *Selection
    +

    +SiblingsMatcher gets the siblings of each element in the Selection +filtered by a matcher. It returns a new Selection object containing the +matched elements. +

    + + + + + + +

    func (*Selection) Size

    +
    func (s *Selection) Size() int
    +

    +Size is an alias for Length. +

    + + + + + + +

    func (*Selection) Slice

    +
    func (s *Selection) Slice(start, end int) *Selection
    +

    +Slice reduces the set of matched elements to a subset specified by a range +of indices. +

    + + + + + + +

    func (*Selection) Text

    +
    func (s *Selection) Text() string
    +

    +Text gets the combined text contents of each element in the set of matched +elements, including their descendants. +

    + + + + + + +

    func (*Selection) ToggleClass

    +
    func (s *Selection) ToggleClass(class ...string) *Selection
    +

    +ToggleClass adds or removes the given class(es) for each element in the set of matched elements. +Multiple class names can be specified, separated by a space or via multiple arguments. +

    + + + + + + +

    func (*Selection) Union

    +
    func (s *Selection) Union(sel *Selection) *Selection
    +

    +Union is an alias for AddSelection. +

    + + + + + + +

    func (*Selection) Unwrap

    +
    func (s *Selection) Unwrap() *Selection
    +

    +Unwrap removes the parents of the set of matched elements, leaving the matched +elements (and their siblings, if any) in their place. +It returns the original selection. +

    + + + + + + +

    func (*Selection) Wrap

    +
    func (s *Selection) Wrap(selector string) *Selection
    +

    +Wrap wraps each element in the set of matched elements inside the first +element matched by the given selector. The matched child is cloned before +being inserted into the document. +

    +

    +It returns the original set of elements. +

    + + + + + + +

    func (*Selection) WrapAll

    +
    func (s *Selection) WrapAll(selector string) *Selection
    +

    +WrapAll wraps a single HTML structure, matched by the given selector, around +all elements in the set of matched elements. The matched child is cloned +before being inserted into the document. +

    +

    +It returns the original set of elements. +

    + + + + + + +

    func (*Selection) WrapAllHtml

    +
    func (s *Selection) WrapAllHtml(html string) *Selection
    +

    +WrapAllHtml wraps the given HTML structure around all elements in the set of +matched elements. The matched child is cloned before being inserted into the +document. +

    +

    +It returns the original set of elements. +

    + + + + + + +

    func (*Selection) WrapAllMatcher

    +
    func (s *Selection) WrapAllMatcher(m Matcher) *Selection
    +

    +WrapAllMatcher wraps a single HTML structure, matched by the given Matcher, +around all elements in the set of matched elements. The matched child is +cloned before being inserted into the document. +

    +

    +It returns the original set of elements. +

    + + + + + + +

    func (*Selection) WrapAllNode

    +
    func (s *Selection) WrapAllNode(n *html.Node) *Selection
    +

    +WrapAllNode wraps the given node around the first element in the Selection, +making all other nodes in the Selection children of the given node. The node +is cloned before being inserted into the document. +

    +

    +It returns the original set of elements. +

    + + + + + + +

    func (*Selection) WrapAllSelection

    +
    func (s *Selection) WrapAllSelection(sel *Selection) *Selection
    +

    +WrapAllSelection wraps a single HTML structure, the first node of the given +Selection, around all elements in the set of matched elements. The matched +child is cloned before being inserted into the document. +

    +

    +It returns the original set of elements. +

    + + + + + + +

    func (*Selection) WrapHtml

    +
    func (s *Selection) WrapHtml(html string) *Selection
    +

    +WrapHtml wraps each element in the set of matched elements inside the inner- +most child of the given HTML. +

    +

    +It returns the original set of elements. +

    + + + + + + +

    func (*Selection) WrapInner

    +
    func (s *Selection) WrapInner(selector string) *Selection
    +

    +WrapInner wraps an HTML structure, matched by the given selector, around the +content of element in the set of matched elements. The matched child is +cloned before being inserted into the document. +

    +

    +It returns the original set of elements. +

    + + + + + + +

    func (*Selection) WrapInnerHtml

    +
    func (s *Selection) WrapInnerHtml(html string) *Selection
    +

    +WrapInnerHtml wraps an HTML structure, matched by the given selector, around +the content of element in the set of matched elements. The matched child is +cloned before being inserted into the document. +

    +

    +It returns the original set of elements. +

    + + + + + + +

    func (*Selection) WrapInnerMatcher

    +
    func (s *Selection) WrapInnerMatcher(m Matcher) *Selection
    +

    +WrapInnerMatcher wraps an HTML structure, matched by the given selector, +around the content of element in the set of matched elements. The matched +child is cloned before being inserted into the document. +

    +

    +It returns the original set of elements. +

    + + + + + + +

    func (*Selection) WrapInnerNode

    +
    func (s *Selection) WrapInnerNode(n *html.Node) *Selection
    +

    +WrapInnerNode wraps an HTML structure, matched by the given selector, around +the content of element in the set of matched elements. The matched child is +cloned before being inserted into the document. +

    +

    +It returns the original set of elements. +

    + + + + + + +

    func (*Selection) WrapInnerSelection

    +
    func (s *Selection) WrapInnerSelection(sel *Selection) *Selection
    +

    +WrapInnerSelection wraps an HTML structure, matched by the given selector, +around the content of element in the set of matched elements. The matched +child is cloned before being inserted into the document. +

    +

    +It returns the original set of elements. +

    + + + + + + +

    func (*Selection) WrapMatcher

    +
    func (s *Selection) WrapMatcher(m Matcher) *Selection
    +

    +WrapMatcher wraps each element in the set of matched elements inside the +first element matched by the given matcher. The matched child is cloned +before being inserted into the document. +

    +

    +It returns the original set of elements. +

    + + + + + + +

    func (*Selection) WrapNode

    +
    func (s *Selection) WrapNode(n *html.Node) *Selection
    +

    +WrapNode wraps each element in the set of matched elements inside the inner- +most child of the given node. The given node is copied before being inserted +into the document. +

    +

    +It returns the original set of elements. +

    + + + + + + +

    func (*Selection) WrapSelection

    +
    func (s *Selection) WrapSelection(sel *Selection) *Selection
    +

    +WrapSelection wraps each element in the set of matched elements inside the +first element in the given Selection. The element is cloned before being +inserted into the document. +

    +

    +It returns the original set of elements. +

    + + + + + + + + + + + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/github.com/PuerkitoBio/index.html b/pkg/github.com/PuerkitoBio/index.html new file mode 100644 index 0000000..265f8e1 --- /dev/null +++ b/pkg/github.com/PuerkitoBio/index.html @@ -0,0 +1,130 @@ + + + + + + + + /src/github.com/PuerkitoBio - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Directory /src/github.com/PuerkitoBio

    + + + + + + + + + + + + + + + + + + + +
    + + + + + + + + + + + + + + + + + + + + +
    NameSynopsis
    ..
    + goquery + + Package goquery implements features similar to jQuery, including the chainable syntax, to manipulate and query an HTML document. +
    +
    + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/github.com/Sirupsen/index.html b/pkg/github.com/Sirupsen/index.html new file mode 100644 index 0000000..a22e42b --- /dev/null +++ b/pkg/github.com/Sirupsen/index.html @@ -0,0 +1,196 @@ + + + + + + + + /src/github.com/Sirupsen - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Directory /src/github.com/Sirupsen

    + + + + + + + + + + + + + + + + + + + +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    NameSynopsis
    ..
    + logrus + + Package logrus is a structured logger for Go, completely API compatible with the standard library logger. +
    + examples + + +
    + basic + + +
    + hook + + +
    + hooks + + +
    + syslog + + +
    + test + + +
    +
    + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/github.com/Sirupsen/logrus/examples/basic/index.html b/pkg/github.com/Sirupsen/logrus/examples/basic/index.html new file mode 100644 index 0000000..171434a --- /dev/null +++ b/pkg/github.com/Sirupsen/logrus/examples/basic/index.html @@ -0,0 +1,106 @@ + + + + + + + + basic - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Command basic

    + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/github.com/Sirupsen/logrus/examples/hook/index.html b/pkg/github.com/Sirupsen/logrus/examples/hook/index.html new file mode 100644 index 0000000..bc8395f --- /dev/null +++ b/pkg/github.com/Sirupsen/logrus/examples/hook/index.html @@ -0,0 +1,106 @@ + + + + + + + + hook - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Command hook

    + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/github.com/Sirupsen/logrus/examples/index.html b/pkg/github.com/Sirupsen/logrus/examples/index.html new file mode 100644 index 0000000..40fae37 --- /dev/null +++ b/pkg/github.com/Sirupsen/logrus/examples/index.html @@ -0,0 +1,141 @@ + + + + + + + + /src/github.com/Sirupsen/logrus/examples - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Directory /src/github.com/Sirupsen/logrus/examples

    + + + + + + + + + + + + + + + + + + + +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    NameSynopsis
    ..
    + basic + + +
    + hook + + +
    +
    + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/github.com/Sirupsen/logrus/hooks/index.html b/pkg/github.com/Sirupsen/logrus/hooks/index.html new file mode 100644 index 0000000..8653110 --- /dev/null +++ b/pkg/github.com/Sirupsen/logrus/hooks/index.html @@ -0,0 +1,141 @@ + + + + + + + + /src/github.com/Sirupsen/logrus/hooks - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Directory /src/github.com/Sirupsen/logrus/hooks

    + + + + + + + + + + + + + + + + + + + +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    NameSynopsis
    ..
    + syslog + + +
    + test + + +
    +
    + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/github.com/Sirupsen/logrus/hooks/syslog/index.html b/pkg/github.com/Sirupsen/logrus/hooks/syslog/index.html new file mode 100644 index 0000000..dfeccd1 --- /dev/null +++ b/pkg/github.com/Sirupsen/logrus/hooks/syslog/index.html @@ -0,0 +1,269 @@ + + + + + + + + logrus_syslog - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Package logrus_syslog

    + + + + + + + + + + + + + + +
    +
    +
    import "github.com/Sirupsen/logrus/hooks/syslog"
    +
    +
    +
    Overview
    +
    Index
    + + +
    +
    + +
    + +
    +

    Overview ▾

    + +
    +
    + + + + + + + + + + + + +

    type SyslogHook

    +
    type SyslogHook struct {
    +    Writer        *syslog.Writer
    +    SyslogNetwork string
    +    SyslogRaddr   string
    +}
    +

    +SyslogHook to send logs via syslog. +

    + + + + + + + + + + + + +

    func NewSyslogHook

    +
    func NewSyslogHook(network, raddr string, priority syslog.Priority, tag string) (*SyslogHook, error)
    +

    +Creates a hook to be added to an instance of logger. This is called with +`hook, err := NewSyslogHook("udp", "localhost:514", syslog.LOG_DEBUG, "")` +`if err == nil { log.Hooks.Add(hook) }` +

    + + + + + + + +

    func (*SyslogHook) Fire

    +
    func (hook *SyslogHook) Fire(entry *logrus.Entry) error
    + + + + + + +

    func (*SyslogHook) Levels

    +
    func (hook *SyslogHook) Levels() []logrus.Level
    + + + + + + + + + + + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/github.com/Sirupsen/logrus/hooks/test/index.html b/pkg/github.com/Sirupsen/logrus/hooks/test/index.html new file mode 100644 index 0000000..e43f95d --- /dev/null +++ b/pkg/github.com/Sirupsen/logrus/hooks/test/index.html @@ -0,0 +1,321 @@ + + + + + + + + test - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Package test

    + + + + + + + + + + + + + + +
    +
    +
    import "github.com/Sirupsen/logrus/hooks/test"
    +
    +
    +
    Overview
    +
    Index
    + + +
    +
    + +
    + +
    +

    Overview ▾

    + +
    +
    + + +
    + + +
    + + + + + + + + +

    func NewNullLogger

    +
    func NewNullLogger() (*logrus.Logger, *Hook)
    +

    +Creates a discarding logger and installs the test hook. +

    + + + + + + + + +

    type Hook

    +
    type Hook struct {
    +    Entries []*logrus.Entry
    +}
    +

    +test.Hook is a hook designed for dealing with logs in test scenarios. +

    + + + + + + + + + + + + +

    func NewGlobal

    +
    func NewGlobal() *Hook
    +

    +Installs a test hook for the global logger. +

    + + + + + +

    func NewLocal

    +
    func NewLocal(logger *logrus.Logger) *Hook
    +

    +Installs a test hook for a given local logger. +

    + + + + + + + +

    func (*Hook) Fire

    +
    func (t *Hook) Fire(e *logrus.Entry) error
    + + + + + + +

    func (*Hook) LastEntry

    +
    func (t *Hook) LastEntry() (l *logrus.Entry)
    +

    +LastEntry returns the last entry that was logged or nil. +

    + + + + + + +

    func (*Hook) Levels

    +
    func (t *Hook) Levels() []logrus.Level
    + + + + + + +

    func (*Hook) Reset

    +
    func (t *Hook) Reset()
    +

    +Reset removes all Entries from this test hook. +

    + + + + + + + + + + + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/github.com/Sirupsen/logrus/index.html b/pkg/github.com/Sirupsen/logrus/index.html new file mode 100644 index 0000000..0fb03d6 --- /dev/null +++ b/pkg/github.com/Sirupsen/logrus/index.html @@ -0,0 +1,2160 @@ + + + + + + + + logrus - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Package logrus

    + + + + + + + + + + + + + + +
    +
    +
    import "github.com/Sirupsen/logrus"
    +
    +
    +
    Overview
    +
    Index
    + + +
    Subdirectories
    + +
    +
    + +
    + +
    +

    Overview ▾

    +

    +Package logrus is a structured logger for Go, completely API compatible with the standard library logger. +

    +

    +The simplest way to use Logrus is simply the package-level exported logger: +

    +
    package main
    +
    +import (
    +  log "github.com/Sirupsen/logrus"
    +)
    +
    +func main() {
    +  log.WithFields(log.Fields{
    +    "animal": "walrus",
    +    "number": 1,
    +    "size":   10,
    +  }).Info("A walrus appears")
    +}
    +
    +

    +Output: +

    +
    time="2015-09-07T08:48:33Z" level=info msg="A walrus appears" animal=walrus number=1 size=10
    +
    +

    +For a full guide visit https://github.com/Sirupsen/logrus +

    + +
    +
    + + +
    + +
    +

    Index ▾

    + + +
    +
    + +
    Constants
    + + +
    Variables
    + + + +
    func AddHook(hook Hook)
    + + +
    func Debug(args ...interface{})
    + + +
    func Debugf(format string, args ...interface{})
    + + +
    func Debugln(args ...interface{})
    + + +
    func Error(args ...interface{})
    + + +
    func Errorf(format string, args ...interface{})
    + + +
    func Errorln(args ...interface{})
    + + +
    func Exit(code int)
    + + +
    func Fatal(args ...interface{})
    + + +
    func Fatalf(format string, args ...interface{})
    + + +
    func Fatalln(args ...interface{})
    + + +
    func Info(args ...interface{})
    + + +
    func Infof(format string, args ...interface{})
    + + +
    func Infoln(args ...interface{})
    + + +
    func IsTerminal() bool
    + + +
    func Panic(args ...interface{})
    + + +
    func Panicf(format string, args ...interface{})
    + + +
    func Panicln(args ...interface{})
    + + +
    func Print(args ...interface{})
    + + +
    func Printf(format string, args ...interface{})
    + + +
    func Println(args ...interface{})
    + + +
    func RegisterExitHandler(handler func())
    + + +
    func SetFormatter(formatter Formatter)
    + + +
    func SetLevel(level Level)
    + + +
    func SetOutput(out io.Writer)
    + + +
    func Warn(args ...interface{})
    + + +
    func Warnf(format string, args ...interface{})
    + + +
    func Warning(args ...interface{})
    + + +
    func Warningf(format string, args ...interface{})
    + + +
    func Warningln(args ...interface{})
    + + +
    func Warnln(args ...interface{})
    + + + +
    type Entry
    + + +
        func NewEntry(logger *Logger) *Entry
    + + +
        func WithError(err error) *Entry
    + + +
        func WithField(key string, value interface{}) *Entry
    + + +
        func WithFields(fields Fields) *Entry
    + + + +
        func (entry *Entry) Debug(args ...interface{})
    + + +
        func (entry *Entry) Debugf(format string, args ...interface{})
    + + +
        func (entry *Entry) Debugln(args ...interface{})
    + + +
        func (entry *Entry) Error(args ...interface{})
    + + +
        func (entry *Entry) Errorf(format string, args ...interface{})
    + + +
        func (entry *Entry) Errorln(args ...interface{})
    + + +
        func (entry *Entry) Fatal(args ...interface{})
    + + +
        func (entry *Entry) Fatalf(format string, args ...interface{})
    + + +
        func (entry *Entry) Fatalln(args ...interface{})
    + + +
        func (entry *Entry) Info(args ...interface{})
    + + +
        func (entry *Entry) Infof(format string, args ...interface{})
    + + +
        func (entry *Entry) Infoln(args ...interface{})
    + + +
        func (entry *Entry) Panic(args ...interface{})
    + + +
        func (entry *Entry) Panicf(format string, args ...interface{})
    + + +
        func (entry *Entry) Panicln(args ...interface{})
    + + +
        func (entry *Entry) Print(args ...interface{})
    + + +
        func (entry *Entry) Printf(format string, args ...interface{})
    + + +
        func (entry *Entry) Println(args ...interface{})
    + + +
        func (entry *Entry) Reader() (*bytes.Buffer, error)
    + + +
        func (entry *Entry) String() (string, error)
    + + +
        func (entry *Entry) Warn(args ...interface{})
    + + +
        func (entry *Entry) Warnf(format string, args ...interface{})
    + + +
        func (entry *Entry) Warning(args ...interface{})
    + + +
        func (entry *Entry) Warningf(format string, args ...interface{})
    + + +
        func (entry *Entry) Warningln(args ...interface{})
    + + +
        func (entry *Entry) Warnln(args ...interface{})
    + + +
        func (entry *Entry) WithError(err error) *Entry
    + + +
        func (entry *Entry) WithField(key string, value interface{}) *Entry
    + + +
        func (entry *Entry) WithFields(fields Fields) *Entry
    + + + +
    type FieldLogger
    + + + + +
    type Fields
    + + + + +
    type Formatter
    + + + + +
    type Hook
    + + + + +
    type JSONFormatter
    + + + +
        func (f *JSONFormatter) Format(entry *Entry) ([]byte, error)
    + + + +
    type Level
    + + +
        func GetLevel() Level
    + + +
        func ParseLevel(lvl string) (Level, error)
    + + + +
        func (level Level) String() string
    + + + +
    type LevelHooks
    + + + +
        func (hooks LevelHooks) Add(hook Hook)
    + + +
        func (hooks LevelHooks) Fire(level Level, entry *Entry) error
    + + + +
    type Logger
    + + +
        func New() *Logger
    + + +
        func StandardLogger() *Logger
    + + + +
        func (logger *Logger) Debug(args ...interface{})
    + + +
        func (logger *Logger) Debugf(format string, args ...interface{})
    + + +
        func (logger *Logger) Debugln(args ...interface{})
    + + +
        func (logger *Logger) Error(args ...interface{})
    + + +
        func (logger *Logger) Errorf(format string, args ...interface{})
    + + +
        func (logger *Logger) Errorln(args ...interface{})
    + + +
        func (logger *Logger) Fatal(args ...interface{})
    + + +
        func (logger *Logger) Fatalf(format string, args ...interface{})
    + + +
        func (logger *Logger) Fatalln(args ...interface{})
    + + +
        func (logger *Logger) Info(args ...interface{})
    + + +
        func (logger *Logger) Infof(format string, args ...interface{})
    + + +
        func (logger *Logger) Infoln(args ...interface{})
    + + +
        func (logger *Logger) Panic(args ...interface{})
    + + +
        func (logger *Logger) Panicf(format string, args ...interface{})
    + + +
        func (logger *Logger) Panicln(args ...interface{})
    + + +
        func (logger *Logger) Print(args ...interface{})
    + + +
        func (logger *Logger) Printf(format string, args ...interface{})
    + + +
        func (logger *Logger) Println(args ...interface{})
    + + +
        func (logger *Logger) Warn(args ...interface{})
    + + +
        func (logger *Logger) Warnf(format string, args ...interface{})
    + + +
        func (logger *Logger) Warning(args ...interface{})
    + + +
        func (logger *Logger) Warningf(format string, args ...interface{})
    + + +
        func (logger *Logger) Warningln(args ...interface{})
    + + +
        func (logger *Logger) Warnln(args ...interface{})
    + + +
        func (logger *Logger) WithError(err error) *Entry
    + + +
        func (logger *Logger) WithField(key string, value interface{}) *Entry
    + + +
        func (logger *Logger) WithFields(fields Fields) *Entry
    + + +
        func (logger *Logger) Writer() *io.PipeWriter
    + + +
        func (logger *Logger) WriterLevel(level Level) *io.PipeWriter
    + + + +
    type StdLogger
    + + + + +
    type Termios
    + + + + +
    type TextFormatter
    + + + +
        func (f *TextFormatter) Format(entry *Entry) ([]byte, error)
    + + + +
    +
    + + + + +

    Package files

    +

    + + + alt_exit.go + + doc.go + + entry.go + + exported.go + + formatter.go + + hooks.go + + json_formatter.go + + logger.go + + logrus.go + + terminal_linux.go + + terminal_notwindows.go + + text_formatter.go + + writer.go + + +

    + +
    +
    + + + + +

    Constants

    + +
    const DefaultTimestampFormat = time.RFC3339
    + + + + +

    Variables

    + +
    var AllLevels = []Level{
    +    PanicLevel,
    +    FatalLevel,
    +    ErrorLevel,
    +    WarnLevel,
    +    InfoLevel,
    +    DebugLevel,
    +}
    +

    +A constant exposing all logging levels +

    + + +
    var ErrorKey = "error"
    +

    +Defines the key when adding errors using WithError. +

    + + + + + + +

    func AddHook

    +
    func AddHook(hook Hook)
    +

    +AddHook adds a hook to the standard logger hooks. +

    + + + + + + + +

    func Debug

    +
    func Debug(args ...interface{})
    +

    +Debug logs a message at level Debug on the standard logger. +

    + + + + + + + +

    func Debugf

    +
    func Debugf(format string, args ...interface{})
    +

    +Debugf logs a message at level Debug on the standard logger. +

    + + + + + + + +

    func Debugln

    +
    func Debugln(args ...interface{})
    +

    +Debugln logs a message at level Debug on the standard logger. +

    + + + + + + + +

    func Error

    +
    func Error(args ...interface{})
    +

    +Error logs a message at level Error on the standard logger. +

    + + + + + + + +

    func Errorf

    +
    func Errorf(format string, args ...interface{})
    +

    +Errorf logs a message at level Error on the standard logger. +

    + + + + + + + +

    func Errorln

    +
    func Errorln(args ...interface{})
    +

    +Errorln logs a message at level Error on the standard logger. +

    + + + + + + + +

    func Exit

    +
    func Exit(code int)
    +

    +Exit runs all the Logrus atexit handlers and then terminates the program using os.Exit(code) +

    + + + + + + + +

    func Fatal

    +
    func Fatal(args ...interface{})
    +

    +Fatal logs a message at level Fatal on the standard logger. +

    + + + + + + + +

    func Fatalf

    +
    func Fatalf(format string, args ...interface{})
    +

    +Fatalf logs a message at level Fatal on the standard logger. +

    + + + + + + + +

    func Fatalln

    +
    func Fatalln(args ...interface{})
    +

    +Fatalln logs a message at level Fatal on the standard logger. +

    + + + + + + + +

    func Info

    +
    func Info(args ...interface{})
    +

    +Info logs a message at level Info on the standard logger. +

    + + + + + + + +

    func Infof

    +
    func Infof(format string, args ...interface{})
    +

    +Infof logs a message at level Info on the standard logger. +

    + + + + + + + +

    func Infoln

    +
    func Infoln(args ...interface{})
    +

    +Infoln logs a message at level Info on the standard logger. +

    + + + + + + + +

    func IsTerminal

    +
    func IsTerminal() bool
    +

    +IsTerminal returns true if stderr's file descriptor is a terminal. +

    + + + + + + + +

    func Panic

    +
    func Panic(args ...interface{})
    +

    +Panic logs a message at level Panic on the standard logger. +

    + + + + + + + +

    func Panicf

    +
    func Panicf(format string, args ...interface{})
    +

    +Panicf logs a message at level Panic on the standard logger. +

    + + + + + + + +

    func Panicln

    +
    func Panicln(args ...interface{})
    +

    +Panicln logs a message at level Panic on the standard logger. +

    + + + + + + + +

    func Print

    +
    func Print(args ...interface{})
    +

    +Print logs a message at level Info on the standard logger. +

    + + + + + + + +

    func Printf

    +
    func Printf(format string, args ...interface{})
    +

    +Printf logs a message at level Info on the standard logger. +

    + + + + + + + +

    func Println

    +
    func Println(args ...interface{})
    +

    +Println logs a message at level Info on the standard logger. +

    + + + + + + + +

    func RegisterExitHandler

    +
    func RegisterExitHandler(handler func())
    +

    +RegisterExitHandler adds a Logrus Exit handler, call logrus.Exit to invoke +all handlers. The handlers will also be invoked when any Fatal log entry is +made. +

    +

    +This method is useful when a caller wishes to use logrus to log a fatal +message but also needs to gracefully shutdown. An example usecase could be +closing database connections, or sending a alert that the application is +closing. +

    + + + + + + + +

    func SetFormatter

    +
    func SetFormatter(formatter Formatter)
    +

    +SetFormatter sets the standard logger formatter. +

    + + + + + + + +

    func SetLevel

    +
    func SetLevel(level Level)
    +

    +SetLevel sets the standard logger level. +

    + + + + + + + +

    func SetOutput

    +
    func SetOutput(out io.Writer)
    +

    +SetOutput sets the standard logger output. +

    + + + + + + + +

    func Warn

    +
    func Warn(args ...interface{})
    +

    +Warn logs a message at level Warn on the standard logger. +

    + + + + + + + +

    func Warnf

    +
    func Warnf(format string, args ...interface{})
    +

    +Warnf logs a message at level Warn on the standard logger. +

    + + + + + + + +

    func Warning

    +
    func Warning(args ...interface{})
    +

    +Warning logs a message at level Warn on the standard logger. +

    + + + + + + + +

    func Warningf

    +
    func Warningf(format string, args ...interface{})
    +

    +Warningf logs a message at level Warn on the standard logger. +

    + + + + + + + +

    func Warningln

    +
    func Warningln(args ...interface{})
    +

    +Warningln logs a message at level Warn on the standard logger. +

    + + + + + + + +

    func Warnln

    +
    func Warnln(args ...interface{})
    +

    +Warnln logs a message at level Warn on the standard logger. +

    + + + + + + + + +

    type Entry

    +
    type Entry struct {
    +    Logger *Logger
    +
    +    // Contains all the fields set by the user.
    +    Data Fields
    +
    +    // Time at which the log entry was created
    +    Time time.Time
    +
    +    // Level the log entry was logged at: Debug, Info, Warn, Error, Fatal or Panic
    +    Level Level
    +
    +    // Message passed to Debug, Info, Warn, Error, Fatal or Panic
    +    Message string
    +}
    +

    +An entry is the final or intermediate Logrus logging entry. It contains all +the fields passed with WithField{,s}. It's finally logged when Debug, Info, +Warn, Error, Fatal or Panic is called on it. These objects can be reused and +passed around as much as you wish to avoid field duplication. +

    + + + + + + + + + + + + +

    func NewEntry

    +
    func NewEntry(logger *Logger) *Entry
    + + + + + +

    func WithError

    +
    func WithError(err error) *Entry
    +

    +WithError creates an entry from the standard logger and adds an error to it, using the value defined in ErrorKey as key. +

    + + + + + +

    func WithField

    +
    func WithField(key string, value interface{}) *Entry
    +

    +WithField creates an entry from the standard logger and adds a field to +it. If you want multiple fields, use `WithFields`. +

    +

    +Note that it doesn't log until you call Debug, Print, Info, Warn, Fatal +or Panic on the Entry it returns. +

    + + + + + +

    func WithFields

    +
    func WithFields(fields Fields) *Entry
    +

    +WithFields creates an entry from the standard logger and adds multiple +fields to it. This is simply a helper for `WithField`, invoking it +once for each field. +

    +

    +Note that it doesn't log until you call Debug, Print, Info, Warn, Fatal +or Panic on the Entry it returns. +

    + + + + + + + +

    func (*Entry) Debug

    +
    func (entry *Entry) Debug(args ...interface{})
    + + + + + + +

    func (*Entry) Debugf

    +
    func (entry *Entry) Debugf(format string, args ...interface{})
    + + + + + + +

    func (*Entry) Debugln

    +
    func (entry *Entry) Debugln(args ...interface{})
    + + + + + + +

    func (*Entry) Error

    +
    func (entry *Entry) Error(args ...interface{})
    + + + + + + +

    func (*Entry) Errorf

    +
    func (entry *Entry) Errorf(format string, args ...interface{})
    + + + + + + +

    func (*Entry) Errorln

    +
    func (entry *Entry) Errorln(args ...interface{})
    + + + + + + +

    func (*Entry) Fatal

    +
    func (entry *Entry) Fatal(args ...interface{})
    + + + + + + +

    func (*Entry) Fatalf

    +
    func (entry *Entry) Fatalf(format string, args ...interface{})
    + + + + + + +

    func (*Entry) Fatalln

    +
    func (entry *Entry) Fatalln(args ...interface{})
    + + + + + + +

    func (*Entry) Info

    +
    func (entry *Entry) Info(args ...interface{})
    + + + + + + +

    func (*Entry) Infof

    +
    func (entry *Entry) Infof(format string, args ...interface{})
    + + + + + + +

    func (*Entry) Infoln

    +
    func (entry *Entry) Infoln(args ...interface{})
    + + + + + + +

    func (*Entry) Panic

    +
    func (entry *Entry) Panic(args ...interface{})
    + + + + + + +

    func (*Entry) Panicf

    +
    func (entry *Entry) Panicf(format string, args ...interface{})
    + + + + + + +

    func (*Entry) Panicln

    +
    func (entry *Entry) Panicln(args ...interface{})
    + + + + + + +

    func (*Entry) Print

    +
    func (entry *Entry) Print(args ...interface{})
    + + + + + + +

    func (*Entry) Printf

    +
    func (entry *Entry) Printf(format string, args ...interface{})
    + + + + + + +

    func (*Entry) Println

    +
    func (entry *Entry) Println(args ...interface{})
    + + + + + + +

    func (*Entry) Reader

    +
    func (entry *Entry) Reader() (*bytes.Buffer, error)
    +

    +Returns a reader for the entry, which is a proxy to the formatter. +

    + + + + + + +

    func (*Entry) String

    +
    func (entry *Entry) String() (string, error)
    +

    +Returns the string representation from the reader and ultimately the +formatter. +

    + + + + + + +

    func (*Entry) Warn

    +
    func (entry *Entry) Warn(args ...interface{})
    + + + + + + +

    func (*Entry) Warnf

    +
    func (entry *Entry) Warnf(format string, args ...interface{})
    + + + + + + +

    func (*Entry) Warning

    +
    func (entry *Entry) Warning(args ...interface{})
    + + + + + + +

    func (*Entry) Warningf

    +
    func (entry *Entry) Warningf(format string, args ...interface{})
    + + + + + + +

    func (*Entry) Warningln

    +
    func (entry *Entry) Warningln(args ...interface{})
    + + + + + + +

    func (*Entry) Warnln

    +
    func (entry *Entry) Warnln(args ...interface{})
    + + + + + + +

    func (*Entry) WithError

    +
    func (entry *Entry) WithError(err error) *Entry
    +

    +Add an error as single field (using the key defined in ErrorKey) to the Entry. +

    + + + + + + +

    func (*Entry) WithField

    +
    func (entry *Entry) WithField(key string, value interface{}) *Entry
    +

    +Add a single field to the Entry. +

    + + + + + + +

    func (*Entry) WithFields

    +
    func (entry *Entry) WithFields(fields Fields) *Entry
    +

    +Add a map of fields to the Entry. +

    + + + + + + + + +

    type FieldLogger

    +
    type FieldLogger interface {
    +    WithField(key string, value interface{}) *Entry
    +    WithFields(fields Fields) *Entry
    +    WithError(err error) *Entry
    +
    +    Debugf(format string, args ...interface{})
    +    Infof(format string, args ...interface{})
    +    Printf(format string, args ...interface{})
    +    Warnf(format string, args ...interface{})
    +    Warningf(format string, args ...interface{})
    +    Errorf(format string, args ...interface{})
    +    Fatalf(format string, args ...interface{})
    +    Panicf(format string, args ...interface{})
    +
    +    Debug(args ...interface{})
    +    Info(args ...interface{})
    +    Print(args ...interface{})
    +    Warn(args ...interface{})
    +    Warning(args ...interface{})
    +    Error(args ...interface{})
    +    Fatal(args ...interface{})
    +    Panic(args ...interface{})
    +
    +    Debugln(args ...interface{})
    +    Infoln(args ...interface{})
    +    Println(args ...interface{})
    +    Warnln(args ...interface{})
    +    Warningln(args ...interface{})
    +    Errorln(args ...interface{})
    +    Fatalln(args ...interface{})
    +    Panicln(args ...interface{})
    +}
    +

    +The FieldLogger interface generalizes the Entry and Logger types +

    + + + + + + + + + + + + + + + + +

    type Fields

    +
    type Fields map[string]interface{}
    +

    +Fields type, used to pass to `WithFields`. +

    + + + + + + + + + + + + + + + + +

    type Formatter

    +
    type Formatter interface {
    +    Format(*Entry) ([]byte, error)
    +}
    +

    +The Formatter interface is used to implement a custom Formatter. It takes an +`Entry`. It exposes all the fields, including the default ones: +

    +

    +* `entry.Data["msg"]`. The message passed from Info, Warn, Error .. +* `entry.Data["time"]`. The timestamp. +* `entry.Data["level"]. The level the entry was logged at. +

    +

    +Any additional fields added with `WithField` or `WithFields` are also in +`entry.Data`. Format is expected to return an array of bytes which are then +logged to `logger.Out`. +

    + + + + + + + + + + + + + + + + +

    type Hook

    +
    type Hook interface {
    +    Levels() []Level
    +    Fire(*Entry) error
    +}
    +

    +A hook to be fired when logging on the logging levels returned from +`Levels()` on your implementation of the interface. Note that this is not +fired in a goroutine or a channel with workers, you should handle such +functionality yourself if your call is non-blocking and you don't wish for +the logging calls for levels returned from `Levels()` to block. +

    + + + + + + + + + + + + + + + + +

    type JSONFormatter

    +
    type JSONFormatter struct {
    +    // TimestampFormat sets the format used for marshaling timestamps.
    +    TimestampFormat string
    +}
    + + + + + + + + + + + + + + +

    func (*JSONFormatter) Format

    +
    func (f *JSONFormatter) Format(entry *Entry) ([]byte, error)
    + + + + + + + + +

    type Level

    +
    type Level uint8
    +

    +Level type +

    + + + +
    const (
    +    // PanicLevel level, highest level of severity. Logs and then calls panic with the
    +    // message passed to Debug, Info, ...
    +    PanicLevel Level = iota
    +    // FatalLevel level. Logs and then calls `os.Exit(1)`. It will exit even if the
    +    // logging level is set to Panic.
    +    FatalLevel
    +    // ErrorLevel level. Logs. Used for errors that should definitely be noted.
    +    // Commonly used for hooks to send errors to an error tracking service.
    +    ErrorLevel
    +    // WarnLevel level. Non-critical entries that deserve eyes.
    +    WarnLevel
    +    // InfoLevel level. General operational entries about what's going on inside the
    +    // application.
    +    InfoLevel
    +    // DebugLevel level. Usually only enabled when debugging. Very verbose logging.
    +    DebugLevel
    +)
    +

    +These are the different logging levels. You can set the logging level to log +on your instance of logger, obtained with `logrus.New()`. +

    + + + + + + + + + + + +

    func GetLevel

    +
    func GetLevel() Level
    +

    +GetLevel returns the standard logger level. +

    + + + + + +

    func ParseLevel

    +
    func ParseLevel(lvl string) (Level, error)
    +

    +ParseLevel takes a string level and returns the Logrus log level constant. +

    + + + + + + + +

    func (Level) String

    +
    func (level Level) String() string
    +

    +Convert the Level to a string. E.g. PanicLevel becomes "panic". +

    + + + + + + + + +

    type LevelHooks

    +
    type LevelHooks map[Level][]Hook
    +

    +Internal type for storing the hooks on a logger instance. +

    + + + + + + + + + + + + + + +

    func (LevelHooks) Add

    +
    func (hooks LevelHooks) Add(hook Hook)
    +

    +Add a hook to an instance of logger. This is called with +`log.Hooks.Add(new(MyHook))` where `MyHook` implements the `Hook` interface. +

    + + + + + + +

    func (LevelHooks) Fire

    +
    func (hooks LevelHooks) Fire(level Level, entry *Entry) error
    +

    +Fire all the hooks for the passed level. Used by `entry.log` to fire +appropriate hooks for a log entry. +

    + + + + + + + + +

    type Logger

    +
    type Logger struct {
    +    // The logs are `io.Copy`'d to this in a mutex. It's common to set this to a
    +    // file, or leave it default which is `os.Stderr`. You can also set this to
    +    // something more adventorous, such as logging to Kafka.
    +    Out io.Writer
    +    // Hooks for the logger instance. These allow firing events based on logging
    +    // levels and log entries. For example, to send errors to an error tracking
    +    // service, log to StatsD or dump the core on fatal errors.
    +    Hooks LevelHooks
    +    // All log entries pass through the formatter before logged to Out. The
    +    // included formatters are `TextFormatter` and `JSONFormatter` for which
    +    // TextFormatter is the default. In development (when a TTY is attached) it
    +    // logs with colors, but to a file it wouldn't. You can easily implement your
    +    // own that implements the `Formatter` interface, see the `README` or included
    +    // formatters for examples.
    +    Formatter Formatter
    +    // The logging level the logger should log at. This is typically (and defaults
    +    // to) `logrus.Info`, which allows Info(), Warn(), Error() and Fatal() to be
    +    // logged. `logrus.Debug` is useful in
    +    Level Level
    +    // contains filtered or unexported fields
    +}
    + + + + + + + + + + + + +

    func New

    +
    func New() *Logger
    +

    +Creates a new logger. Configuration should be set by changing `Formatter`, +`Out` and `Hooks` directly on the default logger instance. You can also just +instantiate your own: +

    +
    var log = &Logger{
    +  Out: os.Stderr,
    +  Formatter: new(JSONFormatter),
    +  Hooks: make(LevelHooks),
    +  Level: logrus.DebugLevel,
    +}
    +
    +

    +It's recommended to make this a global instance called `log`. +

    + + + + + +

    func StandardLogger

    +
    func StandardLogger() *Logger
    + + + + + + + +

    func (*Logger) Debug

    +
    func (logger *Logger) Debug(args ...interface{})
    + + + + + + +

    func (*Logger) Debugf

    +
    func (logger *Logger) Debugf(format string, args ...interface{})
    + + + + + + +

    func (*Logger) Debugln

    +
    func (logger *Logger) Debugln(args ...interface{})
    + + + + + + +

    func (*Logger) Error

    +
    func (logger *Logger) Error(args ...interface{})
    + + + + + + +

    func (*Logger) Errorf

    +
    func (logger *Logger) Errorf(format string, args ...interface{})
    + + + + + + +

    func (*Logger) Errorln

    +
    func (logger *Logger) Errorln(args ...interface{})
    + + + + + + +

    func (*Logger) Fatal

    +
    func (logger *Logger) Fatal(args ...interface{})
    + + + + + + +

    func (*Logger) Fatalf

    +
    func (logger *Logger) Fatalf(format string, args ...interface{})
    + + + + + + +

    func (*Logger) Fatalln

    +
    func (logger *Logger) Fatalln(args ...interface{})
    + + + + + + +

    func (*Logger) Info

    +
    func (logger *Logger) Info(args ...interface{})
    + + + + + + +

    func (*Logger) Infof

    +
    func (logger *Logger) Infof(format string, args ...interface{})
    + + + + + + +

    func (*Logger) Infoln

    +
    func (logger *Logger) Infoln(args ...interface{})
    + + + + + + +

    func (*Logger) Panic

    +
    func (logger *Logger) Panic(args ...interface{})
    + + + + + + +

    func (*Logger) Panicf

    +
    func (logger *Logger) Panicf(format string, args ...interface{})
    + + + + + + +

    func (*Logger) Panicln

    +
    func (logger *Logger) Panicln(args ...interface{})
    + + + + + + +

    func (*Logger) Print

    +
    func (logger *Logger) Print(args ...interface{})
    + + + + + + +

    func (*Logger) Printf

    +
    func (logger *Logger) Printf(format string, args ...interface{})
    + + + + + + +

    func (*Logger) Println

    +
    func (logger *Logger) Println(args ...interface{})
    + + + + + + +

    func (*Logger) Warn

    +
    func (logger *Logger) Warn(args ...interface{})
    + + + + + + +

    func (*Logger) Warnf

    +
    func (logger *Logger) Warnf(format string, args ...interface{})
    + + + + + + +

    func (*Logger) Warning

    +
    func (logger *Logger) Warning(args ...interface{})
    + + + + + + +

    func (*Logger) Warningf

    +
    func (logger *Logger) Warningf(format string, args ...interface{})
    + + + + + + +

    func (*Logger) Warningln

    +
    func (logger *Logger) Warningln(args ...interface{})
    + + + + + + +

    func (*Logger) Warnln

    +
    func (logger *Logger) Warnln(args ...interface{})
    + + + + + + +

    func (*Logger) WithError

    +
    func (logger *Logger) WithError(err error) *Entry
    +

    +Add an error as single field to the log entry. All it does is call +`WithError` for the given `error`. +

    + + + + + + +

    func (*Logger) WithField

    +
    func (logger *Logger) WithField(key string, value interface{}) *Entry
    +

    +Adds a field to the log entry, note that it doesn't log until you call +Debug, Print, Info, Warn, Fatal or Panic. It only creates a log entry. +If you want multiple fields, use `WithFields`. +

    + + + + + + +

    func (*Logger) WithFields

    +
    func (logger *Logger) WithFields(fields Fields) *Entry
    +

    +Adds a struct of fields to the log entry. All it does is call `WithField` for +each `Field`. +

    + + + + + + +

    func (*Logger) Writer

    +
    func (logger *Logger) Writer() *io.PipeWriter
    + + + + + + +

    func (*Logger) WriterLevel

    +
    func (logger *Logger) WriterLevel(level Level) *io.PipeWriter
    + + + + + + + + +

    type StdLogger

    +
    type StdLogger interface {
    +    Print(...interface{})
    +    Printf(string, ...interface{})
    +    Println(...interface{})
    +
    +    Fatal(...interface{})
    +    Fatalf(string, ...interface{})
    +    Fatalln(...interface{})
    +
    +    Panic(...interface{})
    +    Panicf(string, ...interface{})
    +    Panicln(...interface{})
    +}
    +

    +StdLogger is what your logrus-enabled library should take, that way +it'll accept a stdlib logger and a logrus logger. There's no standard +interface, this is the closest we get, unfortunately. +

    + + + + + + + + + + + + + + + + +

    type Termios

    +
    type Termios syscall.Termios
    + + + + + + + + + + + + + + + + +

    type TextFormatter

    +
    type TextFormatter struct {
    +    // Set to true to bypass checking for a TTY before outputting colors.
    +    ForceColors bool
    +
    +    // Force disabling colors.
    +    DisableColors bool
    +
    +    // Disable timestamp logging. useful when output is redirected to logging
    +    // system that already adds timestamps.
    +    DisableTimestamp bool
    +
    +    // Enable logging the full timestamp when a TTY is attached instead of just
    +    // the time passed since beginning of execution.
    +    FullTimestamp bool
    +
    +    // TimestampFormat to use for display when a full timestamp is printed
    +    TimestampFormat string
    +
    +    // The fields are sorted by default for a consistent output. For applications
    +    // that log extremely frequently and don't use the JSON formatter this may not
    +    // be desired.
    +    DisableSorting bool
    +}
    + + + + + + + + + + + + + + +

    func (*TextFormatter) Format

    +
    func (f *TextFormatter) Format(entry *Entry) ([]byte, error)
    + + + + + + + + + + + + + + + + +

    Subdirectories

    + + + + +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    NameSynopsis
    ..
    + examples + + +
    + basic + + +
    + hook + + +
    + hooks + + +
    + syslog + + +
    + test + + +
    +
    + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/github.com/andybalholm/cascadia/fuzz/index.html b/pkg/github.com/andybalholm/cascadia/fuzz/index.html new file mode 100644 index 0000000..0badb6f --- /dev/null +++ b/pkg/github.com/andybalholm/cascadia/fuzz/index.html @@ -0,0 +1,214 @@ + + + + + + + + fuzz - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Package fuzz

    + + + + + + + + + + + + + + +
    +
    +
    import "github.com/andybalholm/cascadia/fuzz"
    +
    +
    +
    Overview
    +
    Index
    + + +
    +
    + +
    + +
    +

    Overview ▾

    + +
    +
    + + +
    + +
    +

    Index ▾

    + + +
    +
    + + + + +
    func Fuzz(data []byte) int
    + + + +
    +
    + + + + +

    Package files

    +

    + + + fuzz.go + + +

    + +
    +
    + + + + + + + + +

    func Fuzz

    +
    func Fuzz(data []byte) int
    + + + + + + + + + + + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/github.com/andybalholm/cascadia/index.html b/pkg/github.com/andybalholm/cascadia/index.html new file mode 100644 index 0000000..95ba5bb --- /dev/null +++ b/pkg/github.com/andybalholm/cascadia/index.html @@ -0,0 +1,357 @@ + + + + + + + + cascadia - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Package cascadia

    + + + + + + + + + + + + + + +
    +
    +
    import "github.com/andybalholm/cascadia"
    +
    +
    +
    Overview
    +
    Index
    + + +
    Subdirectories
    + +
    +
    + +
    + +
    +

    Overview ▾

    +

    +The cascadia package is an implementation of CSS selectors. +

    + +
    +
    + + + + + + + + + + + + +

    type Selector

    +
    type Selector func(*html.Node) bool
    +

    +A Selector is a function which tells whether a node matches or not. +

    + + + + + + + + + + + + +

    func Compile

    +
    func Compile(sel string) (Selector, error)
    +

    +Compile parses a selector and returns, if successful, a Selector object +that can be used to match against html.Node objects. +

    + + + + + +

    func MustCompile

    +
    func MustCompile(sel string) Selector
    +

    +MustCompile is like Compile, but panics instead of returning an error. +

    + + + + + + + +

    func (Selector) Filter

    +
    func (s Selector) Filter(nodes []*html.Node) (result []*html.Node)
    +

    +Filter returns the nodes in nodes that match the selector. +

    + + + + + + +

    func (Selector) Match

    +
    func (s Selector) Match(n *html.Node) bool
    +

    +Match returns true if the node matches the selector. +

    + + + + + + +

    func (Selector) MatchAll

    +
    func (s Selector) MatchAll(n *html.Node) []*html.Node
    +

    +MatchAll returns a slice of the nodes that match the selector, +from n and its children. +

    + + + + + + +

    func (Selector) MatchFirst

    +
    func (s Selector) MatchFirst(n *html.Node) *html.Node
    +

    +MatchFirst returns the first node that matches s, from n and its children. +

    + + + + + + + + + + + + + + + + +

    Subdirectories

    + + + + +
    + + + + + + + + + + + + + + + + + + + + +
    NameSynopsis
    ..
    + fuzz + + +
    +
    + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/github.com/andybalholm/index.html b/pkg/github.com/andybalholm/index.html new file mode 100644 index 0000000..5e6b6d2 --- /dev/null +++ b/pkg/github.com/andybalholm/index.html @@ -0,0 +1,141 @@ + + + + + + + + /src/github.com/andybalholm - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Directory /src/github.com/andybalholm

    + + + + + + + + + + + + + + + + + + + +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    NameSynopsis
    ..
    + cascadia + + The cascadia package is an implementation of CSS selectors. +
    + fuzz + + +
    +
    + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/github.com/andygrunwald/go-jira/index.html b/pkg/github.com/andygrunwald/go-jira/index.html new file mode 100644 index 0000000..c1c228f --- /dev/null +++ b/pkg/github.com/andygrunwald/go-jira/index.html @@ -0,0 +1,2338 @@ + + + + + + + + jira - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Package jira

    + + + + + + + + + + + + + + +
    +
    +
    import "github.com/andygrunwald/go-jira"
    +
    +
    +
    Overview
    +
    Index
    + + +
    +
    + +
    + +
    +

    Overview ▾

    + +
    +
    + + +
    + +
    +

    Index ▾

    + + +
    +
    + +
    Constants
    + + + + +
    func CheckResponse(r *http.Response) error
    + + + +
    type Attachment
    + + + + +
    type AuthenticationService
    + + + +
        func (s *AuthenticationService) AcquireSessionCookie(username, password string) (bool, error)
    + + +
        func (s *AuthenticationService) Authenticated() bool
    + + + +
    type AvatarUrls
    + + + + +
    type Board
    + + + + +
    type BoardListOptions
    + + + + +
    type BoardService
    + + + +
        func (s *BoardService) CreateBoard(board *Board) (*Board, *Response, error)
    + + +
        func (s *BoardService) DeleteBoard(boardID int) (*Board, *Response, error)
    + + +
        func (s *BoardService) GetAllBoards(opt *BoardListOptions) (*BoardsList, *Response, error)
    + + +
        func (s *BoardService) GetAllSprints(boardID string) ([]Sprint, *Response, error)
    + + +
        func (s *BoardService) GetBoard(boardID int) (*Board, *Response, error)
    + + + +
    type BoardsList
    + + + + +
    type Client
    + + +
        func NewClient(httpClient *http.Client, baseURL string) (*Client, error)
    + + + +
        func (c *Client) Do(req *http.Request, v interface{}) (*Response, error)
    + + +
        func (c *Client) GetBaseURL() url.URL
    + + +
        func (c *Client) NewMultiPartRequest(method, urlStr string, buf *bytes.Buffer) (*http.Request, error)
    + + +
        func (c *Client) NewRequest(method, urlStr string, body interface{}) (*http.Request, error)
    + + + +
    type Comment
    + + + + +
    type CommentVisibility
    + + + + +
    type Comments
    + + + + +
    type Component
    + + + + +
    type CreateTransitionPayload
    + + + + +
    type CustomFields
    + + + + +
    type Epic
    + + + + +
    type FixVersion
    + + + + +
    type Issue
    + + + + +
    type IssueFields
    + + + + +
    type IssueLink
    + + + + +
    type IssueLinkType
    + + + + +
    type IssueService
    + + + +
        func (s *IssueService) AddComment(issueID string, comment *Comment) (*Comment, *Response, error)
    + + +
        func (s *IssueService) AddLink(issueLink *IssueLink) (*Response, error)
    + + +
        func (s *IssueService) Create(issue *Issue) (*Issue, *Response, error)
    + + +
        func (s *IssueService) DoTransition(ticketID, transitionID string) (*Response, error)
    + + +
        func (s *IssueService) DownloadAttachment(attachmentID string) (*Response, error)
    + + +
        func (s *IssueService) Get(issueID string) (*Issue, *Response, error)
    + + +
        func (s *IssueService) GetCustomFields(issueID string) (CustomFields, *Response, error)
    + + +
        func (s *IssueService) GetTransitions(id string) ([]Transition, *Response, error)
    + + +
        func (s *IssueService) PostAttachment(attachmentID string, r io.Reader, attachmentName string) (*[]Attachment, *Response, error)
    + + +
        func (s *IssueService) Search(jql string, options *SearchOptions) ([]Issue, *Response, error)
    + + + +
    type IssueType
    + + + + +
    type IssuesInSprintResult
    + + + + +
    type IssuesWrapper
    + + + + +
    type Priority
    + + + + +
    type Progress
    + + + + +
    type Project
    + + + + +
    type ProjectCategory
    + + + + +
    type ProjectComponent
    + + + + +
    type ProjectList
    + + + + +
    type ProjectService
    + + + +
        func (s *ProjectService) Get(projectID string) (*Project, *Response, error)
    + + +
        func (s *ProjectService) GetList() (*ProjectList, *Response, error)
    + + + +
    type Resolution
    + + + + +
    type Response
    + + + + +
    type SearchOptions
    + + + + +
    type Session
    + + + + +
    type Sprint
    + + + + +
    type SprintService
    + + + +
        func (s *SprintService) GetIssuesForSprint(sprintID int) ([]Issue, *Response, error)
    + + +
        func (s *SprintService) MoveIssuesToSprint(sprintID int, issueIDs []string) (*Response, error)
    + + + +
    type Status
    + + + + +
    type StatusCategory
    + + + + +
    type Subtasks
    + + + + +
    type Time
    + + + +
        func (t *Time) UnmarshalJSON(b []byte) error
    + + + +
    type Transition
    + + + + +
    type TransitionField
    + + + + +
    type TransitionPayload
    + + + + +
    type User
    + + + + +
    type Version
    + + + + +
    type Watches
    + + + + +
    type Worklog
    + + + + +
    type WorklogRecord
    + + + + +
    +
    + + + + +

    Package files

    +

    + + + authentication.go + + board.go + + issue.go + + jira.go + + project.go + + sprint.go + + +

    + +
    +
    + + + + +

    Constants

    + +
    const (
    +    // AssigneeAutomatic represents the value of the "Assignee: Automatic" of JIRA
    +    AssigneeAutomatic = "-1"
    +)
    + + + + + + + +

    func CheckResponse

    +
    func CheckResponse(r *http.Response) error
    +

    +CheckResponse checks the API response for errors, and returns them if present. +A response is considered an error if it has a status code outside the 200 range. +The caller is responsible to analyze the response body. +The body can contain JSON (if the error is intended) or xml (sometimes JIRA just failes). +

    + + + + + + + + +

    type Attachment

    +
    type Attachment struct {
    +    Self      string `json:"self,omitempty"`
    +    ID        string `json:"id,omitempty"`
    +    Filename  string `json:"filename,omitempty"`
    +    Author    *User  `json:"author,omitempty"`
    +    Created   string `json:"created,omitempty"`
    +    Size      int    `json:"size,omitempty"`
    +    MimeType  string `json:"mimeType,omitempty"`
    +    Content   string `json:"content,omitempty"`
    +    Thumbnail string `json:"thumbnail,omitempty"`
    +}
    +

    +Attachment represents a JIRA attachment +

    + + + + + + + + + + + + + + + + +

    type AuthenticationService

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

    +AuthenticationService handles authentication for the JIRA instance / API. +

    +

    +JIRA API docs: https://docs.atlassian.com/jira/REST/latest/#authentication +

    + + + + + + + + + + + + + + +

    func (*AuthenticationService) AcquireSessionCookie

    +
    func (s *AuthenticationService) AcquireSessionCookie(username, password string) (bool, error)
    +

    +AcquireSessionCookie creates a new session for a user in JIRA. +Once a session has been successfully created it can be used to access any of JIRA's remote APIs and also the web UI by passing the appropriate HTTP Cookie header. +The header will by automatically applied to every API request. +Note that it is generally preferrable to use HTTP BASIC authentication with the REST API. +However, this resource may be used to mimic the behaviour of JIRA's log-in page (e.g. to display log-in errors to a user). +

    +

    +JIRA API docs: https://docs.atlassian.com/jira/REST/latest/#auth/1/session +

    + + + + + + +

    func (*AuthenticationService) Authenticated

    +
    func (s *AuthenticationService) Authenticated() bool
    +

    +Authenticated reports if the current Client has an authenticated session with JIRA +

    + + + + + + + + +

    type AvatarUrls

    +
    type AvatarUrls struct {
    +    Four8X48  string `json:"48x48,omitempty"`
    +    Two4X24   string `json:"24x24,omitempty"`
    +    One6X16   string `json:"16x16,omitempty"`
    +    Three2X32 string `json:"32x32,omitempty"`
    +}
    +

    +AvatarUrls represents different dimensions of avatars / images +

    + + + + + + + + + + + + + + + + +

    type Board

    +
    type Board struct {
    +    ID       int    `json:"id,omitempty"`
    +    Self     string `json:"self,omitempty"`
    +    Name     string `json:"name,omitempty"`
    +    Type     string `json:"type,omitempty"`
    +    FilterID int    `json:"filterId,omitempty"`
    +}
    +

    +Board represents a JIRA agile board +

    + + + + + + + + + + + + + + + + +

    type BoardListOptions

    +
    type BoardListOptions struct {
    +    // BoardType filters results to boards of the specified type.
    +    // Valid values: scrum, kanban.
    +    BoardType string `url:"boardType,omitempty"`
    +    // Name filters results to boards that match or partially match the specified name.
    +    Name string `url:"name,omitempty"`
    +    // ProjectKeyOrID filters results to boards that are relevant to a project.
    +    // Relevance meaning that the JQL filter defined in board contains a reference to a project.
    +    ProjectKeyOrID string `url:"projectKeyOrId,omitempty"`
    +
    +    SearchOptions
    +}
    +

    +BoardListOptions specifies the optional parameters to the BoardService.GetList +

    + + + + + + + + + + + + + + + + +

    type BoardService

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

    +BoardService handles Agile Boards for the JIRA instance / API. +

    +

    +JIRA API docs: https://docs.atlassian.com/jira-software/REST/server/ +

    + + + + + + + + + + + + + + +

    func (*BoardService) CreateBoard

    +
    func (s *BoardService) CreateBoard(board *Board) (*Board, *Response, error)
    +

    +CreateBoard creates a new board. Board name, type and filter Id is required. +name - Must be less than 255 characters. +type - Valid values: scrum, kanban +filterId - Id of a filter that the user has permissions to view. +Note, if the user does not have the 'Create shared objects' permission and tries to create a shared board, a private +board will be created instead (remember that board sharing depends on the filter sharing). +

    +

    +JIRA API docs: https://docs.atlassian.com/jira-software/REST/cloud/#agile/1.0/board-createBoard +

    + + + + + + +

    func (*BoardService) DeleteBoard

    +
    func (s *BoardService) DeleteBoard(boardID int) (*Board, *Response, error)
    +

    +DeleteBoard will delete an agile board. +

    +

    +JIRA API docs: https://docs.atlassian.com/jira-software/REST/cloud/#agile/1.0/board-deleteBoard +

    + + + + + + +

    func (*BoardService) GetAllBoards

    +
    func (s *BoardService) GetAllBoards(opt *BoardListOptions) (*BoardsList, *Response, error)
    +

    +GetAllBoards will returns all boards. This only includes boards that the user has permission to view. +

    +

    +JIRA API docs: https://docs.atlassian.com/jira-software/REST/cloud/#agile/1.0/board-getAllBoards +

    + + + + + + +

    func (*BoardService) GetAllSprints

    +
    func (s *BoardService) GetAllSprints(boardID string) ([]Sprint, *Response, error)
    +

    +GetAllSprints will returns all sprints from a board, for a given board Id. +This only includes sprints that the user has permission to view. +

    +

    +JIRA API docs: https://docs.atlassian.com/jira-software/REST/cloud/#agile/1.0/board/{boardId}/sprint +

    + + + + + + +

    func (*BoardService) GetBoard

    +
    func (s *BoardService) GetBoard(boardID int) (*Board, *Response, error)
    +

    +GetBoard will returns the board for the given boardID. +This board will only be returned if the user has permission to view it. +

    +

    +JIRA API docs: https://docs.atlassian.com/jira-software/REST/cloud/#agile/1.0/board-getBoard +

    + + + + + + + + +

    type BoardsList

    +
    type BoardsList struct {
    +    MaxResults int     `json:"maxResults"`
    +    StartAt    int     `json:"startAt"`
    +    Total      int     `json:"total"`
    +    IsLast     bool    `json:"isLast"`
    +    Values     []Board `json:"values"`
    +}
    +

    +BoardsList reflects a list of agile boards +

    + + + + + + + + + + + + + + + + +

    type Client

    +
    type Client struct {
    +
    +    // Services used for talking to different parts of the JIRA API.
    +    Authentication *AuthenticationService
    +    Issue          *IssueService
    +    Project        *ProjectService
    +    Board          *BoardService
    +    Sprint         *SprintService
    +    // contains filtered or unexported fields
    +}
    +

    +A Client manages communication with the JIRA API. +

    + + + + + + + + + + + + +

    func NewClient

    +
    func NewClient(httpClient *http.Client, baseURL string) (*Client, error)
    +

    +NewClient returns a new JIRA API client. +If a nil httpClient is provided, http.DefaultClient will be used. +To use API methods which require authentication you can follow the preferred solution and +provide an http.Client that will perform the authentication for you with OAuth and HTTP Basic (such as that provided by the golang.org/x/oauth2 library). +As an alternative you can use Session Cookie based authentication provided by this package as well. +See https://docs.atlassian.com/jira/REST/latest/#authentication +baseURL is the HTTP endpoint of your JIRA instance and should always be specified with a trailing slash. +

    + + + + + + + +

    func (*Client) Do

    +
    func (c *Client) Do(req *http.Request, v interface{}) (*Response, error)
    +

    +Do sends an API request and returns the API response. +The API response is JSON decoded and stored in the value pointed to by v, or returned as an error if an API error has occurred. +

    + + + + + + +

    func (*Client) GetBaseURL

    +
    func (c *Client) GetBaseURL() url.URL
    +

    +GetBaseURL will return you the Base URL. +This is the same URL as in the NewClient constructor +

    + + + + + + +

    func (*Client) NewMultiPartRequest

    +
    func (c *Client) NewMultiPartRequest(method, urlStr string, buf *bytes.Buffer) (*http.Request, error)
    +

    +NewMultiPartRequest creates an API request including a multi-part file. +A relative URL can be provided in urlStr, in which case it is resolved relative to the baseURL of the Client. +Relative URLs should always be specified without a preceding slash. +If specified, the value pointed to by buf is a multipart form. +

    + + + + + + +

    func (*Client) NewRequest

    +
    func (c *Client) NewRequest(method, urlStr string, body interface{}) (*http.Request, error)
    +

    +NewRequest creates an API request. +A relative URL can be provided in urlStr, in which case it is resolved relative to the baseURL of the Client. +Relative URLs should always be specified without a preceding slash. +If specified, the value pointed to by body is JSON encoded and included as the request body. +

    + + + + + + + + +

    type Comment

    +
    type Comment struct {
    +    ID           string            `json:"id,omitempty"`
    +    Self         string            `json:"self,omitempty"`
    +    Name         string            `json:"name,omitempty"`
    +    Author       User              `json:"author,omitempty"`
    +    Body         string            `json:"body,omitempty"`
    +    UpdateAuthor User              `json:"updateAuthor,omitempty"`
    +    Updated      string            `json:"updated,omitempty"`
    +    Created      string            `json:"created,omitempty"`
    +    Visibility   CommentVisibility `json:"visibility,omitempty"`
    +}
    +

    +Comment represents a comment by a person to an issue in JIRA. +

    + + + + + + + + + + + + + + + + +

    type CommentVisibility

    +
    type CommentVisibility struct {
    +    Type  string `json:"type,omitempty"`
    +    Value string `json:"value,omitempty"`
    +}
    +

    +CommentVisibility represents he visibility of a comment. +E.g. Type could be "role" and Value "Administrators" +

    + + + + + + + + + + + + + + + + +

    type Comments

    +
    type Comments struct {
    +    Comments []*Comment `json:"comments,omitempty"`
    +}
    +

    +Comments represents a list of Comment. +

    + + + + + + + + + + + + + + + + +

    type Component

    +
    type Component struct {
    +    Self string `json:"self,omitempty"`
    +    ID   string `json:"id,omitempty"`
    +    Name string `json:"name,omitempty"`
    +}
    +

    +Component represents a "component" of a JIRA issue. +Components can be user defined in every JIRA instance. +

    + + + + + + + + + + + + + + + + +

    type CreateTransitionPayload

    +
    type CreateTransitionPayload struct {
    +    Transition TransitionPayload `json:"transition"`
    +}
    +

    +CreateTransitionPayload is used for creating new issue transitions +

    + + + + + + + + + + + + + + + + +

    type CustomFields

    +
    type CustomFields map[string]string
    +

    +CustomFields represents custom fields of JIRA +This can heavily differ between JIRA instances +

    + + + + + + + + + + + + + + + + +

    type Epic

    +
    type Epic struct {
    +    ID      int    `json:"id"`
    +    Key     string `json:"key"`
    +    Self    string `json:"self"`
    +    Name    string `json:"name"`
    +    Summary string `json:"summary"`
    +    Done    bool   `json:"done"`
    +}
    +

    +Epic represents the epic to which an issue is associated +Not that this struct does not process the returned "color" value +

    + + + + + + + + + + + + + + + + +

    type FixVersion

    +
    type FixVersion struct {
    +    Archived        *bool  `json:"archived,omitempty"`
    +    ID              string `json:"id,omitempty"`
    +    Name            string `json:"name,omitempty"`
    +    ProjectID       int    `json:"projectId,omitempty"`
    +    ReleaseDate     string `json:"releaseDate,omitempty"`
    +    Released        *bool  `json:"released,omitempty"`
    +    Self            string `json:"self,omitempty"`
    +    UserReleaseDate string `json:"userReleaseDate,omitempty"`
    +}
    +

    +FixVersion represents a software release in which an issue is fixed. +

    + + + + + + + + + + + + + + + + +

    type Issue

    +
    type Issue struct {
    +    Expand string       `json:"expand,omitempty"`
    +    ID     string       `json:"id,omitempty"`
    +    Self   string       `json:"self,omitempty"`
    +    Key    string       `json:"key,omitempty"`
    +    Fields *IssueFields `json:"fields,omitempty"`
    +}
    +

    +Issue represents a JIRA issue. +

    + + + + + + + + + + + + + + + + +

    type IssueFields

    +
    type IssueFields struct {
    +    // TODO Missing fields
    +    //	* "timespent": null,
    +    //	* "aggregatetimespent": null,
    +    //	* "workratio": -1,
    +    //	* "lastViewed": null,
    +    //	* "timeestimate": null,
    +    //	* "aggregatetimeoriginalestimate": null,
    +    //	* "timeoriginalestimate": null,
    +    //	* "timetracking": {},
    +    //	* "aggregatetimeestimate": null,
    +    //	* "environment": null,
    +    //	* "duedate": null,
    +    Type              IssueType     `json:"issuetype"`
    +    Project           Project       `json:"project,omitempty"`
    +    Resolution        *Resolution   `json:"resolution,omitempty"`
    +    Priority          *Priority     `json:"priority,omitempty"`
    +    Resolutiondate    string        `json:"resolutiondate,omitempty"`
    +    Created           string        `json:"created,omitempty"`
    +    Watches           *Watches      `json:"watches,omitempty"`
    +    Assignee          *User         `json:"assignee,omitempty"`
    +    Updated           string        `json:"updated,omitempty"`
    +    Description       string        `json:"description,omitempty"`
    +    Summary           string        `json:"summary"`
    +    Creator           *User         `json:"Creator,omitempty"`
    +    Reporter          *User         `json:"reporter,omitempty"`
    +    Components        []*Component  `json:"components,omitempty"`
    +    Status            *Status       `json:"status,omitempty"`
    +    Progress          *Progress     `json:"progress,omitempty"`
    +    AggregateProgress *Progress     `json:"aggregateprogress,omitempty"`
    +    Worklog           *Worklog      `json:"worklog,omitempty"`
    +    IssueLinks        []*IssueLink  `json:"issuelinks,omitempty"`
    +    Comments          *Comments     `json:"comment,omitempty"`
    +    FixVersions       []*FixVersion `json:"fixVersions,omitempty"`
    +    Labels            []string      `json:"labels,omitempty"`
    +    Subtasks          []*Subtasks   `json:"subtasks,omitempty"`
    +    Attachments       []*Attachment `json:"attachment,omitempty"`
    +    Epic              *Epic         `json:"epic,omitempty"`
    +}
    +

    +IssueFields represents single fields of a JIRA issue. +Every JIRA issue has several fields attached. +

    + + + + + + + + + + + + + + + + + +
    type IssueLink struct {
    +    ID           string        `json:"id,omitempty"`
    +    Self         string        `json:"self,omitempty"`
    +    Type         IssueLinkType `json:"type"`
    +    OutwardIssue *Issue        `json:"outwardIssue"`
    +    InwardIssue  *Issue        `json:"inwardIssue"`
    +    Comment      *Comment      `json:"comment,omitempty"`
    +}
    +

    +IssueLink represents a link between two issues in JIRA. +

    + + + + + + + + + + + + + + + + +

    type IssueLinkType

    +
    type IssueLinkType struct {
    +    ID      string `json:"id,omitempty"`
    +    Self    string `json:"self,omitempty"`
    +    Name    string `json:"name"`
    +    Inward  string `json:"inward"`
    +    Outward string `json:"outward"`
    +}
    +

    +IssueLinkType represents a type of a link between to issues in JIRA. +Typical issue link types are "Related to", "Duplicate", "Is blocked by", etc. +

    + + + + + + + + + + + + + + + + +

    type IssueService

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

    +IssueService handles Issues for the JIRA instance / API. +

    +

    +JIRA API docs: https://docs.atlassian.com/jira/REST/latest/#api/2/issue +

    + + + + + + + + + + + + + + +

    func (*IssueService) AddComment

    +
    func (s *IssueService) AddComment(issueID string, comment *Comment) (*Comment, *Response, error)
    +

    +AddComment adds a new comment to issueID. +

    +

    +JIRA API docs: https://docs.atlassian.com/jira/REST/latest/#api/2/issue-addComment +

    + + + + + + + +
    func (s *IssueService) AddLink(issueLink *IssueLink) (*Response, error)
    +

    +AddLink adds a link between two issues. +

    +

    +JIRA API docs: https://docs.atlassian.com/jira/REST/latest/#api/2/issueLink +

    + + + + + + +

    func (*IssueService) Create

    +
    func (s *IssueService) Create(issue *Issue) (*Issue, *Response, error)
    +

    +Create creates an issue or a sub-task from a JSON representation. +Creating a sub-task is similar to creating a regular issue, with two important differences: +The issueType field must correspond to a sub-task issue type and you must provide a parent field in the issue create request containing the id or key of the parent issue. +

    +

    +JIRA API docs: https://docs.atlassian.com/jira/REST/latest/#api/2/issue-createIssues +

    + + + + + + +

    func (*IssueService) DoTransition

    +
    func (s *IssueService) DoTransition(ticketID, transitionID string) (*Response, error)
    +

    +DoTransition performs a transition on an issue. +When performing the transition you can update or set other issue fields. +

    +

    +JIRA API docs: https://docs.atlassian.com/jira/REST/latest/#api/2/issue-doTransition +

    + + + + + + +

    func (*IssueService) DownloadAttachment

    +
    func (s *IssueService) DownloadAttachment(attachmentID string) (*Response, error)
    +

    +DownloadAttachment returns a Response of an attachment for a given attachmentID. +The attachment is in the Response.Body of the response. +This is an io.ReadCloser. +The caller should close the resp.Body. +

    + + + + + + +

    func (*IssueService) Get

    +
    func (s *IssueService) Get(issueID string) (*Issue, *Response, error)
    +

    +Get returns a full representation of the issue for the given issue key. +JIRA will attempt to identify the issue by the issueIdOrKey path parameter. +This can be an issue id, or an issue key. +If the issue cannot be found via an exact match, JIRA will also look for the issue in a case-insensitive way, or by looking to see if the issue was moved. +

    +

    +JIRA API docs: https://docs.atlassian.com/jira/REST/latest/#api/2/issue-getIssue +

    + + + + + + +

    func (*IssueService) GetCustomFields

    +
    func (s *IssueService) GetCustomFields(issueID string) (CustomFields, *Response, error)
    +

    +GetCustomFields returns a map of customfield_* keys with string values +

    + + + + + + +

    func (*IssueService) GetTransitions

    +
    func (s *IssueService) GetTransitions(id string) ([]Transition, *Response, error)
    +

    +GetTransitions gets a list of the transitions possible for this issue by the current user, +along with fields that are required and their types. +

    +

    +JIRA API docs: https://docs.atlassian.com/jira/REST/latest/#api/2/issue-getTransitions +

    + + + + + + +

    func (*IssueService) PostAttachment

    +
    func (s *IssueService) PostAttachment(attachmentID string, r io.Reader, attachmentName string) (*[]Attachment, *Response, error)
    +

    +PostAttachment uploads r (io.Reader) as an attachment to a given attachmentID +

    + + + + + + +

    func (*IssueService) Search

    +
    func (s *IssueService) Search(jql string, options *SearchOptions) ([]Issue, *Response, error)
    +

    +Search will search for tickets according to the jql +

    +

    +JIRA API docs: https://developer.atlassian.com/jiradev/jira-apis/jira-rest-apis/jira-rest-api-tutorials/jira-rest-api-example-query-issues +

    + + + + + + + + +

    type IssueType

    +
    type IssueType struct {
    +    Self        string `json:"self,omitempty"`
    +    ID          string `json:"id,omitempty"`
    +    Description string `json:"description,omitempty"`
    +    IconURL     string `json:"iconUrl,omitempty"`
    +    Name        string `json:"name,omitempty"`
    +    Subtask     bool   `json:"subtask,omitempty"`
    +    AvatarID    int    `json:"avatarId,omitempty"`
    +}
    +

    +IssueType represents a type of a JIRA issue. +Typical types are "Request", "Bug", "Story", ... +

    + + + + + + + + + + + + + + + + +

    type IssuesInSprintResult

    +
    type IssuesInSprintResult struct {
    +    Issues []Issue `json:"issues"`
    +}
    +

    +IssuesInSprintResult represents a wrapper struct for search result +

    + + + + + + + + + + + + + + + + +

    type IssuesWrapper

    +
    type IssuesWrapper struct {
    +    Issues []string `json:"issues"`
    +}
    +

    +IssuesWrapper represents a wrapper struct for moving issues to sprint +

    + + + + + + + + + + + + + + + + +

    type Priority

    +
    type Priority struct {
    +    Self    string `json:"self,omitempty"`
    +    IconURL string `json:"iconUrl,omitempty"`
    +    Name    string `json:"name,omitempty"`
    +    ID      string `json:"id,omitempty"`
    +}
    +

    +Priority represents a priority of a JIRA issue. +Typical types are "Normal", "Moderate", "Urgent", ... +

    + + + + + + + + + + + + + + + + +

    type Progress

    +
    type Progress struct {
    +    Progress int `json:"progress"`
    +    Total    int `json:"total"`
    +}
    +

    +Progress represents the progress of a JIRA issue. +

    + + + + + + + + + + + + + + + + +

    type Project

    +
    type Project struct {
    +    Expand       string             `json:"expand,omitempty"`
    +    Self         string             `json:"self,omitempty"`
    +    ID           string             `json:"id,omitempty"`
    +    Key          string             `json:"key,omitempty"`
    +    Description  string             `json:"description,omitempty"`
    +    Lead         User               `json:"lead,omitempty"`
    +    Components   []ProjectComponent `json:"components,omitempty"`
    +    IssueTypes   []IssueType        `json:"issueTypes,omitempty"`
    +    URL          string             `json:"url,omitempty"`
    +    Email        string             `json:"email,omitempty"`
    +    AssigneeType string             `json:"assigneeType,omitempty"`
    +    Versions     []Version          `json:"versions,omitempty"`
    +    Name         string             `json:"name,omitempty"`
    +    Roles        struct {
    +        Developers string `json:"Developers,omitempty"`
    +    } `json:"roles,omitempty"`
    +    AvatarUrls      AvatarUrls      `json:"avatarUrls,omitempty"`
    +    ProjectCategory ProjectCategory `json:"projectCategory,omitempty"`
    +}
    +

    +Project represents a JIRA Project. +

    + + + + + + + + + + + + + + + + +

    type ProjectCategory

    +
    type ProjectCategory struct {
    +    Self        string `json:"self"`
    +    ID          string `json:"id"`
    +    Name        string `json:"name"`
    +    Description string `json:"description"`
    +}
    +

    +ProjectCategory represents a single project category +

    + + + + + + + + + + + + + + + + +

    type ProjectComponent

    +
    type ProjectComponent struct {
    +    Self                string `json:"self"`
    +    ID                  string `json:"id"`
    +    Name                string `json:"name"`
    +    Description         string `json:"description"`
    +    Lead                User   `json:"lead"`
    +    AssigneeType        string `json:"assigneeType"`
    +    Assignee            User   `json:"assignee"`
    +    RealAssigneeType    string `json:"realAssigneeType"`
    +    RealAssignee        User   `json:"realAssignee"`
    +    IsAssigneeTypeValid bool   `json:"isAssigneeTypeValid"`
    +    Project             string `json:"project"`
    +    ProjectID           int    `json:"projectId"`
    +}
    +

    +ProjectComponent represents a single component of a project +

    + + + + + + + + + + + + + + + + +

    type ProjectList

    +
    type ProjectList []struct {
    +    Expand          string          `json:"expand"`
    +    Self            string          `json:"self"`
    +    ID              string          `json:"id"`
    +    Key             string          `json:"key"`
    +    Name            string          `json:"name"`
    +    AvatarUrls      AvatarUrls      `json:"avatarUrls"`
    +    ProjectTypeKey  string          `json:"projectTypeKey"`
    +    ProjectCategory ProjectCategory `json:"projectCategory,omitempty"`
    +}
    +

    +ProjectList represent a list of Projects +

    + + + + + + + + + + + + + + + + +

    type ProjectService

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

    +ProjectService handles projects for the JIRA instance / API. +

    +

    +JIRA API docs: https://docs.atlassian.com/jira/REST/latest/#api/2/project +

    + + + + + + + + + + + + + + +

    func (*ProjectService) Get

    +
    func (s *ProjectService) Get(projectID string) (*Project, *Response, error)
    +

    +Get returns a full representation of the project for the given issue key. +JIRA will attempt to identify the project by the projectIdOrKey path parameter. +This can be an project id, or an project key. +

    +

    +JIRA API docs: https://docs.atlassian.com/jira/REST/latest/#api/2/project-getProject +

    + + + + + + +

    func (*ProjectService) GetList

    +
    func (s *ProjectService) GetList() (*ProjectList, *Response, error)
    +

    +GetList gets all projects form JIRA +

    +

    +JIRA API docs: https://docs.atlassian.com/jira/REST/latest/#api/2/project-getAllProjects +

    + + + + + + + + +

    type Resolution

    +
    type Resolution struct {
    +    Self        string `json:"self"`
    +    ID          string `json:"id"`
    +    Description string `json:"description"`
    +    Name        string `json:"name"`
    +}
    +

    +Resolution represents a resolution of a JIRA issue. +Typical types are "Fixed", "Suspended", "Won't Fix", ... +

    + + + + + + + + + + + + + + + + +

    type Response

    +
    type Response struct {
    +    *http.Response
    +
    +    StartAt    int
    +    MaxResults int
    +    Total      int
    +}
    +

    +Response represents JIRA API response. It wraps http.Response returned from +API and provides information about paging. +

    + + + + + + + + + + + + + + + + +

    type SearchOptions

    +
    type SearchOptions struct {
    +    // StartAt: The starting index of the returned projects. Base index: 0.
    +    StartAt int `url:"startAt,omitempty"`
    +    // MaxResults: The maximum number of projects to return per page. Default: 50.
    +    MaxResults int `url:"maxResults,omitempty"`
    +}
    +

    +SearchOptions specifies the optional parameters to various List methods that +support pagination. +Pagination is used for the JIRA REST APIs to conserve server resources and limit +response size for resources that return potentially large collection of items. +A request to a pages API will result in a values array wrapped in a JSON object with some paging metadata +Default Pagination options +

    + + + + + + + + + + + + + + + + +

    type Session

    +
    type Session struct {
    +    Self    string `json:"self,omitempty"`
    +    Name    string `json:"name,omitempty"`
    +    Session struct {
    +        Name  string `json:"name"`
    +        Value string `json:"value"`
    +    } `json:"session,omitempty"`
    +    LoginInfo struct {
    +        FailedLoginCount    int    `json:"failedLoginCount"`
    +        LoginCount          int    `json:"loginCount"`
    +        LastFailedLoginTime string `json:"lastFailedLoginTime"`
    +        PreviousLoginTime   string `json:"previousLoginTime"`
    +    } `json:"loginInfo"`
    +    Cookies []*http.Cookie
    +}
    +

    +Session represents a Session JSON response by the JIRA API. +

    + + + + + + + + + + + + + + + + +

    type Sprint

    +
    type Sprint struct {
    +    ID            int        `json:"id"`
    +    Name          string     `json:"name"`
    +    CompleteDate  *time.Time `json:"completeDate"`
    +    EndDate       *time.Time `json:"endDate"`
    +    StartDate     *time.Time `json:"startDate"`
    +    OriginBoardID int        `json:"originBoardId"`
    +    Self          string     `json:"self"`
    +    State         string     `json:"state"`
    +}
    +

    +Sprint represents a sprint on JIRA agile board +

    + + + + + + + + + + + + + + + + +

    type SprintService

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

    +SprintService handles sprints in JIRA Agile API. +See https://docs.atlassian.com/jira-software/REST/cloud/ +

    + + + + + + + + + + + + + + +

    func (*SprintService) GetIssuesForSprint

    +
    func (s *SprintService) GetIssuesForSprint(sprintID int) ([]Issue, *Response, error)
    +

    +GetIssuesForSprint returns all issues in a sprint, for a given sprint Id. +This only includes issues that the user has permission to view. +By default, the returned issues are ordered by rank. +

    +
    JIRA API Docs: https://docs.atlassian.com/jira-software/REST/cloud/#agile/1.0/sprint-getIssuesForSprint
    +
    + + + + + + +

    func (*SprintService) MoveIssuesToSprint

    +
    func (s *SprintService) MoveIssuesToSprint(sprintID int, issueIDs []string) (*Response, error)
    +

    +MoveIssuesToSprint moves issues to a sprint, for a given sprint Id. +Issues can only be moved to open or active sprints. +The maximum number of issues that can be moved in one operation is 50. +

    +

    +JIRA API docs: https://docs.atlassian.com/jira-software/REST/cloud/#agile/1.0/sprint-moveIssuesToSprint +

    + + + + + + + + +

    type Status

    +
    type Status struct {
    +    Self           string         `json:"self"`
    +    Description    string         `json:"description"`
    +    IconURL        string         `json:"iconUrl"`
    +    Name           string         `json:"name"`
    +    ID             string         `json:"id"`
    +    StatusCategory StatusCategory `json:"statusCategory"`
    +}
    +

    +Status represents the current status of a JIRA issue. +Typical status are "Open", "In Progress", "Closed", ... +Status can be user defined in every JIRA instance. +

    + + + + + + + + + + + + + + + + +

    type StatusCategory

    +
    type StatusCategory struct {
    +    Self      string `json:"self"`
    +    ID        int    `json:"id"`
    +    Name      string `json:"name"`
    +    Key       string `json:"key"`
    +    ColorName string `json:"colorName"`
    +}
    +

    +StatusCategory represents the category a status belongs to. +Those categories can be user defined in every JIRA instance. +

    + + + + + + + + + + + + + + + + +

    type Subtasks

    +
    type Subtasks struct {
    +    ID     string      `json:"id"`
    +    Key    string      `json:"key"`
    +    Self   string      `json:"self"`
    +    Fields IssueFields `json:"fields"`
    +}
    +

    +Subtasks represents all issues of a parent issue. +

    + + + + + + + + + + + + + + + + +

    type Time

    +
    type Time time.Time
    +

    +Time represents the Time definition of JIRA as a time.Time of go +

    + + + + + + + + + + + + + + +

    func (*Time) UnmarshalJSON

    +
    func (t *Time) UnmarshalJSON(b []byte) error
    +

    +UnmarshalJSON will transform the JIRA time into a time.Time +during the transformation of the JIRA JSON response +

    + + + + + + + + +

    type Transition

    +
    type Transition struct {
    +    ID     string                     `json:"id"`
    +    Name   string                     `json:"name"`
    +    Fields map[string]TransitionField `json:"fields"`
    +}
    +

    +Transition represents an issue transition in JIRA +

    + + + + + + + + + + + + + + + + +

    type TransitionField

    +
    type TransitionField struct {
    +    Required bool `json:"required"`
    +}
    +

    +TransitionField represents the value of one Transistion +

    + + + + + + + + + + + + + + + + +

    type TransitionPayload

    +
    type TransitionPayload struct {
    +    ID string `json:"id"`
    +}
    +

    +TransitionPayload represents the request payload of Transistion calls like DoTransition +

    + + + + + + + + + + + + + + + + +

    type User

    +
    type User struct {
    +    Self         string     `json:"self,omitempty"`
    +    Name         string     `json:"name,omitempty"`
    +    Key          string     `json:"key,omitempty"`
    +    EmailAddress string     `json:"emailAddress,omitempty"`
    +    AvatarUrls   AvatarUrls `json:"avatarUrls,omitempty"`
    +    DisplayName  string     `json:"displayName,omitempty"`
    +    Active       bool       `json:"active,omitempty"`
    +    TimeZone     string     `json:"timeZone,omitempty"`
    +}
    +

    +User represents a user who is this JIRA issue assigned to. +

    + + + + + + + + + + + + + + + + +

    type Version

    +
    type Version struct {
    +    Self            string `json:"self"`
    +    ID              string `json:"id"`
    +    Name            string `json:"name"`
    +    Archived        bool   `json:"archived"`
    +    Released        bool   `json:"released"`
    +    ReleaseDate     string `json:"releaseDate"`
    +    UserReleaseDate string `json:"userReleaseDate"`
    +    ProjectID       int    `json:"projectId"` // Unlike other IDs, this is returned as a number
    +}
    +

    +Version represents a single release version of a project +

    + + + + + + + + + + + + + + + + +

    type Watches

    +
    type Watches struct {
    +    Self       string `json:"self,omitempty"`
    +    WatchCount int    `json:"watchCount,omitempty"`
    +    IsWatching bool   `json:"isWatching,omitempty"`
    +}
    +

    +Watches represents a type of how many user are "observing" a JIRA issue to track the status / updates. +

    + + + + + + + + + + + + + + + + +

    type Worklog

    +
    type Worklog struct {
    +    StartAt    int             `json:"startAt"`
    +    MaxResults int             `json:"maxResults"`
    +    Total      int             `json:"total"`
    +    Worklogs   []WorklogRecord `json:"worklogs"`
    +}
    +

    +Worklog represents the work log of a JIRA issue. +One Worklog contains zero or n WorklogRecords +JIRA Wiki: https://confluence.atlassian.com/jira/logging-work-on-an-issue-185729605.html +

    + + + + + + + + + + + + + + + + +

    type WorklogRecord

    +
    type WorklogRecord struct {
    +    Self             string `json:"self"`
    +    Author           User   `json:"author"`
    +    UpdateAuthor     User   `json:"updateAuthor"`
    +    Comment          string `json:"comment"`
    +    Created          Time   `json:"created"`
    +    Updated          Time   `json:"updated"`
    +    Started          Time   `json:"started"`
    +    TimeSpent        string `json:"timeSpent"`
    +    TimeSpentSeconds int    `json:"timeSpentSeconds"`
    +    ID               string `json:"id"`
    +    IssueID          string `json:"issueId"`
    +}
    +

    +WorklogRecord represents one entry of a Worklog +

    + + + + + + + + + + + + + + + + + + + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/github.com/andygrunwald/index.html b/pkg/github.com/andygrunwald/index.html new file mode 100644 index 0000000..de56e10 --- /dev/null +++ b/pkg/github.com/andygrunwald/index.html @@ -0,0 +1,130 @@ + + + + + + + + /src/github.com/andygrunwald - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Directory /src/github.com/andygrunwald

    + + + + + + + + + + + + + + + + + + + +
    + + + + + + + + + + + + + + + + + + + + +
    NameSynopsis
    ..
    + go-jira + + +
    +
    + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/github.com/beorn7/index.html b/pkg/github.com/beorn7/index.html new file mode 100644 index 0000000..094e25e --- /dev/null +++ b/pkg/github.com/beorn7/index.html @@ -0,0 +1,141 @@ + + + + + + + + /src/github.com/beorn7 - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Directory /src/github.com/beorn7

    + + + + + + + + + + + + + + + + + + + +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    NameSynopsis
    ..
    + perks + + +
    + quantile + + Package quantile computes approximate quantiles over an unbounded data stream within low memory and CPU bounds. +
    +
    + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/github.com/beorn7/perks/index.html b/pkg/github.com/beorn7/perks/index.html new file mode 100644 index 0000000..4a239a6 --- /dev/null +++ b/pkg/github.com/beorn7/perks/index.html @@ -0,0 +1,130 @@ + + + + + + + + /src/github.com/beorn7/perks - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Directory /src/github.com/beorn7/perks

    + + + + + + + + + + + + + + + + + + + +
    + + + + + + + + + + + + + + + + + + + + +
    NameSynopsis
    ..
    + quantile + + Package quantile computes approximate quantiles over an unbounded data stream within low memory and CPU bounds. +
    +
    + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/github.com/beorn7/perks/quantile/index.html b/pkg/github.com/beorn7/perks/quantile/index.html new file mode 100644 index 0000000..292e530 --- /dev/null +++ b/pkg/github.com/beorn7/perks/quantile/index.html @@ -0,0 +1,630 @@ + + + + + + + + quantile - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Package quantile

    + + + + + + + + + + + + + + +
    +
    +
    import "github.com/beorn7/perks/quantile"
    +
    +
    +
    Overview
    +
    Index
    + +
    Examples
    + + +
    +
    + +
    + +
    +

    Overview ▾

    +

    +Package quantile computes approximate quantiles over an unbounded data +stream within low memory and CPU bounds. +

    +

    +A small amount of accuracy is traded to achieve the above properties. +

    +

    +Multiple streams can be merged before calling Query to generate a single set +of results. This is meaningful when the streams represent the same type of +data. See Merge and Samples. +

    +

    +For more detailed information about the algorithm used, see: +

    +

    Effective Computation of Biased Quantiles over Data Streams

    +

    +http://www.cs.rutgers.edu/~muthu/bquant.pdf +

    + +
    +
    +
    + +
    +

    Example (MergeMultipleStreams)

    + + + +

    Code:

    +
    +// Scenario:
    +// We have multiple database shards. On each shard, there is a process
    +// collecting query response times from the database logs and inserting
    +// them into a Stream (created via NewTargeted(0.90)), much like the
    +// Simple example. These processes expose a network interface for us to
    +// ask them to serialize and send us the results of their
    +// Stream.Samples so we may Merge and Query them.
    +//
    +// NOTES:
    +// * These sample sets are small, allowing us to get them
    +// across the network much faster than sending the entire list of data
    +// points.
    +//
    +// * For this to work correctly, we must supply the same quantiles
    +// a priori the process collecting the samples supplied to NewTargeted,
    +// even if we do not plan to query them all here.
    +ch := make(chan quantile.Samples)
    +getDBQuerySamples(ch)
    +q := quantile.NewTargeted(map[float64]float64{0.90: 0.001})
    +for samples := range ch {
    +    q.Merge(samples)
    +}
    +fmt.Println("perc90:", q.Query(0.90))
    +
    + + +
    +
    +
    + +
    +

    Example (Simple)

    + + + +

    Code:

    +
    ch := make(chan float64)
    +go sendFloats(ch)
    +
    +// Compute the 50th, 90th, and 99th percentile.
    +q := quantile.NewTargeted(map[float64]float64{
    +    0.50: 0.005,
    +    0.90: 0.001,
    +    0.99: 0.0001,
    +})
    +for v := range ch {
    +    q.Insert(v)
    +}
    +
    +fmt.Println("perc50:", q.Query(0.50))
    +fmt.Println("perc90:", q.Query(0.90))
    +fmt.Println("perc99:", q.Query(0.99))
    +fmt.Println("count:", q.Count())
    +
    + +

    Output:

    +
    perc50: 5
    +perc90: 16
    +perc99: 223
    +count: 2388
    +
    + + +
    +
    +
    + +
    +

    Example (Window)

    + + + +

    Code:

    +
    +// Scenario: We want the 90th, 95th, and 99th percentiles for each
    +// minute.
    +
    +ch := make(chan float64)
    +go sendStreamValues(ch)
    +
    +tick := time.NewTicker(1 * time.Minute)
    +q := quantile.NewTargeted(map[float64]float64{
    +    0.90: 0.001,
    +    0.95: 0.0005,
    +    0.99: 0.0001,
    +})
    +for {
    +    select {
    +    case t := <-tick.C:
    +        flushToDB(t, q.Samples())
    +        q.Reset()
    +    case v := <-ch:
    +        q.Insert(v)
    +    }
    +}
    +
    + + +
    +
    + + + + + + + + + + + + +

    type Sample

    +
    type Sample struct {
    +    Value float64 `json:",string"`
    +    Width float64 `json:",string"`
    +    Delta float64 `json:",string"`
    +}
    +

    +Sample holds an observed value and meta information for compression. JSON +tags have been added for convenience. +

    + + + + + + + + + + + + + + + + +

    type Samples

    +
    type Samples []Sample
    +

    +Samples represents a slice of samples. It implements sort.Interface. +

    + + + + + + + + + + + + + + +

    func (Samples) Len

    +
    func (a Samples) Len() int
    + + + + + + +

    func (Samples) Less

    +
    func (a Samples) Less(i, j int) bool
    + + + + + + +

    func (Samples) Swap

    +
    func (a Samples) Swap(i, j int)
    + + + + + + + + +

    type Stream

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

    +Stream computes quantiles for a stream of float64s. It is not thread-safe by +design. Take care when using across multiple goroutines. +

    + + + + + + + + + + + + +

    func NewHighBiased

    +
    func NewHighBiased(epsilon float64) *Stream
    +

    +NewHighBiased returns an initialized Stream for high-biased quantiles +(e.g. 0.01, 0.1, 0.5) where the needed quantiles are not known a priori, but +error guarantees can still be given even for the higher ranks of the data +distribution. +

    +

    +The provided epsilon is a relative error, i.e. the true quantile of a value +returned by a query is guaranteed to be within 1-(1±Epsilon)*(1-Quantile). +

    +

    +See http://www.cs.rutgers.edu/~muthu/bquant.pdf for time, space, and error +properties. +

    + + + + + +

    func NewLowBiased

    +
    func NewLowBiased(epsilon float64) *Stream
    +

    +NewLowBiased returns an initialized Stream for low-biased quantiles +(e.g. 0.01, 0.1, 0.5) where the needed quantiles are not known a priori, but +error guarantees can still be given even for the lower ranks of the data +distribution. +

    +

    +The provided epsilon is a relative error, i.e. the true quantile of a value +returned by a query is guaranteed to be within (1±Epsilon)*Quantile. +

    +

    +See http://www.cs.rutgers.edu/~muthu/bquant.pdf for time, space, and error +properties. +

    + + + + + +

    func NewTargeted

    +
    func NewTargeted(targets map[float64]float64) *Stream
    +

    +NewTargeted returns an initialized Stream concerned with a particular set of +quantile values that are supplied a priori. Knowing these a priori reduces +space and computation time. The targets map maps the desired quantiles to +their absolute errors, i.e. the true quantile of a value returned by a query +is guaranteed to be within (Quantile±Epsilon). +

    +

    +See http://www.cs.rutgers.edu/~muthu/bquant.pdf for time, space, and error properties. +

    + + + + + + + +

    func (*Stream) Count

    +
    func (s *Stream) Count() int
    +

    +Count returns the total number of samples observed in the stream +since initialization. +

    + + + + + + +

    func (*Stream) Insert

    +
    func (s *Stream) Insert(v float64)
    +

    +Insert inserts v into the stream. +

    + + + + + + +

    func (*Stream) Merge

    +
    func (s *Stream) Merge(samples Samples)
    +

    +Merge merges samples into the underlying streams samples. This is handy when +merging multiple streams from separate threads, database shards, etc. +

    +

    +ATTENTION: This method is broken and does not yield correct results. The +underlying algorithm is not capable of merging streams correctly. +

    + + + + + + +

    func (*Stream) Query

    +
    func (s *Stream) Query(q float64) float64
    +

    +Query returns the computed qth percentiles value. If s was created with +NewTargeted, and q is not in the set of quantiles provided a priori, Query +will return an unspecified result. +

    + + + + + + +

    func (*Stream) Reset

    +
    func (s *Stream) Reset()
    +

    +Reset reinitializes and clears the list reusing the samples buffer memory. +

    + + + + + + +

    func (*Stream) Samples

    +
    func (s *Stream) Samples() Samples
    +

    +Samples returns stream samples held by s. +

    + + + + + + + + + + + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/github.com/bradfitz/gomemcache/index.html b/pkg/github.com/bradfitz/gomemcache/index.html new file mode 100644 index 0000000..6e07bf7 --- /dev/null +++ b/pkg/github.com/bradfitz/gomemcache/index.html @@ -0,0 +1,130 @@ + + + + + + + + /src/github.com/bradfitz/gomemcache - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Directory /src/github.com/bradfitz/gomemcache

    + + + + + + + + + + + + + + + + + + + +
    + + + + + + + + + + + + + + + + + + + + +
    NameSynopsis
    ..
    + memcache + + Package memcache provides a client for the memcached cache server. +
    +
    + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/github.com/bradfitz/gomemcache/memcache/index.html b/pkg/github.com/bradfitz/gomemcache/memcache/index.html new file mode 100644 index 0000000..37420a3 --- /dev/null +++ b/pkg/github.com/bradfitz/gomemcache/memcache/index.html @@ -0,0 +1,699 @@ + + + + + + + + memcache - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Package memcache

    + + + + + + + + + + + + + + +
    +
    +
    import "github.com/bradfitz/gomemcache/memcache"
    +
    +
    +
    Overview
    +
    Index
    + + +
    +
    + +
    + +
    +

    Overview ▾

    +

    +Package memcache provides a client for the memcached cache server. +

    + +
    +
    + + + + + + + +

    Constants

    + +
    const DefaultTimeout = 100 * time.Millisecond
    +

    +DefaultTimeout is the default socket read/write timeout. +

    + + + + +

    Variables

    + +
    var (
    +    // ErrCacheMiss means that a Get failed because the item wasn't present.
    +    ErrCacheMiss = errors.New("memcache: cache miss")
    +
    +    // ErrCASConflict means that a CompareAndSwap call failed due to the
    +    // cached value being modified between the Get and the CompareAndSwap.
    +    // If the cached value was simply evicted rather than replaced,
    +    // ErrNotStored will be returned instead.
    +    ErrCASConflict = errors.New("memcache: compare-and-swap conflict")
    +
    +    // ErrNotStored means that a conditional write operation (i.e. Add or
    +    // CompareAndSwap) failed because the condition was not satisfied.
    +    ErrNotStored = errors.New("memcache: item not stored")
    +
    +    // ErrServer means that a server error occurred.
    +    ErrServerError = errors.New("memcache: server error")
    +
    +    // ErrNoStats means that no statistics were available.
    +    ErrNoStats = errors.New("memcache: no statistics available")
    +
    +    // ErrMalformedKey is returned when an invalid key is used.
    +    // Keys must be at maximum 250 bytes long, ASCII, and not
    +    // contain whitespace or control characters.
    +    ErrMalformedKey = errors.New("malformed: key is too long or contains invalid characters")
    +
    +    // ErrNoServers is returned when no servers are configured or available.
    +    ErrNoServers = errors.New("memcache: no servers configured or available")
    +)
    + + + + + + + +

    type Client

    +
    type Client struct {
    +    // Timeout specifies the socket read/write timeout.
    +    // If zero, DefaultTimeout is used.
    +    Timeout time.Duration
    +    // contains filtered or unexported fields
    +}
    +

    +Client is a memcache client. +It is safe for unlocked use by multiple concurrent goroutines. +

    + + + + + + + + + + + + +

    func New

    +
    func New(server ...string) *Client
    +

    +New returns a memcache client using the provided server(s) +with equal weight. If a server is listed multiple times, +it gets a proportional amount of weight. +

    + + + + + +

    func NewFromSelector

    +
    func NewFromSelector(ss ServerSelector) *Client
    +

    +NewFromSelector returns a new Client using the provided ServerSelector. +

    + + + + + + + +

    func (*Client) Add

    +
    func (c *Client) Add(item *Item) error
    +

    +Add writes the given item, if no value already exists for its +key. ErrNotStored is returned if that condition is not met. +

    + + + + + + +

    func (*Client) CompareAndSwap

    +
    func (c *Client) CompareAndSwap(item *Item) error
    +

    +CompareAndSwap writes the given item that was previously returned +by Get, if the value was neither modified or evicted between the +Get and the CompareAndSwap calls. The item's Key should not change +between calls but all other item fields may differ. ErrCASConflict +is returned if the value was modified in between the +calls. ErrNotStored is returned if the value was evicted in between +the calls. +

    + + + + + + +

    func (*Client) Decrement

    +
    func (c *Client) Decrement(key string, delta uint64) (newValue uint64, err error)
    +

    +Decrement atomically decrements key by delta. The return value is +the new value after being decremented or an error. If the value +didn't exist in memcached the error is ErrCacheMiss. The value in +memcached must be an decimal number, or an error will be returned. +On underflow, the new value is capped at zero and does not wrap +around. +

    + + + + + + +

    func (*Client) Delete

    +
    func (c *Client) Delete(key string) error
    +

    +Delete deletes the item with the provided key. The error ErrCacheMiss is +returned if the item didn't already exist in the cache. +

    + + + + + + +

    func (*Client) DeleteAll

    +
    func (c *Client) DeleteAll() error
    +

    +DeleteAll deletes all items in the cache. +

    + + + + + + +

    func (*Client) FlushAll

    +
    func (c *Client) FlushAll() error
    + + + + + + +

    func (*Client) Get

    +
    func (c *Client) Get(key string) (item *Item, err error)
    +

    +Get gets the item for the given key. ErrCacheMiss is returned for a +memcache cache miss. The key must be at most 250 bytes in length. +

    + + + + + + +

    func (*Client) GetMulti

    +
    func (c *Client) GetMulti(keys []string) (map[string]*Item, error)
    +

    +GetMulti is a batch version of Get. The returned map from keys to +items may have fewer elements than the input slice, due to memcache +cache misses. Each key must be at most 250 bytes in length. +If no error is returned, the returned map will also be non-nil. +

    + + + + + + +

    func (*Client) Increment

    +
    func (c *Client) Increment(key string, delta uint64) (newValue uint64, err error)
    +

    +Increment atomically increments key by delta. The return value is +the new value after being incremented or an error. If the value +didn't exist in memcached the error is ErrCacheMiss. The value in +memcached must be an decimal number, or an error will be returned. +On 64-bit overflow, the new value wraps around. +

    + + + + + + +

    func (*Client) Replace

    +
    func (c *Client) Replace(item *Item) error
    +

    +Replace writes the given item, but only if the server *does* +already hold data for this key +

    + + + + + + +

    func (*Client) Set

    +
    func (c *Client) Set(item *Item) error
    +

    +Set writes the given item, unconditionally. +

    + + + + + + +

    func (*Client) Touch

    +
    func (c *Client) Touch(key string, seconds int32) (err error)
    +

    +Touch updates the expiry for the given key. The seconds parameter is either +a Unix timestamp or, if seconds is less than 1 month, the number of seconds +into the future at which time the item will expire. ErrCacheMiss is returned if the +key is not in the cache. The key must be at most 250 bytes in length. +

    + + + + + + + + +

    type ConnectTimeoutError

    +
    type ConnectTimeoutError struct {
    +    Addr net.Addr
    +}
    +

    +ConnectTimeoutError is the error type used when it takes +too long to connect to the desired host. This level of +detail can generally be ignored. +

    + + + + + + + + + + + + + + +

    func (*ConnectTimeoutError) Error

    +
    func (cte *ConnectTimeoutError) Error() string
    + + + + + + + + +

    type Item

    +
    type Item struct {
    +    // Key is the Item's key (250 bytes maximum).
    +    Key string
    +
    +    // Value is the Item's value.
    +    Value []byte
    +
    +    // Flags are server-opaque flags whose semantics are entirely
    +    // up to the app.
    +    Flags uint32
    +
    +    // Expiration is the cache expiration time, in seconds: either a relative
    +    // time from now (up to 1 month), or an absolute Unix epoch time.
    +    // Zero means the Item has no expiration time.
    +    Expiration int32
    +    // contains filtered or unexported fields
    +}
    +

    +Item is an item to be got or stored in a memcached server. +

    + + + + + + + + + + + + + + + + +

    type ServerList

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

    +ServerList is a simple ServerSelector. Its zero value is usable. +

    + + + + + + + + + + + + + + +

    func (*ServerList) Each

    +
    func (ss *ServerList) Each(f func(net.Addr) error) error
    +

    +Each iterates over each server calling the given function +

    + + + + + + +

    func (*ServerList) PickServer

    +
    func (ss *ServerList) PickServer(key string) (net.Addr, error)
    + + + + + + +

    func (*ServerList) SetServers

    +
    func (ss *ServerList) SetServers(servers ...string) error
    +

    +SetServers changes a ServerList's set of servers at runtime and is +safe for concurrent use by multiple goroutines. +

    +

    +Each server is given equal weight. A server is given more weight +if it's listed multiple times. +

    +

    +SetServers returns an error if any of the server names fail to +resolve. No attempt is made to connect to the server. If any error +is returned, no changes are made to the ServerList. +

    + + + + + + + + +

    type ServerSelector

    +
    type ServerSelector interface {
    +    // PickServer returns the server address that a given item
    +    // should be shared onto.
    +    PickServer(key string) (net.Addr, error)
    +    Each(func(net.Addr) error) error
    +}
    +

    +ServerSelector is the interface that selects a memcache server +as a function of the item's key. +

    +

    +All ServerSelector implementations must be safe for concurrent use +by multiple goroutines. +

    + + + + + + + + + + + + + + + + + + + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/github.com/bradfitz/index.html b/pkg/github.com/bradfitz/index.html new file mode 100644 index 0000000..93b4f8f --- /dev/null +++ b/pkg/github.com/bradfitz/index.html @@ -0,0 +1,141 @@ + + + + + + + + /src/github.com/bradfitz - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Directory /src/github.com/bradfitz

    + + + + + + + + + + + + + + + + + + + +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    NameSynopsis
    ..
    + gomemcache + + +
    + memcache + + Package memcache provides a client for the memcached cache server. +
    +
    + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/github.com/cenkalti/backoff/index.html b/pkg/github.com/cenkalti/backoff/index.html new file mode 100644 index 0000000..287adf8 --- /dev/null +++ b/pkg/github.com/cenkalti/backoff/index.html @@ -0,0 +1,872 @@ + + + + + + + + backoff - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Package backoff

    + + + + + + + + + + + + + + +
    +
    +
    import "github.com/cenkalti/backoff"
    +
    +
    +
    Overview
    +
    Index
    + +
    Examples
    + + +
    +
    + +
    + +
    +

    Overview ▾

    +

    +Package backoff implements backoff algorithms for retrying operations. +

    +

    +Also has a Retry() helper for retrying operations that may fail. +

    + +
    +
    + + + + + + + +

    Constants

    + +
    const (
    +    DefaultInitialInterval     = 500 * time.Millisecond
    +    DefaultRandomizationFactor = 0.5
    +    DefaultMultiplier          = 1.5
    +    DefaultMaxInterval         = 60 * time.Second
    +    DefaultMaxElapsedTime      = 15 * time.Minute
    +)
    +

    +Default values for ExponentialBackOff. +

    + + +
    const Stop time.Duration = -1
    +

    +Indicates that no more retries should be made for use in NextBackOff(). +

    + + + + +

    Variables

    + +
    var SystemClock = systemClock{}
    +

    +SystemClock implements Clock interface that uses time.Now(). +

    + + + + + + +

    func Retry

    +
    func Retry(o Operation, b BackOff) error
    +

    +Retry the operation o until it does not return error or BackOff stops. +o is guaranteed to be run at least once. +It is the caller's responsibility to reset b after Retry returns. +

    +

    +Retry sleeps the goroutine for the duration returned by BackOff after a +failed operation returns. +

    + +
    + +
    +

    Example

    + + + +

    Code:

    +
    +operation := func() error {
    +    // An operation that might fail.
    +    return nil // or return errors.New("some error")
    +}
    +
    +err := Retry(operation, NewExponentialBackOff())
    +if err != nil {
    +    // Handle error.
    +    return err
    +}
    +
    +// Operation is successful.
    +return nil
    +
    + + +
    +
    + + + + + + +

    func RetryNotify

    +
    func RetryNotify(operation Operation, b BackOff, notify Notify) error
    +

    +RetryNotify calls notify function with the error and wait duration +for each failed attempt before sleep. +

    + + + + + + + + +

    type BackOff

    +
    type BackOff interface {
    +    // NextBackOff returns the duration to wait before retrying the operation,
    +    // or backoff.Stop to indicate that no more retries should be made.
    +    //
    +    // Example usage:
    +    //
    +    // 	duration := backoff.NextBackOff();
    +    // 	if (duration == backoff.Stop) {
    +    // 		// Do not retry operation.
    +    // 	} else {
    +    // 		// Sleep for duration and retry operation.
    +    // 	}
    +    //
    +    NextBackOff() time.Duration
    +
    +    // Reset to initial state.
    +    Reset()
    +}
    +

    +BackOff is a backoff policy for retrying an operation. +

    + + + + + + + + + + + + + + + + +

    type Clock

    +
    type Clock interface {
    +    Now() time.Time
    +}
    +

    +Clock is an interface that returns current time for BackOff. +

    + + + + + + + + + + + + + + + + +

    type ConstantBackOff

    +
    type ConstantBackOff struct {
    +    Interval time.Duration
    +}
    +

    +ConstantBackOff is a backoff policy that always returns the same backoff delay. +This is in contrast to an exponential backoff policy, +which returns a delay that grows longer as you call NextBackOff() over and over again. +

    + + + + + + + + + + + + +

    func NewConstantBackOff

    +
    func NewConstantBackOff(d time.Duration) *ConstantBackOff
    + + + + + + + +

    func (*ConstantBackOff) NextBackOff

    +
    func (b *ConstantBackOff) NextBackOff() time.Duration
    + + + + + + +

    func (*ConstantBackOff) Reset

    +
    func (b *ConstantBackOff) Reset()
    + + + + + + + + +

    type ExponentialBackOff

    +
    type ExponentialBackOff struct {
    +    InitialInterval     time.Duration
    +    RandomizationFactor float64
    +    Multiplier          float64
    +    MaxInterval         time.Duration
    +    // After MaxElapsedTime the ExponentialBackOff stops.
    +    // It never stops if MaxElapsedTime == 0.
    +    MaxElapsedTime time.Duration
    +    Clock          Clock
    +    // contains filtered or unexported fields
    +}
    +

    +ExponentialBackOff is a backoff implementation that increases the backoff +period for each retry attempt using a randomization function that grows exponentially. +

    +

    +NextBackOff() is calculated using the following formula: +

    +
    randomized interval =
    +    RetryInterval * (random value in range [1 - RandomizationFactor, 1 + RandomizationFactor])
    +
    +

    +In other words NextBackOff() will range between the randomization factor +percentage below and above the retry interval. +

    +

    +For example, given the following parameters: +

    +
    RetryInterval = 2
    +RandomizationFactor = 0.5
    +Multiplier = 2
    +
    +

    +the actual backoff period used in the next retry attempt will range between 1 and 3 seconds, +multiplied by the exponential, that is, between 2 and 6 seconds. +

    +

    +Note: MaxInterval caps the RetryInterval and not the randomized interval. +

    +

    +If the time elapsed since an ExponentialBackOff instance is created goes past the +MaxElapsedTime, then the method NextBackOff() starts returning backoff.Stop. +

    +

    +The elapsed time can be reset by calling Reset(). +

    +

    +Example: Given the following default arguments, for 10 tries the sequence will be, +and assuming we go over the MaxElapsedTime on the 10th try: +

    +
    Request #  RetryInterval (seconds)  Randomized Interval (seconds)
    +
    + 1          0.5                     [0.25,   0.75]
    + 2          0.75                    [0.375,  1.125]
    + 3          1.125                   [0.562,  1.687]
    + 4          1.687                   [0.8435, 2.53]
    + 5          2.53                    [1.265,  3.795]
    + 6          3.795                   [1.897,  5.692]
    + 7          5.692                   [2.846,  8.538]
    + 8          8.538                   [4.269, 12.807]
    + 9         12.807                   [6.403, 19.210]
    +10         19.210                   backoff.Stop
    +
    +

    +Note: Implementation is not thread-safe. +

    + + + + + + + + + + + + +

    func NewExponentialBackOff

    +
    func NewExponentialBackOff() *ExponentialBackOff
    +

    +NewExponentialBackOff creates an instance of ExponentialBackOff using default values. +

    + + + + + + + +

    func (*ExponentialBackOff) GetElapsedTime

    +
    func (b *ExponentialBackOff) GetElapsedTime() time.Duration
    +

    +GetElapsedTime returns the elapsed time since an ExponentialBackOff instance +is created and is reset when Reset() is called. +

    +

    +The elapsed time is computed using time.Now().UnixNano(). +

    + + + + + + +

    func (*ExponentialBackOff) NextBackOff

    +
    func (b *ExponentialBackOff) NextBackOff() time.Duration
    +

    +NextBackOff calculates the next backoff interval using the formula: +

    +
    Randomized interval = RetryInterval +/- (RandomizationFactor * RetryInterval)
    +
    + + + + + + +

    func (*ExponentialBackOff) Reset

    +
    func (b *ExponentialBackOff) Reset()
    +

    +Reset the interval back to the initial retry interval and restarts the timer. +

    + + + + + + + + +

    type Notify

    +
    type Notify func(error, time.Duration)
    +

    +Notify is a notify-on-error function. It receives an operation error and +backoff delay if the operation failed (with an error). +

    +

    +NOTE that if the backoff policy stated to stop retrying, +the notify function isn't called. +

    + + + + + + + + + + + + + + + + +

    type Operation

    +
    type Operation func() error
    +

    +An Operation is executing by Retry() or RetryNotify(). +The operation will be retried using a backoff policy if it returns an error. +

    + + + + + + + + + + + + + + + + +

    type StopBackOff

    +
    type StopBackOff struct{}
    +

    +StopBackOff is a fixed backoff policy that always returns backoff.Stop for +NextBackOff(), meaning that the operation should never be retried. +

    + + + + + + + + + + + + + + +

    func (*StopBackOff) NextBackOff

    +
    func (b *StopBackOff) NextBackOff() time.Duration
    + + + + + + +

    func (*StopBackOff) Reset

    +
    func (b *StopBackOff) Reset()
    + + + + + + + + +

    type Ticker

    +
    type Ticker struct {
    +    C <-chan time.Time
    +    // contains filtered or unexported fields
    +}
    +

    +Ticker holds a channel that delivers `ticks' of a clock at times reported by a BackOff. +

    +

    +Ticks will continue to arrive when the previous operation is still running, +so operations that take a while to fail could run in quick succession. +

    + + + + + + +
    + +
    +

    Example

    + + + +

    Code:

    +
    +operation := func() error {
    +    // An operation that might fail
    +    return nil // or return errors.New("some error")
    +}
    +
    +b := NewExponentialBackOff()
    +ticker := NewTicker(b)
    +
    +var err error
    +
    +// Ticks will continue to arrive when the previous operation is still running,
    +// so operations that take a while to fail could run in quick succession.
    +for _ = range ticker.C {
    +    if err = operation(); err != nil {
    +        log.Println(err, "will retry...")
    +        continue
    +    }
    +
    +    ticker.Stop()
    +    break
    +}
    +
    +if err != nil {
    +    // Operation has failed.
    +    return err
    +}
    +
    +// Operation is successful.
    +return nil
    +
    + + +
    +
    + + + + + + +

    func NewTicker

    +
    func NewTicker(b BackOff) *Ticker
    +

    +NewTicker returns a new Ticker containing a channel that will send the time at times +specified by the BackOff argument. Ticker is guaranteed to tick at least once. +The channel is closed when Stop method is called or BackOff stops. +

    + + + + + + + +

    func (*Ticker) Stop

    +
    func (t *Ticker) Stop()
    +

    +Stop turns off a ticker. After Stop, no more ticks will be sent. +

    + + + + + + + + +

    type ZeroBackOff

    +
    type ZeroBackOff struct{}
    +

    +ZeroBackOff is a fixed backoff policy whose backoff time is always zero, +meaning that the operation is retried immediately without waiting, indefinitely. +

    + + + + + + + + + + + + + + +

    func (*ZeroBackOff) NextBackOff

    +
    func (b *ZeroBackOff) NextBackOff() time.Duration
    + + + + + + +

    func (*ZeroBackOff) Reset

    +
    func (b *ZeroBackOff) Reset()
    + + + + + + + + + + + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/github.com/cenkalti/index.html b/pkg/github.com/cenkalti/index.html new file mode 100644 index 0000000..c13c0dc --- /dev/null +++ b/pkg/github.com/cenkalti/index.html @@ -0,0 +1,130 @@ + + + + + + + + /src/github.com/cenkalti - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Directory /src/github.com/cenkalti

    + + + + + + + + + + + + + + + + + + + +
    + + + + + + + + + + + + + + + + + + + + +
    NameSynopsis
    ..
    + backoff + + Package backoff implements backoff algorithms for retrying operations. +
    +
    + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/github.com/codegangsta/cli/altsrc/index.html b/pkg/github.com/codegangsta/cli/altsrc/index.html new file mode 100644 index 0000000..6ee55e2 --- /dev/null +++ b/pkg/github.com/codegangsta/cli/altsrc/index.html @@ -0,0 +1,1424 @@ + + + + + + + + altsrc - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Package altsrc

    + + + + + + + + + + + + + + +
    +
    +
    import "github.com/codegangsta/cli/altsrc"
    +
    +
    +
    Overview
    +
    Index
    + + +
    +
    + +
    + +
    +

    Overview ▾

    + +
    +
    + + +
    + +
    +

    Index ▾

    + + +
    +
    + + + + +
    func ApplyInputSourceValues(context *cli.Context, inputSourceContext InputSourceContext, flags []cli.Flag) error
    + + +
    func InitInputSource(flags []cli.Flag, createInputSource func() (InputSourceContext, error)) cli.BeforeFunc
    + + +
    func InitInputSourceWithContext(flags []cli.Flag, createInputSource func(context *cli.Context) (InputSourceContext, error)) cli.BeforeFunc
    + + +
    func NewTomlSourceFromFlagFunc(flagFileName string) func(context *cli.Context) (InputSourceContext, error)
    + + +
    func NewYamlSourceFromFlagFunc(flagFileName string) func(context *cli.Context) (InputSourceContext, error)
    + + + +
    type BoolFlag
    + + +
        func NewBoolFlag(fl cli.BoolFlag) *BoolFlag
    + + + +
        func (f *BoolFlag) Apply(set *flag.FlagSet)
    + + +
        func (f *BoolFlag) ApplyInputSourceValue(context *cli.Context, isc InputSourceContext) error
    + + + +
    type BoolTFlag
    + + +
        func NewBoolTFlag(fl cli.BoolTFlag) *BoolTFlag
    + + + +
        func (f *BoolTFlag) Apply(set *flag.FlagSet)
    + + +
        func (f *BoolTFlag) ApplyInputSourceValue(context *cli.Context, isc InputSourceContext) error
    + + + +
    type DurationFlag
    + + +
        func NewDurationFlag(fl cli.DurationFlag) *DurationFlag
    + + + +
        func (f *DurationFlag) Apply(set *flag.FlagSet)
    + + +
        func (f *DurationFlag) ApplyInputSourceValue(context *cli.Context, isc InputSourceContext) error
    + + + +
    type FlagInputSourceExtension
    + + + + +
    type Float64Flag
    + + +
        func NewFloat64Flag(fl cli.Float64Flag) *Float64Flag
    + + + +
        func (f *Float64Flag) Apply(set *flag.FlagSet)
    + + +
        func (f *Float64Flag) ApplyInputSourceValue(context *cli.Context, isc InputSourceContext) error
    + + + +
    type GenericFlag
    + + +
        func NewGenericFlag(fl cli.GenericFlag) *GenericFlag
    + + + +
        func (f *GenericFlag) Apply(set *flag.FlagSet)
    + + +
        func (f *GenericFlag) ApplyInputSourceValue(context *cli.Context, isc InputSourceContext) error
    + + + +
    type InputSourceContext
    + + +
        func NewTomlSourceFromFile(file string) (InputSourceContext, error)
    + + +
        func NewYamlSourceFromFile(file string) (InputSourceContext, error)
    + + + + +
    type Int64Flag
    + + +
        func NewInt64Flag(fl cli.Int64Flag) *Int64Flag
    + + + +
        func (f *Int64Flag) Apply(set *flag.FlagSet)
    + + + +
    type Int64SliceFlag
    + + +
        func NewInt64SliceFlag(fl cli.Int64SliceFlag) *Int64SliceFlag
    + + + +
        func (f *Int64SliceFlag) Apply(set *flag.FlagSet)
    + + + +
    type IntFlag
    + + +
        func NewIntFlag(fl cli.IntFlag) *IntFlag
    + + + +
        func (f *IntFlag) Apply(set *flag.FlagSet)
    + + +
        func (f *IntFlag) ApplyInputSourceValue(context *cli.Context, isc InputSourceContext) error
    + + + +
    type IntSliceFlag
    + + +
        func NewIntSliceFlag(fl cli.IntSliceFlag) *IntSliceFlag
    + + + +
        func (f *IntSliceFlag) Apply(set *flag.FlagSet)
    + + +
        func (f *IntSliceFlag) ApplyInputSourceValue(context *cli.Context, isc InputSourceContext) error
    + + + +
    type MapInputSource
    + + + +
        func (fsm *MapInputSource) Bool(name string) (bool, error)
    + + +
        func (fsm *MapInputSource) BoolT(name string) (bool, error)
    + + +
        func (fsm *MapInputSource) Duration(name string) (time.Duration, error)
    + + +
        func (fsm *MapInputSource) Float64(name string) (float64, error)
    + + +
        func (fsm *MapInputSource) Generic(name string) (cli.Generic, error)
    + + +
        func (fsm *MapInputSource) Int(name string) (int, error)
    + + +
        func (fsm *MapInputSource) IntSlice(name string) ([]int, error)
    + + +
        func (fsm *MapInputSource) String(name string) (string, error)
    + + +
        func (fsm *MapInputSource) StringSlice(name string) ([]string, error)
    + + + +
    type StringFlag
    + + +
        func NewStringFlag(fl cli.StringFlag) *StringFlag
    + + + +
        func (f *StringFlag) Apply(set *flag.FlagSet)
    + + +
        func (f *StringFlag) ApplyInputSourceValue(context *cli.Context, isc InputSourceContext) error
    + + + +
    type StringSliceFlag
    + + +
        func NewStringSliceFlag(fl cli.StringSliceFlag) *StringSliceFlag
    + + + +
        func (f *StringSliceFlag) Apply(set *flag.FlagSet)
    + + +
        func (f *StringSliceFlag) ApplyInputSourceValue(context *cli.Context, isc InputSourceContext) error
    + + + +
    type Uint64Flag
    + + +
        func NewUint64Flag(fl cli.Uint64Flag) *Uint64Flag
    + + + +
        func (f *Uint64Flag) Apply(set *flag.FlagSet)
    + + + +
    type UintFlag
    + + +
        func NewUintFlag(fl cli.UintFlag) *UintFlag
    + + + +
        func (f *UintFlag) Apply(set *flag.FlagSet)
    + + + +
    +
    + + + + +

    Package files

    +

    + + + altsrc.go + + flag.go + + flag_generated.go + + input_source_context.go + + map_input_source.go + + toml_file_loader.go + + yaml_file_loader.go + + +

    + +
    +
    + + + + + + + + +

    func ApplyInputSourceValues

    +
    func ApplyInputSourceValues(context *cli.Context, inputSourceContext InputSourceContext, flags []cli.Flag) error
    +

    +ApplyInputSourceValues iterates over all provided flags and +executes ApplyInputSourceValue on flags implementing the +FlagInputSourceExtension interface to initialize these flags +to an alternate input source. +

    + + + + + + + +

    func InitInputSource

    +
    func InitInputSource(flags []cli.Flag, createInputSource func() (InputSourceContext, error)) cli.BeforeFunc
    +

    +InitInputSource is used to to setup an InputSourceContext on a cli.Command Before method. It will create a new +input source based on the func provided. If there is no error it will then apply the new input source to any flags +that are supported by the input source +

    + + + + + + + +

    func InitInputSourceWithContext

    +
    func InitInputSourceWithContext(flags []cli.Flag, createInputSource func(context *cli.Context) (InputSourceContext, error)) cli.BeforeFunc
    +

    +InitInputSourceWithContext is used to to setup an InputSourceContext on a cli.Command Before method. It will create a new +input source based on the func provided with potentially using existing cli.Context values to initialize itself. If there is +no error it will then apply the new input source to any flags that are supported by the input source +

    + + + + + + + +

    func NewTomlSourceFromFlagFunc

    +
    func NewTomlSourceFromFlagFunc(flagFileName string) func(context *cli.Context) (InputSourceContext, error)
    +

    +NewTomlSourceFromFlagFunc creates a new TOML InputSourceContext from a provided flag name and source context. +

    + + + + + + + +

    func NewYamlSourceFromFlagFunc

    +
    func NewYamlSourceFromFlagFunc(flagFileName string) func(context *cli.Context) (InputSourceContext, error)
    +

    +NewYamlSourceFromFlagFunc creates a new Yaml InputSourceContext from a provided flag name and source context. +

    + + + + + + + + +

    type BoolFlag

    +
    type BoolFlag struct {
    +    cli.BoolFlag
    +    // contains filtered or unexported fields
    +}
    +

    +BoolFlag is the flag type that wraps cli.BoolFlag to allow +for other values to be specified +

    + + + + + + + + + + + + +

    func NewBoolFlag

    +
    func NewBoolFlag(fl cli.BoolFlag) *BoolFlag
    +

    +NewBoolFlag creates a new BoolFlag +

    + + + + + + + +

    func (*BoolFlag) Apply

    +
    func (f *BoolFlag) Apply(set *flag.FlagSet)
    +

    +Apply saves the flagSet for later usage calls, then calls the +wrapped BoolFlag.Apply +

    + + + + + + +

    func (*BoolFlag) ApplyInputSourceValue

    +
    func (f *BoolFlag) ApplyInputSourceValue(context *cli.Context, isc InputSourceContext) error
    +

    +ApplyInputSourceValue applies a Bool value to the flagSet if required +

    + + + + + + + + +

    type BoolTFlag

    +
    type BoolTFlag struct {
    +    cli.BoolTFlag
    +    // contains filtered or unexported fields
    +}
    +

    +BoolTFlag is the flag type that wraps cli.BoolTFlag to allow +for other values to be specified +

    + + + + + + + + + + + + +

    func NewBoolTFlag

    +
    func NewBoolTFlag(fl cli.BoolTFlag) *BoolTFlag
    +

    +NewBoolTFlag creates a new BoolTFlag +

    + + + + + + + +

    func (*BoolTFlag) Apply

    +
    func (f *BoolTFlag) Apply(set *flag.FlagSet)
    +

    +Apply saves the flagSet for later usage calls, then calls the +wrapped BoolTFlag.Apply +

    + + + + + + +

    func (*BoolTFlag) ApplyInputSourceValue

    +
    func (f *BoolTFlag) ApplyInputSourceValue(context *cli.Context, isc InputSourceContext) error
    +

    +ApplyInputSourceValue applies a BoolT value to the flagSet if required +

    + + + + + + + + +

    type DurationFlag

    +
    type DurationFlag struct {
    +    cli.DurationFlag
    +    // contains filtered or unexported fields
    +}
    +

    +DurationFlag is the flag type that wraps cli.DurationFlag to allow +for other values to be specified +

    + + + + + + + + + + + + +

    func NewDurationFlag

    +
    func NewDurationFlag(fl cli.DurationFlag) *DurationFlag
    +

    +NewDurationFlag creates a new DurationFlag +

    + + + + + + + +

    func (*DurationFlag) Apply

    +
    func (f *DurationFlag) Apply(set *flag.FlagSet)
    +

    +Apply saves the flagSet for later usage calls, then calls the +wrapped DurationFlag.Apply +

    + + + + + + +

    func (*DurationFlag) ApplyInputSourceValue

    +
    func (f *DurationFlag) ApplyInputSourceValue(context *cli.Context, isc InputSourceContext) error
    +

    +ApplyInputSourceValue applies a Duration value to the flagSet if required +

    + + + + + + + + +

    type FlagInputSourceExtension

    +
    type FlagInputSourceExtension interface {
    +    cli.Flag
    +    ApplyInputSourceValue(context *cli.Context, isc InputSourceContext) error
    +}
    +

    +FlagInputSourceExtension is an extension interface of cli.Flag that +allows a value to be set on the existing parsed flags. +

    + + + + + + + + + + + + + + + + +

    type Float64Flag

    +
    type Float64Flag struct {
    +    cli.Float64Flag
    +    // contains filtered or unexported fields
    +}
    +

    +Float64Flag is the flag type that wraps cli.Float64Flag to allow +for other values to be specified +

    + + + + + + + + + + + + +

    func NewFloat64Flag

    +
    func NewFloat64Flag(fl cli.Float64Flag) *Float64Flag
    +

    +NewFloat64Flag creates a new Float64Flag +

    + + + + + + + +

    func (*Float64Flag) Apply

    +
    func (f *Float64Flag) Apply(set *flag.FlagSet)
    +

    +Apply saves the flagSet for later usage calls, then calls the +wrapped Float64Flag.Apply +

    + + + + + + +

    func (*Float64Flag) ApplyInputSourceValue

    +
    func (f *Float64Flag) ApplyInputSourceValue(context *cli.Context, isc InputSourceContext) error
    +

    +ApplyInputSourceValue applies a Float64 value to the flagSet if required +

    + + + + + + + + +

    type GenericFlag

    +
    type GenericFlag struct {
    +    cli.GenericFlag
    +    // contains filtered or unexported fields
    +}
    +

    +GenericFlag is the flag type that wraps cli.GenericFlag to allow +for other values to be specified +

    + + + + + + + + + + + + +

    func NewGenericFlag

    +
    func NewGenericFlag(fl cli.GenericFlag) *GenericFlag
    +

    +NewGenericFlag creates a new GenericFlag +

    + + + + + + + +

    func (*GenericFlag) Apply

    +
    func (f *GenericFlag) Apply(set *flag.FlagSet)
    +

    +Apply saves the flagSet for later usage calls, then calls the +wrapped GenericFlag.Apply +

    + + + + + + +

    func (*GenericFlag) ApplyInputSourceValue

    +
    func (f *GenericFlag) ApplyInputSourceValue(context *cli.Context, isc InputSourceContext) error
    +

    +ApplyInputSourceValue applies a generic value to the flagSet if required +

    + + + + + + + + +

    type InputSourceContext

    +
    type InputSourceContext interface {
    +    Int(name string) (int, error)
    +    Duration(name string) (time.Duration, error)
    +    Float64(name string) (float64, error)
    +    String(name string) (string, error)
    +    StringSlice(name string) ([]string, error)
    +    IntSlice(name string) ([]int, error)
    +    Generic(name string) (cli.Generic, error)
    +    Bool(name string) (bool, error)
    +    BoolT(name string) (bool, error)
    +}
    +

    +InputSourceContext is an interface used to allow +other input sources to be implemented as needed. +

    + + + + + + + + + + + + +

    func NewTomlSourceFromFile

    +
    func NewTomlSourceFromFile(file string) (InputSourceContext, error)
    +

    +NewTomlSourceFromFile creates a new TOML InputSourceContext from a filepath. +

    + + + + + +

    func NewYamlSourceFromFile

    +
    func NewYamlSourceFromFile(file string) (InputSourceContext, error)
    +

    +NewYamlSourceFromFile creates a new Yaml InputSourceContext from a filepath. +

    + + + + + + + + + +

    type Int64Flag

    +
    type Int64Flag struct {
    +    cli.Int64Flag
    +    // contains filtered or unexported fields
    +}
    +

    +Int64Flag is the flag type that wraps cli.Int64Flag to allow +for other values to be specified +

    + + + + + + + + + + + + +

    func NewInt64Flag

    +
    func NewInt64Flag(fl cli.Int64Flag) *Int64Flag
    +

    +NewInt64Flag creates a new Int64Flag +

    + + + + + + + +

    func (*Int64Flag) Apply

    +
    func (f *Int64Flag) Apply(set *flag.FlagSet)
    +

    +Apply saves the flagSet for later usage calls, then calls the +wrapped Int64Flag.Apply +

    + + + + + + + + +

    type Int64SliceFlag

    +
    type Int64SliceFlag struct {
    +    cli.Int64SliceFlag
    +    // contains filtered or unexported fields
    +}
    +

    +Int64SliceFlag is the flag type that wraps cli.Int64SliceFlag to allow +for other values to be specified +

    + + + + + + + + + + + + +

    func NewInt64SliceFlag

    +
    func NewInt64SliceFlag(fl cli.Int64SliceFlag) *Int64SliceFlag
    +

    +NewInt64SliceFlag creates a new Int64SliceFlag +

    + + + + + + + +

    func (*Int64SliceFlag) Apply

    +
    func (f *Int64SliceFlag) Apply(set *flag.FlagSet)
    +

    +Apply saves the flagSet for later usage calls, then calls the +wrapped Int64SliceFlag.Apply +

    + + + + + + + + +

    type IntFlag

    +
    type IntFlag struct {
    +    cli.IntFlag
    +    // contains filtered or unexported fields
    +}
    +

    +IntFlag is the flag type that wraps cli.IntFlag to allow +for other values to be specified +

    + + + + + + + + + + + + +

    func NewIntFlag

    +
    func NewIntFlag(fl cli.IntFlag) *IntFlag
    +

    +NewIntFlag creates a new IntFlag +

    + + + + + + + +

    func (*IntFlag) Apply

    +
    func (f *IntFlag) Apply(set *flag.FlagSet)
    +

    +Apply saves the flagSet for later usage calls, then calls the +wrapped IntFlag.Apply +

    + + + + + + +

    func (*IntFlag) ApplyInputSourceValue

    +
    func (f *IntFlag) ApplyInputSourceValue(context *cli.Context, isc InputSourceContext) error
    +

    +ApplyInputSourceValue applies a int value to the flagSet if required +

    + + + + + + + + +

    type IntSliceFlag

    +
    type IntSliceFlag struct {
    +    cli.IntSliceFlag
    +    // contains filtered or unexported fields
    +}
    +

    +IntSliceFlag is the flag type that wraps cli.IntSliceFlag to allow +for other values to be specified +

    + + + + + + + + + + + + +

    func NewIntSliceFlag

    +
    func NewIntSliceFlag(fl cli.IntSliceFlag) *IntSliceFlag
    +

    +NewIntSliceFlag creates a new IntSliceFlag +

    + + + + + + + +

    func (*IntSliceFlag) Apply

    +
    func (f *IntSliceFlag) Apply(set *flag.FlagSet)
    +

    +Apply saves the flagSet for later usage calls, then calls the +wrapped IntSliceFlag.Apply +

    + + + + + + +

    func (*IntSliceFlag) ApplyInputSourceValue

    +
    func (f *IntSliceFlag) ApplyInputSourceValue(context *cli.Context, isc InputSourceContext) error
    +

    +ApplyInputSourceValue applies a IntSlice value if required +

    + + + + + + + + +

    type MapInputSource

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

    +MapInputSource implements InputSourceContext to return +data from the map that is loaded. +

    + + + + + + + + + + + + + + +

    func (*MapInputSource) Bool

    +
    func (fsm *MapInputSource) Bool(name string) (bool, error)
    +

    +Bool returns an bool from the map otherwise returns false +

    + + + + + + +

    func (*MapInputSource) BoolT

    +
    func (fsm *MapInputSource) BoolT(name string) (bool, error)
    +

    +BoolT returns an bool from the map otherwise returns true +

    + + + + + + +

    func (*MapInputSource) Duration

    +
    func (fsm *MapInputSource) Duration(name string) (time.Duration, error)
    +

    +Duration returns a duration from the map if it exists otherwise returns 0 +

    + + + + + + +

    func (*MapInputSource) Float64

    +
    func (fsm *MapInputSource) Float64(name string) (float64, error)
    +

    +Float64 returns an float64 from the map if it exists otherwise returns 0 +

    + + + + + + +

    func (*MapInputSource) Generic

    +
    func (fsm *MapInputSource) Generic(name string) (cli.Generic, error)
    +

    +Generic returns an cli.Generic from the map if it exists otherwise returns nil +

    + + + + + + +

    func (*MapInputSource) Int

    +
    func (fsm *MapInputSource) Int(name string) (int, error)
    +

    +Int returns an int from the map if it exists otherwise returns 0 +

    + + + + + + +

    func (*MapInputSource) IntSlice

    +
    func (fsm *MapInputSource) IntSlice(name string) ([]int, error)
    +

    +IntSlice returns an []int from the map if it exists otherwise returns nil +

    + + + + + + +

    func (*MapInputSource) String

    +
    func (fsm *MapInputSource) String(name string) (string, error)
    +

    +String returns a string from the map if it exists otherwise returns an empty string +

    + + + + + + +

    func (*MapInputSource) StringSlice

    +
    func (fsm *MapInputSource) StringSlice(name string) ([]string, error)
    +

    +StringSlice returns an []string from the map if it exists otherwise returns nil +

    + + + + + + + + +

    type StringFlag

    +
    type StringFlag struct {
    +    cli.StringFlag
    +    // contains filtered or unexported fields
    +}
    +

    +StringFlag is the flag type that wraps cli.StringFlag to allow +for other values to be specified +

    + + + + + + + + + + + + +

    func NewStringFlag

    +
    func NewStringFlag(fl cli.StringFlag) *StringFlag
    +

    +NewStringFlag creates a new StringFlag +

    + + + + + + + +

    func (*StringFlag) Apply

    +
    func (f *StringFlag) Apply(set *flag.FlagSet)
    +

    +Apply saves the flagSet for later usage calls, then calls the +wrapped StringFlag.Apply +

    + + + + + + +

    func (*StringFlag) ApplyInputSourceValue

    +
    func (f *StringFlag) ApplyInputSourceValue(context *cli.Context, isc InputSourceContext) error
    +

    +ApplyInputSourceValue applies a String value to the flagSet if required +

    + + + + + + + + +

    type StringSliceFlag

    +
    type StringSliceFlag struct {
    +    cli.StringSliceFlag
    +    // contains filtered or unexported fields
    +}
    +

    +StringSliceFlag is the flag type that wraps cli.StringSliceFlag to allow +for other values to be specified +

    + + + + + + + + + + + + +

    func NewStringSliceFlag

    +
    func NewStringSliceFlag(fl cli.StringSliceFlag) *StringSliceFlag
    +

    +NewStringSliceFlag creates a new StringSliceFlag +

    + + + + + + + +

    func (*StringSliceFlag) Apply

    +
    func (f *StringSliceFlag) Apply(set *flag.FlagSet)
    +

    +Apply saves the flagSet for later usage calls, then calls the +wrapped StringSliceFlag.Apply +

    + + + + + + +

    func (*StringSliceFlag) ApplyInputSourceValue

    +
    func (f *StringSliceFlag) ApplyInputSourceValue(context *cli.Context, isc InputSourceContext) error
    +

    +ApplyInputSourceValue applies a StringSlice value to the flagSet if required +

    + + + + + + + + +

    type Uint64Flag

    +
    type Uint64Flag struct {
    +    cli.Uint64Flag
    +    // contains filtered or unexported fields
    +}
    +

    +Uint64Flag is the flag type that wraps cli.Uint64Flag to allow +for other values to be specified +

    + + + + + + + + + + + + +

    func NewUint64Flag

    +
    func NewUint64Flag(fl cli.Uint64Flag) *Uint64Flag
    +

    +NewUint64Flag creates a new Uint64Flag +

    + + + + + + + +

    func (*Uint64Flag) Apply

    +
    func (f *Uint64Flag) Apply(set *flag.FlagSet)
    +

    +Apply saves the flagSet for later usage calls, then calls the +wrapped Uint64Flag.Apply +

    + + + + + + + + +

    type UintFlag

    +
    type UintFlag struct {
    +    cli.UintFlag
    +    // contains filtered or unexported fields
    +}
    +

    +UintFlag is the flag type that wraps cli.UintFlag to allow +for other values to be specified +

    + + + + + + + + + + + + +

    func NewUintFlag

    +
    func NewUintFlag(fl cli.UintFlag) *UintFlag
    +

    +NewUintFlag creates a new UintFlag +

    + + + + + + + +

    func (*UintFlag) Apply

    +
    func (f *UintFlag) Apply(set *flag.FlagSet)
    +

    +Apply saves the flagSet for later usage calls, then calls the +wrapped UintFlag.Apply +

    + + + + + + + + + + + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/github.com/codegangsta/cli/index.html b/pkg/github.com/codegangsta/cli/index.html new file mode 100644 index 0000000..2bbd81e --- /dev/null +++ b/pkg/github.com/codegangsta/cli/index.html @@ -0,0 +1,3602 @@ + + + + + + + + cli - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Package cli

    + + + + + + + + + + + + + + +
    +
    +
    import "github.com/codegangsta/cli"
    +
    +
    +
    Overview
    +
    Index
    + +
    Examples
    + + +
    Subdirectories
    + +
    +
    + +
    + +
    +

    Overview ▾

    +

    +Package cli provides a minimal framework for creating and organizing command line +Go applications. cli is designed to be easy to understand and write, the most simple +cli application can be written as follows: +

    +
    func main() {
    +  cli.NewApp().Run(os.Args)
    +}
    +
    +

    +Of course this application does not do much, so let's make this an actual application: +

    +
    func main() {
    +  app := cli.NewApp()
    +  app.Name = "greet"
    +  app.Usage = "say a greeting"
    +  app.Action = func(c *cli.Context) error {
    +    println("Greetings")
    +  }
    +
    +  app.Run(os.Args)
    +}
    +
    + +
    +
    + + +
    + +
    +

    Index ▾

    + + +
    +
    + + +
    Variables
    + + + +
    func DefaultAppComplete(c *Context)
    + + +
    func HandleAction(action interface{}, context *Context) (err error)
    + + +
    func HandleExitCoder(err error)
    + + +
    func ShowAppHelp(c *Context) error
    + + +
    func ShowCommandCompletions(ctx *Context, command string)
    + + +
    func ShowCommandHelp(ctx *Context, command string) error
    + + +
    func ShowCompletions(c *Context)
    + + +
    func ShowSubcommandHelp(c *Context) error
    + + +
    func ShowVersion(c *Context)
    + + + +
    type ActionFunc
    + + + + +
    type AfterFunc
    + + + + +
    type App
    + + +
        func NewApp() *App
    + + + +
        func (a *App) Categories() CommandCategories
    + + +
        func (a *App) Command(name string) *Command
    + + +
        func (a *App) Run(arguments []string) (err error)
    + + +
        func (a *App) RunAndExitOnError()
    + + +
        func (a *App) RunAsSubcommand(ctx *Context) (err error)
    + + +
        func (a *App) Setup()
    + + +
        func (a *App) VisibleCategories() []*CommandCategory
    + + +
        func (a *App) VisibleCommands() []Command
    + + +
        func (a *App) VisibleFlags() []Flag
    + + + +
    type Args
    + + + +
        func (a Args) First() string
    + + +
        func (a Args) Get(n int) string
    + + +
        func (a Args) Present() bool
    + + +
        func (a Args) Swap(from, to int) error
    + + +
        func (a Args) Tail() []string
    + + + +
    type Author
    + + + +
        func (a Author) String() string
    + + + +
    type BashCompleteFunc
    + + + + +
    type BeforeFunc
    + + + + +
    type BoolFlag
    + + + +
        func (f BoolFlag) Apply(set *flag.FlagSet)
    + + +
        func (f BoolFlag) GetName() string
    + + +
        func (f BoolFlag) String() string
    + + + +
    type BoolTFlag
    + + + +
        func (f BoolTFlag) Apply(set *flag.FlagSet)
    + + +
        func (f BoolTFlag) GetName() string
    + + +
        func (f BoolTFlag) String() string
    + + + +
    type Command
    + + + +
        func (c Command) FullName() string
    + + +
        func (c Command) HasName(name string) bool
    + + +
        func (c Command) Names() []string
    + + +
        func (c Command) Run(ctx *Context) (err error)
    + + +
        func (c Command) VisibleFlags() []Flag
    + + + +
    type CommandCategories
    + + + +
        func (c CommandCategories) AddCommand(category string, command Command) CommandCategories
    + + +
        func (c CommandCategories) Len() int
    + + +
        func (c CommandCategories) Less(i, j int) bool
    + + +
        func (c CommandCategories) Swap(i, j int)
    + + + +
    type CommandCategory
    + + + +
        func (c *CommandCategory) VisibleCommands() []Command
    + + + +
    type CommandNotFoundFunc
    + + + + +
    type Commands
    + + + + +
    type Context
    + + +
        func NewContext(app *App, set *flag.FlagSet, parentCtx *Context) *Context
    + + + +
        func (c *Context) Args() Args
    + + +
        func (c *Context) Bool(name string) bool
    + + +
        func (c *Context) BoolT(name string) bool
    + + +
        func (c *Context) Duration(name string) time.Duration
    + + +
        func (c *Context) FlagNames() (names []string)
    + + +
        func (c *Context) Float64(name string) float64
    + + +
        func (c *Context) Generic(name string) interface{}
    + + +
        func (c *Context) GlobalBool(name string) bool
    + + +
        func (c *Context) GlobalBoolT(name string) bool
    + + +
        func (c *Context) GlobalDuration(name string) time.Duration
    + + +
        func (c *Context) GlobalFlagNames() (names []string)
    + + +
        func (c *Context) GlobalFloat64(name string) float64
    + + +
        func (c *Context) GlobalGeneric(name string) interface{}
    + + +
        func (c *Context) GlobalInt(name string) int
    + + +
        func (c *Context) GlobalInt64(name string) int64
    + + +
        func (c *Context) GlobalInt64Slice(name string) []int64
    + + +
        func (c *Context) GlobalIntSlice(name string) []int
    + + +
        func (c *Context) GlobalIsSet(name string) bool
    + + +
        func (c *Context) GlobalSet(name, value string) error
    + + +
        func (c *Context) GlobalString(name string) string
    + + +
        func (c *Context) GlobalStringSlice(name string) []string
    + + +
        func (c *Context) GlobalUint(name string) uint
    + + +
        func (c *Context) GlobalUint64(name string) uint64
    + + +
        func (c *Context) Int(name string) int
    + + +
        func (c *Context) Int64(name string) int64
    + + +
        func (c *Context) Int64Slice(name string) []int64
    + + +
        func (c *Context) IntSlice(name string) []int
    + + +
        func (c *Context) IsSet(name string) bool
    + + +
        func (c *Context) NArg() int
    + + +
        func (c *Context) NumFlags() int
    + + +
        func (c *Context) Parent() *Context
    + + +
        func (c *Context) Set(name, value string) error
    + + +
        func (c *Context) String(name string) string
    + + +
        func (c *Context) StringSlice(name string) []string
    + + +
        func (c *Context) Uint(name string) uint
    + + +
        func (c *Context) Uint64(name string) uint64
    + + + +
    type DurationFlag
    + + + +
        func (f DurationFlag) Apply(set *flag.FlagSet)
    + + +
        func (f DurationFlag) GetName() string
    + + +
        func (f DurationFlag) String() string
    + + + +
    type ExitCoder
    + + + + +
    type ExitError
    + + +
        func NewExitError(message string, exitCode int) *ExitError
    + + + +
        func (ee *ExitError) Error() string
    + + +
        func (ee *ExitError) ExitCode() int
    + + + +
    type Flag
    + + + + +
    type FlagStringFunc
    + + + + +
    type Float64Flag
    + + + +
        func (f Float64Flag) Apply(set *flag.FlagSet)
    + + +
        func (f Float64Flag) GetName() string
    + + +
        func (f Float64Flag) String() string
    + + + +
    type Generic
    + + + + +
    type GenericFlag
    + + + +
        func (f GenericFlag) Apply(set *flag.FlagSet)
    + + +
        func (f GenericFlag) GetName() string
    + + +
        func (f GenericFlag) String() string
    + + + +
    type Int64Flag
    + + + +
        func (f Int64Flag) Apply(set *flag.FlagSet)
    + + +
        func (f Int64Flag) GetName() string
    + + +
        func (f Int64Flag) String() string
    + + + +
    type Int64Slice
    + + + +
        func (f *Int64Slice) Set(value string) error
    + + +
        func (f *Int64Slice) String() string
    + + +
        func (f *Int64Slice) Value() []int64
    + + + +
    type Int64SliceFlag
    + + + +
        func (f Int64SliceFlag) Apply(set *flag.FlagSet)
    + + +
        func (f Int64SliceFlag) GetName() string
    + + +
        func (f Int64SliceFlag) String() string
    + + + +
    type IntFlag
    + + + +
        func (f IntFlag) Apply(set *flag.FlagSet)
    + + +
        func (f IntFlag) GetName() string
    + + +
        func (f IntFlag) String() string
    + + + +
    type IntSlice
    + + + +
        func (f *IntSlice) Set(value string) error
    + + +
        func (f *IntSlice) String() string
    + + +
        func (f *IntSlice) Value() []int
    + + + +
    type IntSliceFlag
    + + + +
        func (f IntSliceFlag) Apply(set *flag.FlagSet)
    + + +
        func (f IntSliceFlag) GetName() string
    + + +
        func (f IntSliceFlag) String() string
    + + + +
    type MultiError
    + + +
        func NewMultiError(err ...error) MultiError
    + + + +
        func (m MultiError) Error() string
    + + + +
    type OnUsageErrorFunc
    + + + + +
    type StringFlag
    + + + +
        func (f StringFlag) Apply(set *flag.FlagSet)
    + + +
        func (f StringFlag) GetName() string
    + + +
        func (f StringFlag) String() string
    + + + +
    type StringSlice
    + + + +
        func (f *StringSlice) Set(value string) error
    + + +
        func (f *StringSlice) String() string
    + + +
        func (f *StringSlice) Value() []string
    + + + +
    type StringSliceFlag
    + + + +
        func (f StringSliceFlag) Apply(set *flag.FlagSet)
    + + +
        func (f StringSliceFlag) GetName() string
    + + +
        func (f StringSliceFlag) String() string
    + + + +
    type Uint64Flag
    + + + +
        func (f Uint64Flag) Apply(set *flag.FlagSet)
    + + +
        func (f Uint64Flag) GetName() string
    + + +
        func (f Uint64Flag) String() string
    + + + +
    type UintFlag
    + + + +
        func (f UintFlag) Apply(set *flag.FlagSet)
    + + +
        func (f UintFlag) GetName() string
    + + +
        func (f UintFlag) String() string
    + + + +
    +
    + + + + + + +

    Package files

    +

    + + + app.go + + category.go + + cli.go + + command.go + + context.go + + errors.go + + flag.go + + flag_generated.go + + funcs.go + + help.go + + +

    + +
    +
    + + + + + +

    Variables

    + +
    var AppHelpTemplate = `NAME:
    +   {{.Name}} - {{.Usage}}
    +
    +USAGE:
    +   {{if .UsageText}}{{.UsageText}}{{else}}{{.HelpName}} {{if .VisibleFlags}}[global options]{{end}}{{if .Commands}} command [command options]{{end}} {{if .ArgsUsage}}{{.ArgsUsage}}{{else}}[arguments...]{{end}}{{end}}
    +   {{if .Version}}{{if not .HideVersion}}
    +VERSION:
    +   {{.Version}}
    +   {{end}}{{end}}{{if len .Authors}}
    +AUTHOR(S):
    +   {{range .Authors}}{{.}}{{end}}
    +   {{end}}{{if .VisibleCommands}}
    +COMMANDS:{{range .VisibleCategories}}{{if .Name}}
    +   {{.Name}}:{{end}}{{range .VisibleCommands}}
    +     {{join .Names ", "}}{{"\t"}}{{.Usage}}{{end}}
    +{{end}}{{end}}{{if .VisibleFlags}}
    +GLOBAL OPTIONS:
    +   {{range .VisibleFlags}}{{.}}
    +   {{end}}{{end}}{{if .Copyright}}
    +COPYRIGHT:
    +   {{.Copyright}}
    +   {{end}}
    +`
    +

    +AppHelpTemplate is the text template for the Default help topic. +cli.go uses text/template to render templates. You can +render custom help text by setting this variable. +

    + + +
    var BashCompletionFlag = BoolFlag{
    +    Name:   "generate-bash-completion",
    +    Hidden: true,
    +}
    +

    +BashCompletionFlag enables bash-completion for all commands and subcommands +

    + + +
    var CommandHelpTemplate = `NAME:
    +   {{.HelpName}} - {{.Usage}}
    +
    +USAGE:
    +   {{.HelpName}}{{if .VisibleFlags}} [command options]{{end}} {{if .ArgsUsage}}{{.ArgsUsage}}{{else}}[arguments...]{{end}}{{if .Category}}
    +
    +CATEGORY:
    +   {{.Category}}{{end}}{{if .Description}}
    +
    +DESCRIPTION:
    +   {{.Description}}{{end}}{{if .VisibleFlags}}
    +
    +OPTIONS:
    +   {{range .VisibleFlags}}{{.}}
    +   {{end}}{{end}}
    +`
    +

    +CommandHelpTemplate is the text template for the command help topic. +cli.go uses text/template to render templates. You can +render custom help text by setting this variable. +

    + + +
    var ErrWriter io.Writer = os.Stderr
    +

    +ErrWriter is used to write errors to the user. This can be anything +implementing the io.Writer interface and defaults to os.Stderr. +

    + + +
    var HelpFlag = BoolFlag{
    +    Name:  "help, h",
    +    Usage: "show help",
    +}
    +

    +HelpFlag prints the help for all commands and subcommands +Set to the zero value (BoolFlag{}) to disable flag -- keeps subcommand +unless HideHelp is set to true) +

    + + +
    var HelpPrinter helpPrinter = printHelp
    +

    +HelpPrinter is a function that writes the help output. If not set a default +is used. The function signature is: +func(w io.Writer, templ string, data interface{}) +

    + + +
    var OsExiter = os.Exit
    +

    +OsExiter is the function used when the app exits. If not set defaults to os.Exit. +

    + + +
    var SubcommandHelpTemplate = `NAME:
    +   {{.HelpName}} - {{.Usage}}
    +
    +USAGE:
    +   {{.HelpName}} command{{if .VisibleFlags}} [command options]{{end}} {{if .ArgsUsage}}{{.ArgsUsage}}{{else}}[arguments...]{{end}}
    +
    +COMMANDS:{{range .VisibleCategories}}{{if .Name}}
    +   {{.Name}}:{{end}}{{range .VisibleCommands}}
    +     {{join .Names ", "}}{{"\t"}}{{.Usage}}{{end}}
    +{{end}}{{if .VisibleFlags}}
    +OPTIONS:
    +   {{range .VisibleFlags}}{{.}}
    +   {{end}}{{end}}
    +`
    +

    +SubcommandHelpTemplate is the text template for the subcommand help topic. +cli.go uses text/template to render templates. You can +render custom help text by setting this variable. +

    + + +
    var VersionFlag = BoolFlag{
    +    Name:  "version, v",
    +    Usage: "print the version",
    +}
    +

    +VersionFlag prints the version for the application +

    + + +
    var VersionPrinter = printVersion
    +

    +VersionPrinter prints the version for the App +

    + + + + + + +

    func DefaultAppComplete

    +
    func DefaultAppComplete(c *Context)
    +

    +DefaultAppComplete prints the list of subcommands as the default app completion method +

    + + + + + + + +

    func HandleAction

    +
    func HandleAction(action interface{}, context *Context) (err error)
    +

    +HandleAction uses ✧✧✧reflection✧✧✧ to figure out if the given Action is an +ActionFunc, a func with the legacy signature for Action, or some other +invalid thing. If it's an ActionFunc or a func with the legacy signature for +Action, the func is run! +

    + + + + + + + +

    func HandleExitCoder

    +
    func HandleExitCoder(err error)
    +

    +HandleExitCoder checks if the error fulfills the ExitCoder interface, and if +so prints the error to stderr (if it is non-empty) and calls OsExiter with the +given exit code. If the given error is a MultiError, then this func is +called on all members of the Errors slice. +

    + + + + + + + +

    func ShowAppHelp

    +
    func ShowAppHelp(c *Context) error
    +

    +ShowAppHelp is an action that displays the help. +

    + + + + + + + +

    func ShowCommandCompletions

    +
    func ShowCommandCompletions(ctx *Context, command string)
    +

    +ShowCommandCompletions prints the custom completions for a given command +

    + + + + + + + +

    func ShowCommandHelp

    +
    func ShowCommandHelp(ctx *Context, command string) error
    +

    +ShowCommandHelp prints help for the given command +

    + + + + + + + +

    func ShowCompletions

    +
    func ShowCompletions(c *Context)
    +

    +ShowCompletions prints the lists of commands within a given context +

    + + + + + + + +

    func ShowSubcommandHelp

    +
    func ShowSubcommandHelp(c *Context) error
    +

    +ShowSubcommandHelp prints help for the given subcommand +

    + + + + + + + +

    func ShowVersion

    +
    func ShowVersion(c *Context)
    +

    +ShowVersion prints the version number of the App +

    + + + + + + + + +

    type ActionFunc

    +
    type ActionFunc func(*Context) error
    +

    +ActionFunc is the action to execute when no subcommands are specified +

    + + + + + + + + + + + + + + + + +

    type AfterFunc

    +
    type AfterFunc func(*Context) error
    +

    +AfterFunc is an action to execute after any subcommands are run, but after the +subcommand has finished it is run even if Action() panics +

    + + + + + + + + + + + + + + + + +

    type App

    +
    type App struct {
    +    // The name of the program. Defaults to path.Base(os.Args[0])
    +    Name string
    +    // Full name of command for help, defaults to Name
    +    HelpName string
    +    // Description of the program.
    +    Usage string
    +    // Text to override the USAGE section of help
    +    UsageText string
    +    // Description of the program argument format.
    +    ArgsUsage string
    +    // Version of the program
    +    Version string
    +    // List of commands to execute
    +    Commands []Command
    +    // List of flags to parse
    +    Flags []Flag
    +    // Boolean to enable bash completion commands
    +    EnableBashCompletion bool
    +    // Boolean to hide built-in help command
    +    HideHelp bool
    +    // Boolean to hide built-in version flag and the VERSION section of help
    +    HideVersion bool
    +
    +    // An action to execute when the bash-completion flag is set
    +    BashComplete BashCompleteFunc
    +    // An action to execute before any subcommands are run, but after the context is ready
    +    // If a non-nil error is returned, no subcommands are run
    +    Before BeforeFunc
    +    // An action to execute after any subcommands are run, but after the subcommand has finished
    +    // It is run even if Action() panics
    +    After AfterFunc
    +
    +    // The action to execute when no subcommands are specified
    +    // Expects a `cli.ActionFunc` but will accept the *deprecated* signature of `func(*cli.Context) {}`
    +    // *Note*: support for the deprecated `Action` signature will be removed in a future version
    +    Action interface{}
    +
    +    // Execute this function if the proper command cannot be found
    +    CommandNotFound CommandNotFoundFunc
    +    // Execute this function if an usage error occurs
    +    OnUsageError OnUsageErrorFunc
    +    // Compilation date
    +    Compiled time.Time
    +    // List of all authors who contributed
    +    Authors []Author
    +    // Copyright of the binary if any
    +    Copyright string
    +    // Name of Author (Note: Use App.Authors, this is deprecated)
    +    Author string
    +    // Email of Author (Note: Use App.Authors, this is deprecated)
    +    Email string
    +    // Writer writer to write output to
    +    Writer io.Writer
    +    // ErrWriter writes error output
    +    ErrWriter io.Writer
    +    // Other custom info
    +    Metadata map[string]interface{}
    +    // contains filtered or unexported fields
    +}
    +

    +App is the main structure of a cli application. It is recommended that +an app be created with the cli.NewApp() function +

    + + + + + + + + + + + + +

    func NewApp

    +
    func NewApp() *App
    +

    +NewApp creates a new cli Application with some reasonable defaults for Name, +Usage, Version and Action. +

    + + + + + + + +

    func (*App) Categories

    +
    func (a *App) Categories() CommandCategories
    +

    +Categories returns a slice containing all the categories with the commands they contain +

    + + + + + + +

    func (*App) Command

    +
    func (a *App) Command(name string) *Command
    +

    +Command returns the named command on App. Returns nil if the command does not exist +

    + + + + + + +

    func (*App) Run

    +
    func (a *App) Run(arguments []string) (err error)
    +

    +Run is the entry point to the cli app. Parses the arguments slice and routes +to the proper flag/args combination +

    + + +
    + +
    +

    Example

    + + + +

    Code:

    +
    // set args for examples sake
    +os.Args = []string{"greet", "--name", "Jeremy"}
    +
    +app := NewApp()
    +app.Name = "greet"
    +app.Flags = []Flag{
    +    StringFlag{Name: "name", Value: "bob", Usage: "a name to say"},
    +}
    +app.Action = func(c *Context) error {
    +    fmt.Printf("Hello %v\n", c.String("name"))
    +    return nil
    +}
    +app.UsageText = "app [first_arg] [second_arg]"
    +app.Author = "Harrison"
    +app.Email = "harrison@lolwut.com"
    +app.Authors = []Author{{Name: "Oliver Allen", Email: "oliver@toyshop.com"}}
    +app.Run(os.Args)
    +
    + +

    Output:

    +
    Hello Jeremy
    +
    + + +
    +
    +
    + +
    +

    Example (BashComplete)

    + + + +

    Code:

    +
    // set args for examples sake
    +os.Args = []string{"greet", "--generate-bash-completion"}
    +
    +app := NewApp()
    +app.Name = "greet"
    +app.EnableBashCompletion = true
    +app.Commands = []Command{
    +    {
    +        Name:        "describeit",
    +        Aliases:     []string{"d"},
    +        Usage:       "use it to see a description",
    +        Description: "This is how we describe describeit the function",
    +        Action: func(c *Context) error {
    +            fmt.Printf("i like to describe things")
    +            return nil
    +        },
    +    }, {
    +        Name:        "next",
    +        Usage:       "next example",
    +        Description: "more stuff to see when generating bash completion",
    +        Action: func(c *Context) error {
    +            fmt.Printf("the next example")
    +            return nil
    +        },
    +    },
    +}
    +
    +app.Run(os.Args)
    +
    + +

    Output:

    +
    describeit
    +d
    +next
    +help
    +h
    +
    + + +
    +
    +
    + +
    +

    Example (Help)

    + + + +

    Code:

    +
    // set args for examples sake
    +os.Args = []string{"greet", "h", "describeit"}
    +
    +app := NewApp()
    +app.Name = "greet"
    +app.Flags = []Flag{
    +    StringFlag{Name: "name", Value: "bob", Usage: "a name to say"},
    +}
    +app.Commands = []Command{
    +    {
    +        Name:        "describeit",
    +        Aliases:     []string{"d"},
    +        Usage:       "use it to see a description",
    +        Description: "This is how we describe describeit the function",
    +        Action: func(c *Context) error {
    +            fmt.Printf("i like to describe things")
    +            return nil
    +        },
    +    },
    +}
    +app.Run(os.Args)
    +
    + +

    Output:

    +
    NAME:
    +   greet describeit - use it to see a description
    +
    +USAGE:
    +   greet describeit [arguments...]
    +
    +DESCRIPTION:
    +   This is how we describe describeit the function
    +
    + + +
    +
    +
    + +
    +

    Example (Subcommand)

    + + + +

    Code:

    +
    // set args for examples sake
    +os.Args = []string{"say", "hi", "english", "--name", "Jeremy"}
    +app := NewApp()
    +app.Name = "say"
    +app.Commands = []Command{
    +    {
    +        Name:        "hello",
    +        Aliases:     []string{"hi"},
    +        Usage:       "use it to see a description",
    +        Description: "This is how we describe hello the function",
    +        Subcommands: []Command{
    +            {
    +                Name:        "english",
    +                Aliases:     []string{"en"},
    +                Usage:       "sends a greeting in english",
    +                Description: "greets someone in english",
    +                Flags: []Flag{
    +                    StringFlag{
    +                        Name:  "name",
    +                        Value: "Bob",
    +                        Usage: "Name of the person to greet",
    +                    },
    +                },
    +                Action: func(c *Context) error {
    +                    fmt.Println("Hello,", c.String("name"))
    +                    return nil
    +                },
    +            },
    +        },
    +    },
    +}
    +
    +app.Run(os.Args)
    +
    + +

    Output:

    +
    Hello, Jeremy
    +
    + + +
    +
    + + + + +

    func (*App) RunAndExitOnError

    +
    func (a *App) RunAndExitOnError()
    +

    +RunAndExitOnError calls .Run() and exits non-zero if an error was returned +

    +

    +Deprecated: instead you should return an error that fulfills cli.ExitCoder +to cli.App.Run. This will cause the application to exit with the given eror +code in the cli.ExitCoder +

    + + + + + + +

    func (*App) RunAsSubcommand

    +
    func (a *App) RunAsSubcommand(ctx *Context) (err error)
    +

    +RunAsSubcommand invokes the subcommand given the context, parses ctx.Args() to +generate command-specific flags +

    + + + + + + +

    func (*App) Setup

    +
    func (a *App) Setup()
    +

    +Setup runs initialization code to ensure all data structures are ready for +`Run` or inspection prior to `Run`. It is internally called by `Run`, but +will return early if setup has already happened. +

    + + + + + + +

    func (*App) VisibleCategories

    +
    func (a *App) VisibleCategories() []*CommandCategory
    +

    +VisibleCategories returns a slice of categories and commands that are +Hidden=false +

    + + + + + + +

    func (*App) VisibleCommands

    +
    func (a *App) VisibleCommands() []Command
    +

    +VisibleCommands returns a slice of the Commands with Hidden=false +

    + + + + + + +

    func (*App) VisibleFlags

    +
    func (a *App) VisibleFlags() []Flag
    +

    +VisibleFlags returns a slice of the Flags with Hidden=false +

    + + + + + + + + +

    type Args

    +
    type Args []string
    +

    +Args contains apps console arguments +

    + + + + + + + + + + + + + + +

    func (Args) First

    +
    func (a Args) First() string
    +

    +First returns the first argument, or else a blank string +

    + + + + + + +

    func (Args) Get

    +
    func (a Args) Get(n int) string
    +

    +Get returns the nth argument, or else a blank string +

    + + + + + + +

    func (Args) Present

    +
    func (a Args) Present() bool
    +

    +Present checks if there are any arguments present +

    + + + + + + +

    func (Args) Swap

    +
    func (a Args) Swap(from, to int) error
    +

    +Swap swaps arguments at the given indexes +

    + + + + + + +

    func (Args) Tail

    +
    func (a Args) Tail() []string
    +

    +Tail returns the rest of the arguments (not the first one) +or else an empty string slice +

    + + + + + + + + +

    type Author

    +
    type Author struct {
    +    Name  string // The Authors name
    +    Email string // The Authors email
    +}
    +

    +Author represents someone who has contributed to a cli project. +

    + + + + + + + + + + + + + + +

    func (Author) String

    +
    func (a Author) String() string
    +

    +String makes Author comply to the Stringer interface, to allow an easy print in the templating process +

    + + + + + + + + +

    type BashCompleteFunc

    +
    type BashCompleteFunc func(*Context)
    +

    +BashCompleteFunc is an action to execute when the bash-completion flag is set +

    + + + + + + + + + + + + + + + + +

    type BeforeFunc

    +
    type BeforeFunc func(*Context) error
    +

    +BeforeFunc is an action to execute before any subcommands are run, but after +the context is ready if a non-nil error is returned, no subcommands are run +

    + + + + + + + + + + + + + + + + +

    type BoolFlag

    +
    type BoolFlag struct {
    +    Name        string
    +    Usage       string
    +    EnvVar      string
    +    Hidden      bool
    +    Destination *bool
    +}
    +

    +BoolFlag is a flag with type bool +

    + + + + + + + + + + + + + + +

    func (BoolFlag) Apply

    +
    func (f BoolFlag) Apply(set *flag.FlagSet)
    +

    +Apply populates the flag given the flag set and environment +

    + + + + + + +

    func (BoolFlag) GetName

    +
    func (f BoolFlag) GetName() string
    +

    +GetName returns the name of the flag +

    + + + + + + +

    func (BoolFlag) String

    +
    func (f BoolFlag) String() string
    +

    +String returns a readable representation of this value +(for usage defaults) +

    + + + + + + + + +

    type BoolTFlag

    +
    type BoolTFlag struct {
    +    Name        string
    +    Usage       string
    +    EnvVar      string
    +    Hidden      bool
    +    Destination *bool
    +}
    +

    +BoolTFlag is a flag with type bool that is true by default +

    + + + + + + + + + + + + + + +

    func (BoolTFlag) Apply

    +
    func (f BoolTFlag) Apply(set *flag.FlagSet)
    +

    +Apply populates the flag given the flag set and environment +

    + + + + + + +

    func (BoolTFlag) GetName

    +
    func (f BoolTFlag) GetName() string
    +

    +GetName returns the name of the flag +

    + + + + + + +

    func (BoolTFlag) String

    +
    func (f BoolTFlag) String() string
    +

    +String returns a readable representation of this value +(for usage defaults) +

    + + + + + + + + +

    type Command

    +
    type Command struct {
    +    // The name of the command
    +    Name string
    +    // short name of the command. Typically one character (deprecated, use `Aliases`)
    +    ShortName string
    +    // A list of aliases for the command
    +    Aliases []string
    +    // A short description of the usage of this command
    +    Usage string
    +    // Custom text to show on USAGE section of help
    +    UsageText string
    +    // A longer explanation of how the command works
    +    Description string
    +    // A short description of the arguments of this command
    +    ArgsUsage string
    +    // The category the command is part of
    +    Category string
    +    // The function to call when checking for bash command completions
    +    BashComplete BashCompleteFunc
    +    // An action to execute before any sub-subcommands are run, but after the context is ready
    +    // If a non-nil error is returned, no sub-subcommands are run
    +    Before BeforeFunc
    +    // An action to execute after any subcommands are run, but after the subcommand has finished
    +    // It is run even if Action() panics
    +    After AfterFunc
    +    // The function to call when this command is invoked
    +    Action interface{}
    +
    +    // Execute this function if a usage error occurs.
    +    OnUsageError OnUsageErrorFunc
    +    // List of child commands
    +    Subcommands Commands
    +    // List of flags to parse
    +    Flags []Flag
    +    // Treat all flags as normal arguments if true
    +    SkipFlagParsing bool
    +    // Skip argument reordering which attempts to move flags before arguments,
    +    // but only works if all flags appear after all arguments. This behavior was
    +    // removed n version 2 since it only works under specific conditions so we
    +    // backport here by exposing it as an option for compatibility.
    +    SkipArgReorder bool
    +    // Boolean to hide built-in help command
    +    HideHelp bool
    +    // Boolean to hide this command from help or completion
    +    Hidden bool
    +
    +    // Full name of command for help, defaults to full command name, including parent commands.
    +    HelpName string
    +    // contains filtered or unexported fields
    +}
    +

    +Command is a subcommand for a cli.App. +

    + + + + + + + + + + + + + + +

    func (Command) FullName

    +
    func (c Command) FullName() string
    +

    +FullName returns the full name of the command. +For subcommands this ensures that parent commands are part of the command path +

    + + + + + + +

    func (Command) HasName

    +
    func (c Command) HasName(name string) bool
    +

    +HasName returns true if Command.Name or Command.ShortName matches given name +

    + + + + + + +

    func (Command) Names

    +
    func (c Command) Names() []string
    +

    +Names returns the names including short names and aliases. +

    + + + + + + +

    func (Command) Run

    +
    func (c Command) Run(ctx *Context) (err error)
    +

    +Run invokes the command given the context, parses ctx.Args() to generate command-specific flags +

    + + + + + + +

    func (Command) VisibleFlags

    +
    func (c Command) VisibleFlags() []Flag
    +

    +VisibleFlags returns a slice of the Flags with Hidden=false +

    + + + + + + + + +

    type CommandCategories

    +
    type CommandCategories []*CommandCategory
    +

    +CommandCategories is a slice of *CommandCategory. +

    + + + + + + + + + + + + + + +

    func (CommandCategories) AddCommand

    +
    func (c CommandCategories) AddCommand(category string, command Command) CommandCategories
    +

    +AddCommand adds a command to a category. +

    + + + + + + +

    func (CommandCategories) Len

    +
    func (c CommandCategories) Len() int
    + + + + + + +

    func (CommandCategories) Less

    +
    func (c CommandCategories) Less(i, j int) bool
    + + + + + + +

    func (CommandCategories) Swap

    +
    func (c CommandCategories) Swap(i, j int)
    + + + + + + + + +

    type CommandCategory

    +
    type CommandCategory struct {
    +    Name     string
    +    Commands Commands
    +}
    +

    +CommandCategory is a category containing commands. +

    + + + + + + + + + + + + + + +

    func (*CommandCategory) VisibleCommands

    +
    func (c *CommandCategory) VisibleCommands() []Command
    +

    +VisibleCommands returns a slice of the Commands with Hidden=false +

    + + + + + + + + +

    type CommandNotFoundFunc

    +
    type CommandNotFoundFunc func(*Context, string)
    +

    +CommandNotFoundFunc is executed if the proper command cannot be found +

    + + + + + + + + + + + + + + + + +

    type Commands

    +
    type Commands []Command
    +

    +Commands is a slice of Command +

    + + + + + + + + + + + + + + + + +

    type Context

    +
    type Context struct {
    +    App     *App
    +    Command Command
    +    // contains filtered or unexported fields
    +}
    +

    +Context is a type that is passed through to +each Handler action in a cli application. Context +can be used to retrieve context-specific Args and +parsed command-line options. +

    + + + + + + + + + + + + +

    func NewContext

    +
    func NewContext(app *App, set *flag.FlagSet, parentCtx *Context) *Context
    +

    +NewContext creates a new context. For use in when invoking an App or Command action. +

    + + + + + + + +

    func (*Context) Args

    +
    func (c *Context) Args() Args
    +

    +Args returns the command line arguments associated with the context. +

    + + + + + + +

    func (*Context) Bool

    +
    func (c *Context) Bool(name string) bool
    +

    +Bool looks up the value of a local BoolFlag, returns +false if not found +

    + + + + + + +

    func (*Context) BoolT

    +
    func (c *Context) BoolT(name string) bool
    +

    +BoolT looks up the value of a local BoolTFlag, returns +false if not found +

    + + + + + + +

    func (*Context) Duration

    +
    func (c *Context) Duration(name string) time.Duration
    +

    +Duration looks up the value of a local DurationFlag, returns +0 if not found +

    + + + + + + +

    func (*Context) FlagNames

    +
    func (c *Context) FlagNames() (names []string)
    +

    +FlagNames returns a slice of flag names used in this context. +

    + + + + + + +

    func (*Context) Float64

    +
    func (c *Context) Float64(name string) float64
    +

    +Float64 looks up the value of a local Float64Flag, returns +0 if not found +

    + + + + + + +

    func (*Context) Generic

    +
    func (c *Context) Generic(name string) interface{}
    +

    +Generic looks up the value of a local GenericFlag, returns +nil if not found +

    + + + + + + +

    func (*Context) GlobalBool

    +
    func (c *Context) GlobalBool(name string) bool
    +

    +GlobalBool looks up the value of a global BoolFlag, returns +false if not found +

    + + + + + + +

    func (*Context) GlobalBoolT

    +
    func (c *Context) GlobalBoolT(name string) bool
    +

    +GlobalBoolT looks up the value of a global BoolTFlag, returns +false if not found +

    + + + + + + +

    func (*Context) GlobalDuration

    +
    func (c *Context) GlobalDuration(name string) time.Duration
    +

    +GlobalDuration looks up the value of a global DurationFlag, returns +0 if not found +

    + + + + + + +

    func (*Context) GlobalFlagNames

    +
    func (c *Context) GlobalFlagNames() (names []string)
    +

    +GlobalFlagNames returns a slice of global flag names used by the app. +

    + + + + + + +

    func (*Context) GlobalFloat64

    +
    func (c *Context) GlobalFloat64(name string) float64
    +

    +GlobalFloat64 looks up the value of a global Float64Flag, returns +0 if not found +

    + + + + + + +

    func (*Context) GlobalGeneric

    +
    func (c *Context) GlobalGeneric(name string) interface{}
    +

    +GlobalGeneric looks up the value of a global GenericFlag, returns +nil if not found +

    + + + + + + +

    func (*Context) GlobalInt

    +
    func (c *Context) GlobalInt(name string) int
    +

    +GlobalInt looks up the value of a global IntFlag, returns +0 if not found +

    + + + + + + +

    func (*Context) GlobalInt64

    +
    func (c *Context) GlobalInt64(name string) int64
    +

    +GlobalInt64 looks up the value of a global Int64Flag, returns +0 if not found +

    + + + + + + +

    func (*Context) GlobalInt64Slice

    +
    func (c *Context) GlobalInt64Slice(name string) []int64
    +

    +GlobalInt64Slice looks up the value of a global Int64SliceFlag, returns +nil if not found +

    + + + + + + +

    func (*Context) GlobalIntSlice

    +
    func (c *Context) GlobalIntSlice(name string) []int
    +

    +GlobalIntSlice looks up the value of a global IntSliceFlag, returns +nil if not found +

    + + + + + + +

    func (*Context) GlobalIsSet

    +
    func (c *Context) GlobalIsSet(name string) bool
    +

    +GlobalIsSet determines if the global flag was actually set +

    + + + + + + +

    func (*Context) GlobalSet

    +
    func (c *Context) GlobalSet(name, value string) error
    +

    +GlobalSet sets a context flag to a value on the global flagset +

    + + + + + + +

    func (*Context) GlobalString

    +
    func (c *Context) GlobalString(name string) string
    +

    +GlobalString looks up the value of a global StringFlag, returns +"" if not found +

    + + + + + + +

    func (*Context) GlobalStringSlice

    +
    func (c *Context) GlobalStringSlice(name string) []string
    +

    +GlobalStringSlice looks up the value of a global StringSliceFlag, returns +nil if not found +

    + + + + + + +

    func (*Context) GlobalUint

    +
    func (c *Context) GlobalUint(name string) uint
    +

    +GlobalUint looks up the value of a global UintFlag, returns +0 if not found +

    + + + + + + +

    func (*Context) GlobalUint64

    +
    func (c *Context) GlobalUint64(name string) uint64
    +

    +GlobalUint64 looks up the value of a global Uint64Flag, returns +0 if not found +

    + + + + + + +

    func (*Context) Int

    +
    func (c *Context) Int(name string) int
    +

    +Int looks up the value of a local IntFlag, returns +0 if not found +

    + + + + + + +

    func (*Context) Int64

    +
    func (c *Context) Int64(name string) int64
    +

    +Int64 looks up the value of a local Int64Flag, returns +0 if not found +

    + + + + + + +

    func (*Context) Int64Slice

    +
    func (c *Context) Int64Slice(name string) []int64
    +

    +Int64Slice looks up the value of a local Int64SliceFlag, returns +nil if not found +

    + + + + + + +

    func (*Context) IntSlice

    +
    func (c *Context) IntSlice(name string) []int
    +

    +IntSlice looks up the value of a local IntSliceFlag, returns +nil if not found +

    + + + + + + +

    func (*Context) IsSet

    +
    func (c *Context) IsSet(name string) bool
    +

    +IsSet determines if the flag was actually set +

    + + + + + + +

    func (*Context) NArg

    +
    func (c *Context) NArg() int
    +

    +NArg returns the number of the command line arguments. +

    + + + + + + +

    func (*Context) NumFlags

    +
    func (c *Context) NumFlags() int
    +

    +NumFlags returns the number of flags set +

    + + + + + + +

    func (*Context) Parent

    +
    func (c *Context) Parent() *Context
    +

    +Parent returns the parent context, if any +

    + + + + + + +

    func (*Context) Set

    +
    func (c *Context) Set(name, value string) error
    +

    +Set sets a context flag to a value. +

    + + + + + + +

    func (*Context) String

    +
    func (c *Context) String(name string) string
    +

    +String looks up the value of a local StringFlag, returns +"" if not found +

    + + + + + + +

    func (*Context) StringSlice

    +
    func (c *Context) StringSlice(name string) []string
    +

    +StringSlice looks up the value of a local StringSliceFlag, returns +nil if not found +

    + + + + + + +

    func (*Context) Uint

    +
    func (c *Context) Uint(name string) uint
    +

    +Uint looks up the value of a local UintFlag, returns +0 if not found +

    + + + + + + +

    func (*Context) Uint64

    +
    func (c *Context) Uint64(name string) uint64
    +

    +Uint64 looks up the value of a local Uint64Flag, returns +0 if not found +

    + + + + + + + + +

    type DurationFlag

    +
    type DurationFlag struct {
    +    Name        string
    +    Usage       string
    +    EnvVar      string
    +    Hidden      bool
    +    Value       time.Duration
    +    Destination *time.Duration
    +}
    +

    +DurationFlag is a flag with type time.Duration (see https://golang.org/pkg/time/#ParseDuration) +

    + + + + + + + + + + + + + + +

    func (DurationFlag) Apply

    +
    func (f DurationFlag) Apply(set *flag.FlagSet)
    +

    +Apply populates the flag given the flag set and environment +

    + + + + + + +

    func (DurationFlag) GetName

    +
    func (f DurationFlag) GetName() string
    +

    +GetName returns the name of the flag +

    + + + + + + +

    func (DurationFlag) String

    +
    func (f DurationFlag) String() string
    +

    +String returns a readable representation of this value +(for usage defaults) +

    + + + + + + + + +

    type ExitCoder

    +
    type ExitCoder interface {
    +    error
    +    ExitCode() int
    +}
    +

    +ExitCoder is the interface checked by `App` and `Command` for a custom exit +code +

    + + + + + + + + + + + + + + + + +

    type ExitError

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

    +ExitError fulfills both the builtin `error` interface and `ExitCoder` +

    + + + + + + + + + + + + +

    func NewExitError

    +
    func NewExitError(message string, exitCode int) *ExitError
    +

    +NewExitError makes a new *ExitError +

    + + + + + + + +

    func (*ExitError) Error

    +
    func (ee *ExitError) Error() string
    +

    +Error returns the string message, fulfilling the interface required by +`error` +

    + + + + + + +

    func (*ExitError) ExitCode

    +
    func (ee *ExitError) ExitCode() int
    +

    +ExitCode returns the exit code, fulfilling the interface required by +`ExitCoder` +

    + + + + + + + + +

    type Flag

    +
    type Flag interface {
    +    fmt.Stringer
    +    // Apply Flag settings to the given flag set
    +    Apply(*flag.FlagSet)
    +    GetName() string
    +}
    +

    +Flag is a common interface related to parsing flags in cli. +For more advanced flag parsing techniques, it is recommended that +this interface be implemented. +

    + + + + + + + + + + + + + + + + +

    type FlagStringFunc

    +
    type FlagStringFunc func(Flag) string
    +

    +FlagStringFunc is used by the help generation to display a flag, which is +expected to be a single line. +

    + + + + + +
    var FlagStringer FlagStringFunc = stringifyFlag
    +

    +FlagStringer converts a flag definition to a string. This is used by help +to display a flag. +

    + + + + + + + + + + + + + +

    type Float64Flag

    +
    type Float64Flag struct {
    +    Name        string
    +    Usage       string
    +    EnvVar      string
    +    Hidden      bool
    +    Value       float64
    +    Destination *float64
    +}
    +

    +Float64Flag is a flag with type float64 +

    + + + + + + + + + + + + + + +

    func (Float64Flag) Apply

    +
    func (f Float64Flag) Apply(set *flag.FlagSet)
    +

    +Apply populates the flag given the flag set and environment +

    + + + + + + +

    func (Float64Flag) GetName

    +
    func (f Float64Flag) GetName() string
    +

    +GetName returns the name of the flag +

    + + + + + + +

    func (Float64Flag) String

    +
    func (f Float64Flag) String() string
    +

    +String returns a readable representation of this value +(for usage defaults) +

    + + + + + + + + +

    type Generic

    +
    type Generic interface {
    +    Set(value string) error
    +    String() string
    +}
    +

    +Generic is a generic parseable type identified by a specific flag +

    + + + + + + + + + + + + + + + + +

    type GenericFlag

    +
    type GenericFlag struct {
    +    Name   string
    +    Usage  string
    +    EnvVar string
    +    Hidden bool
    +    Value  Generic
    +}
    +

    +GenericFlag is a flag with type Generic +

    + + + + + + + + + + + + + + +

    func (GenericFlag) Apply

    +
    func (f GenericFlag) Apply(set *flag.FlagSet)
    +

    +Apply takes the flagset and calls Set on the generic flag with the value +provided by the user for parsing by the flag +

    + + + + + + +

    func (GenericFlag) GetName

    +
    func (f GenericFlag) GetName() string
    +

    +GetName returns the name of the flag +

    + + + + + + +

    func (GenericFlag) String

    +
    func (f GenericFlag) String() string
    +

    +String returns a readable representation of this value +(for usage defaults) +

    + + + + + + + + +

    type Int64Flag

    +
    type Int64Flag struct {
    +    Name        string
    +    Usage       string
    +    EnvVar      string
    +    Hidden      bool
    +    Value       int64
    +    Destination *int64
    +}
    +

    +Int64Flag is a flag with type int64 +

    + + + + + + + + + + + + + + +

    func (Int64Flag) Apply

    +
    func (f Int64Flag) Apply(set *flag.FlagSet)
    +

    +Apply populates the flag given the flag set and environment +

    + + + + + + +

    func (Int64Flag) GetName

    +
    func (f Int64Flag) GetName() string
    +

    +GetName returns the name of the flag +

    + + + + + + +

    func (Int64Flag) String

    +
    func (f Int64Flag) String() string
    +

    +String returns a readable representation of this value +(for usage defaults) +

    + + + + + + + + +

    type Int64Slice

    +
    type Int64Slice []int64
    +

    +Int64Slice is an opaque type for []int to satisfy flag.Value +

    + + + + + + + + + + + + + + +

    func (*Int64Slice) Set

    +
    func (f *Int64Slice) Set(value string) error
    +

    +Set parses the value into an integer and appends it to the list of values +

    + + + + + + +

    func (*Int64Slice) String

    +
    func (f *Int64Slice) String() string
    +

    +String returns a readable representation of this value (for usage defaults) +

    + + + + + + +

    func (*Int64Slice) Value

    +
    func (f *Int64Slice) Value() []int64
    +

    +Value returns the slice of ints set by this flag +

    + + + + + + + + +

    type Int64SliceFlag

    +
    type Int64SliceFlag struct {
    +    Name   string
    +    Usage  string
    +    EnvVar string
    +    Hidden bool
    +    Value  *Int64Slice
    +}
    +

    +Int64SliceFlag is a flag with type *Int64Slice +

    + + + + + + + + + + + + + + +

    func (Int64SliceFlag) Apply

    +
    func (f Int64SliceFlag) Apply(set *flag.FlagSet)
    +

    +Apply populates the flag given the flag set and environment +

    + + + + + + +

    func (Int64SliceFlag) GetName

    +
    func (f Int64SliceFlag) GetName() string
    +

    +GetName returns the name of the flag +

    + + + + + + +

    func (Int64SliceFlag) String

    +
    func (f Int64SliceFlag) String() string
    +

    +String returns a readable representation of this value +(for usage defaults) +

    + + + + + + + + +

    type IntFlag

    +
    type IntFlag struct {
    +    Name        string
    +    Usage       string
    +    EnvVar      string
    +    Hidden      bool
    +    Value       int
    +    Destination *int
    +}
    +

    +IntFlag is a flag with type int +

    + + + + + + + + + + + + + + +

    func (IntFlag) Apply

    +
    func (f IntFlag) Apply(set *flag.FlagSet)
    +

    +Apply populates the flag given the flag set and environment +

    + + + + + + +

    func (IntFlag) GetName

    +
    func (f IntFlag) GetName() string
    +

    +GetName returns the name of the flag +

    + + + + + + +

    func (IntFlag) String

    +
    func (f IntFlag) String() string
    +

    +String returns a readable representation of this value +(for usage defaults) +

    + + + + + + + + +

    type IntSlice

    +
    type IntSlice []int
    +

    +IntSlice is an opaque type for []int to satisfy flag.Value +

    + + + + + + + + + + + + + + +

    func (*IntSlice) Set

    +
    func (f *IntSlice) Set(value string) error
    +

    +Set parses the value into an integer and appends it to the list of values +

    + + + + + + +

    func (*IntSlice) String

    +
    func (f *IntSlice) String() string
    +

    +String returns a readable representation of this value (for usage defaults) +

    + + + + + + +

    func (*IntSlice) Value

    +
    func (f *IntSlice) Value() []int
    +

    +Value returns the slice of ints set by this flag +

    + + + + + + + + +

    type IntSliceFlag

    +
    type IntSliceFlag struct {
    +    Name   string
    +    Usage  string
    +    EnvVar string
    +    Hidden bool
    +    Value  *IntSlice
    +}
    +

    +IntSliceFlag is a flag with type *IntSlice +

    + + + + + + + + + + + + + + +

    func (IntSliceFlag) Apply

    +
    func (f IntSliceFlag) Apply(set *flag.FlagSet)
    +

    +Apply populates the flag given the flag set and environment +

    + + + + + + +

    func (IntSliceFlag) GetName

    +
    func (f IntSliceFlag) GetName() string
    +

    +GetName returns the name of the flag +

    + + + + + + +

    func (IntSliceFlag) String

    +
    func (f IntSliceFlag) String() string
    +

    +String returns a readable representation of this value +(for usage defaults) +

    + + + + + + + + +

    type MultiError

    +
    type MultiError struct {
    +    Errors []error
    +}
    +

    +MultiError is an error that wraps multiple errors. +

    + + + + + + + + + + + + +

    func NewMultiError

    +
    func NewMultiError(err ...error) MultiError
    +

    +NewMultiError creates a new MultiError. Pass in one or more errors. +

    + + + + + + + +

    func (MultiError) Error

    +
    func (m MultiError) Error() string
    +

    +Error implents the error interface. +

    + + + + + + + + +

    type OnUsageErrorFunc

    +
    type OnUsageErrorFunc func(context *Context, err error, isSubcommand bool) error
    +

    +OnUsageErrorFunc is executed if an usage error occurs. This is useful for displaying +customized usage error messages. This function is able to replace the +original error messages. If this function is not set, the "Incorrect usage" +is displayed and the execution is interrupted. +

    + + + + + + + + + + + + + + + + +

    type StringFlag

    +
    type StringFlag struct {
    +    Name        string
    +    Usage       string
    +    EnvVar      string
    +    Hidden      bool
    +    Value       string
    +    Destination *string
    +}
    +

    +StringFlag is a flag with type string +

    + + + + + + + + + + + + + + +

    func (StringFlag) Apply

    +
    func (f StringFlag) Apply(set *flag.FlagSet)
    +

    +Apply populates the flag given the flag set and environment +

    + + + + + + +

    func (StringFlag) GetName

    +
    func (f StringFlag) GetName() string
    +

    +GetName returns the name of the flag +

    + + + + + + +

    func (StringFlag) String

    +
    func (f StringFlag) String() string
    +

    +String returns a readable representation of this value +(for usage defaults) +

    + + + + + + + + +

    type StringSlice

    +
    type StringSlice []string
    +

    +StringSlice is an opaque type for []string to satisfy flag.Value +

    + + + + + + + + + + + + + + +

    func (*StringSlice) Set

    +
    func (f *StringSlice) Set(value string) error
    +

    +Set appends the string value to the list of values +

    + + + + + + +

    func (*StringSlice) String

    +
    func (f *StringSlice) String() string
    +

    +String returns a readable representation of this value (for usage defaults) +

    + + + + + + +

    func (*StringSlice) Value

    +
    func (f *StringSlice) Value() []string
    +

    +Value returns the slice of strings set by this flag +

    + + + + + + + + +

    type StringSliceFlag

    +
    type StringSliceFlag struct {
    +    Name   string
    +    Usage  string
    +    EnvVar string
    +    Hidden bool
    +    Value  *StringSlice
    +}
    +

    +StringSliceFlag is a flag with type *StringSlice +

    + + + + + + + + + + + + + + +

    func (StringSliceFlag) Apply

    +
    func (f StringSliceFlag) Apply(set *flag.FlagSet)
    +

    +Apply populates the flag given the flag set and environment +

    + + + + + + +

    func (StringSliceFlag) GetName

    +
    func (f StringSliceFlag) GetName() string
    +

    +GetName returns the name of the flag +

    + + + + + + +

    func (StringSliceFlag) String

    +
    func (f StringSliceFlag) String() string
    +

    +String returns a readable representation of this value +(for usage defaults) +

    + + + + + + + + +

    type Uint64Flag

    +
    type Uint64Flag struct {
    +    Name        string
    +    Usage       string
    +    EnvVar      string
    +    Hidden      bool
    +    Value       uint64
    +    Destination *uint64
    +}
    +

    +Uint64Flag is a flag with type uint64 +

    + + + + + + + + + + + + + + +

    func (Uint64Flag) Apply

    +
    func (f Uint64Flag) Apply(set *flag.FlagSet)
    +

    +Apply populates the flag given the flag set and environment +

    + + + + + + +

    func (Uint64Flag) GetName

    +
    func (f Uint64Flag) GetName() string
    +

    +GetName returns the name of the flag +

    + + + + + + +

    func (Uint64Flag) String

    +
    func (f Uint64Flag) String() string
    +

    +String returns a readable representation of this value +(for usage defaults) +

    + + + + + + + + +

    type UintFlag

    +
    type UintFlag struct {
    +    Name        string
    +    Usage       string
    +    EnvVar      string
    +    Hidden      bool
    +    Value       uint
    +    Destination *uint
    +}
    +

    +UintFlag is a flag with type uint +

    + + + + + + + + + + + + + + +

    func (UintFlag) Apply

    +
    func (f UintFlag) Apply(set *flag.FlagSet)
    +

    +Apply populates the flag given the flag set and environment +

    + + + + + + +

    func (UintFlag) GetName

    +
    func (f UintFlag) GetName() string
    +

    +GetName returns the name of the flag +

    + + + + + + +

    func (UintFlag) String

    +
    func (f UintFlag) String() string
    +

    +String returns a readable representation of this value +(for usage defaults) +

    + + + + + + + + + + + + + + + + +

    Subdirectories

    + + + + +
    + + + + + + + + + + + + + + + + + + + + +
    NameSynopsis
    ..
    + altsrc + + +
    +
    + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/github.com/codegangsta/index.html b/pkg/github.com/codegangsta/index.html new file mode 100644 index 0000000..98c12b3 --- /dev/null +++ b/pkg/github.com/codegangsta/index.html @@ -0,0 +1,141 @@ + + + + + + + + /src/github.com/codegangsta - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Directory /src/github.com/codegangsta

    + + + + + + + + + + + + + + + + + + + +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    NameSynopsis
    ..
    + cli + + Package cli provides a minimal framework for creating and organizing command line Go applications. +
    + altsrc + + +
    +
    + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/github.com/dghubble/go-twitter/index.html b/pkg/github.com/dghubble/go-twitter/index.html new file mode 100644 index 0000000..2d634e1 --- /dev/null +++ b/pkg/github.com/dghubble/go-twitter/index.html @@ -0,0 +1,130 @@ + + + + + + + + /src/github.com/dghubble/go-twitter - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Directory /src/github.com/dghubble/go-twitter

    + + + + + + + + + + + + + + + + + + + +
    + + + + + + + + + + + + + + + + + + + + +
    NameSynopsis
    ..
    + twitter + + Package twitter provides a Client for the Twitter API. +
    +
    + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/github.com/dghubble/go-twitter/twitter/index.html b/pkg/github.com/dghubble/go-twitter/twitter/index.html new file mode 100644 index 0000000..115df65 --- /dev/null +++ b/pkg/github.com/dghubble/go-twitter/twitter/index.html @@ -0,0 +1,3028 @@ + + + + + + + + twitter - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Package twitter

    + + + + + + + + + + + + + + +
    +
    +
    import "github.com/dghubble/go-twitter/twitter"
    +
    +
    +
    Overview
    +
    Index
    + + +
    +
    + +
    + +
    +

    Overview ▾

    +

    +Package twitter provides a Client for the Twitter API. +

    +

    +The twitter package provides a Client for accessing the Twitter API. Here are +some example requests. +

    +
    // Twitter client
    +client := twitter.NewClient(httpClient)
    +// Home Timeline
    +tweets, resp, err := client.Timelines.HomeTimeline(&HomeTimelineParams{})
    +// Send a Tweet
    +tweet, resp, err := client.Statuses.Update("just setting up my twttr", nil)
    +// Status Show
    +tweet, resp, err := client.Statuses.Show(585613041028431872, nil)
    +// User Show
    +params := &twitter.UserShowParams{ScreenName: "dghubble"}
    +user, resp, err := client.Users.Show(params)
    +// Followers
    +followers, resp, err := client.Followers.List(&FollowerListParams{})
    +
    +

    +Required parameters are passed as positional arguments. Optional parameters +are passed in a typed params struct (or pass nil). +

    +

    Authentication

    +

    +By design, the Twitter Client accepts any http.Client so user auth (OAuth1) or +application auth (OAuth2) requests can be made by using the appropriate +authenticated client. Use the https://github.com/dghubble/oauth1 and +https://github.com/golang/oauth2 packages to obtain an http.Client which +transparently authorizes requests. +

    +

    +For example, make requests as a consumer application on behalf of a user who +has granted access, with OAuth1. +

    +
    // OAuth1
    +import (
    +	"github.com/dghubble/go-twitter/twitter"
    +	"github.com/dghubble/oauth1"
    +)
    +
    +config := oauth1.NewConfig("consumerKey", "consumerSecret")
    +token := oauth1.NewToken("accessToken", "accessSecret")
    +// http.Client will automatically authorize Requests
    +httpClient := config.Client(oauth1.NoContext, token)
    +
    +// twitter client
    +client := twitter.NewClient(httpClient)
    +
    +

    +If no user auth context is needed, make requests as your application with +application auth. +

    +
    // OAuth2
    +import (
    +	"github.com/dghubble/go-twitter/twitter"
    +	"golang.org/x/oauth2"
    +)
    +
    +config := &oauth2.Config{}
    +token := &oauth2.Token{AccessToken: accessToken}
    +// http.Client will automatically authorize Requests
    +httpClient := config.Client(oauth2.NoContext, token)
    +
    +// twitter client
    +client := twitter.NewClient(httpClient)
    +
    +

    +To implement Login with Twitter, see https://github.com/dghubble/gologin. +

    + +
    +
    + + +
    + +
    +

    Index ▾

    + + +
    +
    + + + + +
    func Bool(v bool) *bool
    + + +
    func Float(v float64) *float64
    + + + +
    type APIError
    + + + +
        func (e APIError) Empty() bool
    + + +
        func (e APIError) Error() string
    + + + +
    type AccountService
    + + + +
        func (s *AccountService) VerifyCredentials(params *AccountVerifyParams) (*User, *http.Response, error)
    + + + +
    type AccountVerifyParams
    + + + + +
    type BoundingBox
    + + + + +
    type Client
    + + +
        func NewClient(httpClient *http.Client) *Client
    + + + + +
    type Contributor
    + + + + +
    type Coordinates
    + + + + +
    type Demux
    + + + + +
    type DirectMessage
    + + + + +
    type DirectMessageDestroyParams
    + + + + +
    type DirectMessageGetParams
    + + + + +
    type DirectMessageNewParams
    + + + + +
    type DirectMessageSentParams
    + + + + +
    type DirectMessageService
    + + + +
        func (s *DirectMessageService) Destroy(id int64, params *DirectMessageDestroyParams) (*DirectMessage, *http.Response, error)
    + + +
        func (s *DirectMessageService) Get(params *DirectMessageGetParams) ([]DirectMessage, *http.Response, error)
    + + +
        func (s *DirectMessageService) New(params *DirectMessageNewParams) (*DirectMessage, *http.Response, error)
    + + +
        func (s *DirectMessageService) Sent(params *DirectMessageSentParams) ([]DirectMessage, *http.Response, error)
    + + +
        func (s *DirectMessageService) Show(id int64) (*DirectMessage, *http.Response, error)
    + + + +
    type Entities
    + + + + +
    type ErrorDetail
    + + + + +
    type Event
    + + + + +
    type ExtendedEntity
    + + + + +
    type FollowerIDParams
    + + + + +
    type FollowerIDs
    + + + + +
    type FollowerListParams
    + + + + +
    type FollowerService
    + + + +
        func (s *FollowerService) IDs(params *FollowerIDParams) (*FollowerIDs, *http.Response, error)
    + + +
        func (s *FollowerService) List(params *FollowerListParams) (*Followers, *http.Response, error)
    + + + +
    type Followers
    + + + + +
    type FriendsList
    + + + + +
    type HashtagEntity
    + + + + +
    type HomeTimelineParams
    + + + + +
    type Indices
    + + + +
        func (i Indices) End() int
    + + +
        func (i Indices) Start() int
    + + + +
    type LocationDeletion
    + + + + +
    type MediaEntity
    + + + + +
    type MentionEntity
    + + + + +
    type MentionTimelineParams
    + + + + +
    type OEmbedTweet
    + + + + +
    type Place
    + + + + +
    type RetweetsOfMeTimelineParams
    + + + + +
    type StallWarning
    + + + + +
    type StatusDeletion
    + + + + +
    type StatusDestroyParams
    + + + + +
    type StatusLookupParams
    + + + + +
    type StatusOEmbedParams
    + + + + +
    type StatusRetweetParams
    + + + + +
    type StatusService
    + + + +
        func (s *StatusService) Destroy(id int64, params *StatusDestroyParams) (*Tweet, *http.Response, error)
    + + +
        func (s *StatusService) Lookup(ids []int64, params *StatusLookupParams) ([]Tweet, *http.Response, error)
    + + +
        func (s *StatusService) OEmbed(params *StatusOEmbedParams) (*OEmbedTweet, *http.Response, error)
    + + +
        func (s *StatusService) Retweet(id int64, params *StatusRetweetParams) (*Tweet, *http.Response, error)
    + + +
        func (s *StatusService) Show(id int64, params *StatusShowParams) (*Tweet, *http.Response, error)
    + + +
        func (s *StatusService) Update(status string, params *StatusUpdateParams) (*Tweet, *http.Response, error)
    + + + +
    type StatusShowParams
    + + + + +
    type StatusUpdateParams
    + + + + +
    type StatusWithheld
    + + + + +
    type Stream
    + + + +
        func (s *Stream) Stop()
    + + + +
    type StreamDisconnect
    + + + + +
    type StreamFilterParams
    + + + + +
    type StreamFirehoseParams
    + + + + +
    type StreamLimit
    + + + + +
    type StreamSampleParams
    + + + + +
    type StreamService
    + + + +
        func (srv *StreamService) Filter(params *StreamFilterParams) (*Stream, error)
    + + +
        func (srv *StreamService) Firehose(params *StreamFirehoseParams) (*Stream, error)
    + + +
        func (srv *StreamService) Sample(params *StreamSampleParams) (*Stream, error)
    + + +
        func (srv *StreamService) Site(params *StreamSiteParams) (*Stream, error)
    + + +
        func (srv *StreamService) User(params *StreamUserParams) (*Stream, error)
    + + + +
    type StreamSiteParams
    + + + + +
    type StreamUserParams
    + + + + +
    type SwitchDemux
    + + +
        func NewSwitchDemux() SwitchDemux
    + + + +
        func (d SwitchDemux) Handle(message interface{})
    + + +
        func (d SwitchDemux) HandleChan(messages <-chan interface{})
    + + + +
    type TimelineService
    + + + +
        func (s *TimelineService) HomeTimeline(params *HomeTimelineParams) ([]Tweet, *http.Response, error)
    + + +
        func (s *TimelineService) MentionTimeline(params *MentionTimelineParams) ([]Tweet, *http.Response, error)
    + + +
        func (s *TimelineService) RetweetsOfMeTimeline(params *RetweetsOfMeTimelineParams) ([]Tweet, *http.Response, error)
    + + +
        func (s *TimelineService) UserTimeline(params *UserTimelineParams) ([]Tweet, *http.Response, error)
    + + + +
    type Tweet
    + + + + +
    type TweetIdentifier
    + + + + +
    type URLEntity
    + + + + +
    type User
    + + + + +
    type UserEntities
    + + + + +
    type UserLookupParams
    + + + + +
    type UserSearchParams
    + + + + +
    type UserService
    + + + +
        func (s *UserService) Lookup(params *UserLookupParams) ([]User, *http.Response, error)
    + + +
        func (s *UserService) Search(query string, params *UserSearchParams) ([]User, *http.Response, error)
    + + +
        func (s *UserService) Show(params *UserShowParams) (*User, *http.Response, error)
    + + + +
    type UserShowParams
    + + + + +
    type UserTimelineParams
    + + + + +
    type UserWithheld
    + + + + +
    +
    + + + + +

    Package files

    +

    + + + accounts.go + + backoffs.go + + demux.go + + direct_messages.go + + doc.go + + entities.go + + errors.go + + followers.go + + statuses.go + + stream_messages.go + + stream_utils.go + + streams.go + + timelines.go + + twitter.go + + users.go + + +

    + +
    +
    + + + + + + + + +

    func Bool

    +
    func Bool(v bool) *bool
    +

    +Bool returns a new pointer to the given bool value. +

    + + + + + + + +

    func Float

    +
    func Float(v float64) *float64
    +

    +Float returns a new pointer to the given float64 value. +

    + + + + + + + + +

    type APIError

    +
    type APIError struct {
    +    Errors []ErrorDetail `json:"errors"`
    +}
    +

    +APIError represents a Twitter API Error response +https://dev.twitter.com/overview/api/response-codes +

    + + + + + + + + + + + + + + +

    func (APIError) Empty

    +
    func (e APIError) Empty() bool
    +

    +Empty returns true if empty. Otherwise, at least 1 error message/code is +present and false is returned. +

    + + + + + + +

    func (APIError) Error

    +
    func (e APIError) Error() string
    + + + + + + + + +

    type AccountService

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

    +AccountService provides a method for account credential verification. +

    + + + + + + + + + + + + + + +

    func (*AccountService) VerifyCredentials

    +
    func (s *AccountService) VerifyCredentials(params *AccountVerifyParams) (*User, *http.Response, error)
    +

    +VerifyCredentials returns the authorized user if credentials are valid and +returns an error otherwise. +Requires a user auth context. +https://dev.twitter.com/rest/reference/get/account/verify_credentials +

    + + + + + + + + +

    type AccountVerifyParams

    +
    type AccountVerifyParams struct {
    +    IncludeEntities *bool `url:"include_entities,omitempty"`
    +    SkipStatus      *bool `url:"skip_status,omitempty"`
    +    IncludeEmail    *bool `url:"include_email,omitempty"`
    +}
    +

    +AccountVerifyParams are the params for AccountService.VerifyCredentials. +

    + + + + + + + + + + + + + + + + +

    type BoundingBox

    +
    type BoundingBox struct {
    +    Coordinates [][][2]float64 `json:"coordinates"`
    +    Type        string         `json:"type"`
    +}
    +

    +BoundingBox represents the bounding coordinates (longitude, latitutde) +defining the bounds of a box containing a Place entity. +

    + + + + + + + + + + + + + + + + +

    type Client

    +
    type Client struct {
    +
    +    // Twitter API Services
    +    Accounts       *AccountService
    +    Statuses       *StatusService
    +    Timelines      *TimelineService
    +    Users          *UserService
    +    Followers      *FollowerService
    +    DirectMessages *DirectMessageService
    +    Streams        *StreamService
    +    // contains filtered or unexported fields
    +}
    +

    +Client is a Twitter client for making Twitter API requests. +

    + + + + + + + + + + + + +

    func NewClient

    +
    func NewClient(httpClient *http.Client) *Client
    +

    +NewClient returns a new Client. +

    + + + + + + + + + +

    type Contributor

    +
    type Contributor struct {
    +    ID         int64  `json:"id"`
    +    IDStr      string `json:"id_str"`
    +    ScreenName string `json:"screen_name"`
    +}
    +

    +Contributor represents a brief summary of a User identifiers. +

    + + + + + + + + + + + + + + + + +

    type Coordinates

    +
    type Coordinates struct {
    +    Coordinates [2]float64 `json:"coordinates"`
    +    Type        string     `json:"type"`
    +}
    +

    +Coordinates are pairs of longitude and latitude locations. +

    + + + + + + + + + + + + + + + + +

    type Demux

    +
    type Demux interface {
    +    Handle(message interface{})
    +    HandleChan(messages <-chan interface{})
    +}
    +

    +A Demux receives interface{} messages individually or from a channel and +sends those messages to one or more outputs determined by the +implementation. +

    + + + + + + + + + + + + + + + + +

    type DirectMessage

    +
    type DirectMessage struct {
    +    CreatedAt           string    `json:"created_at"`
    +    Entities            *Entities `json:"entities"`
    +    ID                  int64     `json:"id"`
    +    IDStr               string    `json:"id_str"`
    +    Recipient           *User     `json:"recipient"`
    +    RecipientID         int64     `json:"recipient_id"`
    +    RecipientScreenName string    `json:"recipient_screen_name"`
    +    Sender              *User     `json:"sender"`
    +    SenderID            int64     `json:"sender_id"`
    +    SenderScreenName    string    `json:"sender_screen_name"`
    +    Text                string    `json:"text"`
    +}
    +

    +DirectMessage is a direct message to a single recipient. +

    + + + + + + + + + + + + + + + + +

    type DirectMessageDestroyParams

    +
    type DirectMessageDestroyParams struct {
    +    ID              int64 `url:"id,omitempty"`
    +    IncludeEntities *bool `url:"include_entities,omitempty"`
    +}
    +

    +DirectMessageDestroyParams are the parameters for DirectMessageService.Destroy +

    + + + + + + + + + + + + + + + + +

    type DirectMessageGetParams

    +
    type DirectMessageGetParams struct {
    +    SinceID         int64 `url:"since_id,omitempty"`
    +    MaxID           int64 `url:"max_id,omitempty"`
    +    Count           int   `url:"count,omitempty"`
    +    IncludeEntities *bool `url:"include_entities,omitempty"`
    +    SkipStatus      *bool `url:"skip_status,omitempty"`
    +}
    +

    +DirectMessageGetParams are the parameters for DirectMessageService.Get +

    + + + + + + + + + + + + + + + + +

    type DirectMessageNewParams

    +
    type DirectMessageNewParams struct {
    +    UserID     int64  `url:"user_id,omitempty"`
    +    ScreenName string `url:"screen_name,omitempty"`
    +    Text       string `url:"text"`
    +}
    +

    +DirectMessageNewParams are the parameters for DirectMessageService.New +

    + + + + + + + + + + + + + + + + +

    type DirectMessageSentParams

    +
    type DirectMessageSentParams struct {
    +    SinceID         int64 `url:"since_id,omitempty"`
    +    MaxID           int64 `url:"max_id,omitempty"`
    +    Count           int   `url:"count,omitempty"`
    +    Page            int   `url:"page,omitempty"`
    +    IncludeEntities *bool `url:"include_entities,omitempty"`
    +}
    +

    +DirectMessageSentParams are the parameters for DirectMessageService.Sent +

    + + + + + + + + + + + + + + + + +

    type DirectMessageService

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

    +DirectMessageService provides methods for accessing Twitter direct message +API endpoints. +

    + + + + + + + + + + + + + + +

    func (*DirectMessageService) Destroy

    +
    func (s *DirectMessageService) Destroy(id int64, params *DirectMessageDestroyParams) (*DirectMessage, *http.Response, error)
    +

    +Destroy deletes the Direct Message with the given id and returns it if +successful. +Requires a user auth context with DM scope. +https://dev.twitter.com/rest/reference/post/direct_messages/destroy +

    + + + + + + +

    func (*DirectMessageService) Get

    +
    func (s *DirectMessageService) Get(params *DirectMessageGetParams) ([]DirectMessage, *http.Response, error)
    +

    +Get returns recent Direct Messages received by the authenticated user. +Requires a user auth context with DM scope. +https://dev.twitter.com/rest/reference/get/direct_messages +

    + + + + + + +

    func (*DirectMessageService) New

    +
    func (s *DirectMessageService) New(params *DirectMessageNewParams) (*DirectMessage, *http.Response, error)
    +

    +New sends a new Direct Message to a specified user as the authenticated +user. +Requires a user auth context with DM scope. +https://dev.twitter.com/rest/reference/post/direct_messages/new +

    + + + + + + +

    func (*DirectMessageService) Sent

    +
    func (s *DirectMessageService) Sent(params *DirectMessageSentParams) ([]DirectMessage, *http.Response, error)
    +

    +Sent returns recent Direct Messages sent by the authenticated user. +Requires a user auth context with DM scope. +https://dev.twitter.com/rest/reference/get/direct_messages/sent +

    + + + + + + +

    func (*DirectMessageService) Show

    +
    func (s *DirectMessageService) Show(id int64) (*DirectMessage, *http.Response, error)
    +

    +Show returns the requested Direct Message. +Requires a user auth context with DM scope. +https://dev.twitter.com/rest/reference/get/direct_messages/show +

    + + + + + + + + +

    type Entities

    +
    type Entities struct {
    +    Hashtags     []HashtagEntity `json:"hashtags"`
    +    Media        []MediaEntity   `json:"media"`
    +    Urls         []URLEntity     `json:"urls"`
    +    UserMentions []MentionEntity `json:"user_mentions"`
    +}
    +

    +Entities represent metadata and context info parsed from Twitter components. +https://dev.twitter.com/overview/api/entities +TODO: symbols +

    + + + + + + + + + + + + + + + + +

    type ErrorDetail

    +
    type ErrorDetail struct {
    +    Message string `json:"message"`
    +    Code    int    `json:"code"`
    +}
    +

    +ErrorDetail represents an individual item in an APIError. +

    + + + + + + + + + + + + + + + + +

    type Event

    +
    type Event struct {
    +    Event     string `json:"event"`
    +    CreatedAt string `json:"created_at"`
    +    Target    *User  `json:"target"`
    +    Source    *User  `json:"source"`
    +    // TODO: add List or deprecate it
    +    TargetObject *Tweet `json:"target_object"`
    +}
    +

    +Event is a non-Tweet notification message (e.g. like, retweet, follow). +https://dev.twitter.com/streaming/overview/messages-types#Events_event +

    + + + + + + + + + + + + + + + + +

    type ExtendedEntity

    +
    type ExtendedEntity struct {
    +    Media []MediaEntity `json:"media"`
    +}
    +

    +ExtendedEntity contains media information. +https://dev.twitter.com/overview/api/entities-in-twitter-objects#extended_entities +

    + + + + + + + + + + + + + + + + +

    type FollowerIDParams

    +
    type FollowerIDParams struct {
    +    UserID     int64  `url:"user_id,omitempty"`
    +    ScreenName string `url:"screen_name,omitempty"`
    +    Cursor     int64  `url:"cursor,omitempty"`
    +    Count      int    `url:"count,omitempty"`
    +}
    +

    +FollowerIDParams are the parameters for FollowerService.Ids +

    + + + + + + + + + + + + + + + + +

    type FollowerIDs

    +
    type FollowerIDs struct {
    +    IDs               []int64 `json:"ids"`
    +    NextCursor        int64   `json:"next_cursor"`
    +    NextCursorStr     string  `json:"next_cursor_str"`
    +    PreviousCursor    int64   `json:"previous_cursor"`
    +    PreviousCursorStr string  `json:"previous_cursor_str"`
    +}
    +

    +FollowerIDs is a cursored collection of follower ids. +

    + + + + + + + + + + + + + + + + +

    type FollowerListParams

    +
    type FollowerListParams struct {
    +    UserID              int64  `url:"user_id,omitempty"`
    +    ScreenName          string `url:"screen_name,omitempty"`
    +    Cursor              int    `url:"cursor,omitempty"`
    +    Count               int    `url:"count,omitempty"`
    +    SkipStatus          *bool  `url:"skip_status,omitempty"`
    +    IncludeUserEntities *bool  `url:"include_user_entities,omitempty"`
    +}
    +

    +FollowerListParams are the parameters for FollowerService.List +

    + + + + + + + + + + + + + + + + +

    type FollowerService

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

    +FollowerService provides methods for accessing Twitter followers endpoints. +

    + + + + + + + + + + + + + + +

    func (*FollowerService) IDs

    +
    func (s *FollowerService) IDs(params *FollowerIDParams) (*FollowerIDs, *http.Response, error)
    +

    +IDs returns a cursored collection of user ids following the specified user. +https://dev.twitter.com/rest/reference/get/followers/ids +

    + + + + + + +

    func (*FollowerService) List

    +
    func (s *FollowerService) List(params *FollowerListParams) (*Followers, *http.Response, error)
    +

    +List returns a cursored collection of Users following the specified user. +https://dev.twitter.com/rest/reference/get/followers/list +

    + + + + + + + + +

    type Followers

    +
    type Followers struct {
    +    Users             []User `json:"users"`
    +    NextCursor        int64  `json:"next_cursor"`
    +    NextCursorStr     string `json:"next_cursor_str"`
    +    PreviousCursor    int64  `json:"previous_cursor"`
    +    PreviousCursorStr string `json:"previous_cursor_str"`
    +}
    +

    +Followers is a cursored collection of followers. +

    + + + + + + + + + + + + + + + + +

    type FriendsList

    +
    type FriendsList struct {
    +    Friends []int64 `json:"friends"`
    +}
    +

    +FriendsList is a list of some of a user's friends. +https://dev.twitter.com/streaming/overview/messages-types#friends_list_friends +

    + + + + + + + + + + + + + + + + +

    type HashtagEntity

    +
    type HashtagEntity struct {
    +    Indices Indices `json:"indices"`
    +    Text    string  `json:"text"`
    +}
    +

    +HashtagEntity represents a hashtag which has been parsed from text. +

    + + + + + + + + + + + + + + + + +

    type HomeTimelineParams

    +
    type HomeTimelineParams struct {
    +    Count              int   `url:"count,omitempty"`
    +    SinceID            int64 `url:"since_id,omitempty"`
    +    MaxID              int64 `url:"max_id,omitempty"`
    +    TrimUser           *bool `url:"trim_user,omitempty"`
    +    ExcludeReplies     *bool `url:"exclude_replies,omitempty"`
    +    ContributorDetails *bool `url:"contributor_details,omitempty"`
    +    IncludeEntities    *bool `url:"include_entities,omitempty"`
    +}
    +

    +HomeTimelineParams are the parameters for TimelineService.HomeTimeline. +

    + + + + + + + + + + + + + + + + +

    type Indices

    +
    type Indices [2]int
    +

    +Indices represent the start and end offsets within text. +

    + + + + + + + + + + + + + + +

    func (Indices) End

    +
    func (i Indices) End() int
    +

    +End returns the index at which an entity ends, exclusive. +

    + + + + + + +

    func (Indices) Start

    +
    func (i Indices) Start() int
    +

    +Start returns the index at which an entity starts, inclusive. +

    + + + + + + + + +

    type LocationDeletion

    +
    type LocationDeletion struct {
    +    UserID          int64  `json:"user_id"`
    +    UserIDStr       string `json:"user_id_str"`
    +    UpToStatusID    int64  `json:"up_to_status_id"`
    +    UpToStatusIDStr string `json:"up_to_status_id_str"`
    +}
    +

    +LocationDeletion indicates geolocation data must be stripped from a range +of Tweets. +https://dev.twitter.com/streaming/overview/messages-types#Location_deletion_notices_scrub_geo +

    + + + + + + + + + + + + + + + + +

    type MediaEntity

    +
    type MediaEntity struct {
    +    URLEntity
    +    ID                int64  `json:"id"`
    +    IDStr             string `json:"id_str"`
    +    MediaURL          string `json:"media_url"`
    +    MediaURLHttps     string `json:"media_url_https"`
    +    SourceStatusID    int64  `json:"source_status_id"`
    +    SourceStatusIDStr string `json:"source_status_id_str"`
    +    Type              string `json:"type"`
    +}
    +

    +MediaEntity represents media elements associated with a Tweet. +TODO: add Sizes +

    + + + + + + + + + + + + + + + + +

    type MentionEntity

    +
    type MentionEntity struct {
    +    Indices    Indices `json:"indices"`
    +    ID         int64   `json:"id"`
    +    IDStr      string  `json:"id_str"`
    +    Name       string  `json:"name"`
    +    ScreenName string  `json:"screen_name"`
    +}
    +

    +MentionEntity represents Twitter user mentions parsed from text. +

    + + + + + + + + + + + + + + + + +

    type MentionTimelineParams

    +
    type MentionTimelineParams struct {
    +    Count              int   `url:"count,omitempty"`
    +    SinceID            int64 `url:"since_id,omitempty"`
    +    MaxID              int64 `url:"max_id,omitempty"`
    +    TrimUser           *bool `url:"trim_user,omitempty"`
    +    ContributorDetails *bool `url:"contributor_details,omitempty"`
    +    IncludeEntities    *bool `url:"include_entities,omitempty"`
    +}
    +

    +MentionTimelineParams are the parameters for TimelineService.MentionTimeline. +

    + + + + + + + + + + + + + + + + +

    type OEmbedTweet

    +
    type OEmbedTweet struct {
    +    URL          string `json:"url"`
    +    ProviderURL  string `json:"provider_url"`
    +    ProviderName string `json:"provider_name"`
    +    AuthorName   string `json:"author_name"`
    +    Version      string `json:"version"`
    +    AuthorURL    string `json:"author_url"`
    +    Type         string `json:"type"`
    +    HTML         string `json:"html"`
    +    Height       int64  `json:"height"`
    +    Width        int64  `json:"width"`
    +    CacheAge     string `json:"cache_age"`
    +}
    +

    +OEmbedTweet represents a Tweet in oEmbed format. +

    + + + + + + + + + + + + + + + + +

    type Place

    +
    type Place struct {
    +    Attributes  map[string]string `json:"attributes"`
    +    BoundingBox *BoundingBox      `json:"bounding_box"`
    +    Country     string            `json:"country"`
    +    CountryCode string            `json:"country_code"`
    +    FullName    string            `json:"full_name"`
    +    Geometry    *BoundingBox      `json:"geometry"`
    +    ID          string            `json:"id"`
    +    Name        string            `json:"name"`
    +    PlaceType   string            `json:"place_type"`
    +    Polylines   []string          `json:"polylines"`
    +    URL         string            `json:"url"`
    +}
    +

    +Place represents a Twitter Place / Location +https://dev.twitter.com/overview/api/places +

    + + + + + + + + + + + + + + + + +

    type RetweetsOfMeTimelineParams

    +
    type RetweetsOfMeTimelineParams struct {
    +    Count               int   `url:"count,omitempty"`
    +    SinceID             int64 `url:"since_id,omitempty"`
    +    MaxID               int64 `url:"max_id,omitempty"`
    +    TrimUser            *bool `url:"trim_user,omitempty"`
    +    IncludeEntities     *bool `url:"include_entities,omitempty"`
    +    IncludeUserEntities *bool `url:"include_user_entities"`
    +}
    +

    +RetweetsOfMeTimelineParams are the parameters for +TimelineService.RetweetsOfMeTimeline. +

    + + + + + + + + + + + + + + + + +

    type StallWarning

    +
    type StallWarning struct {
    +    Code        string `json:"code"`
    +    Message     string `json:"message"`
    +    PercentFull int    `json:"percent_full"`
    +}
    +

    +StallWarning indicates the client is falling behind in the stream. +https://dev.twitter.com/streaming/overview/messages-types#stall_warnings +

    + + + + + + + + + + + + + + + + +

    type StatusDeletion

    +
    type StatusDeletion struct {
    +    ID        int64  `json:"id"`
    +    IDStr     string `json:"id_str"`
    +    UserID    int64  `json:"user_id"`
    +    UserIDStr string `json:"user_id_str"`
    +}
    +

    +StatusDeletion indicates that a given Tweet has been deleted. +https://dev.twitter.com/streaming/overview/messages-types#status_deletion_notices_delete +

    + + + + + + + + + + + + + + + + +

    type StatusDestroyParams

    +
    type StatusDestroyParams struct {
    +    ID       int64 `url:"id,omitempty"`
    +    TrimUser *bool `url:"trim_user,omitempty"`
    +}
    +

    +StatusDestroyParams are the parameters for StatusService.Destroy +

    + + + + + + + + + + + + + + + + +

    type StatusLookupParams

    +
    type StatusLookupParams struct {
    +    ID              []int64 `url:"id,omitempty,comma"`
    +    TrimUser        *bool   `url:"trim_user,omitempty"`
    +    IncludeEntities *bool   `url:"include_entities,omitempty"`
    +    Map             *bool   `url:"map,omitempty"`
    +}
    +

    +StatusLookupParams are the parameters for StatusService.Lookup +

    + + + + + + + + + + + + + + + + +

    type StatusOEmbedParams

    +
    type StatusOEmbedParams struct {
    +    ID         int64  `url:"id,omitempty"`
    +    URL        string `url:"url,omitempty"`
    +    Align      string `url:"align,omitempty"`
    +    MaxWidth   int64  `url:"maxwidth,omitempty"`
    +    HideMedia  *bool  `url:"hide_media,omitempty"`
    +    HideThread *bool  `url:"hide_media,omitempty"`
    +    OmitScript *bool  `url:"hide_media,omitempty"`
    +    WidgetType string `url:"widget_type,omitempty"`
    +    HideTweet  *bool  `url:"hide_tweet,omitempty"`
    +}
    +

    +StatusOEmbedParams are the parameters for StatusService.OEmbed +

    + + + + + + + + + + + + + + + + +

    type StatusRetweetParams

    +
    type StatusRetweetParams struct {
    +    ID       int64 `url:"id,omitempty"`
    +    TrimUser *bool `url:"trim_user,omitempty"`
    +}
    +

    +StatusRetweetParams are the parameters for StatusService.Retweet +

    + + + + + + + + + + + + + + + + +

    type StatusService

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

    +StatusService provides methods for accessing Twitter status API endpoints. +

    + + + + + + + + + + + + + + +

    func (*StatusService) Destroy

    +
    func (s *StatusService) Destroy(id int64, params *StatusDestroyParams) (*Tweet, *http.Response, error)
    +

    +Destroy deletes the Tweet with the given id and returns it if successful. +Requires a user auth context. +https://dev.twitter.com/rest/reference/post/statuses/destroy/%3Aid +

    + + + + + + +

    func (*StatusService) Lookup

    +
    func (s *StatusService) Lookup(ids []int64, params *StatusLookupParams) ([]Tweet, *http.Response, error)
    +

    +Lookup returns the requested Tweets as a slice. Combines ids from the +required ids argument and from params.Id. +https://dev.twitter.com/rest/reference/get/statuses/lookup +

    + + + + + + +

    func (*StatusService) OEmbed

    +
    func (s *StatusService) OEmbed(params *StatusOEmbedParams) (*OEmbedTweet, *http.Response, error)
    +

    +OEmbed returns the requested Tweet in oEmbed format. +https://dev.twitter.com/rest/reference/get/statuses/oembed +

    + + + + + + +

    func (*StatusService) Retweet

    +
    func (s *StatusService) Retweet(id int64, params *StatusRetweetParams) (*Tweet, *http.Response, error)
    +

    +Retweet retweets the Tweet with the given id and returns the original Tweet +with embedded retweet details. +Requires a user auth context. +https://dev.twitter.com/rest/reference/post/statuses/retweet/%3Aid +

    + + + + + + +

    func (*StatusService) Show

    +
    func (s *StatusService) Show(id int64, params *StatusShowParams) (*Tweet, *http.Response, error)
    +

    +Show returns the requested Tweet. +https://dev.twitter.com/rest/reference/get/statuses/show/%3Aid +

    + + + + + + +

    func (*StatusService) Update

    +
    func (s *StatusService) Update(status string, params *StatusUpdateParams) (*Tweet, *http.Response, error)
    +

    +Update updates the user's status, also known as Tweeting. +Requires a user auth context. +https://dev.twitter.com/rest/reference/post/statuses/update +

    + + + + + + + + +

    type StatusShowParams

    +
    type StatusShowParams struct {
    +    ID               int64 `url:"id,omitempty"`
    +    TrimUser         *bool `url:"trim_user,omitempty"`
    +    IncludeMyRetweet *bool `url:"include_my_retweet,omitempty"`
    +    IncludeEntities  *bool `url:"include_entities,omitempty"`
    +}
    +

    +StatusShowParams are the parameters for StatusService.Show +

    + + + + + + + + + + + + + + + + +

    type StatusUpdateParams

    +
    type StatusUpdateParams struct {
    +    Status             string   `url:"status,omitempty"`
    +    InReplyToStatusID  int64    `url:"in_reply_to_status_id,omitempty"`
    +    PossiblySensitive  *bool    `url:"possibly_sensitive,omitempty"`
    +    Lat                *float64 `url:"lat,omitempty"`
    +    Long               *float64 `url:"long,omitempty"`
    +    PlaceID            string   `url:"place_id,omitempty"`
    +    DisplayCoordinates *bool    `url:"display_coordinates,omitempty"`
    +    TrimUser           *bool    `url:"trim_user,omitempty"`
    +    MediaIds           []int64  `url:"media_ids,omitempty,comma"`
    +}
    +

    +StatusUpdateParams are the parameters for StatusService.Update +

    + + + + + + + + + + + + + + + + +

    type StatusWithheld

    +
    type StatusWithheld struct {
    +    ID                  int64    `json:"id"`
    +    UserID              int64    `json:"user_id"`
    +    WithheldInCountries []string `json:"withheld_in_countries"`
    +}
    +

    +StatusWithheld indicates a Tweet with the given ID, belonging to UserId, +has been withheld in certain countries. +https://dev.twitter.com/streaming/overview/messages-types#withheld_content_notices +

    + + + + + + + + + + + + + + + + +

    type Stream

    +
    type Stream struct {
    +    Messages chan interface{}
    +    // contains filtered or unexported fields
    +}
    +

    +Stream maintains a connection to the Twitter Streaming API, receives +messages from the streaming response, and sends them on the Messages +channel from a goroutine. The stream goroutine stops itself if an EOF is +reached or retry errors occur, also closing the Messages channel. +

    +

    +The client must Stop() the stream when finished receiving, which will +wait until the stream is properly stopped. +

    + + + + + + + + + + + + + + +

    func (*Stream) Stop

    +
    func (s *Stream) Stop()
    +

    +Stop signals retry and receiver to stop, closes the Messages channel, and +blocks until done. +

    + + + + + + + + +

    type StreamDisconnect

    +
    type StreamDisconnect struct {
    +    Code       int64  `json:"code"`
    +    StreamName string `json:"stream_name"`
    +    Reason     string `json:"reason"`
    +}
    +

    +StreamDisconnect indicates the stream has been shutdown for some reason. +https://dev.twitter.com/streaming/overview/messages-types#disconnect_messages +

    + + + + + + + + + + + + + + + + +

    type StreamFilterParams

    +
    type StreamFilterParams struct {
    +    FilterLevel   string   `url:"filter_level,omitempty"`
    +    Follow        []string `url:"follow,omitempty,comma"`
    +    Language      []string `url:"language,omitempty,comma"`
    +    Locations     []string `url:"locations,omitempty,comma"`
    +    StallWarnings *bool    `url:"stall_warnings,omitempty"`
    +    Track         []string `url:"track,omitempty,comma"`
    +}
    +

    +StreamFilterParams are parameters for StreamService.Filter. +

    + + + + + + + + + + + + + + + + +

    type StreamFirehoseParams

    +
    type StreamFirehoseParams struct {
    +    Count         int      `url:"count,omitempty"`
    +    FilterLevel   string   `url:"filter_level,omitempty"`
    +    Language      []string `url:"language,omitempty,comma"`
    +    StallWarnings *bool    `url:"stall_warnings,omitempty"`
    +}
    +

    +StreamFirehoseParams are the parameters for StreamService.Firehose. +

    + + + + + + + + + + + + + + + + +

    type StreamLimit

    +
    type StreamLimit struct {
    +    Track int64 `json:"track"`
    +}
    +

    +StreamLimit indicates a stream matched more statuses than its rate limit +allowed. The track number is the number of undelivered matches. +https://dev.twitter.com/streaming/overview/messages-types#limit_notices +

    + + + + + + + + + + + + + + + + +

    type StreamSampleParams

    +
    type StreamSampleParams struct {
    +    StallWarnings *bool `url:"stall_warnings,omitempty"`
    +}
    +

    +StreamSampleParams are the parameters for StreamService.Sample. +

    + + + + + + + + + + + + + + + + +

    type StreamService

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

    +StreamService provides methods for accessing the Twitter Streaming API. +

    + + + + + + + + + + + + + + +

    func (*StreamService) Filter

    +
    func (srv *StreamService) Filter(params *StreamFilterParams) (*Stream, error)
    +

    +Filter returns messages that match one or more filter predicates. +https://dev.twitter.com/streaming/reference/post/statuses/filter +

    + + + + + + +

    func (*StreamService) Firehose

    +
    func (srv *StreamService) Firehose(params *StreamFirehoseParams) (*Stream, error)
    +

    +Firehose returns all public messages and statuses. +Requires special permission to access. +https://dev.twitter.com/streaming/reference/get/statuses/firehose +

    + + + + + + +

    func (*StreamService) Sample

    +
    func (srv *StreamService) Sample(params *StreamSampleParams) (*Stream, error)
    +

    +Sample returns a small sample of public stream messages. +https://dev.twitter.com/streaming/reference/get/statuses/sample +

    + + + + + + +

    func (*StreamService) Site

    +
    func (srv *StreamService) Site(params *StreamSiteParams) (*Stream, error)
    +

    +Site returns messages for a set of users. +Requires special permission to access. +https://dev.twitter.com/streaming/reference/get/site +

    + + + + + + +

    func (*StreamService) User

    +
    func (srv *StreamService) User(params *StreamUserParams) (*Stream, error)
    +

    +User returns a stream of messages specific to the authenticated User. +https://dev.twitter.com/streaming/reference/get/user +

    + + + + + + + + +

    type StreamSiteParams

    +
    type StreamSiteParams struct {
    +    FilterLevel   string   `url:"filter_level,omitempty"`
    +    Follow        []string `url:"follow,omitempty,comma"`
    +    Language      []string `url:"language,omitempty,comma"`
    +    Replies       string   `url:"replies,omitempty"`
    +    StallWarnings *bool    `url:"stall_warnings,omitempty"`
    +    With          string   `url:"with,omitempty"`
    +}
    +

    +StreamSiteParams are the parameters for StreamService.Site. +

    + + + + + + + + + + + + + + + + +

    type StreamUserParams

    +
    type StreamUserParams struct {
    +    FilterLevel   string   `url:"filter_level,omitempty"`
    +    Language      []string `url:"language,omitempty,comma"`
    +    Locations     []string `url:"locations,omitempty,comma"`
    +    Replies       string   `url:"replies,omitempty"`
    +    StallWarnings *bool    `url:"stall_warnings,omitempty"`
    +    Track         []string `url:"track,omitempty,comma"`
    +    With          string   `url:"with,omitempty"`
    +}
    +

    +StreamUserParams are the parameters for StreamService.User. +

    + + + + + + + + + + + + + + + + +

    type SwitchDemux

    +
    type SwitchDemux struct {
    +    All              func(message interface{})
    +    Tweet            func(tweet *Tweet)
    +    DM               func(dm *DirectMessage)
    +    StatusDeletion   func(deletion *StatusDeletion)
    +    LocationDeletion func(LocationDeletion *LocationDeletion)
    +    StreamLimit      func(limit *StreamLimit)
    +    StatusWithheld   func(statusWithheld *StatusWithheld)
    +    UserWithheld     func(userWithheld *UserWithheld)
    +    StreamDisconnect func(disconnect *StreamDisconnect)
    +    Warning          func(warning *StallWarning)
    +    FriendsList      func(friendsList *FriendsList)
    +    Event            func(event *Event)
    +    Other            func(message interface{})
    +}
    +

    +SwitchDemux receives messages and uses a type switch to send each typed +message to a handler function. +

    + + + + + + + + + + + + +

    func NewSwitchDemux

    +
    func NewSwitchDemux() SwitchDemux
    +

    +NewSwitchDemux returns a new SwitchMux which has NoOp handler functions. +

    + + + + + + + +

    func (SwitchDemux) Handle

    +
    func (d SwitchDemux) Handle(message interface{})
    +

    +Handle determines the type of a message and calls the corresponding receiver +function with the typed message. All messages are passed to the All func. +Messages with unmatched types are passed to the Other func. +

    + + + + + + +

    func (SwitchDemux) HandleChan

    +
    func (d SwitchDemux) HandleChan(messages <-chan interface{})
    +

    +HandleChan receives messages and calls the corresponding receiver function +with the typed message. All messages are passed to the All func. Messages +with unmatched type are passed to the Other func. +

    + + + + + + + + +

    type TimelineService

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

    +TimelineService provides methods for accessing Twitter status timeline +API endpoints. +

    + + + + + + + + + + + + + + +

    func (*TimelineService) HomeTimeline

    +
    func (s *TimelineService) HomeTimeline(params *HomeTimelineParams) ([]Tweet, *http.Response, error)
    +

    +HomeTimeline returns recent Tweets and retweets from the user and those +users they follow. +Requires a user auth context. +https://dev.twitter.com/rest/reference/get/statuses/home_timeline +

    + + + + + + +

    func (*TimelineService) MentionTimeline

    +
    func (s *TimelineService) MentionTimeline(params *MentionTimelineParams) ([]Tweet, *http.Response, error)
    +

    +MentionTimeline returns recent Tweet mentions of the authenticated user. +Requires a user auth context. +https://dev.twitter.com/rest/reference/get/statuses/mentions_timeline +

    + + + + + + +

    func (*TimelineService) RetweetsOfMeTimeline

    +
    func (s *TimelineService) RetweetsOfMeTimeline(params *RetweetsOfMeTimelineParams) ([]Tweet, *http.Response, error)
    +

    +RetweetsOfMeTimeline returns the most recent Tweets by the authenticated +user that have been retweeted by others. +Requires a user auth context. +https://dev.twitter.com/rest/reference/get/statuses/retweets_of_me +

    + + + + + + +

    func (*TimelineService) UserTimeline

    +
    func (s *TimelineService) UserTimeline(params *UserTimelineParams) ([]Tweet, *http.Response, error)
    +

    +UserTimeline returns recent Tweets from the specified user. +https://dev.twitter.com/rest/reference/get/statuses/user_timeline +

    + + + + + + + + +

    type Tweet

    +
    type Tweet struct {
    +    Contributors         []Contributor          `json:"contributors"`
    +    Coordinates          *Coordinates           `json:"coordinates"`
    +    CreatedAt            string                 `json:"created_at"`
    +    CurrentUserRetweet   *TweetIdentifier       `json:"current_user_retweet"`
    +    Entities             *Entities              `json:"entities"`
    +    FavoriteCount        int                    `json:"favorite_count"`
    +    Favorited            bool                   `json:"favorited"`
    +    FilterLevel          string                 `json:"filter_level"`
    +    ID                   int64                  `json:"id"`
    +    IDStr                string                 `json:"id_str"`
    +    InReplyToScreenName  string                 `json:"in_reply_to_screen_name"`
    +    InReplyToStatusID    int64                  `json:"in_reply_to_status_id"`
    +    InReplyToStatusIDStr string                 `json:"in_reply_to_status_id_str"`
    +    InReplyToUserID      int64                  `json:"in_reply_to_user_id"`
    +    InReplyToUserIDStr   string                 `json:"in_reply_to_user_id_str"`
    +    Lang                 string                 `json:"lang"`
    +    PossiblySensitive    bool                   `json:"possibly_sensitive"`
    +    RetweetCount         int                    `json:"retweet_count"`
    +    Retweeted            bool                   `json:"retweeted"`
    +    RetweetedStatus      *Tweet                 `json:"retweeted_status"`
    +    Source               string                 `json:"source"`
    +    Scopes               map[string]interface{} `json:"scopes"`
    +    Text                 string                 `json:"text"`
    +    Place                *Place                 `json:"place"`
    +    Truncated            bool                   `json:"truncated"`
    +    User                 *User                  `json:"user"`
    +    WithheldCopyright    bool                   `json:"withheld_copyright"`
    +    WithheldInCountries  []string               `json:"withheld_in_countries"`
    +    WithheldScope        string                 `json:"withheld_scope"`
    +    ExtendedEntities     *ExtendedEntity        `json:"extended_entities"`
    +    QuotedStatusID       int64                  `json:"quoted_status_id"`
    +    QuotedStatusIDStr    string                 `json:"quoted_status_id_str"`
    +    QuotedStatus         *Tweet                 `json:"quoted_status"`
    +}
    +

    +Tweet represents a Twitter Tweet, previously called a status. +https://dev.twitter.com/overview/api/tweets +Unused or deprecated fields not provided: Geo, Annotations +

    + + + + + + + + + + + + + + + + +

    type TweetIdentifier

    +
    type TweetIdentifier struct {
    +    ID    int64  `json:"id"`
    +    IDStr string `json:"id_str"`
    +}
    +

    +TweetIdentifier represents the id by which a Tweet can be identified. +

    + + + + + + + + + + + + + + + + +

    type URLEntity

    +
    type URLEntity struct {
    +    Indices     Indices `json:"indices"`
    +    DisplayURL  string  `json:"display_url"`
    +    ExpandedURL string  `json:"expanded_url"`
    +    URL         string  `json:"url"`
    +}
    +

    +URLEntity represents a URL which has been parsed from text. +

    + + + + + + + + + + + + + + + + +

    type User

    +
    type User struct {
    +    ContributorsEnabled            bool          `json:"contributors_enabled"`
    +    CreatedAt                      string        `json:"created_at"`
    +    DefaultProfile                 bool          `json:"default_profile"`
    +    DefaultProfileImage            bool          `json:"default_profile_image"`
    +    Description                    string        `json:"description"`
    +    Email                          string        `json:"email"`
    +    Entities                       *UserEntities `json:"entities"`
    +    FavouritesCount                int           `json:"favourites_count"`
    +    FollowRequestSent              bool          `json:"follow_request_sent"`
    +    Following                      bool          `json:"following"`
    +    FollowersCount                 int           `json:"followers_count"`
    +    FriendsCount                   int           `json:"friends_count"`
    +    GeoEnabled                     bool          `json:"geo_enabled"`
    +    ID                             int64         `json:"id"`
    +    IDStr                          string        `json:"id_str"`
    +    IsTranslator                   bool          `json:"id_translator"`
    +    Lang                           string        `json:"lang"`
    +    ListedCount                    int           `json:"listed_count"`
    +    Location                       string        `json:"location"`
    +    Name                           string        `json:"name"`
    +    Notifications                  bool          `json:"notifications"`
    +    ProfileBackgroundColor         string        `json:"profile_background_color"`
    +    ProfileBackgroundImageURL      string        `json:"profile_background_image_url"`
    +    ProfileBackgroundImageURLHttps string        `json:"profile_background_image_url_https"`
    +    ProfileBackgroundTile          bool          `json:"profile_background_tile"`
    +    ProfileBannerURL               string        `json:"profile_banner_url"`
    +    ProfileImageURL                string        `json:"profile_image_url"`
    +    ProfileImageURLHttps           string        `json:"profile_image_url_https"`
    +    ProfileLinkColor               string        `json:"profile_link_color"`
    +    ProfileSidebarBorderColor      string        `json:"profile_sidebar_border_color"`
    +    ProfileSidebarFillColor        string        `json:"profile_sidebar_fill_color"`
    +    ProfileTextColor               string        `json:"profile_text_color"`
    +    ProfileUseBackgroundImage      bool          `json:"profile_use_background_image"`
    +    Protected                      bool          `json:"protected"`
    +    ScreenName                     string        `json:"screen_name"`
    +    ShowAllInlineMedia             bool          `json:"show_all_inline_media"`
    +    Status                         *Tweet        `json:"status"`
    +    StatusesCount                  int           `json:"statuses_count"`
    +    Timezone                       string        `json:"time_zone"`
    +    URL                            string        `json:"url"`
    +    UtcOffset                      int           `json:"utc_offset"`
    +    Verified                       bool          `json:"verified"`
    +    WithheldInCountries            string        `json:"withheld_in_countries"`
    +    WithholdScope                  string        `json:"withheld_scope"`
    +}
    +

    +User represents a Twitter User. +https://dev.twitter.com/overview/api/users +

    + + + + + + + + + + + + + + + + +

    type UserEntities

    +
    type UserEntities struct {
    +    URL         Entities `json:"url"`
    +    Description Entities `json:"description"`
    +}
    +

    +UserEntities contain Entities parsed from User url and description fields. +https://dev.twitter.com/overview/api/entities-in-twitter-objects#users +

    + + + + + + + + + + + + + + + + +

    type UserLookupParams

    +
    type UserLookupParams struct {
    +    UserID          []int64  `url:"user_id,omitempty,comma"`
    +    ScreenName      []string `url:"screen_name,omitempty,comma"`
    +    IncludeEntities *bool    `url:"include_entities,omitempty"` // whether 'status' should include entities
    +}
    +

    +UserLookupParams are the parameters for UserService.Lookup. +

    + + + + + + + + + + + + + + + + +

    type UserSearchParams

    +
    type UserSearchParams struct {
    +    Query           string `url:"q,omitempty"`
    +    Page            int    `url:"page,omitempty"` // 1-based page number
    +    Count           int    `url:"count,omitempty"`
    +    IncludeEntities *bool  `url:"include_entities,omitempty"` // whether 'status' should include entities
    +}
    +

    +UserSearchParams are the parameters for UserService.Search. +

    + + + + + + + + + + + + + + + + +

    type UserService

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

    +UserService provides methods for accessing Twitter user API endpoints. +

    + + + + + + + + + + + + + + +

    func (*UserService) Lookup

    +
    func (s *UserService) Lookup(params *UserLookupParams) ([]User, *http.Response, error)
    +

    +Lookup returns the requested Users as a slice. +https://dev.twitter.com/rest/reference/get/users/lookup +

    + + + + + + +

    func (*UserService) Search

    +
    func (s *UserService) Search(query string, params *UserSearchParams) ([]User, *http.Response, error)
    +

    +Search queries public user accounts. +Requires a user auth context. +https://dev.twitter.com/rest/reference/get/users/search +

    + + + + + + +

    func (*UserService) Show

    +
    func (s *UserService) Show(params *UserShowParams) (*User, *http.Response, error)
    +

    +Show returns the requested User. +https://dev.twitter.com/rest/reference/get/users/show +

    + + + + + + + + +

    type UserShowParams

    +
    type UserShowParams struct {
    +    UserID          int64  `url:"user_id,omitempty"`
    +    ScreenName      string `url:"screen_name,omitempty"`
    +    IncludeEntities *bool  `url:"include_entities,omitempty"` // whether 'status' should include entities
    +}
    +

    +UserShowParams are the parameters for UserService.Show. +

    + + + + + + + + + + + + + + + + +

    type UserTimelineParams

    +
    type UserTimelineParams struct {
    +    UserID             int64  `url:"user_id,omitempty"`
    +    ScreenName         string `url:"screen_name,omitempty"`
    +    Count              int    `url:"count,omitempty"`
    +    SinceID            int64  `url:"since_id,omitempty"`
    +    MaxID              int64  `url:"max_id,omitempty"`
    +    TrimUser           *bool  `url:"trim_user,omitempty"`
    +    ExcludeReplies     *bool  `url:"exclude_replies,omitempty"`
    +    ContributorDetails *bool  `url:"contributor_details,omitempty"`
    +    IncludeRetweets    *bool  `url:"include_rts,omitempty"`
    +}
    +

    +UserTimelineParams are the parameters for TimelineService.UserTimeline. +

    + + + + + + + + + + + + + + + + +

    type UserWithheld

    +
    type UserWithheld struct {
    +    ID                  int64    `json:"id"`
    +    WithheldInCountries []string `json:"withheld_in_countries"`
    +}
    +

    +UserWithheld indicates a User with the given ID has been withheld in +certain countries. +https://dev.twitter.com/streaming/overview/messages-types#withheld_content_notices +

    + + + + + + + + + + + + + + + + + + + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/github.com/dghubble/index.html b/pkg/github.com/dghubble/index.html new file mode 100644 index 0000000..7e5c601 --- /dev/null +++ b/pkg/github.com/dghubble/index.html @@ -0,0 +1,218 @@ + + + + + + + + /src/github.com/dghubble - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Directory /src/github.com/dghubble

    + + + + + + + + + + + + + + + + + + + +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    NameSynopsis
    ..
    + go-twitter + + +
    + twitter + + Package twitter provides a Client for the Twitter API. +
    + oauth1 + + Package oauth1 is a Go implementation of the OAuth1 spec RFC 5849. +
    + dropbox + + Package dropbox provides constants for using OAuth1 to access Dropbox. +
    + examples + + +
    + tumblr + + Package tumblr provides constants for using OAuth 1 to access Tumblr. +
    + twitter + + Package twitter provides constants for using OAuth1 to access Twitter. +
    + sling + + Package sling is a Go HTTP client library for creating and sending API requests. +
    + examples + + +
    +
    + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/github.com/dghubble/oauth1/dropbox/index.html b/pkg/github.com/dghubble/oauth1/dropbox/index.html new file mode 100644 index 0000000..8c54945 --- /dev/null +++ b/pkg/github.com/dghubble/oauth1/dropbox/index.html @@ -0,0 +1,220 @@ + + + + + + + + dropbox - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Package dropbox

    + + + + + + + + + + + + + + +
    +
    +
    import "github.com/dghubble/oauth1/dropbox"
    +
    +
    +
    Overview
    +
    Index
    + + +
    +
    + +
    + +
    +

    Overview ▾

    +

    +Package dropbox provides constants for using OAuth1 to access Dropbox. +

    + +
    +
    + + +
    + +
    +

    Index ▾

    + + +
    +
    + + +
    Variables
    + + + + +
    +
    + + + + +

    Package files

    +

    + + + dropbox.go + + +

    + +
    +
    + + + + + +

    Variables

    + +
    var Endpoint = oauth1.Endpoint{
    +    RequestTokenURL: "https://api.dropbox.com/1/oauth/request_token",
    +    AuthorizeURL:    "https://api.dropbox.com/1/oauth/authorize",
    +    AccessTokenURL:  "https://api.dropbox.com/1/oauth/access_token",
    +}
    +

    +Endpoint is Dropbox's OAuth 1 endpoint. +

    + + + + + + + + + + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/github.com/dghubble/oauth1/examples/index.html b/pkg/github.com/dghubble/oauth1/examples/index.html new file mode 100644 index 0000000..1f3b900 --- /dev/null +++ b/pkg/github.com/dghubble/oauth1/examples/index.html @@ -0,0 +1,106 @@ + + + + + + + + examples - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Command examples

    + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/github.com/dghubble/oauth1/index.html b/pkg/github.com/dghubble/oauth1/index.html new file mode 100644 index 0000000..a06faa7 --- /dev/null +++ b/pkg/github.com/dghubble/oauth1/index.html @@ -0,0 +1,902 @@ + + + + + + + + oauth1 - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Package oauth1

    + + + + + + + + + + + + + + +
    +
    +
    import "github.com/dghubble/oauth1"
    +
    +
    +
    Overview
    +
    Index
    + + +
    Subdirectories
    + +
    +
    + +
    + +
    +

    Overview ▾

    +

    +Package oauth1 is a Go implementation of the OAuth1 spec RFC 5849. +

    +

    +It allows end-users to authorize a client (consumer) to access protected +resources on their behalf (e.g. login) and allows clients to make signed and +authorized requests on behalf of a user (e.g. API calls). +

    +

    +It takes design cues from golang.org/x/oauth2, providing an http.Client which +handles request signing and authorization. +

    +

    Usage

    +

    +Package oauth1 implements the OAuth1 authorization flow and provides an +http.Client which can sign and authorize OAuth1 requests. +

    +

    +To implement "Login with X", use the https://github.com/dghubble/gologin +packages which provide login handlers for OAuth1 and OAuth2 providers. +

    +

    +To call the Twitter, Digits, or Tumblr OAuth1 APIs, use the higher level Go API +clients. +

    +

    +* https://github.com/dghubble/go-twitter +* https://github.com/dghubble/go-digits +* https://github.com/benfb/go-tumblr +

    +

    Authorization Flow

    +

    +Perform the OAuth 1 authorization flow to ask a user to grant an application +access to his/her resources via an access token. +

    +
    import (
    +	"github.com/dghubble/oauth1"
    +	"github.com/dghubble/oauth1/twitter""
    +)
    +...
    +
    +config := oauth1.Config{
    +	ConsumerKey:    "consumerKey",
    +	ConsumerSecret: "consumerSecret",
    +	CallbackURL:    "http://mysite.com/oauth/twitter/callback",
    +	Endpoint:       twitter.AuthorizeEndpoint,
    +}
    +
    +

    +1. When a user performs an action (e.g. "Login with X" button calls "/login" +route) get an OAuth1 request token (temporary credentials). +

    +
    requestToken, requestSecret, err = config.RequestToken()
    +// handle err
    +
    +

    +2. Obtain authorization from the user by redirecting them to the OAuth1 +provider's authorization URL to grant the application access. +

    +
    authorizationURL, err := config.AuthorizationURL(requestToken)
    +// handle err
    +http.Redirect(w, req, authorizationURL.String(), htt.StatusFound)
    +
    +

    +Receive the callback from the OAuth1 provider in a handler. +

    +
    requestToken, verifier, err := oauth1.ParseAuthorizationCallback(req)
    +// handle err
    +
    +

    +3. Acquire the access token (token credentials) which can later be used +to make requests on behalf of the user. +

    +
    accessToken, accessSecret, err := config.AccessToken(requestToken, requestSecret, verifier)
    +// handle error
    +token := NewToken(accessToken, accessSecret)
    +
    +

    +Check the examples to see this authorization flow in action from the command +line, with Twitter PIN-based login and Tumblr login. +

    +

    Authorized Requests

    +

    +Use an access Token to make authorized requests on behalf of a user. +

    +
    import (
    +	"github.com/dghubble/oauth1"
    +)
    +
    +func main() {
    +    config := oauth1.NewConfig("consumerKey", "consumerSecret")
    +    token := oauth1.NewToken("token", "tokenSecret")
    +
    +    // httpClient will automatically authorize http.Request's
    +    httpClient := config.Client(token)
    +
    +    // example Twitter API request
    +    path := "https://api.twitter.com/1.1/statuses/home_timeline.json?count=2"
    +    resp, _ := httpClient.Get(path)
    +    defer resp.Body.Close()
    +    body, _ := ioutil.ReadAll(resp.Body)
    +    fmt.Printf("Raw Response Body:\n%v\n", string(body))
    +}
    +
    +

    +Check the examples to see Twitter and Tumblr requests in action. +

    + +
    +
    + + +
    + +
    +

    Index ▾

    + + + + + + + +

    Package files

    +

    + + + auther.go + + config.go + + context.go + + doc.go + + encode.go + + endpoint.go + + signer.go + + token.go + + transport.go + + +

    + +
    +
    + + + + + +

    Variables

    + +
    var HTTPClient contextKey
    +

    +HTTPClient is the context key to associate an *http.Client value with +a context. +

    + + +
    var NoContext = context.TODO()
    +

    +NoContext is the default context to use in most cases. +

    + + + + + + +

    func NewClient

    +
    func NewClient(ctx context.Context, config *Config, token *Token) *http.Client
    +

    +NewClient returns a new http Client which signs requests via OAuth1. +

    + + + + + + + +

    func ParseAuthorizationCallback

    +
    func ParseAuthorizationCallback(req *http.Request) (requestToken, verifier string, err error)
    +

    +ParseAuthorizationCallback parses an OAuth1 authorization callback request +from a provider server. The oauth_token and oauth_verifier parameters are +parsed to return the request token from earlier in the flow and the +verifier string. +See RFC 5849 2.2 Resource Owner Authorization. +

    + + + + + + + +

    func PercentEncode

    +
    func PercentEncode(input string) string
    +

    +PercentEncode percent encodes a string according to RFC 3986 2.1. +

    + + + + + + + + +

    type Config

    +
    type Config struct {
    +    // Consumer Key (Client Identifier)
    +    ConsumerKey string
    +    // Consumer Secret (Client Shared-Secret)
    +    ConsumerSecret string
    +    // Callback URL
    +    CallbackURL string
    +    // Provider Endpoint specifying OAuth1 endpoint URLs
    +    Endpoint Endpoint
    +    // OAuth1 Signer (defaults to HMAC-SHA1)
    +    Signer Signer
    +}
    +

    +Config represents an OAuth1 consumer's (client's) key and secret, the +callback URL, and the provider Endpoint to which the consumer corresponds. +

    + + + + + + + + + + + + +

    func NewConfig

    +
    func NewConfig(consumerKey, consumerSecret string) *Config
    +

    +NewConfig returns a new Config with the given consumer key and secret. +

    + + + + + + + +

    func (*Config) AccessToken

    +
    func (c *Config) AccessToken(requestToken, requestSecret, verifier string) (accessToken, accessSecret string, err error)
    +

    +AccessToken obtains an access token (token credential) by POSTing a +request (with oauth_token and oauth_verifier in the auth header) to the +Endpoint AccessTokenURL. Returns the access token and secret (token +credentials). +See RFC 5849 2.3 Token Credentials. +

    + + + + + + +

    func (*Config) AuthorizationURL

    +
    func (c *Config) AuthorizationURL(requestToken string) (*url.URL, error)
    +

    +AuthorizationURL accepts a request token and returns the *url.URL to the +Endpoint's authorization page that asks the user (resource owner) for to +authorize the consumer to act on his/her/its behalf. +See RFC 5849 2.2 Resource Owner Authorization. +

    + + + + + + +

    func (*Config) Client

    +
    func (c *Config) Client(ctx context.Context, t *Token) *http.Client
    +

    +Client returns an HTTP client which uses the provided ctx and access Token. +

    + + + + + + +

    func (*Config) RequestToken

    +
    func (c *Config) RequestToken() (requestToken, requestSecret string, err error)
    +

    +RequestToken obtains a Request token and secret (temporary credential) by +POSTing a request (with oauth_callback in the auth header) to the Endpoint +RequestTokenURL. The response body form is validated to ensure +oauth_callback_confirmed is true. Returns the request token and secret +(temporary credentials). +See RFC 5849 2.1 Temporary Credentials. +

    + + + + + + + + +

    type Endpoint

    +
    type Endpoint struct {
    +    // Request URL (Temporary Credential Request URI)
    +    RequestTokenURL string
    +    // Authorize URL (Resource Owner Authorization URI)
    +    AuthorizeURL string
    +    // Access Token URL (Token Request URI)
    +    AccessTokenURL string
    +}
    +

    +Endpoint represents an OAuth1 provider's (server's) request token, +owner authorization, and access token request URLs. +

    + + + + + + + + + + + + + + + + +

    type HMACSigner

    +
    type HMACSigner struct {
    +    ConsumerSecret string
    +}
    +

    +HMACSigner signs messages with an HMAC SHA1 digest, using the concatenated +consumer secret and token secret as the key. +

    + + + + + + + + + + + + + + +

    func (*HMACSigner) Name

    +
    func (s *HMACSigner) Name() string
    +

    +Name returns the HMAC-SHA1 method. +

    + + + + + + +

    func (*HMACSigner) Sign

    +
    func (s *HMACSigner) Sign(tokenSecret, message string) (string, error)
    +

    +Sign creates a concatenated consumer and token secret key and calculates +the HMAC digest of the message. Returns the base64 encoded digest bytes. +

    + + + + + + + + +

    type RSASigner

    +
    type RSASigner struct {
    +    PrivateKey *rsa.PrivateKey
    +}
    +

    +RSASigner RSA PKCS1-v1_5 signs SHA1 digests of messages using the given +RSA private key. +

    + + + + + + + + + + + + + + +

    func (*RSASigner) Name

    +
    func (s *RSASigner) Name() string
    +

    +Name returns the RSA-SHA1 method. +

    + + + + + + +

    func (*RSASigner) Sign

    +
    func (s *RSASigner) Sign(tokenSecret, message string) (string, error)
    +

    +Sign uses RSA PKCS1-v1_5 to sign a SHA1 digest of the given message. The +tokenSecret is not used with this signing scheme. +

    + + + + + + + + +

    type Signer

    +
    type Signer interface {
    +    // Name returns the name of the signing method.
    +    Name() string
    +    // Sign signs the message using the given secret key.
    +    Sign(key string, message string) (string, error)
    +}
    +

    +A Signer signs messages to create signed OAuth1 Requests. +

    + + + + + + + + + + + + + + + + +

    type Token

    +
    type Token struct {
    +    Token       string
    +    TokenSecret string
    +}
    +

    +Token is an AccessToken (token credential) which allows a consumer (client) +to access resources from an OAuth1 provider server. +

    + + + + + + + + + + + + +

    func NewToken

    +
    func NewToken(token, tokenSecret string) *Token
    +

    +NewToken returns a new Token with the given token and token secret. +

    + + + + + + + + + +

    type TokenSource

    +
    type TokenSource interface {
    +    Token() (*Token, error)
    +}
    +

    +A TokenSource can return a Token. +

    + + + + + + + + + + + + +

    func StaticTokenSource

    +
    func StaticTokenSource(token *Token) TokenSource
    +

    +StaticTokenSource returns a TokenSource which always returns the same Token. +This is appropriate for tokens which do not have a time expiration. +

    + + + + + + + + + +

    type Transport

    +
    type Transport struct {
    +    // Base is the base RoundTripper used to make HTTP requests. If nil, then
    +    // http.DefaultTransport is used
    +    Base http.RoundTripper
    +    // contains filtered or unexported fields
    +}
    +

    +Transport is an http.RoundTripper which makes OAuth1 HTTP requests. It +wraps a base RoundTripper and adds an Authorization header using the +token from a TokenSource. +

    +

    +Transport is a low-level component, most users should use Config to create +an http.Client instead. +

    + + + + + + + + + + + + + + +

    func (*Transport) RoundTrip

    +
    func (t *Transport) RoundTrip(req *http.Request) (*http.Response, error)
    +

    +RoundTrip authorizes the request with a signed OAuth1 Authorization header +using the auther and TokenSource. +

    + + + + + + + + + + + + + + + + +

    Subdirectories

    + + + + +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    NameSynopsis
    ..
    + dropbox + + Package dropbox provides constants for using OAuth1 to access Dropbox. +
    + examples + + +
    + tumblr + + Package tumblr provides constants for using OAuth 1 to access Tumblr. +
    + twitter + + Package twitter provides constants for using OAuth1 to access Twitter. +
    +
    + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/github.com/dghubble/oauth1/tumblr/index.html b/pkg/github.com/dghubble/oauth1/tumblr/index.html new file mode 100644 index 0000000..8509ae6 --- /dev/null +++ b/pkg/github.com/dghubble/oauth1/tumblr/index.html @@ -0,0 +1,220 @@ + + + + + + + + tumblr - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Package tumblr

    + + + + + + + + + + + + + + +
    +
    +
    import "github.com/dghubble/oauth1/tumblr"
    +
    +
    +
    Overview
    +
    Index
    + + +
    +
    + +
    + +
    +

    Overview ▾

    +

    +Package tumblr provides constants for using OAuth 1 to access Tumblr. +

    + +
    +
    + + +
    + +
    +

    Index ▾

    + + +
    +
    + + +
    Variables
    + + + + +
    +
    + + + + +

    Package files

    +

    + + + tumblr.go + + +

    + +
    +
    + + + + + +

    Variables

    + +
    var Endpoint = oauth1.Endpoint{
    +    RequestTokenURL: "http://www.tumblr.com/oauth/request_token",
    +    AuthorizeURL:    "http://www.tumblr.com/oauth/authorize",
    +    AccessTokenURL:  "http://www.tumblr.com/oauth/access_token",
    +}
    +

    +Endpoint is Tumblr's OAuth 1a endpoint. +

    + + + + + + + + + + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/github.com/dghubble/oauth1/twitter/index.html b/pkg/github.com/dghubble/oauth1/twitter/index.html new file mode 100644 index 0000000..a88c1cb --- /dev/null +++ b/pkg/github.com/dghubble/oauth1/twitter/index.html @@ -0,0 +1,235 @@ + + + + + + + + twitter - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Package twitter

    + + + + + + + + + + + + + + +
    +
    +
    import "github.com/dghubble/oauth1/twitter"
    +
    +
    +
    Overview
    +
    Index
    + + +
    +
    + +
    + +
    +

    Overview ▾

    +

    +Package twitter provides constants for using OAuth1 to access Twitter. +

    + +
    +
    + + +
    + +
    +

    Index ▾

    + + +
    +
    + + +
    Variables
    + + + + +
    +
    + + + + +

    Package files

    +

    + + + twitter.go + + +

    + +
    +
    + + + + + +

    Variables

    + +
    var AuthenticateEndpoint = oauth1.Endpoint{
    +    RequestTokenURL: "https://api.twitter.com/oauth/request_token",
    +    AuthorizeURL:    "https://api.twitter.com/oauth/authenticate",
    +    AccessTokenURL:  "https://api.twitter.com/oauth/access_token",
    +}
    +

    +AuthenticateEndpoint is Twitter's OAuth 1 endpoint which uses the +oauth/authenticate AuthorizeURL redirect. Logged in users who have granted +access are immediately authenticated and redirected to the callback URL. +

    + + +
    var AuthorizeEndpoint = oauth1.Endpoint{
    +    RequestTokenURL: "https://api.twitter.com/oauth/request_token",
    +    AuthorizeURL:    "https://api.twitter.com/oauth/authorize",
    +    AccessTokenURL:  "https://api.twitter.com/oauth/access_token",
    +}
    +

    +AuthorizeEndpoint is Twitter's OAuth 1 endpoint which uses the +oauth/authorize AuthorizeURL redirect. Note that this requires users who +have granted access previously, to re-grant access at AuthorizeURL. +Prefer AuthenticateEndpoint over AuthorizeEndpoint if you are unsure. +

    + + + + + + + + + + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/github.com/dghubble/sling/examples/index.html b/pkg/github.com/dghubble/sling/examples/index.html new file mode 100644 index 0000000..1f3b900 --- /dev/null +++ b/pkg/github.com/dghubble/sling/examples/index.html @@ -0,0 +1,106 @@ + + + + + + + + examples - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Command examples

    + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/github.com/dghubble/sling/index.html b/pkg/github.com/dghubble/sling/index.html new file mode 100644 index 0000000..13986ff --- /dev/null +++ b/pkg/github.com/dghubble/sling/index.html @@ -0,0 +1,858 @@ + + + + + + + + sling - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Package sling

    + + + + + + + + + + + + + + +
    +
    +
    import "github.com/dghubble/sling"
    +
    +
    +
    Overview
    +
    Index
    + + +
    Subdirectories
    + +
    +
    + +
    + +
    +

    Overview ▾

    +

    +Package sling is a Go HTTP client library for creating and sending API requests. +

    +

    +Slings store HTTP Request properties to simplify sending requests and decoding +responses. Check the examples to learn how to compose a Sling into your API +client. +

    +

    Usage

    +

    +Use a Sling to set path, method, header, query, or body properties and create an +http.Request. +

    +
    type Params struct {
    +    Count int `url:"count,omitempty"`
    +}
    +params := &Params{Count: 5}
    +
    +req, err := sling.New().Get("https://example.com").QueryStruct(params).Request()
    +client.Do(req)
    +
    +

    Path

    +

    +Use Path to set or extend the URL for created Requests. Extension means the +path will be resolved relative to the existing URL. +

    +
    // creates a GET request to https://example.com/foo/bar
    +req, err := sling.New().Base("https://example.com/").Path("foo/").Path("bar").Request()
    +
    +

    +Use Get, Post, Put, Patch, Delete, or Head which are exactly the same as Path +except they set the HTTP method too. +

    +
    req, err := sling.New().Post("http://upload.com/gophers")
    +
    +

    Headers

    +

    +Add or Set headers for requests created by a Sling. +

    +
    s := sling.New().Base(baseUrl).Set("User-Agent", "Gophergram API Client")
    +req, err := s.New().Get("gophergram/list").Request()
    +
    +

    QueryStruct

    +

    +Define url parameter structs (https://godoc.org/github.com/google/go-querystring/query). +Use QueryStruct to encode a struct as query parameters on requests. +

    +
    // Github Issue Parameters
    +type IssueParams struct {
    +    Filter    string `url:"filter,omitempty"`
    +    State     string `url:"state,omitempty"`
    +    Labels    string `url:"labels,omitempty"`
    +    Sort      string `url:"sort,omitempty"`
    +    Direction string `url:"direction,omitempty"`
    +    Since     string `url:"since,omitempty"`
    +}
    +
    +githubBase := sling.New().Base("https://api.github.com/").Client(httpClient)
    +
    +path := fmt.Sprintf("repos/%s/%s/issues", owner, repo)
    +params := &IssueParams{Sort: "updated", State: "open"}
    +req, err := githubBase.New().Get(path).QueryStruct(params).Request()
    +
    +

    Json Body

    +

    +Define JSON tagged structs (https://golang.org/pkg/encoding/json/). +Use BodyJSON to JSON encode a struct as the Body on requests. +

    +
    type IssueRequest struct {
    +    Title     string   `json:"title,omitempty"`
    +    Body      string   `json:"body,omitempty"`
    +    Assignee  string   `json:"assignee,omitempty"`
    +    Milestone int      `json:"milestone,omitempty"`
    +    Labels    []string `json:"labels,omitempty"`
    +}
    +
    +githubBase := sling.New().Base("https://api.github.com/").Client(httpClient)
    +path := fmt.Sprintf("repos/%s/%s/issues", owner, repo)
    +
    +body := &IssueRequest{
    +    Title: "Test title",
    +    Body:  "Some issue",
    +}
    +req, err := githubBase.New().Post(path).BodyJSON(body).Request()
    +
    +

    +Requests will include an "application/json" Content-Type header. +

    +

    Form Body

    +

    +Define url tagged structs (https://godoc.org/github.com/google/go-querystring/query). +Use BodyForm to form url encode a struct as the Body on requests. +

    +
    type StatusUpdateParams struct {
    +    Status             string   `url:"status,omitempty"`
    +    InReplyToStatusId  int64    `url:"in_reply_to_status_id,omitempty"`
    +    MediaIds           []int64  `url:"media_ids,omitempty,comma"`
    +}
    +
    +tweetParams := &StatusUpdateParams{Status: "writing some Go"}
    +req, err := twitterBase.New().Post(path).BodyForm(tweetParams).Request()
    +
    +

    +Requests will include an "application/x-www-form-urlencoded" Content-Type +header. +

    +

    Plain Body

    +

    +Use Body to set a plain io.Reader on requests created by a Sling. +

    +
    body := strings.NewReader("raw body")
    +req, err := sling.New().Base("https://example.com").Body(body).Request()
    +
    +

    +Set a content type header, if desired (e.g. Set("Content-Type", "text/plain")). +

    +

    Extend a Sling

    +

    +Each Sling generates an http.Request (say with some path and query params) +each time Request() is called, based on its state. When creating +different slings, you may wish to extend an existing Sling to minimize +duplication (e.g. a common client). +

    +

    +Each Sling instance provides a New() method which creates an independent copy, +so setting properties on the child won't mutate the parent Sling. +

    +
    const twitterApi = "https://api.twitter.com/1.1/"
    +base := sling.New().Base(twitterApi).Client(authClient)
    +
    +// statuses/show.json Sling
    +tweetShowSling := base.New().Get("statuses/show.json").QueryStruct(params)
    +req, err := tweetShowSling.Request()
    +
    +// statuses/update.json Sling
    +tweetPostSling := base.New().Post("statuses/update.json").BodyForm(params)
    +req, err := tweetPostSling.Request()
    +
    +

    +Without the calls to base.New(), tweetShowSling and tweetPostSling would +reference the base Sling and POST to +"https://api.twitter.com/1.1/statuses/show.json/statuses/update.json", which +is undesired. +

    +

    +Recap: If you wish to extend a Sling, create a new child copy with New(). +

    +

    Receive

    +

    +Define a JSON struct to decode a type from 2XX success responses. Use +ReceiveSuccess(successV interface{}) to send a new Request and decode the +response body into successV if it succeeds. +

    +
    // Github Issue (abbreviated)
    +type Issue struct {
    +    Title  string `json:"title"`
    +    Body   string `json:"body"`
    +}
    +
    +issues := new([]Issue)
    +resp, err := githubBase.New().Get(path).QueryStruct(params).ReceiveSuccess(issues)
    +fmt.Println(issues, resp, err)
    +
    +

    +Most APIs return failure responses with JSON error details. To decode these, +define success and failure JSON structs. Use +Receive(successV, failureV interface{}) to send a new Request that will +automatically decode the response into the successV for 2XX responses or into +failureV for non-2XX responses. +

    +
    type GithubError struct {
    +    Message string `json:"message"`
    +    Errors  []struct {
    +        Resource string `json:"resource"`
    +        Field    string `json:"field"`
    +        Code     string `json:"code"`
    +    } `json:"errors"`
    +    DocumentationURL string `json:"documentation_url"`
    +}
    +
    +issues := new([]Issue)
    +githubError := new(GithubError)
    +resp, err := githubBase.New().Get(path).QueryStruct(params).Receive(issues, githubError)
    +fmt.Println(issues, githubError, resp, err)
    +
    +

    +Pass a nil successV or failureV argument to skip JSON decoding into that value. +

    + +
    +
    + + +
    + +
    +

    Index ▾

    + + + + + + + +

    Package files

    +

    + + + doc.go + + sling.go + + +

    + +
    +
    + + + + + + + + + +

    type Doer

    +
    type Doer interface {
    +    Do(req *http.Request) (*http.Response, error)
    +}
    +

    +Doer executes http requests. It is implemented by *http.Client. You can +wrap *http.Client with layers of Doers to form a stack of client-side +middleware. +

    + + + + + + + + + + + + + + + + +

    type Sling

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

    +Sling is an HTTP Request builder and sender. +

    + + + + + + + + + + + + +

    func New

    +
    func New() *Sling
    +

    +New returns a new Sling with an http DefaultClient. +

    + + + + + + + +

    func (*Sling) Add

    +
    func (s *Sling) Add(key, value string) *Sling
    +

    +Add adds the key, value pair in Headers, appending values for existing keys +to the key's values. Header keys are canonicalized. +

    + + + + + + +

    func (*Sling) Base

    +
    func (s *Sling) Base(rawURL string) *Sling
    +

    +Base sets the rawURL. If you intend to extend the url with Path, +baseUrl should be specified with a trailing slash. +

    + + + + + + +

    func (*Sling) Body

    +
    func (s *Sling) Body(body io.Reader) *Sling
    +

    +Body sets the Sling's body. The body value will be set as the Body on new +requests (see Request()). +If the provided body is also an io.Closer, the request Body will be closed +by http.Client methods. +

    + + + + + + +

    func (*Sling) BodyForm

    +
    func (s *Sling) BodyForm(bodyForm interface{}) *Sling
    +

    +BodyForm sets the Sling's bodyForm. The value pointed to by the bodyForm +will be url encoded as the Body on new requests (see Request()). +The bodyStruct argument should be a pointer to a url tagged struct. See +https://godoc.org/github.com/google/go-querystring/query for details. +

    + + + + + + +

    func (*Sling) BodyJSON

    +
    func (s *Sling) BodyJSON(bodyJSON interface{}) *Sling
    +

    +BodyJSON sets the Sling's bodyJSON. The value pointed to by the bodyJSON +will be JSON encoded as the Body on new requests (see Request()). +The bodyJSON argument should be a pointer to a JSON tagged struct. See +https://golang.org/pkg/encoding/json/#MarshalIndent for details. +

    + + + + + + +

    func (*Sling) Client

    +
    func (s *Sling) Client(httpClient *http.Client) *Sling
    +

    +Client sets the http Client used to do requests. If a nil client is given, +the http.DefaultClient will be used. +

    + + + + + + +

    func (*Sling) Delete

    +
    func (s *Sling) Delete(pathURL string) *Sling
    +

    +Delete sets the Sling method to DELETE and sets the given pathURL. +

    + + + + + + +

    func (*Sling) Do

    +
    func (s *Sling) Do(req *http.Request, successV, failureV interface{}) (*http.Response, error)
    +

    +Do sends an HTTP request and returns the response. Success responses (2XX) +are JSON decoded into the value pointed to by successV and other responses +are JSON decoded into the value pointed to by failureV. +Any error sending the request or decoding the response is returned. +

    + + + + + + +

    func (*Sling) Doer

    +
    func (s *Sling) Doer(doer Doer) *Sling
    +

    +Doer sets the custom Doer implementation used to do requests. +If a nil client is given, the http.DefaultClient will be used. +

    + + + + + + +

    func (*Sling) Get

    +
    func (s *Sling) Get(pathURL string) *Sling
    +

    +Get sets the Sling method to GET and sets the given pathURL. +

    + + + + + + +

    func (*Sling) Head

    +
    func (s *Sling) Head(pathURL string) *Sling
    +

    +Head sets the Sling method to HEAD and sets the given pathURL. +

    + + + + + + +

    func (*Sling) New

    +
    func (s *Sling) New() *Sling
    +

    +New returns a copy of a Sling for creating a new Sling with properties +from a parent Sling. For example, +

    +
    parentSling := sling.New().Client(client).Base("https://api.io/")
    +fooSling := parentSling.New().Get("foo/")
    +barSling := parentSling.New().Get("bar/")
    +
    +

    +fooSling and barSling will both use the same client, but send requests to +https://api.io/foo/ and https://api.io/bar/ respectively. +

    +

    +Note that query and body values are copied so if pointer values are used, +mutating the original value will mutate the value within the child Sling. +

    + + + + + + +

    func (*Sling) Patch

    +
    func (s *Sling) Patch(pathURL string) *Sling
    +

    +Patch sets the Sling method to PATCH and sets the given pathURL. +

    + + + + + + +

    func (*Sling) Path

    +
    func (s *Sling) Path(path string) *Sling
    +

    +Path extends the rawURL with the given path by resolving the reference to +an absolute URL. If parsing errors occur, the rawURL is left unmodified. +

    + + + + + + +

    func (*Sling) Post

    +
    func (s *Sling) Post(pathURL string) *Sling
    +

    +Post sets the Sling method to POST and sets the given pathURL. +

    + + + + + + +

    func (*Sling) Put

    +
    func (s *Sling) Put(pathURL string) *Sling
    +

    +Put sets the Sling method to PUT and sets the given pathURL. +

    + + + + + + +

    func (*Sling) QueryStruct

    +
    func (s *Sling) QueryStruct(queryStruct interface{}) *Sling
    +

    +QueryStruct appends the queryStruct to the Sling's queryStructs. The value +pointed to by each queryStruct will be encoded as url query parameters on +new requests (see Request()). +The queryStruct argument should be a pointer to a url tagged struct. See +https://godoc.org/github.com/google/go-querystring/query for details. +

    + + + + + + +

    func (*Sling) Receive

    +
    func (s *Sling) Receive(successV, failureV interface{}) (*http.Response, error)
    +

    +Receive creates a new HTTP request and returns the response. Success +responses (2XX) are JSON decoded into the value pointed to by successV and +other responses are JSON decoded into the value pointed to by failureV. +Any error creating the request, sending it, or decoding the response is +returned. +Receive is shorthand for calling Request and Do. +

    + + + + + + +

    func (*Sling) ReceiveSuccess

    +
    func (s *Sling) ReceiveSuccess(successV interface{}) (*http.Response, error)
    +

    +ReceiveSuccess creates a new HTTP request and returns the response. Success +responses (2XX) are JSON decoded into the value pointed to by successV. +Any error creating the request, sending it, or decoding a 2XX response +is returned. +

    + + + + + + +

    func (*Sling) Request

    +
    func (s *Sling) Request() (*http.Request, error)
    +

    +Request returns a new http.Request created with the Sling properties. +Returns any errors parsing the rawURL, encoding query structs, encoding +the body, or creating the http.Request. +

    + + + + + + +

    func (*Sling) Set

    +
    func (s *Sling) Set(key, value string) *Sling
    +

    +Set sets the key, value pair in Headers, replacing existing values +associated with key. Header keys are canonicalized. +

    + + + + + + +

    func (*Sling) SetBasicAuth

    +
    func (s *Sling) SetBasicAuth(username, password string) *Sling
    +

    +SetBasicAuth sets the Authorization header to use HTTP Basic Authentication +with the provided username and password. With HTTP Basic Authentication +the provided username and password are not encrypted. +

    + + + + + + + + + + + + + + + + +

    Subdirectories

    + + + + +
    + + + + + + + + + + + + + + + + + + + + +
    NameSynopsis
    ..
    + examples + + +
    +
    + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/github.com/die-net/index.html b/pkg/github.com/die-net/index.html new file mode 100644 index 0000000..01a0944 --- /dev/null +++ b/pkg/github.com/die-net/index.html @@ -0,0 +1,141 @@ + + + + + + + + /src/github.com/die-net - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Directory /src/github.com/die-net

    + + + + + + + + + + + + + + + + + + + +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    NameSynopsis
    ..
    + lrucache + + Package lrucache provides a byte-size-limited implementation of httpcache.Cache that stores data in memory. +
    + twotier + + Package twotier provides a wrapper for two httpcache.Cache instances, allowing you to use both a small and fast cache for popular objects and fall back to a larger and slower cache for less popular ones. +
    +
    + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/github.com/die-net/lrucache/index.html b/pkg/github.com/die-net/lrucache/index.html new file mode 100644 index 0000000..a6d0ea1 --- /dev/null +++ b/pkg/github.com/die-net/lrucache/index.html @@ -0,0 +1,351 @@ + + + + + + + + lrucache - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Package lrucache

    + + + + + + + + + + + + + + +
    +
    +
    import "github.com/die-net/lrucache"
    +
    +
    +
    Overview
    +
    Index
    + + +
    Subdirectories
    + +
    +
    + +
    + +
    +

    Overview ▾

    +

    +Package lrucache provides a byte-size-limited implementation of +httpcache.Cache that stores data in memory. +

    + +
    +
    + + +
    + + +
    + + + + + + + + + +

    type LruCache

    +
    type LruCache struct {
    +    MaxSize int64
    +    MaxAge  int64
    +    // contains filtered or unexported fields
    +}
    +

    +LruCache is a thread-safe, in-memory httpcache.Cache that evicts the +least recently used entries from memory when either MaxSize (in bytes) +limit would be exceeded or (if set) the entries are older than MaxAge (in +seconds). Use the New constructor to create one. +

    + + + + + + + + + + + + +

    func New

    +
    func New(maxSize int64, maxAge int64) *LruCache
    +

    +New creates an LruCache that will restrict itself to maxSize bytes of +memory. If maxAge > 0, entries will also be expired after maxAge +seconds. +

    + + + + + + + +

    func (*LruCache) Delete

    +
    func (c *LruCache) Delete(key string)
    +

    +Delete removes the value associated with a key. +

    + + + + + + +

    func (*LruCache) Get

    +
    func (c *LruCache) Get(key string) ([]byte, bool)
    +

    +Get returns the []byte representation of a cached response and a bool +set to true if the key was found. +

    + + + + + + +

    func (*LruCache) Set

    +
    func (c *LruCache) Set(key string, value []byte)
    +

    +Set stores the []byte representation of a response for a given key. +

    + + + + + + +

    func (*LruCache) Size

    +
    func (c *LruCache) Size() int64
    +

    +Size returns the estimated current memory usage of LruCache. +

    + + + + + + + + + + + + + + + + +

    Subdirectories

    + + + + +
    + + + + + + + + + + + + + + + + + + + + +
    NameSynopsis
    ..
    + twotier + + Package twotier provides a wrapper for two httpcache.Cache instances, allowing you to use both a small and fast cache for popular objects and fall back to a larger and slower cache for less popular ones. +
    +
    + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/github.com/die-net/lrucache/twotier/index.html b/pkg/github.com/die-net/lrucache/twotier/index.html new file mode 100644 index 0000000..03e9111 --- /dev/null +++ b/pkg/github.com/die-net/lrucache/twotier/index.html @@ -0,0 +1,297 @@ + + + + + + + + twotier - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Package twotier

    + + + + + + + + + + + + + + +
    +
    +
    import "github.com/die-net/lrucache/twotier"
    +
    +
    +
    Overview
    +
    Index
    + + +
    +
    + +
    + +
    +

    Overview ▾

    +

    +Package twotier provides a wrapper for two httpcache.Cache instances, +allowing you to use both a small and fast cache for popular objects and +fall back to a larger and slower cache for less popular ones. +

    + +
    +
    + + +
    + + +
    + + + + + + + + + +

    type TwoTier

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

    +TwoTier creates a two-tiered cache out of two httpcache.Cache instances. +Reads are favored from first, and writes affect both first and second. +

    + + + + + + + + + + + + +

    func New

    +
    func New(first httpcache.Cache, second httpcache.Cache) *TwoTier
    +

    +New creates a TwoTier. Both first and second must be non-nil. +

    + + + + + + + +

    func (*TwoTier) Delete

    +
    func (c *TwoTier) Delete(key string)
    +

    +Delete removes the value associated with a key from both the first and +second tier caches. +

    + + + + + + +

    func (*TwoTier) Get

    +
    func (c *TwoTier) Get(key string) ([]byte, bool)
    +

    +Get returns the []byte representation of a cached response and a bool set +to true if the key was found. It tries the first tier cache, and if +that's not successful, copies the result from the second tier into the +first tier. +

    + + + + + + +

    func (*TwoTier) Set

    +
    func (c *TwoTier) Set(key string, value []byte)
    +

    +Set stores the []byte representation of a response for a given key into +the second tier cache, and deletes the cache entry from the first tier +cache. +

    + + + + + + + + + + + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/github.com/garyburd/index.html b/pkg/github.com/garyburd/index.html new file mode 100644 index 0000000..4b2eda5 --- /dev/null +++ b/pkg/github.com/garyburd/index.html @@ -0,0 +1,141 @@ + + + + + + + + /src/github.com/garyburd - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Directory /src/github.com/garyburd

    + + + + + + + + + + + + + + + + + + + +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    NameSynopsis
    ..
    + redigo + + +
    + redis + + Package redis is a client for the Redis database. +
    +
    + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/github.com/garyburd/redigo/index.html b/pkg/github.com/garyburd/redigo/index.html new file mode 100644 index 0000000..233c36b --- /dev/null +++ b/pkg/github.com/garyburd/redigo/index.html @@ -0,0 +1,130 @@ + + + + + + + + /src/github.com/garyburd/redigo - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Directory /src/github.com/garyburd/redigo

    + + + + + + + + + + + + + + + + + + + +
    + + + + + + + + + + + + + + + + + + + + +
    NameSynopsis
    ..
    + redis + + Package redis is a client for the Redis database. +
    +
    + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/github.com/garyburd/redigo/redis/index.html b/pkg/github.com/garyburd/redigo/redis/index.html new file mode 100644 index 0000000..9c8c0e2 --- /dev/null +++ b/pkg/github.com/garyburd/redigo/redis/index.html @@ -0,0 +1,2264 @@ + + + + + + + + redis - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Package redis

    + + + + + + + + + + + + + + +
    +
    +
    import "github.com/garyburd/redigo/redis"
    +
    +
    +
    Overview
    +
    Index
    + +
    Examples
    + + +
    +
    + +
    + +
    +

    Overview ▾

    +

    +Package redis is a client for the Redis database. +

    +

    +The Redigo FAQ (https://github.com/garyburd/redigo/wiki/FAQ) contains more +documentation about this package. +

    +

    Connections

    +

    +The Conn interface is the primary interface for working with Redis. +Applications create connections by calling the Dial, DialWithTimeout or +NewConn functions. In the future, functions will be added for creating +sharded and other types of connections. +

    +

    +The application must call the connection Close method when the application +is done with the connection. +

    +

    Executing Commands

    +

    +The Conn interface has a generic method for executing Redis commands: +

    +
    Do(commandName string, args ...interface{}) (reply interface{}, err error)
    +
    +

    +The Redis command reference (http://redis.io/commands) lists the available +commands. An example of using the Redis APPEND command is: +

    +
    n, err := conn.Do("APPEND", "key", "value")
    +
    +

    +The Do method converts command arguments to binary strings for transmission +to the server as follows: +

    +
    Go Type                 Conversion
    +[]byte                  Sent as is
    +string                  Sent as is
    +int, int64              strconv.FormatInt(v)
    +float64                 strconv.FormatFloat(v, 'g', -1, 64)
    +bool                    true -> "1", false -> "0"
    +nil                     ""
    +all other types         fmt.Print(v)
    +
    +

    +Redis command reply types are represented using the following Go types: +

    +
    Redis type              Go type
    +error                   redis.Error
    +integer                 int64
    +simple string           string
    +bulk string             []byte or nil if value not present.
    +array                   []interface{} or nil if value not present.
    +
    +

    +Use type assertions or the reply helper functions to convert from +interface{} to the specific Go type for the command result. +

    +

    Pipelining

    +

    +Connections support pipelining using the Send, Flush and Receive methods. +

    +
    Send(commandName string, args ...interface{}) error
    +Flush() error
    +Receive() (reply interface{}, err error)
    +
    +

    +Send writes the command to the connection's output buffer. Flush flushes the +connection's output buffer to the server. Receive reads a single reply from +the server. The following example shows a simple pipeline. +

    +
    c.Send("SET", "foo", "bar")
    +c.Send("GET", "foo")
    +c.Flush()
    +c.Receive() // reply from SET
    +v, err = c.Receive() // reply from GET
    +
    +

    +The Do method combines the functionality of the Send, Flush and Receive +methods. The Do method starts by writing the command and flushing the output +buffer. Next, the Do method receives all pending replies including the reply +for the command just sent by Do. If any of the received replies is an error, +then Do returns the error. If there are no errors, then Do returns the last +reply. If the command argument to the Do method is "", then the Do method +will flush the output buffer and receive pending replies without sending a +command. +

    +

    +Use the Send and Do methods to implement pipelined transactions. +

    +
    c.Send("MULTI")
    +c.Send("INCR", "foo")
    +c.Send("INCR", "bar")
    +r, err := c.Do("EXEC")
    +fmt.Println(r) // prints [1, 1]
    +
    +

    Concurrency

    +

    +Connections support one concurrent caller to the Receive method and one +concurrent caller to the Send and Flush methods. No other concurrency is +supported including concurrent calls to the Do method. +

    +

    +For full concurrent access to Redis, use the thread-safe Pool to get, use +and release a connection from within a goroutine. Connections returned from +a Pool have the concurrency restrictions described in the previous +paragraph. +

    +

    Publish and Subscribe

    +

    +Use the Send, Flush and Receive methods to implement Pub/Sub subscribers. +

    +
    c.Send("SUBSCRIBE", "example")
    +c.Flush()
    +for {
    +    reply, err := c.Receive()
    +    if err != nil {
    +        return err
    +    }
    +    // process pushed message
    +}
    +
    +

    +The PubSubConn type wraps a Conn with convenience methods for implementing +subscribers. The Subscribe, PSubscribe, Unsubscribe and PUnsubscribe methods +send and flush a subscription management command. The receive method +converts a pushed message to convenient types for use in a type switch. +

    +
    psc := redis.PubSubConn{c}
    +psc.Subscribe("example")
    +for {
    +    switch v := psc.Receive().(type) {
    +    case redis.Message:
    +        fmt.Printf("%s: message: %s\n", v.Channel, v.Data)
    +    case redis.Subscription:
    +        fmt.Printf("%s: %s %d\n", v.Channel, v.Kind, v.Count)
    +    case error:
    +        return v
    +    }
    +}
    +
    +

    Reply Helpers

    +

    +The Bool, Int, Bytes, String, Strings and Values functions convert a reply +to a value of a specific type. To allow convenient wrapping of calls to the +connection Do and Receive methods, the functions take a second argument of +type error. If the error is non-nil, then the helper function returns the +error. If the error is nil, the function converts the reply to the specified +type: +

    +
    exists, err := redis.Bool(c.Do("EXISTS", "foo"))
    +if err != nil {
    +    // handle error return from c.Do or type conversion error.
    +}
    +
    +

    +The Scan function converts elements of a array reply to Go types: +

    +
    var value1 int
    +var value2 string
    +reply, err := redis.Values(c.Do("MGET", "key1", "key2"))
    +if err != nil {
    +    // handle error
    +}
    + if _, err := redis.Scan(reply, &value1, &value2); err != nil {
    +    // handle error
    +}
    +
    + +
    +
    +
    + +
    +

    Example (Zpop)

    +

    This example implements ZPOP as described at +http://redis.io/topics/transactions using WATCH/MULTI/EXEC and scripting. +

    + + +

    Code:

    +
    package redis_test
    +
    +import (
    +    "fmt"
    +    "github.com/garyburd/redigo/redis"
    +)
    +
    +// zpop pops a value from the ZSET key using WATCH/MULTI/EXEC commands.
    +func zpop(c redis.Conn, key string) (result string, err error) {
    +
    +    defer func() {
    +        // Return connection to normal state on error.
    +        if err != nil {
    +            c.Do("DISCARD")
    +        }
    +    }()
    +
    +    // Loop until transaction is successful.
    +    for {
    +        if _, err := c.Do("WATCH", key); err != nil {
    +            return "", err
    +        }
    +
    +        members, err := redis.Strings(c.Do("ZRANGE", key, 0, 0))
    +        if err != nil {
    +            return "", err
    +        }
    +        if len(members) != 1 {
    +            return "", redis.ErrNil
    +        }
    +
    +        c.Send("MULTI")
    +        c.Send("ZREM", key, members[0])
    +        queued, err := c.Do("EXEC")
    +        if err != nil {
    +            return "", err
    +        }
    +
    +        if queued != nil {
    +            result = members[0]
    +            break
    +        }
    +    }
    +
    +    return result, nil
    +}
    +
    +// zpopScript pops a value from a ZSET.
    +var zpopScript = redis.NewScript(1, `
    +    local r = redis.call('ZRANGE', KEYS[1], 0, 0)
    +    if r ~= nil then
    +        r = r[1]
    +        redis.call('ZREM', KEYS[1], r)
    +    end
    +    return r
    +`)
    +
    +// This example implements ZPOP as described at
    +// http://redis.io/topics/transactions using WATCH/MULTI/EXEC and scripting.
    +func Example_zpop() {
    +    c, err := dial()
    +    if err != nil {
    +        fmt.Println(err)
    +        return
    +    }
    +    defer c.Close()
    +
    +    // Add test data using a pipeline.
    +
    +    for i, member := range []string{"red", "blue", "green"} {
    +        c.Send("ZADD", "zset", i, member)
    +    }
    +    if _, err := c.Do(""); err != nil {
    +        fmt.Println(err)
    +        return
    +    }
    +
    +    // Pop using WATCH/MULTI/EXEC
    +
    +    v, err := zpop(c, "zset")
    +    if err != nil {
    +        fmt.Println(err)
    +        return
    +    }
    +    fmt.Println(v)
    +
    +    // Pop using a script.
    +
    +    v, err = redis.String(zpopScript.Do(c, "zset"))
    +    if err != nil {
    +        fmt.Println(err)
    +        return
    +    }
    +    fmt.Println(v)
    +
    +    // Output:
    +    // red
    +    // blue
    +}
    +
    + + +
    +
    + + +
    + +
    +

    Index ▾

    + + +
    +
    + + +
    Variables
    + + + +
    func Bool(reply interface{}, err error) (bool, error)
    + + +
    func ByteSlices(reply interface{}, err error) ([][]byte, error)
    + + +
    func Bytes(reply interface{}, err error) ([]byte, error)
    + + +
    func Float64(reply interface{}, err error) (float64, error)
    + + +
    func Int(reply interface{}, err error) (int, error)
    + + +
    func Int64(reply interface{}, err error) (int64, error)
    + + +
    func Int64Map(result interface{}, err error) (map[string]int64, error)
    + + +
    func IntMap(result interface{}, err error) (map[string]int, error)
    + + +
    func Ints(reply interface{}, err error) ([]int, error)
    + + +
    func MultiBulk(reply interface{}, err error) ([]interface{}, error)
    + + +
    func Scan(src []interface{}, dest ...interface{}) ([]interface{}, error)
    + + +
    func ScanSlice(src []interface{}, dest interface{}, fieldNames ...string) error
    + + +
    func ScanStruct(src []interface{}, dest interface{}) error
    + + +
    func String(reply interface{}, err error) (string, error)
    + + +
    func StringMap(result interface{}, err error) (map[string]string, error)
    + + +
    func Strings(reply interface{}, err error) ([]string, error)
    + + +
    func Uint64(reply interface{}, err error) (uint64, error)
    + + +
    func Values(reply interface{}, err error) ([]interface{}, error)
    + + + +
    type Args
    + + + +
        func (args Args) Add(value ...interface{}) Args
    + + +
        func (args Args) AddFlat(v interface{}) Args
    + + + +
    type Conn
    + + +
        func Dial(network, address string, options ...DialOption) (Conn, error)
    + + +
        func DialTimeout(network, address string, connectTimeout, readTimeout, writeTimeout time.Duration) (Conn, error)
    + + +
        func DialURL(rawurl string, options ...DialOption) (Conn, error)
    + + +
        func NewConn(netConn net.Conn, readTimeout, writeTimeout time.Duration) Conn
    + + +
        func NewLoggingConn(conn Conn, logger *log.Logger, prefix string) Conn
    + + + + +
    type DialOption
    + + +
        func DialConnectTimeout(d time.Duration) DialOption
    + + +
        func DialDatabase(db int) DialOption
    + + +
        func DialNetDial(dial func(network, addr string) (net.Conn, error)) DialOption
    + + +
        func DialPassword(password string) DialOption
    + + +
        func DialReadTimeout(d time.Duration) DialOption
    + + +
        func DialWriteTimeout(d time.Duration) DialOption
    + + + + +
    type Error
    + + + +
        func (err Error) Error() string
    + + + +
    type Message
    + + + + +
    type PMessage
    + + + + +
    type Pong
    + + + + +
    type Pool
    + + +
        func NewPool(newFn func() (Conn, error), maxIdle int) *Pool
    + + + +
        func (p *Pool) ActiveCount() int
    + + +
        func (p *Pool) Close() error
    + + +
        func (p *Pool) Get() Conn
    + + + +
    type PubSubConn
    + + + +
        func (c PubSubConn) Close() error
    + + +
        func (c PubSubConn) PSubscribe(channel ...interface{}) error
    + + +
        func (c PubSubConn) PUnsubscribe(channel ...interface{}) error
    + + +
        func (c PubSubConn) Ping(data string) error
    + + +
        func (c PubSubConn) Receive() interface{}
    + + +
        func (c PubSubConn) Subscribe(channel ...interface{}) error
    + + +
        func (c PubSubConn) Unsubscribe(channel ...interface{}) error
    + + + +
    type Script
    + + +
        func NewScript(keyCount int, src string) *Script
    + + + +
        func (s *Script) Do(c Conn, keysAndArgs ...interface{}) (interface{}, error)
    + + +
        func (s *Script) Load(c Conn) error
    + + +
        func (s *Script) Send(c Conn, keysAndArgs ...interface{}) error
    + + +
        func (s *Script) SendHash(c Conn, keysAndArgs ...interface{}) error
    + + + +
    type Subscription
    + + + + +
    +
    + + +
    +

    Examples

    +
    + +
    Args
    + +
    Bool
    + +
    Dial
    + +
    DialURL
    + +
    Int
    + +
    Ints
    + +
    PubSubConn
    + +
    Scan
    + +
    ScanSlice
    + +
    Script
    + +
    String
    + +
    Package (Zpop)
    + +
    +
    + + + +

    Package files

    +

    + + + conn.go + + doc.go + + log.go + + pool.go + + pubsub.go + + redis.go + + reply.go + + scan.go + + script.go + + +

    + +
    +
    + + + + + +

    Variables

    + +
    var ErrNil = errors.New("redigo: nil returned")
    +

    +ErrNil indicates that a reply value is nil. +

    + + +
    var ErrPoolExhausted = errors.New("redigo: connection pool exhausted")
    +

    +ErrPoolExhausted is returned from a pool connection method (Do, Send, +Receive, Flush, Err) when the maximum number of database connections in the +pool has been reached. +

    + + + + + + +

    func Bool

    +
    func Bool(reply interface{}, err error) (bool, error)
    +

    +Bool is a helper that converts a command reply to a boolean. If err is not +equal to nil, then Bool returns false, err. Otherwise Bool converts the +reply to boolean as follows: +

    +
    Reply type      Result
    +integer         value != 0, nil
    +bulk string     strconv.ParseBool(reply)
    +nil             false, ErrNil
    +other           false, error
    +
    + +
    + +
    +

    Example

    + + + +

    Code:

    +
    c, err := dial()
    +if err != nil {
    +    fmt.Println(err)
    +    return
    +}
    +defer c.Close()
    +
    +c.Do("SET", "foo", 1)
    +exists, _ := redis.Bool(c.Do("EXISTS", "foo"))
    +fmt.Printf("%#v\n", exists)
    +
    + +

    Output:

    +
    true
    +
    + + +
    +
    + + + + + + +

    func ByteSlices

    +
    func ByteSlices(reply interface{}, err error) ([][]byte, error)
    +

    +ByteSlices is a helper that converts an array command reply to a [][]byte. +If err is not equal to nil, then ByteSlices returns nil, err. Nil array +items are stay nil. ByteSlices returns an error if an array item is not a +bulk string or nil. +

    + + + + + + + +

    func Bytes

    +
    func Bytes(reply interface{}, err error) ([]byte, error)
    +

    +Bytes is a helper that converts a command reply to a slice of bytes. If err +is not equal to nil, then Bytes returns nil, err. Otherwise Bytes converts +the reply to a slice of bytes as follows: +

    +
    Reply type      Result
    +bulk string     reply, nil
    +simple string   []byte(reply), nil
    +nil             nil, ErrNil
    +other           nil, error
    +
    + + + + + + + +

    func Float64

    +
    func Float64(reply interface{}, err error) (float64, error)
    +

    +Float64 is a helper that converts a command reply to 64 bit float. If err is +not equal to nil, then Float64 returns 0, err. Otherwise, Float64 converts +the reply to an int as follows: +

    +
    Reply type    Result
    +bulk string   parsed reply, nil
    +nil           0, ErrNil
    +other         0, error
    +
    + + + + + + + +

    func Int

    +
    func Int(reply interface{}, err error) (int, error)
    +

    +Int is a helper that converts a command reply to an integer. If err is not +equal to nil, then Int returns 0, err. Otherwise, Int converts the +reply to an int as follows: +

    +
    Reply type    Result
    +integer       int(reply), nil
    +bulk string   parsed reply, nil
    +nil           0, ErrNil
    +other         0, error
    +
    + +
    + +
    +

    Example

    + + + +

    Code:

    +
    c, err := dial()
    +if err != nil {
    +    fmt.Println(err)
    +    return
    +}
    +defer c.Close()
    +
    +c.Do("SET", "k1", 1)
    +n, _ := redis.Int(c.Do("GET", "k1"))
    +fmt.Printf("%#v\n", n)
    +n, _ = redis.Int(c.Do("INCR", "k1"))
    +fmt.Printf("%#v\n", n)
    +
    + +

    Output:

    +
    1
    +2
    +
    + + +
    +
    + + + + + + +

    func Int64

    +
    func Int64(reply interface{}, err error) (int64, error)
    +

    +Int64 is a helper that converts a command reply to 64 bit integer. If err is +not equal to nil, then Int returns 0, err. Otherwise, Int64 converts the +reply to an int64 as follows: +

    +
    Reply type    Result
    +integer       reply, nil
    +bulk string   parsed reply, nil
    +nil           0, ErrNil
    +other         0, error
    +
    + + + + + + + +

    func Int64Map

    +
    func Int64Map(result interface{}, err error) (map[string]int64, error)
    +

    +Int64Map is a helper that converts an array of strings (alternating key, value) +into a map[string]int64. The HGETALL commands return replies in this format. +Requires an even number of values in result. +

    + + + + + + + +

    func IntMap

    +
    func IntMap(result interface{}, err error) (map[string]int, error)
    +

    +IntMap is a helper that converts an array of strings (alternating key, value) +into a map[string]int. The HGETALL commands return replies in this format. +Requires an even number of values in result. +

    + + + + + + + +

    func Ints

    +
    func Ints(reply interface{}, err error) ([]int, error)
    +

    +Ints is a helper that converts an array command reply to a []int. If +err is not equal to nil, then Ints returns nil, err. +

    + +
    + +
    +

    Example

    + + + +

    Code:

    +
    c, err := dial()
    +if err != nil {
    +    fmt.Println(err)
    +    return
    +}
    +defer c.Close()
    +
    +c.Do("SADD", "set_with_integers", 4, 5, 6)
    +ints, _ := redis.Ints(c.Do("SMEMBERS", "set_with_integers"))
    +fmt.Printf("%#v\n", ints)
    +
    + +

    Output:

    +
    []int{4, 5, 6}
    +
    + + +
    +
    + + + + + + +

    func MultiBulk

    +
    func MultiBulk(reply interface{}, err error) ([]interface{}, error)
    +

    +MultiBulk is a helper that converts an array command reply to a []interface{}. +

    +

    +Deprecated: Use Values instead. +

    + + + + + + + +

    func Scan

    +
    func Scan(src []interface{}, dest ...interface{}) ([]interface{}, error)
    +

    +Scan copies from src to the values pointed at by dest. +

    +

    +The values pointed at by dest must be an integer, float, boolean, string, +[]byte, interface{} or slices of these types. Scan uses the standard strconv +package to convert bulk strings to numeric and boolean types. +

    +

    +If a dest value is nil, then the corresponding src value is skipped. +

    +

    +If a src element is nil, then the corresponding dest value is not modified. +

    +

    +To enable easy use of Scan in a loop, Scan returns the slice of src +following the copied values. +

    + +
    + +
    +

    Example

    + + + +

    Code:

    +
    c, err := dial()
    +if err != nil {
    +    fmt.Println(err)
    +    return
    +}
    +defer c.Close()
    +
    +c.Send("HMSET", "album:1", "title", "Red", "rating", 5)
    +c.Send("HMSET", "album:2", "title", "Earthbound", "rating", 1)
    +c.Send("HMSET", "album:3", "title", "Beat")
    +c.Send("LPUSH", "albums", "1")
    +c.Send("LPUSH", "albums", "2")
    +c.Send("LPUSH", "albums", "3")
    +values, err := redis.Values(c.Do("SORT", "albums",
    +    "BY", "album:*->rating",
    +    "GET", "album:*->title",
    +    "GET", "album:*->rating"))
    +if err != nil {
    +    fmt.Println(err)
    +    return
    +}
    +
    +for len(values) > 0 {
    +    var title string
    +    rating := -1 // initialize to illegal value to detect nil.
    +    values, err = redis.Scan(values, &title, &rating)
    +    if err != nil {
    +        fmt.Println(err)
    +        return
    +    }
    +    if rating == -1 {
    +        fmt.Println(title, "not-rated")
    +    } else {
    +        fmt.Println(title, rating)
    +    }
    +}
    +
    + +

    Output:

    +
    Beat not-rated
    +Earthbound 1
    +Red 5
    +
    + + +
    +
    + + + + + + +

    func ScanSlice

    +
    func ScanSlice(src []interface{}, dest interface{}, fieldNames ...string) error
    +

    +ScanSlice scans src to the slice pointed to by dest. The elements the dest +slice must be integer, float, boolean, string, struct or pointer to struct +values. +

    +

    +Struct fields must be integer, float, boolean or string values. All struct +fields are used unless a subset is specified using fieldNames. +

    + +
    + +
    +

    Example

    + + + +

    Code:

    +
    c, err := dial()
    +if err != nil {
    +    fmt.Println(err)
    +    return
    +}
    +defer c.Close()
    +
    +c.Send("HMSET", "album:1", "title", "Red", "rating", 5)
    +c.Send("HMSET", "album:2", "title", "Earthbound", "rating", 1)
    +c.Send("HMSET", "album:3", "title", "Beat", "rating", 4)
    +c.Send("LPUSH", "albums", "1")
    +c.Send("LPUSH", "albums", "2")
    +c.Send("LPUSH", "albums", "3")
    +values, err := redis.Values(c.Do("SORT", "albums",
    +    "BY", "album:*->rating",
    +    "GET", "album:*->title",
    +    "GET", "album:*->rating"))
    +if err != nil {
    +    fmt.Println(err)
    +    return
    +}
    +
    +var albums []struct {
    +    Title  string
    +    Rating int
    +}
    +if err := redis.ScanSlice(values, &albums); err != nil {
    +    fmt.Println(err)
    +    return
    +}
    +fmt.Printf("%v\n", albums)
    +
    + +

    Output:

    +
    [{Earthbound 1} {Beat 4} {Red 5}]
    +
    + + +
    +
    + + + + + + +

    func ScanStruct

    +
    func ScanStruct(src []interface{}, dest interface{}) error
    +

    +ScanStruct scans alternating names and values from src to a struct. The +HGETALL and CONFIG GET commands return replies in this format. +

    +

    +ScanStruct uses exported field names to match values in the response. Use +'redis' field tag to override the name: +

    +
    Field int `redis:"myName"`
    +
    +

    +Fields with the tag redis:"-" are ignored. +

    +

    +Integer, float, boolean, string and []byte fields are supported. Scan uses the +standard strconv package to convert bulk string values to numeric and +boolean types. +

    +

    +If a src element is nil, then the corresponding field is not modified. +

    + + + + + + + +

    func String

    +
    func String(reply interface{}, err error) (string, error)
    +

    +String is a helper that converts a command reply to a string. If err is not +equal to nil, then String returns "", err. Otherwise String converts the +reply to a string as follows: +

    +
    Reply type      Result
    +bulk string     string(reply), nil
    +simple string   reply, nil
    +nil             "",  ErrNil
    +other           "",  error
    +
    + +
    + +
    +

    Example

    + + + +

    Code:

    +
    c, err := dial()
    +if err != nil {
    +    fmt.Println(err)
    +    return
    +}
    +defer c.Close()
    +
    +c.Do("SET", "hello", "world")
    +s, err := redis.String(c.Do("GET", "hello"))
    +fmt.Printf("%#v\n", s)
    +
    + +

    Output:

    +
    "world"
    +
    + + +
    +
    + + + + + + +

    func StringMap

    +
    func StringMap(result interface{}, err error) (map[string]string, error)
    +

    +StringMap is a helper that converts an array of strings (alternating key, value) +into a map[string]string. The HGETALL and CONFIG GET commands return replies in this format. +Requires an even number of values in result. +

    + + + + + + + +

    func Strings

    +
    func Strings(reply interface{}, err error) ([]string, error)
    +

    +Strings is a helper that converts an array command reply to a []string. If +err is not equal to nil, then Strings returns nil, err. Nil array items are +converted to "" in the output slice. Strings returns an error if an array +item is not a bulk string or nil. +

    + + + + + + + +

    func Uint64

    +
    func Uint64(reply interface{}, err error) (uint64, error)
    +

    +Uint64 is a helper that converts a command reply to 64 bit integer. If err is +not equal to nil, then Int returns 0, err. Otherwise, Int64 converts the +reply to an int64 as follows: +

    +
    Reply type    Result
    +integer       reply, nil
    +bulk string   parsed reply, nil
    +nil           0, ErrNil
    +other         0, error
    +
    + + + + + + + +

    func Values

    +
    func Values(reply interface{}, err error) ([]interface{}, error)
    +

    +Values is a helper that converts an array command reply to a []interface{}. +If err is not equal to nil, then Values returns nil, err. Otherwise, Values +converts the reply as follows: +

    +
    Reply type      Result
    +array           reply, nil
    +nil             nil, ErrNil
    +other           nil, error
    +
    + + + + + + + + +

    type Args

    +
    type Args []interface{}
    +

    +Args is a helper for constructing command arguments from structured values. +

    + + + + + + +
    + +
    +

    Example

    + + + +

    Code:

    +
    c, err := dial()
    +if err != nil {
    +    fmt.Println(err)
    +    return
    +}
    +defer c.Close()
    +
    +var p1, p2 struct {
    +    Title  string `redis:"title"`
    +    Author string `redis:"author"`
    +    Body   string `redis:"body"`
    +}
    +
    +p1.Title = "Example"
    +p1.Author = "Gary"
    +p1.Body = "Hello"
    +
    +if _, err := c.Do("HMSET", redis.Args{}.Add("id1").AddFlat(&p1)...); err != nil {
    +    fmt.Println(err)
    +    return
    +}
    +
    +m := map[string]string{
    +    "title":  "Example2",
    +    "author": "Steve",
    +    "body":   "Map",
    +}
    +
    +if _, err := c.Do("HMSET", redis.Args{}.Add("id2").AddFlat(m)...); err != nil {
    +    fmt.Println(err)
    +    return
    +}
    +
    +for _, id := range []string{"id1", "id2"} {
    +
    +    v, err := redis.Values(c.Do("HGETALL", id))
    +    if err != nil {
    +        fmt.Println(err)
    +        return
    +    }
    +
    +    if err := redis.ScanStruct(v, &p2); err != nil {
    +        fmt.Println(err)
    +        return
    +    }
    +
    +    fmt.Printf("%+v\n", p2)
    +}
    +
    +
    + +

    Output:

    +
    {Title:Example Author:Gary Body:Hello}
    +{Title:Example2 Author:Steve Body:Map}
    +
    + + +
    +
    + + + + + + + + +

    func (Args) Add

    +
    func (args Args) Add(value ...interface{}) Args
    +

    +Add returns the result of appending value to args. +

    + + + + + + +

    func (Args) AddFlat

    +
    func (args Args) AddFlat(v interface{}) Args
    +

    +AddFlat returns the result of appending the flattened value of v to args. +

    +

    +Maps are flattened by appending the alternating keys and map values to args. +

    +

    +Slices are flattened by appending the slice elements to args. +

    +

    +Structs are flattened by appending the alternating names and values of +exported fields to args. If v is a nil struct pointer, then nothing is +appended. The 'redis' field tag overrides struct field names. See ScanStruct +for more information on the use of the 'redis' field tag. +

    +

    +Other types are appended to args as is. +

    + + + + + + + + +

    type Conn

    +
    type Conn interface {
    +    // Close closes the connection.
    +    Close() error
    +
    +    // Err returns a non-nil value if the connection is broken. The returned
    +    // value is either the first non-nil value returned from the underlying
    +    // network connection or a protocol parsing error. Applications should
    +    // close broken connections.
    +    Err() error
    +
    +    // Do sends a command to the server and returns the received reply.
    +    Do(commandName string, args ...interface{}) (reply interface{}, err error)
    +
    +    // Send writes the command to the client's output buffer.
    +    Send(commandName string, args ...interface{}) error
    +
    +    // Flush flushes the output buffer to the Redis server.
    +    Flush() error
    +
    +    // Receive receives a single reply from the Redis server
    +    Receive() (reply interface{}, err error)
    +}
    +

    +Conn represents a connection to a Redis server. +

    + + + + + + + + + + + + +

    func Dial

    +
    func Dial(network, address string, options ...DialOption) (Conn, error)
    +

    +Dial connects to the Redis server at the given network and +address using the specified options. +

    + +
    + +
    +

    Example

    +

    Connect to local instance of Redis running on the default port. +

    + + +

    Code:

    +
    +c, err := redis.Dial("tcp", ":6379")
    +if err != nil {
    +    // handle error
    +}
    +defer c.Close()
    +
    + + +
    +
    + + + + +

    func DialTimeout

    +
    func DialTimeout(network, address string, connectTimeout, readTimeout, writeTimeout time.Duration) (Conn, error)
    +

    +DialTimeout acts like Dial but takes timeouts for establishing the +connection to the server, writing a command and reading a reply. +

    +

    +Deprecated: Use Dial with options instead. +

    + + + + + +

    func DialURL

    +
    func DialURL(rawurl string, options ...DialOption) (Conn, error)
    +

    +DialURL connects to a Redis server at the given URL using the Redis +URI scheme. URLs should follow the draft IANA specification for the +scheme (https://www.iana.org/assignments/uri-schemes/prov/redis). +

    + +
    + +
    +

    Example

    +

    Connect to remote instance of Redis using a URL. +

    + + +

    Code:

    +
    +c, err := redis.DialURL(os.Getenv("REDIS_URL"))
    +if err != nil {
    +    // handle connection error
    +}
    +defer c.Close()
    +
    + + +
    +
    + + + + +

    func NewConn

    +
    func NewConn(netConn net.Conn, readTimeout, writeTimeout time.Duration) Conn
    +

    +NewConn returns a new Redigo connection for the given net connection. +

    + + + + + +

    func NewLoggingConn

    +
    func NewLoggingConn(conn Conn, logger *log.Logger, prefix string) Conn
    +

    +NewLoggingConn returns a logging wrapper around a connection. +

    + + + + + + + + + +

    type DialOption

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

    +DialOption specifies an option for dialing a Redis server. +

    + + + + + + + + + + + + +

    func DialConnectTimeout

    +
    func DialConnectTimeout(d time.Duration) DialOption
    +

    +DialConnectTimeout specifies the timeout for connecting to the Redis server. +

    + + + + + +

    func DialDatabase

    +
    func DialDatabase(db int) DialOption
    +

    +DialDatabase specifies the database to select when dialing a connection. +

    + + + + + +

    func DialNetDial

    +
    func DialNetDial(dial func(network, addr string) (net.Conn, error)) DialOption
    +

    +DialNetDial specifies a custom dial function for creating TCP +connections. If this option is left out, then net.Dial is +used. DialNetDial overrides DialConnectTimeout. +

    + + + + + +

    func DialPassword

    +
    func DialPassword(password string) DialOption
    +

    +DialPassword specifies the password to use when connecting to +the Redis server. +

    + + + + + +

    func DialReadTimeout

    +
    func DialReadTimeout(d time.Duration) DialOption
    +

    +DialReadTimeout specifies the timeout for reading a single command reply. +

    + + + + + +

    func DialWriteTimeout

    +
    func DialWriteTimeout(d time.Duration) DialOption
    +

    +DialWriteTimeout specifies the timeout for writing a single command. +

    + + + + + + + + + +

    type Error

    +
    type Error string
    +

    +Error represents an error returned in a command reply. +

    + + + + + + + + + + + + + + +

    func (Error) Error

    +
    func (err Error) Error() string
    + + + + + + + + +

    type Message

    +
    type Message struct {
    +
    +    // The originating channel.
    +    Channel string
    +
    +    // The message data.
    +    Data []byte
    +}
    +

    +Message represents a message notification. +

    + + + + + + + + + + + + + + + + +

    type PMessage

    +
    type PMessage struct {
    +
    +    // The matched pattern.
    +    Pattern string
    +
    +    // The originating channel.
    +    Channel string
    +
    +    // The message data.
    +    Data []byte
    +}
    +

    +PMessage represents a pmessage notification. +

    + + + + + + + + + + + + + + + + +

    type Pong

    +
    type Pong struct {
    +    Data string
    +}
    +

    +Pong represents a pubsub pong notification. +

    + + + + + + + + + + + + + + + + +

    type Pool

    +
    type Pool struct {
    +
    +    // Dial is an application supplied function for creating and configuring a
    +    // connection.
    +    //
    +    // The connection returned from Dial must not be in a special state
    +    // (subscribed to pubsub channel, transaction started, ...).
    +    Dial func() (Conn, error)
    +
    +    // TestOnBorrow is an optional application supplied function for checking
    +    // the health of an idle connection before the connection is used again by
    +    // the application. Argument t is the time that the connection was returned
    +    // to the pool. If the function returns an error, then the connection is
    +    // closed.
    +    TestOnBorrow func(c Conn, t time.Time) error
    +
    +    // Maximum number of idle connections in the pool.
    +    MaxIdle int
    +
    +    // Maximum number of connections allocated by the pool at a given time.
    +    // When zero, there is no limit on the number of connections in the pool.
    +    MaxActive int
    +
    +    // Close connections after remaining idle for this duration. If the value
    +    // is zero, then idle connections are not closed. Applications should set
    +    // the timeout to a value less than the server's timeout.
    +    IdleTimeout time.Duration
    +
    +    // If Wait is true and the pool is at the MaxActive limit, then Get() waits
    +    // for a connection to be returned to the pool before returning.
    +    Wait bool
    +    // contains filtered or unexported fields
    +}
    +

    +Pool maintains a pool of connections. The application calls the Get method +to get a connection from the pool and the connection's Close method to +return the connection's resources to the pool. +

    +

    +The following example shows how to use a pool in a web application. The +application creates a pool at application startup and makes it available to +request handlers using a global variable. The pool configuration used here +is an example, not a recommendation. +

    +
    func newPool(server, password string) *redis.Pool {
    +    return &redis.Pool{
    +        MaxIdle: 3,
    +        IdleTimeout: 240 * time.Second,
    +        Dial: func () (redis.Conn, error) {
    +            c, err := redis.Dial("tcp", server)
    +            if err != nil {
    +                return nil, err
    +            }
    +            if _, err := c.Do("AUTH", password); err != nil {
    +                c.Close()
    +                return nil, err
    +            }
    +            return c, err
    +        },
    +        TestOnBorrow: func(c redis.Conn, t time.Time) error {
    +            if time.Since(t) < time.Minute {
    +                return nil
    +            }
    +            _, err := c.Do("PING")
    +            return err
    +        },
    +    }
    +}
    +
    +var (
    +    pool *redis.Pool
    +    redisServer = flag.String("redisServer", ":6379", "")
    +    redisPassword = flag.String("redisPassword", "", "")
    +)
    +
    +func main() {
    +    flag.Parse()
    +    pool = newPool(*redisServer, *redisPassword)
    +    ...
    +}
    +
    +

    +A request handler gets a connection from the pool and closes the connection +when the handler is done: +

    +
    func serveHome(w http.ResponseWriter, r *http.Request) {
    +    conn := pool.Get()
    +    defer conn.Close()
    +    ....
    +}
    +
    + + + + + + + + + + + + +

    func NewPool

    +
    func NewPool(newFn func() (Conn, error), maxIdle int) *Pool
    +

    +NewPool creates a new pool. +

    +

    +Deprecated: Initialize the Pool directory as shown in the example. +

    + + + + + + + +

    func (*Pool) ActiveCount

    +
    func (p *Pool) ActiveCount() int
    +

    +ActiveCount returns the number of active connections in the pool. +

    + + + + + + +

    func (*Pool) Close

    +
    func (p *Pool) Close() error
    +

    +Close releases the resources used by the pool. +

    + + + + + + +

    func (*Pool) Get

    +
    func (p *Pool) Get() Conn
    +

    +Get gets a connection. The application must close the returned connection. +This method always returns a valid connection so that applications can defer +error handling to the first use of the connection. If there is an error +getting an underlying connection, then the connection Err, Do, Send, Flush +and Receive methods return that error. +

    + + + + + + + + +

    type PubSubConn

    +
    type PubSubConn struct {
    +    Conn Conn
    +}
    +

    +PubSubConn wraps a Conn with convenience methods for subscribers. +

    + + + + + + +
    + +
    +

    Example

    +

    Applications can receive pushed messages from one goroutine and manage subscriptions from another goroutine. +

    + + +

    Code:

    +
    c, err := dial()
    +if err != nil {
    +    fmt.Println(err)
    +    return
    +}
    +defer c.Close()
    +var wg sync.WaitGroup
    +wg.Add(2)
    +
    +psc := redis.PubSubConn{Conn: c}
    +
    +// This goroutine receives and prints pushed notifications from the server.
    +// The goroutine exits when the connection is unsubscribed from all
    +// channels or there is an error.
    +go func() {
    +    defer wg.Done()
    +    for {
    +        switch n := psc.Receive().(type) {
    +        case redis.Message:
    +            fmt.Printf("Message: %s %s\n", n.Channel, n.Data)
    +        case redis.PMessage:
    +            fmt.Printf("PMessage: %s %s %s\n", n.Pattern, n.Channel, n.Data)
    +        case redis.Subscription:
    +            fmt.Printf("Subscription: %s %s %d\n", n.Kind, n.Channel, n.Count)
    +            if n.Count == 0 {
    +                return
    +            }
    +        case error:
    +            fmt.Printf("error: %v\n", n)
    +            return
    +        }
    +    }
    +}()
    +
    +// This goroutine manages subscriptions for the connection.
    +go func() {
    +    defer wg.Done()
    +
    +    psc.Subscribe("example")
    +    psc.PSubscribe("p*")
    +
    +    // The following function calls publish a message using another
    +    // connection to the Redis server.
    +    publish("example", "hello")
    +    publish("example", "world")
    +    publish("pexample", "foo")
    +    publish("pexample", "bar")
    +
    +    // Unsubscribe from all connections. This will cause the receiving
    +    // goroutine to exit.
    +    psc.Unsubscribe()
    +    psc.PUnsubscribe()
    +}()
    +
    +wg.Wait()
    +
    +
    + +

    Output:

    +
    Subscription: subscribe example 1
    +Subscription: psubscribe p* 2
    +Message: example hello
    +Message: example world
    +PMessage: p* pexample foo
    +PMessage: p* pexample bar
    +Subscription: unsubscribe example 1
    +Subscription: punsubscribe p* 0
    +
    + + +
    +
    + + + + + + + + +

    func (PubSubConn) Close

    +
    func (c PubSubConn) Close() error
    +

    +Close closes the connection. +

    + + + + + + +

    func (PubSubConn) PSubscribe

    +
    func (c PubSubConn) PSubscribe(channel ...interface{}) error
    +

    +PSubscribe subscribes the connection to the given patterns. +

    + + + + + + +

    func (PubSubConn) PUnsubscribe

    +
    func (c PubSubConn) PUnsubscribe(channel ...interface{}) error
    +

    +PUnsubscribe unsubscribes the connection from the given patterns, or from all +of them if none is given. +

    + + + + + + +

    func (PubSubConn) Ping

    +
    func (c PubSubConn) Ping(data string) error
    +

    +Ping sends a PING to the server with the specified data. +

    + + + + + + +

    func (PubSubConn) Receive

    +
    func (c PubSubConn) Receive() interface{}
    +

    +Receive returns a pushed message as a Subscription, Message, PMessage, Pong +or error. The return value is intended to be used directly in a type switch +as illustrated in the PubSubConn example. +

    + + + + + + +

    func (PubSubConn) Subscribe

    +
    func (c PubSubConn) Subscribe(channel ...interface{}) error
    +

    +Subscribe subscribes the connection to the specified channels. +

    + + + + + + +

    func (PubSubConn) Unsubscribe

    +
    func (c PubSubConn) Unsubscribe(channel ...interface{}) error
    +

    +Unsubscribe unsubscribes the connection from the given channels, or from all +of them if none is given. +

    + + + + + + + + +

    type Script

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

    +Script encapsulates the source, hash and key count for a Lua script. See +http://redis.io/commands/eval for information on scripts in Redis. +

    + + + + + + +
    + +
    +

    Example

    + + + +

    Code:

    +
    +// Initialize a package-level variable with a script.
    +var getScript = redis.NewScript(1, `return redis.call('get', KEYS[1])`)
    +
    +// In a function, use the script Do method to evaluate the script. The Do
    +// method optimistically uses the EVALSHA command. If the script is not
    +// loaded, then the Do method falls back to the EVAL command.
    +reply, err = getScript.Do(c, "foo")
    +
    + + +
    +
    + + + + + + +

    func NewScript

    +
    func NewScript(keyCount int, src string) *Script
    +

    +NewScript returns a new script object. If keyCount is greater than or equal +to zero, then the count is automatically inserted in the EVAL command +argument list. If keyCount is less than zero, then the application supplies +the count as the first value in the keysAndArgs argument to the Do, Send and +SendHash methods. +

    + + + + + + + +

    func (*Script) Do

    +
    func (s *Script) Do(c Conn, keysAndArgs ...interface{}) (interface{}, error)
    +

    +Do evaluates the script. Under the covers, Do optimistically evaluates the +script using the EVALSHA command. If the command fails because the script is +not loaded, then Do evaluates the script using the EVAL command (thus +causing the script to load). +

    + + + + + + +

    func (*Script) Load

    +
    func (s *Script) Load(c Conn) error
    +

    +Load loads the script without evaluating it. +

    + + + + + + +

    func (*Script) Send

    +
    func (s *Script) Send(c Conn, keysAndArgs ...interface{}) error
    +

    +Send evaluates the script without waiting for the reply. +

    + + + + + + +

    func (*Script) SendHash

    +
    func (s *Script) SendHash(c Conn, keysAndArgs ...interface{}) error
    +

    +SendHash evaluates the script without waiting for the reply. The script is +evaluated with the EVALSHA command. The application must ensure that the +script is loaded by a previous call to Send, Do or Load methods. +

    + + + + + + + + +

    type Subscription

    +
    type Subscription struct {
    +
    +    // Kind is "subscribe", "unsubscribe", "psubscribe" or "punsubscribe"
    +    Kind string
    +
    +    // The channel that was changed.
    +    Channel string
    +
    +    // The current number of subscriptions for connection.
    +    Count int
    +}
    +

    +Subscription represents a subscribe or unsubscribe notification. +

    + + + + + + + + + + + + + + + + + + + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/github.com/golang/index.html b/pkg/github.com/golang/index.html new file mode 100644 index 0000000..d87c197 --- /dev/null +++ b/pkg/github.com/golang/index.html @@ -0,0 +1,163 @@ + + + + + + + + /src/github.com/golang - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Directory /src/github.com/golang

    + + + + + + + + + + + + + + + + + + + +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    NameSynopsis
    ..
    + protobuf + + +
    + proto + + Package proto converts data structures to and from the wire format of protocol buffers. +
    + proto3_proto + + Package proto3_proto is a generated protocol buffer package. +
    + snappy + + Package snappy implements the snappy block-based compression format. +
    +
    + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/github.com/golang/protobuf/index.html b/pkg/github.com/golang/protobuf/index.html new file mode 100644 index 0000000..4ffa58f --- /dev/null +++ b/pkg/github.com/golang/protobuf/index.html @@ -0,0 +1,141 @@ + + + + + + + + /src/github.com/golang/protobuf - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Directory /src/github.com/golang/protobuf

    + + + + + + + + + + + + + + + + + + + +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    NameSynopsis
    ..
    + proto + + Package proto converts data structures to and from the wire format of protocol buffers. +
    + proto3_proto + + Package proto3_proto is a generated protocol buffer package. +
    +
    + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/github.com/golang/protobuf/proto/index.html b/pkg/github.com/golang/protobuf/proto/index.html new file mode 100644 index 0000000..adc5572 --- /dev/null +++ b/pkg/github.com/golang/protobuf/proto/index.html @@ -0,0 +1,2397 @@ + + + + + + + + proto - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Package proto

    + + + + + + + + + + + + + + +
    +
    +
    import "github.com/golang/protobuf/proto"
    +
    +
    +
    Overview
    +
    Index
    + + +
    Subdirectories
    + +
    +
    + +
    + +
    +

    Overview ▾

    +

    +Package proto converts data structures to and from the wire format of +protocol buffers. It works in concert with the Go source code generated +for .proto files by the protocol compiler. +

    +

    +A summary of the properties of the protocol buffer interface +for a protocol buffer variable v: +

    +
      - Names are turned from camel_case to CamelCase for export.
    +  - There are no methods on v to set fields; just treat
    +	them as structure fields.
    +  - There are getters that return a field's value if set,
    +	and return the field's default value if unset.
    +	The getters work even if the receiver is a nil message.
    +  - The zero value for a struct is its correct initialization state.
    +	All desired fields must be set before marshaling.
    +  - A Reset() method will restore a protobuf struct to its zero state.
    +  - Non-repeated fields are pointers to the values; nil means unset.
    +	That is, optional or required field int32 f becomes F *int32.
    +  - Repeated fields are slices.
    +  - Helper functions are available to aid the setting of fields.
    +	msg.Foo = proto.String("hello") // set field
    +  - Constants are defined to hold the default values of all fields that
    +	have them.  They have the form Default_StructName_FieldName.
    +	Because the getter methods handle defaulted values,
    +	direct use of these constants should be rare.
    +  - Enums are given type names and maps from names to values.
    +	Enum values are prefixed by the enclosing message's name, or by the
    +	enum's type name if it is a top-level enum. Enum types have a String
    +	method, and a Enum method to assist in message construction.
    +  - Nested messages, groups and enums have type names prefixed with the name of
    +	the surrounding message type.
    +  - Extensions are given descriptor names that start with E_,
    +	followed by an underscore-delimited list of the nested messages
    +	that contain it (if any) followed by the CamelCased name of the
    +	extension field itself.  HasExtension, ClearExtension, GetExtension
    +	and SetExtension are functions for manipulating extensions.
    +  - Oneof field sets are given a single field in their message,
    +	with distinguished wrapper types for each possible field value.
    +  - Marshal and Unmarshal are functions to encode and decode the wire format.
    +
    +

    +When the .proto file specifies `syntax="proto3"`, there are some differences: +

    +
    - Non-repeated fields of non-message type are values instead of pointers.
    +- Getters are only generated for message and oneof fields.
    +- Enum types do not get an Enum method.
    +
    +

    +The simplest way to describe this is to see an example. +Given file test.proto, containing +

    +
    package example;
    +
    +enum FOO { X = 17; }
    +
    +message Test {
    +  required string label = 1;
    +  optional int32 type = 2 [default=77];
    +  repeated int64 reps = 3;
    +  optional group OptionalGroup = 4 {
    +    required string RequiredField = 5;
    +  }
    +  oneof union {
    +    int32 number = 6;
    +    string name = 7;
    +  }
    +}
    +
    +

    +The resulting file, test.pb.go, is: +

    +
    package example
    +
    +import proto "github.com/golang/protobuf/proto"
    +import math "math"
    +
    +type FOO int32
    +const (
    +	FOO_X FOO = 17
    +)
    +var FOO_name = map[int32]string{
    +	17: "X",
    +}
    +var FOO_value = map[string]int32{
    +	"X": 17,
    +}
    +
    +func (x FOO) Enum() *FOO {
    +	p := new(FOO)
    +	*p = x
    +	return p
    +}
    +func (x FOO) String() string {
    +	return proto.EnumName(FOO_name, int32(x))
    +}
    +func (x *FOO) UnmarshalJSON(data []byte) error {
    +	value, err := proto.UnmarshalJSONEnum(FOO_value, data)
    +	if err != nil {
    +		return err
    +	}
    +	*x = FOO(value)
    +	return nil
    +}
    +
    +type Test struct {
    +	Label         *string             `protobuf:"bytes,1,req,name=label" json:"label,omitempty"`
    +	Type          *int32              `protobuf:"varint,2,opt,name=type,def=77" json:"type,omitempty"`
    +	Reps          []int64             `protobuf:"varint,3,rep,name=reps" json:"reps,omitempty"`
    +	Optionalgroup *Test_OptionalGroup `protobuf:"group,4,opt,name=OptionalGroup" json:"optionalgroup,omitempty"`
    +	// Types that are valid to be assigned to Union:
    +	//	*Test_Number
    +	//	*Test_Name
    +	Union            isTest_Union `protobuf_oneof:"union"`
    +	XXX_unrecognized []byte       `json:"-"`
    +}
    +func (m *Test) Reset()         { *m = Test{} }
    +func (m *Test) String() string { return proto.CompactTextString(m) }
    +func (*Test) ProtoMessage() {}
    +
    +type isTest_Union interface {
    +	isTest_Union()
    +}
    +
    +type Test_Number struct {
    +	Number int32 `protobuf:"varint,6,opt,name=number"`
    +}
    +type Test_Name struct {
    +	Name string `protobuf:"bytes,7,opt,name=name"`
    +}
    +
    +func (*Test_Number) isTest_Union() {}
    +func (*Test_Name) isTest_Union()   {}
    +
    +func (m *Test) GetUnion() isTest_Union {
    +	if m != nil {
    +		return m.Union
    +	}
    +	return nil
    +}
    +const Default_Test_Type int32 = 77
    +
    +func (m *Test) GetLabel() string {
    +	if m != nil && m.Label != nil {
    +		return *m.Label
    +	}
    +	return ""
    +}
    +
    +func (m *Test) GetType() int32 {
    +	if m != nil && m.Type != nil {
    +		return *m.Type
    +	}
    +	return Default_Test_Type
    +}
    +
    +func (m *Test) GetOptionalgroup() *Test_OptionalGroup {
    +	if m != nil {
    +		return m.Optionalgroup
    +	}
    +	return nil
    +}
    +
    +type Test_OptionalGroup struct {
    +	RequiredField *string `protobuf:"bytes,5,req" json:"RequiredField,omitempty"`
    +}
    +func (m *Test_OptionalGroup) Reset()         { *m = Test_OptionalGroup{} }
    +func (m *Test_OptionalGroup) String() string { return proto.CompactTextString(m) }
    +
    +func (m *Test_OptionalGroup) GetRequiredField() string {
    +	if m != nil && m.RequiredField != nil {
    +		return *m.RequiredField
    +	}
    +	return ""
    +}
    +
    +func (m *Test) GetNumber() int32 {
    +	if x, ok := m.GetUnion().(*Test_Number); ok {
    +		return x.Number
    +	}
    +	return 0
    +}
    +
    +func (m *Test) GetName() string {
    +	if x, ok := m.GetUnion().(*Test_Name); ok {
    +		return x.Name
    +	}
    +	return ""
    +}
    +
    +func init() {
    +	proto.RegisterEnum("example.FOO", FOO_name, FOO_value)
    +}
    +
    +

    +To create and play with a Test object: +

    +
    package main
    +
    +import (
    +	"log"
    +
    +	"github.com/golang/protobuf/proto"
    +	pb "./example.pb"
    +)
    +
    +func main() {
    +	test := &pb.Test{
    +		Label: proto.String("hello"),
    +		Type:  proto.Int32(17),
    +		Reps:  []int64{1, 2, 3},
    +		Optionalgroup: &pb.Test_OptionalGroup{
    +			RequiredField: proto.String("good bye"),
    +		},
    +		Union: &pb.Test_Name{"fred"},
    +	}
    +	data, err := proto.Marshal(test)
    +	if err != nil {
    +		log.Fatal("marshaling error: ", err)
    +	}
    +	newTest := &pb.Test{}
    +	err = proto.Unmarshal(data, newTest)
    +	if err != nil {
    +		log.Fatal("unmarshaling error: ", err)
    +	}
    +	// Now test and newTest contain the same data.
    +	if test.GetLabel() != newTest.GetLabel() {
    +		log.Fatalf("data mismatch %q != %q", test.GetLabel(), newTest.GetLabel())
    +	}
    +	// Use a type switch to determine which oneof was set.
    +	switch u := test.Union.(type) {
    +	case *pb.Test_Number: // u.Number contains the number.
    +	case *pb.Test_Name: // u.Name contains the string.
    +	}
    +	// etc.
    +}
    +
    + +
    +
    + + +
    + +
    +

    Index ▾

    + + +
    +
    + +
    Constants
    + + +
    Variables
    + + + +
    func Bool(v bool) *bool
    + + +
    func ClearAllExtensions(pb Message)
    + + +
    func ClearExtension(pb Message, extension *ExtensionDesc)
    + + +
    func CompactText(w io.Writer, pb Message) error
    + + +
    func CompactTextString(pb Message) string
    + + +
    func DecodeVarint(buf []byte) (x uint64, n int)
    + + +
    func EncodeVarint(x uint64) []byte
    + + +
    func EnumName(m map[int32]string, v int32) string
    + + +
    func EnumValueMap(enumType string) map[string]int32
    + + +
    func Equal(a, b Message) bool
    + + +
    func ExtensionDescs(pb Message) ([]*ExtensionDesc, error)
    + + +
    func FileDescriptor(filename string) []byte
    + + +
    func Float32(v float32) *float32
    + + +
    func Float64(v float64) *float64
    + + +
    func GetExtension(pb Message, extension *ExtensionDesc) (interface{}, error)
    + + +
    func GetExtensions(pb Message, es []*ExtensionDesc) (extensions []interface{}, err error)
    + + +
    func HasExtension(pb Message, extension *ExtensionDesc) bool
    + + +
    func Int(v int) *int32
    + + +
    func Int32(v int32) *int32
    + + +
    func Int64(v int64) *int64
    + + +
    func Marshal(pb Message) ([]byte, error)
    + + +
    func MarshalMessageSet(exts interface{}) ([]byte, error)
    + + +
    func MarshalMessageSetJSON(exts interface{}) ([]byte, error)
    + + +
    func MarshalText(w io.Writer, pb Message) error
    + + +
    func MarshalTextString(pb Message) string
    + + +
    func Merge(dst, src Message)
    + + +
    func MessageName(x Message) string
    + + +
    func MessageType(name string) reflect.Type
    + + +
    func RegisterEnum(typeName string, unusedNameMap map[int32]string, valueMap map[string]int32)
    + + +
    func RegisterExtension(desc *ExtensionDesc)
    + + +
    func RegisterFile(filename string, fileDescriptor []byte)
    + + +
    func RegisterMessageSetType(m Message, fieldNum int32, name string)
    + + +
    func RegisterType(x Message, name string)
    + + +
    func RegisteredExtensions(pb Message) map[int32]*ExtensionDesc
    + + +
    func SetDefaults(pb Message)
    + + +
    func SetExtension(pb Message, extension *ExtensionDesc, value interface{}) error
    + + +
    func SetRawExtension(base Message, id int32, b []byte)
    + + +
    func Size(pb Message) (n int)
    + + +
    func SizeVarint(x uint64) int
    + + +
    func String(v string) *string
    + + +
    func Uint32(v uint32) *uint32
    + + +
    func Uint64(v uint64) *uint64
    + + +
    func Unmarshal(buf []byte, pb Message) error
    + + +
    func UnmarshalJSONEnum(m map[string]int32, data []byte, enumName string) (int32, error)
    + + +
    func UnmarshalMerge(buf []byte, pb Message) error
    + + +
    func UnmarshalMessageSet(buf []byte, exts interface{}) error
    + + +
    func UnmarshalMessageSetJSON(buf []byte, exts interface{}) error
    + + +
    func UnmarshalText(s string, pb Message) error
    + + + +
    type Buffer
    + + +
        func NewBuffer(e []byte) *Buffer
    + + + +
        func (p *Buffer) Bytes() []byte
    + + +
        func (p *Buffer) DebugPrint(s string, b []byte)
    + + +
        func (p *Buffer) DecodeFixed32() (x uint64, err error)
    + + +
        func (p *Buffer) DecodeFixed64() (x uint64, err error)
    + + +
        func (p *Buffer) DecodeGroup(pb Message) error
    + + +
        func (p *Buffer) DecodeMessage(pb Message) error
    + + +
        func (p *Buffer) DecodeRawBytes(alloc bool) (buf []byte, err error)
    + + +
        func (p *Buffer) DecodeStringBytes() (s string, err error)
    + + +
        func (p *Buffer) DecodeVarint() (x uint64, err error)
    + + +
        func (p *Buffer) DecodeZigzag32() (x uint64, err error)
    + + +
        func (p *Buffer) DecodeZigzag64() (x uint64, err error)
    + + +
        func (p *Buffer) EncodeFixed32(x uint64) error
    + + +
        func (p *Buffer) EncodeFixed64(x uint64) error
    + + +
        func (p *Buffer) EncodeMessage(pb Message) error
    + + +
        func (p *Buffer) EncodeRawBytes(b []byte) error
    + + +
        func (p *Buffer) EncodeStringBytes(s string) error
    + + +
        func (p *Buffer) EncodeVarint(x uint64) error
    + + +
        func (p *Buffer) EncodeZigzag32(x uint64) error
    + + +
        func (p *Buffer) EncodeZigzag64(x uint64) error
    + + +
        func (p *Buffer) Marshal(pb Message) error
    + + +
        func (p *Buffer) Reset()
    + + +
        func (p *Buffer) SetBuf(s []byte)
    + + +
        func (p *Buffer) Unmarshal(pb Message) error
    + + + +
    type Extension
    + + + + +
    type ExtensionDesc
    + + + + +
    type ExtensionRange
    + + + + +
    type Marshaler
    + + + + +
    type Message
    + + +
        func Clone(pb Message) Message
    + + + + +
    type OneofProperties
    + + + + +
    type ParseError
    + + + +
        func (p *ParseError) Error() string
    + + + +
    type Properties
    + + + +
        func (p *Properties) Init(typ reflect.Type, name, tag string, f *reflect.StructField)
    + + +
        func (p *Properties) Parse(s string)
    + + +
        func (p *Properties) String() string
    + + + +
    type RequiredNotSetError
    + + + +
        func (e *RequiredNotSetError) Error() string
    + + + +
    type Stats
    + + +
        func GetStats() Stats
    + + + + +
    type StructProperties
    + + +
        func GetProperties(t reflect.Type) *StructProperties
    + + + +
        func (sp *StructProperties) Len() int
    + + +
        func (sp *StructProperties) Less(i, j int) bool
    + + +
        func (sp *StructProperties) Swap(i, j int)
    + + + +
    type TextMarshaler
    + + + +
        func (tm *TextMarshaler) Marshal(w io.Writer, pb Message) error
    + + +
        func (tm *TextMarshaler) Text(pb Message) string
    + + + +
    type Unmarshaler
    + + + + +
    type XXX_InternalExtensions
    + + + + +
    +
    + + + + +

    Package files

    +

    + + + clone.go + + decode.go + + encode.go + + equal.go + + extensions.go + + lib.go + + message_set.go + + pointer_unsafe.go + + properties.go + + text.go + + text_parser.go + + +

    + +
    +
    + + + + +

    Constants

    + +
    const (
    +    WireVarint     = 0
    +    WireFixed64    = 1
    +    WireBytes      = 2
    +    WireStartGroup = 3
    +    WireEndGroup   = 4
    +    WireFixed32    = 5
    +)
    +

    +Constants that identify the encoding of a value on the wire. +

    + + +
    const ProtoPackageIsVersion1 = true
    +

    +ProtoPackageIsVersion1 is referenced from generated protocol buffer files +to assert that that code is compatible with this version of the proto package. +

    + + +
    const ProtoPackageIsVersion2 = true
    +

    +ProtoPackageIsVersion2 is referenced from generated protocol buffer files +to assert that that code is compatible with this version of the proto package. +

    + + + + +

    Variables

    + +
    var (
    +
    +    // ErrNil is the error returned if Marshal is called with nil.
    +    ErrNil = errors.New("proto: Marshal called with nil")
    +
    +    // ErrTooLarge is the error returned if Marshal is called with a
    +    // message that encodes to >2GB.
    +    ErrTooLarge = errors.New("proto: message encodes to over 2 GB")
    +)
    + + +
    var ErrInternalBadWireType = errors.New("proto: internal error: bad wiretype for oneof")
    +

    +ErrInternalBadWireType is returned by generated code when an incorrect +wire type is encountered. It does not get returned to user code. +

    + + +
    var ErrMissingExtension = errors.New("proto: missing extension")
    +

    +ErrMissingExtension is the error returned by GetExtension if the named extension is not in the message. +

    + + + + + + +

    func Bool

    +
    func Bool(v bool) *bool
    +

    +Bool is a helper routine that allocates a new bool value +to store v and returns a pointer to it. +

    + + + + + + + +

    func ClearAllExtensions

    +
    func ClearAllExtensions(pb Message)
    +

    +ClearAllExtensions clears all extensions from pb. +

    + + + + + + + +

    func ClearExtension

    +
    func ClearExtension(pb Message, extension *ExtensionDesc)
    +

    +ClearExtension removes the given extension from pb. +

    + + + + + + + +

    func CompactText

    +
    func CompactText(w io.Writer, pb Message) error
    +

    +CompactText writes a given protocol buffer in compact text format (one line). +

    + + + + + + + +

    func CompactTextString

    +
    func CompactTextString(pb Message) string
    +

    +CompactTextString is the same as CompactText, but returns the string directly. +

    + + + + + + + +

    func DecodeVarint

    +
    func DecodeVarint(buf []byte) (x uint64, n int)
    +

    +DecodeVarint reads a varint-encoded integer from the slice. +It returns the integer and the number of bytes consumed, or +zero if there is not enough. +This is the format for the +int32, int64, uint32, uint64, bool, and enum +protocol buffer types. +

    + + + + + + + +

    func EncodeVarint

    +
    func EncodeVarint(x uint64) []byte
    +

    +EncodeVarint returns the varint encoding of x. +This is the format for the +int32, int64, uint32, uint64, bool, and enum +protocol buffer types. +Not used by the package itself, but helpful to clients +wishing to use the same encoding. +

    + + + + + + + +

    func EnumName

    +
    func EnumName(m map[int32]string, v int32) string
    +

    +EnumName is a helper function to simplify printing protocol buffer enums +by name. Given an enum map and a value, it returns a useful string. +

    + + + + + + + +

    func EnumValueMap

    +
    func EnumValueMap(enumType string) map[string]int32
    +

    +EnumValueMap returns the mapping from names to integers of the +enum type enumType, or a nil if not found. +

    + + + + + + + +

    func Equal

    +
    func Equal(a, b Message) bool
    +

    +Equal returns true iff protocol buffers a and b are equal. +The arguments must both be pointers to protocol buffer structs. +

    +

    +Equality is defined in this way: +

    +
    - Two messages are equal iff they are the same type,
    +  corresponding fields are equal, unknown field sets
    +  are equal, and extensions sets are equal.
    +- Two set scalar fields are equal iff their values are equal.
    +  If the fields are of a floating-point type, remember that
    +  NaN != x for all x, including NaN. If the message is defined
    +  in a proto3 .proto file, fields are not "set"; specifically,
    +  zero length proto3 "bytes" fields are equal (nil == {}).
    +- Two repeated fields are equal iff their lengths are the same,
    +  and their corresponding elements are equal. Note a "bytes" field,
    +  although represented by []byte, is not a repeated field and the
    +  rule for the scalar fields described above applies.
    +- Two unset fields are equal.
    +- Two unknown field sets are equal if their current
    +  encoded state is equal.
    +- Two extension sets are equal iff they have corresponding
    +  elements that are pairwise equal.
    +- Two map fields are equal iff their lengths are the same,
    +  and they contain the same set of elements. Zero-length map
    +  fields are equal.
    +- Every other combination of things are not equal.
    +
    +

    +The return value is undefined if a and b are not protocol buffers. +

    + + + + + + + +

    func ExtensionDescs

    +
    func ExtensionDescs(pb Message) ([]*ExtensionDesc, error)
    +

    +ExtensionDescs returns a new slice containing pb's extension descriptors, in undefined order. +For non-registered extensions, ExtensionDescs returns an incomplete descriptor containing +just the Field field, which defines the extension's field number. +

    + + + + + + + +

    func FileDescriptor

    +
    func FileDescriptor(filename string) []byte
    +

    +FileDescriptor returns the compressed FileDescriptorProto for a .proto file. +

    + + + + + + + +

    func Float32

    +
    func Float32(v float32) *float32
    +

    +Float32 is a helper routine that allocates a new float32 value +to store v and returns a pointer to it. +

    + + + + + + + +

    func Float64

    +
    func Float64(v float64) *float64
    +

    +Float64 is a helper routine that allocates a new float64 value +to store v and returns a pointer to it. +

    + + + + + + + +

    func GetExtension

    +
    func GetExtension(pb Message, extension *ExtensionDesc) (interface{}, error)
    +

    +GetExtension parses and returns the given extension of pb. +If the extension is not present and has no default value it returns ErrMissingExtension. +

    + + + + + + + +

    func GetExtensions

    +
    func GetExtensions(pb Message, es []*ExtensionDesc) (extensions []interface{}, err error)
    +

    +GetExtensions returns a slice of the extensions present in pb that are also listed in es. +The returned slice has the same length as es; missing extensions will appear as nil elements. +

    + + + + + + + +

    func HasExtension

    +
    func HasExtension(pb Message, extension *ExtensionDesc) bool
    +

    +HasExtension returns whether the given extension is present in pb. +

    + + + + + + + +

    func Int

    +
    func Int(v int) *int32
    +

    +Int is a helper routine that allocates a new int32 value +to store v and returns a pointer to it, but unlike Int32 +its argument value is an int. +

    + + + + + + + +

    func Int32

    +
    func Int32(v int32) *int32
    +

    +Int32 is a helper routine that allocates a new int32 value +to store v and returns a pointer to it. +

    + + + + + + + +

    func Int64

    +
    func Int64(v int64) *int64
    +

    +Int64 is a helper routine that allocates a new int64 value +to store v and returns a pointer to it. +

    + + + + + + + +

    func Marshal

    +
    func Marshal(pb Message) ([]byte, error)
    +

    +Marshal takes the protocol buffer +and encodes it into the wire format, returning the data. +

    + + + + + + + +

    func MarshalMessageSet

    +
    func MarshalMessageSet(exts interface{}) ([]byte, error)
    +

    +MarshalMessageSet encodes the extension map represented by m in the message set wire format. +It is called by generated Marshal methods on protocol buffer messages with the message_set_wire_format option. +

    + + + + + + + +

    func MarshalMessageSetJSON

    +
    func MarshalMessageSetJSON(exts interface{}) ([]byte, error)
    +

    +MarshalMessageSetJSON encodes the extension map represented by m in JSON format. +It is called by generated MarshalJSON methods on protocol buffer messages with the message_set_wire_format option. +

    + + + + + + + +

    func MarshalText

    +
    func MarshalText(w io.Writer, pb Message) error
    +

    +MarshalText writes a given protocol buffer in text format. +The only errors returned are from w. +

    + + + + + + + +

    func MarshalTextString

    +
    func MarshalTextString(pb Message) string
    +

    +MarshalTextString is the same as MarshalText, but returns the string directly. +

    + + + + + + + +

    func Merge

    +
    func Merge(dst, src Message)
    +

    +Merge merges src into dst. +Required and optional fields that are set in src will be set to that value in dst. +Elements of repeated fields will be appended. +Merge panics if src and dst are not the same type, or if dst is nil. +

    + + + + + + + +

    func MessageName

    +
    func MessageName(x Message) string
    +

    +MessageName returns the fully-qualified proto name for the given message type. +

    + + + + + + + +

    func MessageType

    +
    func MessageType(name string) reflect.Type
    +

    +MessageType returns the message type (pointer to struct) for a named message. +

    + + + + + + + +

    func RegisterEnum

    +
    func RegisterEnum(typeName string, unusedNameMap map[int32]string, valueMap map[string]int32)
    +

    +RegisterEnum is called from the generated code to install the enum descriptor +maps into the global table to aid parsing text format protocol buffers. +

    + + + + + + + +

    func RegisterExtension

    +
    func RegisterExtension(desc *ExtensionDesc)
    +

    +RegisterExtension is called from the generated code. +

    + + + + + + + +

    func RegisterFile

    +
    func RegisterFile(filename string, fileDescriptor []byte)
    +

    +RegisterFile is called from generated code and maps from the +full file name of a .proto file to its compressed FileDescriptorProto. +

    + + + + + + + +

    func RegisterMessageSetType

    +
    func RegisterMessageSetType(m Message, fieldNum int32, name string)
    +

    +RegisterMessageSetType is called from the generated code. +

    + + + + + + + +

    func RegisterType

    +
    func RegisterType(x Message, name string)
    +

    +RegisterType is called from generated code and maps from the fully qualified +proto name to the type (pointer to struct) of the protocol buffer. +

    + + + + + + + +

    func RegisteredExtensions

    +
    func RegisteredExtensions(pb Message) map[int32]*ExtensionDesc
    +

    +RegisteredExtensions returns a map of the registered extensions of a +protocol buffer struct, indexed by the extension number. +The argument pb should be a nil pointer to the struct type. +

    + + + + + + + +

    func SetDefaults

    +
    func SetDefaults(pb Message)
    +

    +SetDefaults sets unset protocol buffer fields to their default values. +It only modifies fields that are both unset and have defined defaults. +It recursively sets default values in any non-nil sub-messages. +

    + + + + + + + +

    func SetExtension

    +
    func SetExtension(pb Message, extension *ExtensionDesc, value interface{}) error
    +

    +SetExtension sets the specified extension of pb to the specified value. +

    + + + + + + + +

    func SetRawExtension

    +
    func SetRawExtension(base Message, id int32, b []byte)
    +

    +SetRawExtension is for testing only. +

    + + + + + + + +

    func Size

    +
    func Size(pb Message) (n int)
    +

    +Size returns the encoded size of a protocol buffer. +

    + + + + + + + +

    func SizeVarint

    +
    func SizeVarint(x uint64) int
    +

    +SizeVarint returns the varint encoding size of an integer. +

    + + + + + + + +

    func String

    +
    func String(v string) *string
    +

    +String is a helper routine that allocates a new string value +to store v and returns a pointer to it. +

    + + + + + + + +

    func Uint32

    +
    func Uint32(v uint32) *uint32
    +

    +Uint32 is a helper routine that allocates a new uint32 value +to store v and returns a pointer to it. +

    + + + + + + + +

    func Uint64

    +
    func Uint64(v uint64) *uint64
    +

    +Uint64 is a helper routine that allocates a new uint64 value +to store v and returns a pointer to it. +

    + + + + + + + +

    func Unmarshal

    +
    func Unmarshal(buf []byte, pb Message) error
    +

    +Unmarshal parses the protocol buffer representation in buf and places the +decoded result in pb. If the struct underlying pb does not match +the data in buf, the results can be unpredictable. +

    +

    +Unmarshal resets pb before starting to unmarshal, so any +existing data in pb is always removed. Use UnmarshalMerge +to preserve and append to existing data. +

    + + + + + + + +

    func UnmarshalJSONEnum

    +
    func UnmarshalJSONEnum(m map[string]int32, data []byte, enumName string) (int32, error)
    +

    +UnmarshalJSONEnum is a helper function to simplify recovering enum int values +from their JSON-encoded representation. Given a map from the enum's symbolic +names to its int values, and a byte buffer containing the JSON-encoded +value, it returns an int32 that can be cast to the enum type by the caller. +

    +

    +The function can deal with both JSON representations, numeric and symbolic. +

    + + + + + + + +

    func UnmarshalMerge

    +
    func UnmarshalMerge(buf []byte, pb Message) error
    +

    +UnmarshalMerge parses the protocol buffer representation in buf and +writes the decoded result to pb. If the struct underlying pb does not match +the data in buf, the results can be unpredictable. +

    +

    +UnmarshalMerge merges into existing data in pb. +Most code should use Unmarshal instead. +

    + + + + + + + +

    func UnmarshalMessageSet

    +
    func UnmarshalMessageSet(buf []byte, exts interface{}) error
    +

    +UnmarshalMessageSet decodes the extension map encoded in buf in the message set wire format. +It is called by generated Unmarshal methods on protocol buffer messages with the message_set_wire_format option. +

    + + + + + + + +

    func UnmarshalMessageSetJSON

    +
    func UnmarshalMessageSetJSON(buf []byte, exts interface{}) error
    +

    +UnmarshalMessageSetJSON decodes the extension map encoded in buf in JSON format. +It is called by generated UnmarshalJSON methods on protocol buffer messages with the message_set_wire_format option. +

    + + + + + + + +

    func UnmarshalText

    +
    func UnmarshalText(s string, pb Message) error
    +

    +UnmarshalText reads a protocol buffer in Text format. UnmarshalText resets pb +before starting to unmarshal, so any existing data in pb is always removed. +If a required field is not set and no other error occurs, +UnmarshalText returns *RequiredNotSetError. +

    + + + + + + + + +

    type Buffer

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

    +A Buffer is a buffer manager for marshaling and unmarshaling +protocol buffers. It may be reused between invocations to +reduce memory usage. It is not necessary to use a Buffer; +the global functions Marshal and Unmarshal create a +temporary Buffer and are fine for most applications. +

    + + + + + + + + + + + + +

    func NewBuffer

    +
    func NewBuffer(e []byte) *Buffer
    +

    +NewBuffer allocates a new Buffer and initializes its internal data to +the contents of the argument slice. +

    + + + + + + + +

    func (*Buffer) Bytes

    +
    func (p *Buffer) Bytes() []byte
    +

    +Bytes returns the contents of the Buffer. +

    + + + + + + +

    func (*Buffer) DebugPrint

    +
    func (p *Buffer) DebugPrint(s string, b []byte)
    +

    +DebugPrint dumps the encoded data in b in a debugging format with a header +including the string s. Used in testing but made available for general debugging. +

    + + + + + + +

    func (*Buffer) DecodeFixed32

    +
    func (p *Buffer) DecodeFixed32() (x uint64, err error)
    +

    +DecodeFixed32 reads a 32-bit integer from the Buffer. +This is the format for the +fixed32, sfixed32, and float protocol buffer types. +

    + + + + + + +

    func (*Buffer) DecodeFixed64

    +
    func (p *Buffer) DecodeFixed64() (x uint64, err error)
    +

    +DecodeFixed64 reads a 64-bit integer from the Buffer. +This is the format for the +fixed64, sfixed64, and double protocol buffer types. +

    + + + + + + +

    func (*Buffer) DecodeGroup

    +
    func (p *Buffer) DecodeGroup(pb Message) error
    +

    +DecodeGroup reads a tag-delimited group from the Buffer. +

    + + + + + + +

    func (*Buffer) DecodeMessage

    +
    func (p *Buffer) DecodeMessage(pb Message) error
    +

    +DecodeMessage reads a count-delimited message from the Buffer. +

    + + + + + + +

    func (*Buffer) DecodeRawBytes

    +
    func (p *Buffer) DecodeRawBytes(alloc bool) (buf []byte, err error)
    +

    +DecodeRawBytes reads a count-delimited byte buffer from the Buffer. +This is the format used for the bytes protocol buffer +type and for embedded messages. +

    + + + + + + +

    func (*Buffer) DecodeStringBytes

    +
    func (p *Buffer) DecodeStringBytes() (s string, err error)
    +

    +DecodeStringBytes reads an encoded string from the Buffer. +This is the format used for the proto2 string type. +

    + + + + + + +

    func (*Buffer) DecodeVarint

    +
    func (p *Buffer) DecodeVarint() (x uint64, err error)
    +

    +DecodeVarint reads a varint-encoded integer from the Buffer. +This is the format for the +int32, int64, uint32, uint64, bool, and enum +protocol buffer types. +

    + + + + + + +

    func (*Buffer) DecodeZigzag32

    +
    func (p *Buffer) DecodeZigzag32() (x uint64, err error)
    +

    +DecodeZigzag32 reads a zigzag-encoded 32-bit integer +from the Buffer. +This is the format used for the sint32 protocol buffer type. +

    + + + + + + +

    func (*Buffer) DecodeZigzag64

    +
    func (p *Buffer) DecodeZigzag64() (x uint64, err error)
    +

    +DecodeZigzag64 reads a zigzag-encoded 64-bit integer +from the Buffer. +This is the format used for the sint64 protocol buffer type. +

    + + + + + + +

    func (*Buffer) EncodeFixed32

    +
    func (p *Buffer) EncodeFixed32(x uint64) error
    +

    +EncodeFixed32 writes a 32-bit integer to the Buffer. +This is the format for the +fixed32, sfixed32, and float protocol buffer types. +

    + + + + + + +

    func (*Buffer) EncodeFixed64

    +
    func (p *Buffer) EncodeFixed64(x uint64) error
    +

    +EncodeFixed64 writes a 64-bit integer to the Buffer. +This is the format for the +fixed64, sfixed64, and double protocol buffer types. +

    + + + + + + +

    func (*Buffer) EncodeMessage

    +
    func (p *Buffer) EncodeMessage(pb Message) error
    +

    +EncodeMessage writes the protocol buffer to the Buffer, +prefixed by a varint-encoded length. +

    + + + + + + +

    func (*Buffer) EncodeRawBytes

    +
    func (p *Buffer) EncodeRawBytes(b []byte) error
    +

    +EncodeRawBytes writes a count-delimited byte buffer to the Buffer. +This is the format used for the bytes protocol buffer +type and for embedded messages. +

    + + + + + + +

    func (*Buffer) EncodeStringBytes

    +
    func (p *Buffer) EncodeStringBytes(s string) error
    +

    +EncodeStringBytes writes an encoded string to the Buffer. +This is the format used for the proto2 string type. +

    + + + + + + +

    func (*Buffer) EncodeVarint

    +
    func (p *Buffer) EncodeVarint(x uint64) error
    +

    +EncodeVarint writes a varint-encoded integer to the Buffer. +This is the format for the +int32, int64, uint32, uint64, bool, and enum +protocol buffer types. +

    + + + + + + +

    func (*Buffer) EncodeZigzag32

    +
    func (p *Buffer) EncodeZigzag32(x uint64) error
    +

    +EncodeZigzag32 writes a zigzag-encoded 32-bit integer +to the Buffer. +This is the format used for the sint32 protocol buffer type. +

    + + + + + + +

    func (*Buffer) EncodeZigzag64

    +
    func (p *Buffer) EncodeZigzag64(x uint64) error
    +

    +EncodeZigzag64 writes a zigzag-encoded 64-bit integer +to the Buffer. +This is the format used for the sint64 protocol buffer type. +

    + + + + + + +

    func (*Buffer) Marshal

    +
    func (p *Buffer) Marshal(pb Message) error
    +

    +Marshal takes the protocol buffer +and encodes it into the wire format, writing the result to the +Buffer. +

    + + + + + + +

    func (*Buffer) Reset

    +
    func (p *Buffer) Reset()
    +

    +Reset resets the Buffer, ready for marshaling a new protocol buffer. +

    + + + + + + +

    func (*Buffer) SetBuf

    +
    func (p *Buffer) SetBuf(s []byte)
    +

    +SetBuf replaces the internal buffer with the slice, +ready for unmarshaling the contents of the slice. +

    + + + + + + +

    func (*Buffer) Unmarshal

    +
    func (p *Buffer) Unmarshal(pb Message) error
    +

    +Unmarshal parses the protocol buffer representation in the +Buffer and places the decoded result in pb. If the struct +underlying pb does not match the data in the buffer, the results can be +unpredictable. +

    +

    +Unlike proto.Unmarshal, this does not reset pb before starting to unmarshal. +

    + + + + + + + + +

    type Extension

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

    +Extension represents an extension in a message. +

    + + + + + + + + + + + + + + + + +

    type ExtensionDesc

    +
    type ExtensionDesc struct {
    +    ExtendedType  Message     // nil pointer to the type that is being extended
    +    ExtensionType interface{} // nil pointer to the extension type
    +    Field         int32       // field number
    +    Name          string      // fully-qualified name of extension, for text formatting
    +    Tag           string      // protobuf tag style
    +}
    +

    +ExtensionDesc represents an extension specification. +Used in generated code from the protocol compiler. +

    + + + + + + + + + + + + + + + + +

    type ExtensionRange

    +
    type ExtensionRange struct {
    +    Start, End int32 // both inclusive
    +}
    +

    +ExtensionRange represents a range of message extensions for a protocol buffer. +Used in code generated by the protocol compiler. +

    + + + + + + + + + + + + + + + + +

    type Marshaler

    +
    type Marshaler interface {
    +    Marshal() ([]byte, error)
    +}
    +

    +Marshaler is the interface representing objects that can marshal themselves. +

    + + + + + + + + + + + + + + + + +

    type Message

    +
    type Message interface {
    +    Reset()
    +    String() string
    +    ProtoMessage()
    +}
    +

    +Message is implemented by generated protocol buffer messages. +

    + + + + + + + + + + + + +

    func Clone

    +
    func Clone(pb Message) Message
    +

    +Clone returns a deep copy of a protocol buffer. +

    + + + + + + + + + +

    type OneofProperties

    +
    type OneofProperties struct {
    +    Type  reflect.Type // pointer to generated struct type for this oneof field
    +    Field int          // struct field number of the containing oneof in the message
    +    Prop  *Properties
    +}
    +

    +OneofProperties represents information about a specific field in a oneof. +

    + + + + + + + + + + + + + + + + +

    type ParseError

    +
    type ParseError struct {
    +    Message string
    +    Line    int // 1-based line number
    +    Offset  int // 0-based byte offset from start of input
    +}
    + + + + + + + + + + + + + + +

    func (*ParseError) Error

    +
    func (p *ParseError) Error() string
    + + + + + + + + +

    type Properties

    +
    type Properties struct {
    +    Name     string // name of the field, for error messages
    +    OrigName string // original name before protocol compiler (always set)
    +    JSONName string // name to use for JSON; determined by protoc
    +    Wire     string
    +    WireType int
    +    Tag      int
    +    Required bool
    +    Optional bool
    +    Repeated bool
    +    Packed   bool   // relevant for repeated primitives only
    +    Enum     string // set for enum types only
    +
    +    Default    string // default value
    +    HasDefault bool   // whether an explicit default was provided
    +    // contains filtered or unexported fields
    +}
    +

    +Properties represents the protocol-specific behavior of a single struct field. +

    + + + + + + + + + + + + + + +

    func (*Properties) Init

    +
    func (p *Properties) Init(typ reflect.Type, name, tag string, f *reflect.StructField)
    +

    +Init populates the properties from a protocol buffer struct tag. +

    + + + + + + +

    func (*Properties) Parse

    +
    func (p *Properties) Parse(s string)
    +

    +Parse populates p by parsing a string in the protobuf struct field tag style. +

    + + + + + + +

    func (*Properties) String

    +
    func (p *Properties) String() string
    +

    +String formats the properties in the protobuf struct field tag style. +

    + + + + + + + + +

    type RequiredNotSetError

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

    +RequiredNotSetError is the error returned if Marshal is called with +a protocol buffer struct whose required fields have not +all been initialized. It is also the error returned if Unmarshal is +called with an encoded protocol buffer that does not include all the +required fields. +

    +

    +When printed, RequiredNotSetError reports the first unset required field in a +message. If the field cannot be precisely determined, it is reported as +"{Unknown}". +

    + + + + + + + + + + + + + + +

    func (*RequiredNotSetError) Error

    +
    func (e *RequiredNotSetError) Error() string
    + + + + + + + + +

    type Stats

    +
    type Stats struct {
    +    Emalloc uint64 // mallocs in encode
    +    Dmalloc uint64 // mallocs in decode
    +    Encode  uint64 // number of encodes
    +    Decode  uint64 // number of decodes
    +    Chit    uint64 // number of cache hits
    +    Cmiss   uint64 // number of cache misses
    +    Size    uint64 // number of sizes
    +}
    +

    +Stats records allocation details about the protocol buffer encoders +and decoders. Useful for tuning the library itself. +

    + + + + + + + + + + + + +

    func GetStats

    +
    func GetStats() Stats
    +

    +GetStats returns a copy of the global Stats structure. +

    + + + + + + + + + +

    type StructProperties

    +
    type StructProperties struct {
    +    Prop []*Properties // properties for each field
    +
    +    // OneofTypes contains information about the oneof fields in this message.
    +    // It is keyed by the original name of a field.
    +    OneofTypes map[string]*OneofProperties
    +    // contains filtered or unexported fields
    +}
    +

    +StructProperties represents properties for all the fields of a struct. +decoderTags and decoderOrigNames should only be used by the decoder. +

    + + + + + + + + + + + + +

    func GetProperties

    +
    func GetProperties(t reflect.Type) *StructProperties
    +

    +GetProperties returns the list of properties for the type represented by t. +t must represent a generated struct type of a protocol message. +

    + + + + + + + +

    func (*StructProperties) Len

    +
    func (sp *StructProperties) Len() int
    + + + + + + +

    func (*StructProperties) Less

    +
    func (sp *StructProperties) Less(i, j int) bool
    + + + + + + +

    func (*StructProperties) Swap

    +
    func (sp *StructProperties) Swap(i, j int)
    + + + + + + + + +

    type TextMarshaler

    +
    type TextMarshaler struct {
    +    Compact   bool // use compact text format (one line).
    +    ExpandAny bool // expand google.protobuf.Any messages of known types
    +}
    +

    +TextMarshaler is a configurable text format marshaler. +

    + + + + + + + + + + + + + + +

    func (*TextMarshaler) Marshal

    +
    func (tm *TextMarshaler) Marshal(w io.Writer, pb Message) error
    +

    +Marshal writes a given protocol buffer in text format. +The only errors returned are from w. +

    + + + + + + +

    func (*TextMarshaler) Text

    +
    func (tm *TextMarshaler) Text(pb Message) string
    +

    +Text is the same as Marshal, but returns the string directly. +

    + + + + + + + + +

    type Unmarshaler

    +
    type Unmarshaler interface {
    +    Unmarshal([]byte) error
    +}
    +

    +Unmarshaler is the interface representing objects that can +unmarshal themselves. The method should reset the receiver before +decoding starts. The argument points to data that may be +overwritten, so implementations should not keep references to the +buffer. +

    + + + + + + + + + + + + + + + + +

    type XXX_InternalExtensions

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

    +XXX_InternalExtensions is an internal representation of proto extensions. +

    +

    +Each generated message struct type embeds an anonymous XXX_InternalExtensions field, +thus gaining the unexported 'extensions' method, which can be called only from the proto package. +

    +

    +The methods of XXX_InternalExtensions are not concurrency safe in general, +but calls to logically read-only methods such as has and get may be executed concurrently. +

    + + + + + + + + + + + + + + + + + + + + + + + + +

    Subdirectories

    + + + + +
    + + + + + + + + + + + + + + + + + + + + +
    NameSynopsis
    ..
    + proto3_proto + + Package proto3_proto is a generated protocol buffer package. +
    +
    + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/github.com/golang/protobuf/proto/proto3_proto/index.html b/pkg/github.com/golang/protobuf/proto/proto3_proto/index.html new file mode 100644 index 0000000..b9205f5 --- /dev/null +++ b/pkg/github.com/golang/protobuf/proto/proto3_proto/index.html @@ -0,0 +1,615 @@ + + + + + + + + proto3_proto - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Package proto3_proto

    + + + + + + + + + + + + + + +
    +
    +
    import "github.com/golang/protobuf/proto/proto3_proto"
    +
    +
    +
    Overview
    +
    Index
    + + +
    +
    + +
    + +
    +

    Overview ▾

    +

    +Package proto3_proto is a generated protocol buffer package. +

    +

    +It is generated from these files: +

    +
    proto3_proto/proto3.proto
    +
    +

    +It has these top-level messages: +

    +
    Message
    +Nested
    +MessageWithMap
    +
    + +
    +
    + + + + + + + + +

    Variables

    + +
    var Message_Humour_name = map[int32]string{
    +    0: "UNKNOWN",
    +    1: "PUNS",
    +    2: "SLAPSTICK",
    +    3: "BILL_BAILEY",
    +}
    + + +
    var Message_Humour_value = map[string]int32{
    +    "UNKNOWN":     0,
    +    "PUNS":        1,
    +    "SLAPSTICK":   2,
    +    "BILL_BAILEY": 3,
    +}
    + + + + + + + +

    type Message

    +
    type Message struct {
    +    Name         string                           `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"`
    +    Hilarity     Message_Humour                   `protobuf:"varint,2,opt,name=hilarity,enum=proto3_proto.Message_Humour" json:"hilarity,omitempty"`
    +    HeightInCm   uint32                           `protobuf:"varint,3,opt,name=height_in_cm,json=heightInCm" json:"height_in_cm,omitempty"`
    +    Data         []byte                           `protobuf:"bytes,4,opt,name=data,proto3" json:"data,omitempty"`
    +    ResultCount  int64                            `protobuf:"varint,7,opt,name=result_count,json=resultCount" json:"result_count,omitempty"`
    +    TrueScotsman bool                             `protobuf:"varint,8,opt,name=true_scotsman,json=trueScotsman" json:"true_scotsman,omitempty"`
    +    Score        float32                          `protobuf:"fixed32,9,opt,name=score" json:"score,omitempty"`
    +    Key          []uint64                         `protobuf:"varint,5,rep,name=key" json:"key,omitempty"`
    +    ShortKey     []int32                          `protobuf:"varint,19,rep,name=short_key,json=shortKey" json:"short_key,omitempty"`
    +    Nested       *Nested                          `protobuf:"bytes,6,opt,name=nested" json:"nested,omitempty"`
    +    RFunny       []Message_Humour                 `protobuf:"varint,16,rep,name=r_funny,json=rFunny,enum=proto3_proto.Message_Humour" json:"r_funny,omitempty"`
    +    Terrain      map[string]*Nested               `protobuf:"bytes,10,rep,name=terrain" json:"terrain,omitempty" protobuf_key:"bytes,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"`
    +    Proto2Field  *testdata.SubDefaults            `protobuf:"bytes,11,opt,name=proto2_field,json=proto2Field" json:"proto2_field,omitempty"`
    +    Proto2Value  map[string]*testdata.SubDefaults `protobuf:"bytes,13,rep,name=proto2_value,json=proto2Value" json:"proto2_value,omitempty" protobuf_key:"bytes,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"`
    +    Anything     *google_protobuf.Any             `protobuf:"bytes,14,opt,name=anything" json:"anything,omitempty"`
    +    ManyThings   []*google_protobuf.Any           `protobuf:"bytes,15,rep,name=many_things,json=manyThings" json:"many_things,omitempty"`
    +    Submessage   *Message                         `protobuf:"bytes,17,opt,name=submessage" json:"submessage,omitempty"`
    +    Children     []*Message                       `protobuf:"bytes,18,rep,name=children" json:"children,omitempty"`
    +}
    + + + + + + + + + + + + + + +

    func (*Message) Descriptor

    +
    func (*Message) Descriptor() ([]byte, []int)
    + + + + + + +

    func (*Message) GetAnything

    +
    func (m *Message) GetAnything() *google_protobuf.Any
    + + + + + + +

    func (*Message) GetChildren

    +
    func (m *Message) GetChildren() []*Message
    + + + + + + +

    func (*Message) GetManyThings

    +
    func (m *Message) GetManyThings() []*google_protobuf.Any
    + + + + + + +

    func (*Message) GetNested

    +
    func (m *Message) GetNested() *Nested
    + + + + + + +

    func (*Message) GetProto2Field

    +
    func (m *Message) GetProto2Field() *testdata.SubDefaults
    + + + + + + +

    func (*Message) GetProto2Value

    +
    func (m *Message) GetProto2Value() map[string]*testdata.SubDefaults
    + + + + + + +

    func (*Message) GetSubmessage

    +
    func (m *Message) GetSubmessage() *Message
    + + + + + + +

    func (*Message) GetTerrain

    +
    func (m *Message) GetTerrain() map[string]*Nested
    + + + + + + +

    func (*Message) ProtoMessage

    +
    func (*Message) ProtoMessage()
    + + + + + + +

    func (*Message) Reset

    +
    func (m *Message) Reset()
    + + + + + + +

    func (*Message) String

    +
    func (m *Message) String() string
    + + + + + + + + +

    type MessageWithMap

    +
    type MessageWithMap struct {
    +    ByteMapping map[bool][]byte `protobuf:"bytes,1,rep,name=byte_mapping,json=byteMapping" json:"byte_mapping,omitempty" protobuf_key:"varint,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value,proto3"`
    +}
    + + + + + + + + + + + + + + +

    func (*MessageWithMap) Descriptor

    +
    func (*MessageWithMap) Descriptor() ([]byte, []int)
    + + + + + + +

    func (*MessageWithMap) GetByteMapping

    +
    func (m *MessageWithMap) GetByteMapping() map[bool][]byte
    + + + + + + +

    func (*MessageWithMap) ProtoMessage

    +
    func (*MessageWithMap) ProtoMessage()
    + + + + + + +

    func (*MessageWithMap) Reset

    +
    func (m *MessageWithMap) Reset()
    + + + + + + +

    func (*MessageWithMap) String

    +
    func (m *MessageWithMap) String() string
    + + + + + + + + +

    type Message_Humour

    +
    type Message_Humour int32
    + + + +
    const (
    +    Message_UNKNOWN     Message_Humour = 0
    +    Message_PUNS        Message_Humour = 1
    +    Message_SLAPSTICK   Message_Humour = 2
    +    Message_BILL_BAILEY Message_Humour = 3
    +)
    + + + + + + + + + + + + + +

    func (Message_Humour) EnumDescriptor

    +
    func (Message_Humour) EnumDescriptor() ([]byte, []int)
    + + + + + + +

    func (Message_Humour) String

    +
    func (x Message_Humour) String() string
    + + + + + + + + +

    type Nested

    +
    type Nested struct {
    +    Bunny string `protobuf:"bytes,1,opt,name=bunny" json:"bunny,omitempty"`
    +    Cute  bool   `protobuf:"varint,2,opt,name=cute" json:"cute,omitempty"`
    +}
    + + + + + + + + + + + + + + +

    func (*Nested) Descriptor

    +
    func (*Nested) Descriptor() ([]byte, []int)
    + + + + + + +

    func (*Nested) ProtoMessage

    +
    func (*Nested) ProtoMessage()
    + + + + + + +

    func (*Nested) Reset

    +
    func (m *Nested) Reset()
    + + + + + + +

    func (*Nested) String

    +
    func (m *Nested) String() string
    + + + + + + + + + + + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/github.com/golang/protobuf/proto/testdata/index.html b/pkg/github.com/golang/protobuf/proto/testdata/index.html new file mode 100644 index 0000000..661b843 --- /dev/null +++ b/pkg/github.com/golang/protobuf/proto/testdata/index.html @@ -0,0 +1,7762 @@ + + + + + + + + testdata - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Package testdata

    + + + + + + + + + + + + + + +
    +
    +
    import "github.com/golang/protobuf/proto/testdata"
    +
    +
    +
    Overview
    +
    Index
    + + +
    +
    + +
    + +
    +

    Overview ▾

    +

    +Package testdata is a generated protocol buffer package. +

    +

    +It is generated from these files: +

    +
    test.proto
    +
    +

    +It has these top-level messages: +

    +
    GoEnum
    +GoTestField
    +GoTest
    +GoTestRequiredGroupField
    +GoSkipTest
    +NonPackedTest
    +PackedTest
    +MaxTag
    +OldMessage
    +NewMessage
    +InnerMessage
    +OtherMessage
    +RequiredInnerMessage
    +MyMessage
    +Ext
    +ComplexExtension
    +DefaultsMessage
    +MyMessageSet
    +Empty
    +MessageList
    +Strings
    +Defaults
    +SubDefaults
    +RepeatedEnum
    +MoreRepeated
    +GroupOld
    +GroupNew
    +FloatingPoint
    +MessageWithMap
    +Oneof
    +Communique
    +
    + +
    +
    + + +
    + +
    +

    Index ▾

    + + +
    +
    + +
    Constants
    + + +
    Variables
    + + + + +
    type Communique
    + + + +
        func (*Communique) Descriptor() ([]byte, []int)
    + + +
        func (m *Communique) GetCol() MyMessage_Color
    + + +
        func (m *Communique) GetData() []byte
    + + +
        func (m *Communique) GetMakeMeCry() bool
    + + +
        func (m *Communique) GetMsg() *Strings
    + + +
        func (m *Communique) GetName() string
    + + +
        func (m *Communique) GetNumber() int32
    + + +
        func (m *Communique) GetTempC() float64
    + + +
        func (m *Communique) GetUnion() isCommunique_Union
    + + +
        func (*Communique) ProtoMessage()
    + + +
        func (m *Communique) Reset()
    + + +
        func (m *Communique) String() string
    + + +
        func (*Communique) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{})
    + + + +
    type Communique_Col
    + + + + +
    type Communique_Data
    + + + + +
    type Communique_Msg
    + + + + +
    type Communique_Name
    + + + + +
    type Communique_Number
    + + + + +
    type Communique_TempC
    + + + + +
    type ComplexExtension
    + + + +
        func (*ComplexExtension) Descriptor() ([]byte, []int)
    + + +
        func (m *ComplexExtension) GetFirst() int32
    + + +
        func (m *ComplexExtension) GetSecond() int32
    + + +
        func (m *ComplexExtension) GetThird() []int32
    + + +
        func (*ComplexExtension) ProtoMessage()
    + + +
        func (m *ComplexExtension) Reset()
    + + +
        func (m *ComplexExtension) String() string
    + + + +
    type Defaults
    + + + +
        func (*Defaults) Descriptor() ([]byte, []int)
    + + +
        func (m *Defaults) GetF_Bool() bool
    + + +
        func (m *Defaults) GetF_Bytes() []byte
    + + +
        func (m *Defaults) GetF_Double() float64
    + + +
        func (m *Defaults) GetF_Enum() Defaults_Color
    + + +
        func (m *Defaults) GetF_Fixed32() uint32
    + + +
        func (m *Defaults) GetF_Fixed64() uint64
    + + +
        func (m *Defaults) GetF_Float() float32
    + + +
        func (m *Defaults) GetF_Int32() int32
    + + +
        func (m *Defaults) GetF_Int64() int64
    + + +
        func (m *Defaults) GetF_Nan() float32
    + + +
        func (m *Defaults) GetF_Ninf() float32
    + + +
        func (m *Defaults) GetF_Pinf() float32
    + + +
        func (m *Defaults) GetF_Sint32() int32
    + + +
        func (m *Defaults) GetF_Sint64() int64
    + + +
        func (m *Defaults) GetF_String() string
    + + +
        func (m *Defaults) GetF_Uint32() uint32
    + + +
        func (m *Defaults) GetF_Uint64() uint64
    + + +
        func (m *Defaults) GetStrZero() string
    + + +
        func (m *Defaults) GetSub() *SubDefaults
    + + +
        func (*Defaults) ProtoMessage()
    + + +
        func (m *Defaults) Reset()
    + + +
        func (m *Defaults) String() string
    + + + +
    type DefaultsMessage
    + + + +
        func (*DefaultsMessage) Descriptor() ([]byte, []int)
    + + +
        func (*DefaultsMessage) ExtensionRangeArray() []proto.ExtensionRange
    + + +
        func (*DefaultsMessage) ProtoMessage()
    + + +
        func (m *DefaultsMessage) Reset()
    + + +
        func (m *DefaultsMessage) String() string
    + + + +
    type DefaultsMessage_DefaultsEnum
    + + + +
        func (x DefaultsMessage_DefaultsEnum) Enum() *DefaultsMessage_DefaultsEnum
    + + +
        func (DefaultsMessage_DefaultsEnum) EnumDescriptor() ([]byte, []int)
    + + +
        func (x DefaultsMessage_DefaultsEnum) String() string
    + + +
        func (x *DefaultsMessage_DefaultsEnum) UnmarshalJSON(data []byte) error
    + + + +
    type Defaults_Color
    + + + +
        func (x Defaults_Color) Enum() *Defaults_Color
    + + +
        func (Defaults_Color) EnumDescriptor() ([]byte, []int)
    + + +
        func (x Defaults_Color) String() string
    + + +
        func (x *Defaults_Color) UnmarshalJSON(data []byte) error
    + + + +
    type Empty
    + + + +
        func (*Empty) Descriptor() ([]byte, []int)
    + + +
        func (*Empty) ProtoMessage()
    + + +
        func (m *Empty) Reset()
    + + +
        func (m *Empty) String() string
    + + + +
    type Ext
    + + + +
        func (*Ext) Descriptor() ([]byte, []int)
    + + +
        func (m *Ext) GetData() string
    + + +
        func (*Ext) ProtoMessage()
    + + +
        func (m *Ext) Reset()
    + + +
        func (m *Ext) String() string
    + + + +
    type FOO
    + + + +
        func (x FOO) Enum() *FOO
    + + +
        func (FOO) EnumDescriptor() ([]byte, []int)
    + + +
        func (x FOO) String() string
    + + +
        func (x *FOO) UnmarshalJSON(data []byte) error
    + + + +
    type FloatingPoint
    + + + +
        func (*FloatingPoint) Descriptor() ([]byte, []int)
    + + +
        func (m *FloatingPoint) GetExact() bool
    + + +
        func (m *FloatingPoint) GetF() float64
    + + +
        func (*FloatingPoint) ProtoMessage()
    + + +
        func (m *FloatingPoint) Reset()
    + + +
        func (m *FloatingPoint) String() string
    + + + +
    type GoEnum
    + + + +
        func (*GoEnum) Descriptor() ([]byte, []int)
    + + +
        func (m *GoEnum) GetFoo() FOO
    + + +
        func (*GoEnum) ProtoMessage()
    + + +
        func (m *GoEnum) Reset()
    + + +
        func (m *GoEnum) String() string
    + + + +
    type GoSkipTest
    + + + +
        func (*GoSkipTest) Descriptor() ([]byte, []int)
    + + +
        func (m *GoSkipTest) GetSkipFixed32() uint32
    + + +
        func (m *GoSkipTest) GetSkipFixed64() uint64
    + + +
        func (m *GoSkipTest) GetSkipInt32() int32
    + + +
        func (m *GoSkipTest) GetSkipString() string
    + + +
        func (m *GoSkipTest) GetSkipgroup() *GoSkipTest_SkipGroup
    + + +
        func (*GoSkipTest) ProtoMessage()
    + + +
        func (m *GoSkipTest) Reset()
    + + +
        func (m *GoSkipTest) String() string
    + + + +
    type GoSkipTest_SkipGroup
    + + + +
        func (*GoSkipTest_SkipGroup) Descriptor() ([]byte, []int)
    + + +
        func (m *GoSkipTest_SkipGroup) GetGroupInt32() int32
    + + +
        func (m *GoSkipTest_SkipGroup) GetGroupString() string
    + + +
        func (*GoSkipTest_SkipGroup) ProtoMessage()
    + + +
        func (m *GoSkipTest_SkipGroup) Reset()
    + + +
        func (m *GoSkipTest_SkipGroup) String() string
    + + + +
    type GoTest
    + + + +
        func (*GoTest) Descriptor() ([]byte, []int)
    + + +
        func (m *GoTest) GetF_BoolDefaulted() bool
    + + +
        func (m *GoTest) GetF_BoolOptional() bool
    + + +
        func (m *GoTest) GetF_BoolRepeated() []bool
    + + +
        func (m *GoTest) GetF_BoolRepeatedPacked() []bool
    + + +
        func (m *GoTest) GetF_BoolRequired() bool
    + + +
        func (m *GoTest) GetF_BytesDefaulted() []byte
    + + +
        func (m *GoTest) GetF_BytesOptional() []byte
    + + +
        func (m *GoTest) GetF_BytesRepeated() [][]byte
    + + +
        func (m *GoTest) GetF_BytesRequired() []byte
    + + +
        func (m *GoTest) GetF_DoubleDefaulted() float64
    + + +
        func (m *GoTest) GetF_DoubleOptional() float64
    + + +
        func (m *GoTest) GetF_DoubleRepeated() []float64
    + + +
        func (m *GoTest) GetF_DoubleRepeatedPacked() []float64
    + + +
        func (m *GoTest) GetF_DoubleRequired() float64
    + + +
        func (m *GoTest) GetF_Fixed32Defaulted() uint32
    + + +
        func (m *GoTest) GetF_Fixed32Optional() uint32
    + + +
        func (m *GoTest) GetF_Fixed32Repeated() []uint32
    + + +
        func (m *GoTest) GetF_Fixed32RepeatedPacked() []uint32
    + + +
        func (m *GoTest) GetF_Fixed32Required() uint32
    + + +
        func (m *GoTest) GetF_Fixed64Defaulted() uint64
    + + +
        func (m *GoTest) GetF_Fixed64Optional() uint64
    + + +
        func (m *GoTest) GetF_Fixed64Repeated() []uint64
    + + +
        func (m *GoTest) GetF_Fixed64RepeatedPacked() []uint64
    + + +
        func (m *GoTest) GetF_Fixed64Required() uint64
    + + +
        func (m *GoTest) GetF_FloatDefaulted() float32
    + + +
        func (m *GoTest) GetF_FloatOptional() float32
    + + +
        func (m *GoTest) GetF_FloatRepeated() []float32
    + + +
        func (m *GoTest) GetF_FloatRepeatedPacked() []float32
    + + +
        func (m *GoTest) GetF_FloatRequired() float32
    + + +
        func (m *GoTest) GetF_Int32Defaulted() int32
    + + +
        func (m *GoTest) GetF_Int32Optional() int32
    + + +
        func (m *GoTest) GetF_Int32Repeated() []int32
    + + +
        func (m *GoTest) GetF_Int32RepeatedPacked() []int32
    + + +
        func (m *GoTest) GetF_Int32Required() int32
    + + +
        func (m *GoTest) GetF_Int64Defaulted() int64
    + + +
        func (m *GoTest) GetF_Int64Optional() int64
    + + +
        func (m *GoTest) GetF_Int64Repeated() []int64
    + + +
        func (m *GoTest) GetF_Int64RepeatedPacked() []int64
    + + +
        func (m *GoTest) GetF_Int64Required() int64
    + + +
        func (m *GoTest) GetF_Sint32Defaulted() int32
    + + +
        func (m *GoTest) GetF_Sint32Optional() int32
    + + +
        func (m *GoTest) GetF_Sint32Repeated() []int32
    + + +
        func (m *GoTest) GetF_Sint32RepeatedPacked() []int32
    + + +
        func (m *GoTest) GetF_Sint32Required() int32
    + + +
        func (m *GoTest) GetF_Sint64Defaulted() int64
    + + +
        func (m *GoTest) GetF_Sint64Optional() int64
    + + +
        func (m *GoTest) GetF_Sint64Repeated() []int64
    + + +
        func (m *GoTest) GetF_Sint64RepeatedPacked() []int64
    + + +
        func (m *GoTest) GetF_Sint64Required() int64
    + + +
        func (m *GoTest) GetF_StringDefaulted() string
    + + +
        func (m *GoTest) GetF_StringOptional() string
    + + +
        func (m *GoTest) GetF_StringRepeated() []string
    + + +
        func (m *GoTest) GetF_StringRequired() string
    + + +
        func (m *GoTest) GetF_Uint32Defaulted() uint32
    + + +
        func (m *GoTest) GetF_Uint32Optional() uint32
    + + +
        func (m *GoTest) GetF_Uint32Repeated() []uint32
    + + +
        func (m *GoTest) GetF_Uint32RepeatedPacked() []uint32
    + + +
        func (m *GoTest) GetF_Uint32Required() uint32
    + + +
        func (m *GoTest) GetF_Uint64Defaulted() uint64
    + + +
        func (m *GoTest) GetF_Uint64Optional() uint64
    + + +
        func (m *GoTest) GetF_Uint64Repeated() []uint64
    + + +
        func (m *GoTest) GetF_Uint64RepeatedPacked() []uint64
    + + +
        func (m *GoTest) GetF_Uint64Required() uint64
    + + +
        func (m *GoTest) GetKind() GoTest_KIND
    + + +
        func (m *GoTest) GetOptionalField() *GoTestField
    + + +
        func (m *GoTest) GetOptionalgroup() *GoTest_OptionalGroup
    + + +
        func (m *GoTest) GetParam() int32
    + + +
        func (m *GoTest) GetRepeatedField() []*GoTestField
    + + +
        func (m *GoTest) GetRepeatedgroup() []*GoTest_RepeatedGroup
    + + +
        func (m *GoTest) GetRequiredField() *GoTestField
    + + +
        func (m *GoTest) GetRequiredgroup() *GoTest_RequiredGroup
    + + +
        func (m *GoTest) GetTable() string
    + + +
        func (*GoTest) ProtoMessage()
    + + +
        func (m *GoTest) Reset()
    + + +
        func (m *GoTest) String() string
    + + + +
    type GoTestField
    + + + +
        func (*GoTestField) Descriptor() ([]byte, []int)
    + + +
        func (m *GoTestField) GetLabel() string
    + + +
        func (m *GoTestField) GetType() string
    + + +
        func (*GoTestField) ProtoMessage()
    + + +
        func (m *GoTestField) Reset()
    + + +
        func (m *GoTestField) String() string
    + + + +
    type GoTestRequiredGroupField
    + + + +
        func (*GoTestRequiredGroupField) Descriptor() ([]byte, []int)
    + + +
        func (m *GoTestRequiredGroupField) GetGroup() *GoTestRequiredGroupField_Group
    + + +
        func (*GoTestRequiredGroupField) ProtoMessage()
    + + +
        func (m *GoTestRequiredGroupField) Reset()
    + + +
        func (m *GoTestRequiredGroupField) String() string
    + + + +
    type GoTestRequiredGroupField_Group
    + + + +
        func (*GoTestRequiredGroupField_Group) Descriptor() ([]byte, []int)
    + + +
        func (m *GoTestRequiredGroupField_Group) GetField() int32
    + + +
        func (*GoTestRequiredGroupField_Group) ProtoMessage()
    + + +
        func (m *GoTestRequiredGroupField_Group) Reset()
    + + +
        func (m *GoTestRequiredGroupField_Group) String() string
    + + + +
    type GoTest_KIND
    + + + +
        func (x GoTest_KIND) Enum() *GoTest_KIND
    + + +
        func (GoTest_KIND) EnumDescriptor() ([]byte, []int)
    + + +
        func (x GoTest_KIND) String() string
    + + +
        func (x *GoTest_KIND) UnmarshalJSON(data []byte) error
    + + + +
    type GoTest_OptionalGroup
    + + + +
        func (*GoTest_OptionalGroup) Descriptor() ([]byte, []int)
    + + +
        func (m *GoTest_OptionalGroup) GetRequiredField() string
    + + +
        func (*GoTest_OptionalGroup) ProtoMessage()
    + + +
        func (m *GoTest_OptionalGroup) Reset()
    + + +
        func (m *GoTest_OptionalGroup) String() string
    + + + +
    type GoTest_RepeatedGroup
    + + + +
        func (*GoTest_RepeatedGroup) Descriptor() ([]byte, []int)
    + + +
        func (m *GoTest_RepeatedGroup) GetRequiredField() string
    + + +
        func (*GoTest_RepeatedGroup) ProtoMessage()
    + + +
        func (m *GoTest_RepeatedGroup) Reset()
    + + +
        func (m *GoTest_RepeatedGroup) String() string
    + + + +
    type GoTest_RequiredGroup
    + + + +
        func (*GoTest_RequiredGroup) Descriptor() ([]byte, []int)
    + + +
        func (m *GoTest_RequiredGroup) GetRequiredField() string
    + + +
        func (*GoTest_RequiredGroup) ProtoMessage()
    + + +
        func (m *GoTest_RequiredGroup) Reset()
    + + +
        func (m *GoTest_RequiredGroup) String() string
    + + + +
    type GroupNew
    + + + +
        func (*GroupNew) Descriptor() ([]byte, []int)
    + + +
        func (m *GroupNew) GetG() *GroupNew_G
    + + +
        func (*GroupNew) ProtoMessage()
    + + +
        func (m *GroupNew) Reset()
    + + +
        func (m *GroupNew) String() string
    + + + +
    type GroupNew_G
    + + + +
        func (*GroupNew_G) Descriptor() ([]byte, []int)
    + + +
        func (m *GroupNew_G) GetX() int32
    + + +
        func (m *GroupNew_G) GetY() int32
    + + +
        func (*GroupNew_G) ProtoMessage()
    + + +
        func (m *GroupNew_G) Reset()
    + + +
        func (m *GroupNew_G) String() string
    + + + +
    type GroupOld
    + + + +
        func (*GroupOld) Descriptor() ([]byte, []int)
    + + +
        func (m *GroupOld) GetG() *GroupOld_G
    + + +
        func (*GroupOld) ProtoMessage()
    + + +
        func (m *GroupOld) Reset()
    + + +
        func (m *GroupOld) String() string
    + + + +
    type GroupOld_G
    + + + +
        func (*GroupOld_G) Descriptor() ([]byte, []int)
    + + +
        func (m *GroupOld_G) GetX() int32
    + + +
        func (*GroupOld_G) ProtoMessage()
    + + +
        func (m *GroupOld_G) Reset()
    + + +
        func (m *GroupOld_G) String() string
    + + + +
    type InnerMessage
    + + + +
        func (*InnerMessage) Descriptor() ([]byte, []int)
    + + +
        func (m *InnerMessage) GetConnected() bool
    + + +
        func (m *InnerMessage) GetHost() string
    + + +
        func (m *InnerMessage) GetPort() int32
    + + +
        func (*InnerMessage) ProtoMessage()
    + + +
        func (m *InnerMessage) Reset()
    + + +
        func (m *InnerMessage) String() string
    + + + +
    type MaxTag
    + + + +
        func (*MaxTag) Descriptor() ([]byte, []int)
    + + +
        func (m *MaxTag) GetLastField() string
    + + +
        func (*MaxTag) ProtoMessage()
    + + +
        func (m *MaxTag) Reset()
    + + +
        func (m *MaxTag) String() string
    + + + +
    type MessageList
    + + + +
        func (*MessageList) Descriptor() ([]byte, []int)
    + + +
        func (m *MessageList) GetMessage() []*MessageList_Message
    + + +
        func (*MessageList) ProtoMessage()
    + + +
        func (m *MessageList) Reset()
    + + +
        func (m *MessageList) String() string
    + + + +
    type MessageList_Message
    + + + +
        func (*MessageList_Message) Descriptor() ([]byte, []int)
    + + +
        func (m *MessageList_Message) GetCount() int32
    + + +
        func (m *MessageList_Message) GetName() string
    + + +
        func (*MessageList_Message) ProtoMessage()
    + + +
        func (m *MessageList_Message) Reset()
    + + +
        func (m *MessageList_Message) String() string
    + + + +
    type MessageWithMap
    + + + +
        func (*MessageWithMap) Descriptor() ([]byte, []int)
    + + +
        func (m *MessageWithMap) GetByteMapping() map[bool][]byte
    + + +
        func (m *MessageWithMap) GetMsgMapping() map[int64]*FloatingPoint
    + + +
        func (m *MessageWithMap) GetNameMapping() map[int32]string
    + + +
        func (m *MessageWithMap) GetStrToStr() map[string]string
    + + +
        func (*MessageWithMap) ProtoMessage()
    + + +
        func (m *MessageWithMap) Reset()
    + + +
        func (m *MessageWithMap) String() string
    + + + +
    type MoreRepeated
    + + + +
        func (*MoreRepeated) Descriptor() ([]byte, []int)
    + + +
        func (m *MoreRepeated) GetBools() []bool
    + + +
        func (m *MoreRepeated) GetBoolsPacked() []bool
    + + +
        func (m *MoreRepeated) GetFixeds() []uint32
    + + +
        func (m *MoreRepeated) GetInt64SPacked() []int64
    + + +
        func (m *MoreRepeated) GetInts() []int32
    + + +
        func (m *MoreRepeated) GetIntsPacked() []int32
    + + +
        func (m *MoreRepeated) GetStrings() []string
    + + +
        func (*MoreRepeated) ProtoMessage()
    + + +
        func (m *MoreRepeated) Reset()
    + + +
        func (m *MoreRepeated) String() string
    + + + +
    type MyMessage
    + + + +
        func (*MyMessage) Descriptor() ([]byte, []int)
    + + +
        func (*MyMessage) ExtensionRangeArray() []proto.ExtensionRange
    + + +
        func (m *MyMessage) GetBigfloat() float64
    + + +
        func (m *MyMessage) GetBikeshed() MyMessage_Color
    + + +
        func (m *MyMessage) GetCount() int32
    + + +
        func (m *MyMessage) GetInner() *InnerMessage
    + + +
        func (m *MyMessage) GetName() string
    + + +
        func (m *MyMessage) GetOthers() []*OtherMessage
    + + +
        func (m *MyMessage) GetPet() []string
    + + +
        func (m *MyMessage) GetQuote() string
    + + +
        func (m *MyMessage) GetRepBytes() [][]byte
    + + +
        func (m *MyMessage) GetRepInner() []*InnerMessage
    + + +
        func (m *MyMessage) GetSomegroup() *MyMessage_SomeGroup
    + + +
        func (m *MyMessage) GetWeMustGoDeeper() *RequiredInnerMessage
    + + +
        func (*MyMessage) ProtoMessage()
    + + +
        func (m *MyMessage) Reset()
    + + +
        func (m *MyMessage) String() string
    + + + +
    type MyMessageSet
    + + + +
        func (*MyMessageSet) Descriptor() ([]byte, []int)
    + + +
        func (*MyMessageSet) ExtensionRangeArray() []proto.ExtensionRange
    + + +
        func (m *MyMessageSet) Marshal() ([]byte, error)
    + + +
        func (m *MyMessageSet) MarshalJSON() ([]byte, error)
    + + +
        func (*MyMessageSet) ProtoMessage()
    + + +
        func (m *MyMessageSet) Reset()
    + + +
        func (m *MyMessageSet) String() string
    + + +
        func (m *MyMessageSet) Unmarshal(buf []byte) error
    + + +
        func (m *MyMessageSet) UnmarshalJSON(buf []byte) error
    + + + +
    type MyMessage_Color
    + + + +
        func (x MyMessage_Color) Enum() *MyMessage_Color
    + + +
        func (MyMessage_Color) EnumDescriptor() ([]byte, []int)
    + + +
        func (x MyMessage_Color) String() string
    + + +
        func (x *MyMessage_Color) UnmarshalJSON(data []byte) error
    + + + +
    type MyMessage_SomeGroup
    + + + +
        func (*MyMessage_SomeGroup) Descriptor() ([]byte, []int)
    + + +
        func (m *MyMessage_SomeGroup) GetGroupField() int32
    + + +
        func (*MyMessage_SomeGroup) ProtoMessage()
    + + +
        func (m *MyMessage_SomeGroup) Reset()
    + + +
        func (m *MyMessage_SomeGroup) String() string
    + + + +
    type NewMessage
    + + + +
        func (*NewMessage) Descriptor() ([]byte, []int)
    + + +
        func (m *NewMessage) GetNested() *NewMessage_Nested
    + + +
        func (m *NewMessage) GetNum() int64
    + + +
        func (*NewMessage) ProtoMessage()
    + + +
        func (m *NewMessage) Reset()
    + + +
        func (m *NewMessage) String() string
    + + + +
    type NewMessage_Nested
    + + + +
        func (*NewMessage_Nested) Descriptor() ([]byte, []int)
    + + +
        func (m *NewMessage_Nested) GetFoodGroup() string
    + + +
        func (m *NewMessage_Nested) GetName() string
    + + +
        func (*NewMessage_Nested) ProtoMessage()
    + + +
        func (m *NewMessage_Nested) Reset()
    + + +
        func (m *NewMessage_Nested) String() string
    + + + +
    type NonPackedTest
    + + + +
        func (*NonPackedTest) Descriptor() ([]byte, []int)
    + + +
        func (m *NonPackedTest) GetA() []int32
    + + +
        func (*NonPackedTest) ProtoMessage()
    + + +
        func (m *NonPackedTest) Reset()
    + + +
        func (m *NonPackedTest) String() string
    + + + +
    type OldMessage
    + + + +
        func (*OldMessage) Descriptor() ([]byte, []int)
    + + +
        func (m *OldMessage) GetNested() *OldMessage_Nested
    + + +
        func (m *OldMessage) GetNum() int32
    + + +
        func (*OldMessage) ProtoMessage()
    + + +
        func (m *OldMessage) Reset()
    + + +
        func (m *OldMessage) String() string
    + + + +
    type OldMessage_Nested
    + + + +
        func (*OldMessage_Nested) Descriptor() ([]byte, []int)
    + + +
        func (m *OldMessage_Nested) GetName() string
    + + +
        func (*OldMessage_Nested) ProtoMessage()
    + + +
        func (m *OldMessage_Nested) Reset()
    + + +
        func (m *OldMessage_Nested) String() string
    + + + +
    type Oneof
    + + + +
        func (*Oneof) Descriptor() ([]byte, []int)
    + + +
        func (m *Oneof) GetFGroup() *Oneof_F_Group
    + + +
        func (m *Oneof) GetF_Bool() bool
    + + +
        func (m *Oneof) GetF_Bytes() []byte
    + + +
        func (m *Oneof) GetF_Double() float64
    + + +
        func (m *Oneof) GetF_Enum() MyMessage_Color
    + + +
        func (m *Oneof) GetF_Fixed32() uint32
    + + +
        func (m *Oneof) GetF_Fixed64() uint64
    + + +
        func (m *Oneof) GetF_Float() float32
    + + +
        func (m *Oneof) GetF_Int32() int32
    + + +
        func (m *Oneof) GetF_Int64() int64
    + + +
        func (m *Oneof) GetF_Largest_Tag() int32
    + + +
        func (m *Oneof) GetF_Message() *GoTestField
    + + +
        func (m *Oneof) GetF_Sint32() int32
    + + +
        func (m *Oneof) GetF_Sint64() int64
    + + +
        func (m *Oneof) GetF_String() string
    + + +
        func (m *Oneof) GetF_Uint32() uint32
    + + +
        func (m *Oneof) GetF_Uint64() uint64
    + + +
        func (m *Oneof) GetTormato() isOneof_Tormato
    + + +
        func (m *Oneof) GetUnion() isOneof_Union
    + + +
        func (m *Oneof) GetValue() int32
    + + +
        func (*Oneof) ProtoMessage()
    + + +
        func (m *Oneof) Reset()
    + + +
        func (m *Oneof) String() string
    + + +
        func (*Oneof) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{})
    + + + +
    type Oneof_FGroup
    + + + + +
    type Oneof_F_Bool
    + + + + +
    type Oneof_F_Bytes
    + + + + +
    type Oneof_F_Double
    + + + + +
    type Oneof_F_Enum
    + + + + +
    type Oneof_F_Fixed32
    + + + + +
    type Oneof_F_Fixed64
    + + + + +
    type Oneof_F_Float
    + + + + +
    type Oneof_F_Group
    + + + +
        func (*Oneof_F_Group) Descriptor() ([]byte, []int)
    + + +
        func (m *Oneof_F_Group) GetX() int32
    + + +
        func (*Oneof_F_Group) ProtoMessage()
    + + +
        func (m *Oneof_F_Group) Reset()
    + + +
        func (m *Oneof_F_Group) String() string
    + + + +
    type Oneof_F_Int32
    + + + + +
    type Oneof_F_Int64
    + + + + +
    type Oneof_F_Largest_Tag
    + + + + +
    type Oneof_F_Message
    + + + + +
    type Oneof_F_Sint32
    + + + + +
    type Oneof_F_Sint64
    + + + + +
    type Oneof_F_String
    + + + + +
    type Oneof_F_Uint32
    + + + + +
    type Oneof_F_Uint64
    + + + + +
    type Oneof_Value
    + + + + +
    type OtherMessage
    + + + +
        func (*OtherMessage) Descriptor() ([]byte, []int)
    + + +
        func (*OtherMessage) ExtensionRangeArray() []proto.ExtensionRange
    + + +
        func (m *OtherMessage) GetInner() *InnerMessage
    + + +
        func (m *OtherMessage) GetKey() int64
    + + +
        func (m *OtherMessage) GetValue() []byte
    + + +
        func (m *OtherMessage) GetWeight() float32
    + + +
        func (*OtherMessage) ProtoMessage()
    + + +
        func (m *OtherMessage) Reset()
    + + +
        func (m *OtherMessage) String() string
    + + + +
    type PackedTest
    + + + +
        func (*PackedTest) Descriptor() ([]byte, []int)
    + + +
        func (m *PackedTest) GetB() []int32
    + + +
        func (*PackedTest) ProtoMessage()
    + + +
        func (m *PackedTest) Reset()
    + + +
        func (m *PackedTest) String() string
    + + + +
    type RepeatedEnum
    + + + +
        func (*RepeatedEnum) Descriptor() ([]byte, []int)
    + + +
        func (m *RepeatedEnum) GetColor() []RepeatedEnum_Color
    + + +
        func (*RepeatedEnum) ProtoMessage()
    + + +
        func (m *RepeatedEnum) Reset()
    + + +
        func (m *RepeatedEnum) String() string
    + + + +
    type RepeatedEnum_Color
    + + + +
        func (x RepeatedEnum_Color) Enum() *RepeatedEnum_Color
    + + +
        func (RepeatedEnum_Color) EnumDescriptor() ([]byte, []int)
    + + +
        func (x RepeatedEnum_Color) String() string
    + + +
        func (x *RepeatedEnum_Color) UnmarshalJSON(data []byte) error
    + + + +
    type RequiredInnerMessage
    + + + +
        func (*RequiredInnerMessage) Descriptor() ([]byte, []int)
    + + +
        func (m *RequiredInnerMessage) GetLeoFinallyWonAnOscar() *InnerMessage
    + + +
        func (*RequiredInnerMessage) ProtoMessage()
    + + +
        func (m *RequiredInnerMessage) Reset()
    + + +
        func (m *RequiredInnerMessage) String() string
    + + + +
    type Strings
    + + + +
        func (*Strings) Descriptor() ([]byte, []int)
    + + +
        func (m *Strings) GetBytesField() []byte
    + + +
        func (m *Strings) GetStringField() string
    + + +
        func (*Strings) ProtoMessage()
    + + +
        func (m *Strings) Reset()
    + + +
        func (m *Strings) String() string
    + + + +
    type SubDefaults
    + + + +
        func (*SubDefaults) Descriptor() ([]byte, []int)
    + + +
        func (m *SubDefaults) GetN() int64
    + + +
        func (*SubDefaults) ProtoMessage()
    + + +
        func (m *SubDefaults) Reset()
    + + +
        func (m *SubDefaults) String() string
    + + + +
    +
    + + + + +

    Package files

    +

    + + + test.pb.go + + +

    + +
    +
    + + + + +

    Constants

    + +
    const Default_Defaults_F_Bool bool = true
    + + +
    const Default_Defaults_F_Double float64 = 271828
    + + +
    const Default_Defaults_F_Fixed32 uint32 = 320
    + + +
    const Default_Defaults_F_Fixed64 uint64 = 640
    + + +
    const Default_Defaults_F_Float float32 = 314159
    + + +
    const Default_Defaults_F_Int32 int32 = 32
    + + +
    const Default_Defaults_F_Int64 int64 = 64
    + + +
    const Default_Defaults_F_Sint32 int32 = -32
    + + +
    const Default_Defaults_F_Sint64 int64 = -64
    + + +
    const Default_Defaults_F_String string = "hello, \"world!\"\n"
    + + +
    const Default_Defaults_F_Uint32 uint32 = 3200
    + + +
    const Default_Defaults_F_Uint64 uint64 = 6400
    + + +
    const Default_GoTest_F_BoolDefaulted bool = true
    + + +
    const Default_GoTest_F_DoubleDefaulted float64 = 271828
    + + +
    const Default_GoTest_F_Fixed32Defaulted uint32 = 320
    + + +
    const Default_GoTest_F_Fixed64Defaulted uint64 = 640
    + + +
    const Default_GoTest_F_FloatDefaulted float32 = 314159
    + + +
    const Default_GoTest_F_Int32Defaulted int32 = 32
    + + +
    const Default_GoTest_F_Int64Defaulted int64 = 64
    + + +
    const Default_GoTest_F_Sint32Defaulted int32 = -32
    + + +
    const Default_GoTest_F_Sint64Defaulted int64 = -64
    + + +
    const Default_GoTest_F_StringDefaulted string = "hello, \"world!\"\n"
    + + +
    const Default_GoTest_F_Uint32Defaulted uint32 = 3200
    + + +
    const Default_GoTest_F_Uint64Defaulted uint64 = 6400
    + + +
    const Default_InnerMessage_Port int32 = 4000
    + + +
    const Default_SubDefaults_N int64 = 7
    + + + + +

    Variables

    + +
    var Default_Defaults_F_Bytes []byte = []byte("Bignose")
    + + +
    var Default_Defaults_F_Nan float32 = float32(math.NaN())
    + + +
    var Default_Defaults_F_Ninf float32 = float32(math.Inf(-1))
    + + +
    var Default_Defaults_F_Pinf float32 = float32(math.Inf(1))
    + + +
    var Default_GoTest_F_BytesDefaulted []byte = []byte("Bignose")
    + + +
    var DefaultsMessage_DefaultsEnum_name = map[int32]string{
    +    0: "ZERO",
    +    1: "ONE",
    +    2: "TWO",
    +}
    + + +
    var DefaultsMessage_DefaultsEnum_value = map[string]int32{
    +    "ZERO": 0,
    +    "ONE":  1,
    +    "TWO":  2,
    +}
    + + +
    var Defaults_Color_name = map[int32]string{
    +    0: "RED",
    +    1: "GREEN",
    +    2: "BLUE",
    +}
    + + +
    var Defaults_Color_value = map[string]int32{
    +    "RED":   0,
    +    "GREEN": 1,
    +    "BLUE":  2,
    +}
    + + +
    var E_Complex = &proto.ExtensionDesc{
    +    ExtendedType:  (*OtherMessage)(nil),
    +    ExtensionType: (*ComplexExtension)(nil),
    +    Field:         200,
    +    Name:          "testdata.complex",
    +    Tag:           "bytes,200,opt,name=complex",
    +}
    + + +
    var E_DefaultBool = &proto.ExtensionDesc{
    +    ExtendedType:  (*DefaultsMessage)(nil),
    +    ExtensionType: (*bool)(nil),
    +    Field:         213,
    +    Name:          "testdata.default_bool",
    +    Tag:           "varint,213,opt,name=default_bool,json=defaultBool,def=1",
    +}
    + + +
    var E_DefaultBytes = &proto.ExtensionDesc{
    +    ExtendedType:  (*DefaultsMessage)(nil),
    +    ExtensionType: ([]byte)(nil),
    +    Field:         215,
    +    Name:          "testdata.default_bytes",
    +    Tag:           "bytes,215,opt,name=default_bytes,json=defaultBytes,def=Hello, bytes",
    +}
    + + +
    var E_DefaultDouble = &proto.ExtensionDesc{
    +    ExtendedType:  (*DefaultsMessage)(nil),
    +    ExtensionType: (*float64)(nil),
    +    Field:         201,
    +    Name:          "testdata.default_double",
    +    Tag:           "fixed64,201,opt,name=default_double,json=defaultDouble,def=3.1415",
    +}
    + + +
    var E_DefaultEnum = &proto.ExtensionDesc{
    +    ExtendedType:  (*DefaultsMessage)(nil),
    +    ExtensionType: (*DefaultsMessage_DefaultsEnum)(nil),
    +    Field:         216,
    +    Name:          "testdata.default_enum",
    +    Tag:           "varint,216,opt,name=default_enum,json=defaultEnum,enum=testdata.DefaultsMessage_DefaultsEnum,def=1",
    +}
    + + +
    var E_DefaultFixed32 = &proto.ExtensionDesc{
    +    ExtendedType:  (*DefaultsMessage)(nil),
    +    ExtensionType: (*uint32)(nil),
    +    Field:         209,
    +    Name:          "testdata.default_fixed32",
    +    Tag:           "fixed32,209,opt,name=default_fixed32,json=defaultFixed32,def=48",
    +}
    + + +
    var E_DefaultFixed64 = &proto.ExtensionDesc{
    +    ExtendedType:  (*DefaultsMessage)(nil),
    +    ExtensionType: (*uint64)(nil),
    +    Field:         210,
    +    Name:          "testdata.default_fixed64",
    +    Tag:           "fixed64,210,opt,name=default_fixed64,json=defaultFixed64,def=49",
    +}
    + + +
    var E_DefaultFloat = &proto.ExtensionDesc{
    +    ExtendedType:  (*DefaultsMessage)(nil),
    +    ExtensionType: (*float32)(nil),
    +    Field:         202,
    +    Name:          "testdata.default_float",
    +    Tag:           "fixed32,202,opt,name=default_float,json=defaultFloat,def=3.14",
    +}
    + + +
    var E_DefaultInt32 = &proto.ExtensionDesc{
    +    ExtendedType:  (*DefaultsMessage)(nil),
    +    ExtensionType: (*int32)(nil),
    +    Field:         203,
    +    Name:          "testdata.default_int32",
    +    Tag:           "varint,203,opt,name=default_int32,json=defaultInt32,def=42",
    +}
    + + +
    var E_DefaultInt64 = &proto.ExtensionDesc{
    +    ExtendedType:  (*DefaultsMessage)(nil),
    +    ExtensionType: (*int64)(nil),
    +    Field:         204,
    +    Name:          "testdata.default_int64",
    +    Tag:           "varint,204,opt,name=default_int64,json=defaultInt64,def=43",
    +}
    + + +
    var E_DefaultSfixed32 = &proto.ExtensionDesc{
    +    ExtendedType:  (*DefaultsMessage)(nil),
    +    ExtensionType: (*int32)(nil),
    +    Field:         211,
    +    Name:          "testdata.default_sfixed32",
    +    Tag:           "fixed32,211,opt,name=default_sfixed32,json=defaultSfixed32,def=50",
    +}
    + + +
    var E_DefaultSfixed64 = &proto.ExtensionDesc{
    +    ExtendedType:  (*DefaultsMessage)(nil),
    +    ExtensionType: (*int64)(nil),
    +    Field:         212,
    +    Name:          "testdata.default_sfixed64",
    +    Tag:           "fixed64,212,opt,name=default_sfixed64,json=defaultSfixed64,def=51",
    +}
    + + +
    var E_DefaultSint32 = &proto.ExtensionDesc{
    +    ExtendedType:  (*DefaultsMessage)(nil),
    +    ExtensionType: (*int32)(nil),
    +    Field:         207,
    +    Name:          "testdata.default_sint32",
    +    Tag:           "zigzag32,207,opt,name=default_sint32,json=defaultSint32,def=46",
    +}
    + + +
    var E_DefaultSint64 = &proto.ExtensionDesc{
    +    ExtendedType:  (*DefaultsMessage)(nil),
    +    ExtensionType: (*int64)(nil),
    +    Field:         208,
    +    Name:          "testdata.default_sint64",
    +    Tag:           "zigzag64,208,opt,name=default_sint64,json=defaultSint64,def=47",
    +}
    + + +
    var E_DefaultString = &proto.ExtensionDesc{
    +    ExtendedType:  (*DefaultsMessage)(nil),
    +    ExtensionType: (*string)(nil),
    +    Field:         214,
    +    Name:          "testdata.default_string",
    +    Tag:           "bytes,214,opt,name=default_string,json=defaultString,def=Hello, string",
    +}
    + + +
    var E_DefaultUint32 = &proto.ExtensionDesc{
    +    ExtendedType:  (*DefaultsMessage)(nil),
    +    ExtensionType: (*uint32)(nil),
    +    Field:         205,
    +    Name:          "testdata.default_uint32",
    +    Tag:           "varint,205,opt,name=default_uint32,json=defaultUint32,def=44",
    +}
    + + +
    var E_DefaultUint64 = &proto.ExtensionDesc{
    +    ExtendedType:  (*DefaultsMessage)(nil),
    +    ExtensionType: (*uint64)(nil),
    +    Field:         206,
    +    Name:          "testdata.default_uint64",
    +    Tag:           "varint,206,opt,name=default_uint64,json=defaultUint64,def=45",
    +}
    + + +
    var E_Ext_More = &proto.ExtensionDesc{
    +    ExtendedType:  (*MyMessage)(nil),
    +    ExtensionType: (*Ext)(nil),
    +    Field:         103,
    +    Name:          "testdata.Ext.more",
    +    Tag:           "bytes,103,opt,name=more",
    +}
    + + +
    var E_Ext_Number = &proto.ExtensionDesc{
    +    ExtendedType:  (*MyMessage)(nil),
    +    ExtensionType: (*int32)(nil),
    +    Field:         105,
    +    Name:          "testdata.Ext.number",
    +    Tag:           "varint,105,opt,name=number",
    +}
    + + +
    var E_Ext_Text = &proto.ExtensionDesc{
    +    ExtendedType:  (*MyMessage)(nil),
    +    ExtensionType: (*string)(nil),
    +    Field:         104,
    +    Name:          "testdata.Ext.text",
    +    Tag:           "bytes,104,opt,name=text",
    +}
    + + +
    var E_Greeting = &proto.ExtensionDesc{
    +    ExtendedType:  (*MyMessage)(nil),
    +    ExtensionType: ([]string)(nil),
    +    Field:         106,
    +    Name:          "testdata.greeting",
    +    Tag:           "bytes,106,rep,name=greeting",
    +}
    + + +
    var E_NoDefaultBool = &proto.ExtensionDesc{
    +    ExtendedType:  (*DefaultsMessage)(nil),
    +    ExtensionType: (*bool)(nil),
    +    Field:         113,
    +    Name:          "testdata.no_default_bool",
    +    Tag:           "varint,113,opt,name=no_default_bool,json=noDefaultBool",
    +}
    + + +
    var E_NoDefaultBytes = &proto.ExtensionDesc{
    +    ExtendedType:  (*DefaultsMessage)(nil),
    +    ExtensionType: ([]byte)(nil),
    +    Field:         115,
    +    Name:          "testdata.no_default_bytes",
    +    Tag:           "bytes,115,opt,name=no_default_bytes,json=noDefaultBytes",
    +}
    + + +
    var E_NoDefaultDouble = &proto.ExtensionDesc{
    +    ExtendedType:  (*DefaultsMessage)(nil),
    +    ExtensionType: (*float64)(nil),
    +    Field:         101,
    +    Name:          "testdata.no_default_double",
    +    Tag:           "fixed64,101,opt,name=no_default_double,json=noDefaultDouble",
    +}
    + + +
    var E_NoDefaultEnum = &proto.ExtensionDesc{
    +    ExtendedType:  (*DefaultsMessage)(nil),
    +    ExtensionType: (*DefaultsMessage_DefaultsEnum)(nil),
    +    Field:         116,
    +    Name:          "testdata.no_default_enum",
    +    Tag:           "varint,116,opt,name=no_default_enum,json=noDefaultEnum,enum=testdata.DefaultsMessage_DefaultsEnum",
    +}
    + + +
    var E_NoDefaultFixed32 = &proto.ExtensionDesc{
    +    ExtendedType:  (*DefaultsMessage)(nil),
    +    ExtensionType: (*uint32)(nil),
    +    Field:         109,
    +    Name:          "testdata.no_default_fixed32",
    +    Tag:           "fixed32,109,opt,name=no_default_fixed32,json=noDefaultFixed32",
    +}
    + + +
    var E_NoDefaultFixed64 = &proto.ExtensionDesc{
    +    ExtendedType:  (*DefaultsMessage)(nil),
    +    ExtensionType: (*uint64)(nil),
    +    Field:         110,
    +    Name:          "testdata.no_default_fixed64",
    +    Tag:           "fixed64,110,opt,name=no_default_fixed64,json=noDefaultFixed64",
    +}
    + + +
    var E_NoDefaultFloat = &proto.ExtensionDesc{
    +    ExtendedType:  (*DefaultsMessage)(nil),
    +    ExtensionType: (*float32)(nil),
    +    Field:         102,
    +    Name:          "testdata.no_default_float",
    +    Tag:           "fixed32,102,opt,name=no_default_float,json=noDefaultFloat",
    +}
    + + +
    var E_NoDefaultInt32 = &proto.ExtensionDesc{
    +    ExtendedType:  (*DefaultsMessage)(nil),
    +    ExtensionType: (*int32)(nil),
    +    Field:         103,
    +    Name:          "testdata.no_default_int32",
    +    Tag:           "varint,103,opt,name=no_default_int32,json=noDefaultInt32",
    +}
    + + +
    var E_NoDefaultInt64 = &proto.ExtensionDesc{
    +    ExtendedType:  (*DefaultsMessage)(nil),
    +    ExtensionType: (*int64)(nil),
    +    Field:         104,
    +    Name:          "testdata.no_default_int64",
    +    Tag:           "varint,104,opt,name=no_default_int64,json=noDefaultInt64",
    +}
    + + +
    var E_NoDefaultSfixed32 = &proto.ExtensionDesc{
    +    ExtendedType:  (*DefaultsMessage)(nil),
    +    ExtensionType: (*int32)(nil),
    +    Field:         111,
    +    Name:          "testdata.no_default_sfixed32",
    +    Tag:           "fixed32,111,opt,name=no_default_sfixed32,json=noDefaultSfixed32",
    +}
    + + +
    var E_NoDefaultSfixed64 = &proto.ExtensionDesc{
    +    ExtendedType:  (*DefaultsMessage)(nil),
    +    ExtensionType: (*int64)(nil),
    +    Field:         112,
    +    Name:          "testdata.no_default_sfixed64",
    +    Tag:           "fixed64,112,opt,name=no_default_sfixed64,json=noDefaultSfixed64",
    +}
    + + +
    var E_NoDefaultSint32 = &proto.ExtensionDesc{
    +    ExtendedType:  (*DefaultsMessage)(nil),
    +    ExtensionType: (*int32)(nil),
    +    Field:         107,
    +    Name:          "testdata.no_default_sint32",
    +    Tag:           "zigzag32,107,opt,name=no_default_sint32,json=noDefaultSint32",
    +}
    + + +
    var E_NoDefaultSint64 = &proto.ExtensionDesc{
    +    ExtendedType:  (*DefaultsMessage)(nil),
    +    ExtensionType: (*int64)(nil),
    +    Field:         108,
    +    Name:          "testdata.no_default_sint64",
    +    Tag:           "zigzag64,108,opt,name=no_default_sint64,json=noDefaultSint64",
    +}
    + + +
    var E_NoDefaultString = &proto.ExtensionDesc{
    +    ExtendedType:  (*DefaultsMessage)(nil),
    +    ExtensionType: (*string)(nil),
    +    Field:         114,
    +    Name:          "testdata.no_default_string",
    +    Tag:           "bytes,114,opt,name=no_default_string,json=noDefaultString",
    +}
    + + +
    var E_NoDefaultUint32 = &proto.ExtensionDesc{
    +    ExtendedType:  (*DefaultsMessage)(nil),
    +    ExtensionType: (*uint32)(nil),
    +    Field:         105,
    +    Name:          "testdata.no_default_uint32",
    +    Tag:           "varint,105,opt,name=no_default_uint32,json=noDefaultUint32",
    +}
    + + +
    var E_NoDefaultUint64 = &proto.ExtensionDesc{
    +    ExtendedType:  (*DefaultsMessage)(nil),
    +    ExtensionType: (*uint64)(nil),
    +    Field:         106,
    +    Name:          "testdata.no_default_uint64",
    +    Tag:           "varint,106,opt,name=no_default_uint64,json=noDefaultUint64",
    +}
    + + +
    var E_RComplex = &proto.ExtensionDesc{
    +    ExtendedType:  (*OtherMessage)(nil),
    +    ExtensionType: ([]*ComplexExtension)(nil),
    +    Field:         201,
    +    Name:          "testdata.r_complex",
    +    Tag:           "bytes,201,rep,name=r_complex,json=rComplex",
    +}
    + + +
    var E_X201 = &proto.ExtensionDesc{
    +    ExtendedType:  (*MyMessageSet)(nil),
    +    ExtensionType: (*Empty)(nil),
    +    Field:         201,
    +    Name:          "testdata.x201",
    +    Tag:           "bytes,201,opt,name=x201",
    +}
    + + +
    var E_X202 = &proto.ExtensionDesc{
    +    ExtendedType:  (*MyMessageSet)(nil),
    +    ExtensionType: (*Empty)(nil),
    +    Field:         202,
    +    Name:          "testdata.x202",
    +    Tag:           "bytes,202,opt,name=x202",
    +}
    + + +
    var E_X203 = &proto.ExtensionDesc{
    +    ExtendedType:  (*MyMessageSet)(nil),
    +    ExtensionType: (*Empty)(nil),
    +    Field:         203,
    +    Name:          "testdata.x203",
    +    Tag:           "bytes,203,opt,name=x203",
    +}
    + + +
    var E_X204 = &proto.ExtensionDesc{
    +    ExtendedType:  (*MyMessageSet)(nil),
    +    ExtensionType: (*Empty)(nil),
    +    Field:         204,
    +    Name:          "testdata.x204",
    +    Tag:           "bytes,204,opt,name=x204",
    +}
    + + +
    var E_X205 = &proto.ExtensionDesc{
    +    ExtendedType:  (*MyMessageSet)(nil),
    +    ExtensionType: (*Empty)(nil),
    +    Field:         205,
    +    Name:          "testdata.x205",
    +    Tag:           "bytes,205,opt,name=x205",
    +}
    + + +
    var E_X206 = &proto.ExtensionDesc{
    +    ExtendedType:  (*MyMessageSet)(nil),
    +    ExtensionType: (*Empty)(nil),
    +    Field:         206,
    +    Name:          "testdata.x206",
    +    Tag:           "bytes,206,opt,name=x206",
    +}
    + + +
    var E_X207 = &proto.ExtensionDesc{
    +    ExtendedType:  (*MyMessageSet)(nil),
    +    ExtensionType: (*Empty)(nil),
    +    Field:         207,
    +    Name:          "testdata.x207",
    +    Tag:           "bytes,207,opt,name=x207",
    +}
    + + +
    var E_X208 = &proto.ExtensionDesc{
    +    ExtendedType:  (*MyMessageSet)(nil),
    +    ExtensionType: (*Empty)(nil),
    +    Field:         208,
    +    Name:          "testdata.x208",
    +    Tag:           "bytes,208,opt,name=x208",
    +}
    + + +
    var E_X209 = &proto.ExtensionDesc{
    +    ExtendedType:  (*MyMessageSet)(nil),
    +    ExtensionType: (*Empty)(nil),
    +    Field:         209,
    +    Name:          "testdata.x209",
    +    Tag:           "bytes,209,opt,name=x209",
    +}
    + + +
    var E_X210 = &proto.ExtensionDesc{
    +    ExtendedType:  (*MyMessageSet)(nil),
    +    ExtensionType: (*Empty)(nil),
    +    Field:         210,
    +    Name:          "testdata.x210",
    +    Tag:           "bytes,210,opt,name=x210",
    +}
    + + +
    var E_X211 = &proto.ExtensionDesc{
    +    ExtendedType:  (*MyMessageSet)(nil),
    +    ExtensionType: (*Empty)(nil),
    +    Field:         211,
    +    Name:          "testdata.x211",
    +    Tag:           "bytes,211,opt,name=x211",
    +}
    + + +
    var E_X212 = &proto.ExtensionDesc{
    +    ExtendedType:  (*MyMessageSet)(nil),
    +    ExtensionType: (*Empty)(nil),
    +    Field:         212,
    +    Name:          "testdata.x212",
    +    Tag:           "bytes,212,opt,name=x212",
    +}
    + + +
    var E_X213 = &proto.ExtensionDesc{
    +    ExtendedType:  (*MyMessageSet)(nil),
    +    ExtensionType: (*Empty)(nil),
    +    Field:         213,
    +    Name:          "testdata.x213",
    +    Tag:           "bytes,213,opt,name=x213",
    +}
    + + +
    var E_X214 = &proto.ExtensionDesc{
    +    ExtendedType:  (*MyMessageSet)(nil),
    +    ExtensionType: (*Empty)(nil),
    +    Field:         214,
    +    Name:          "testdata.x214",
    +    Tag:           "bytes,214,opt,name=x214",
    +}
    + + +
    var E_X215 = &proto.ExtensionDesc{
    +    ExtendedType:  (*MyMessageSet)(nil),
    +    ExtensionType: (*Empty)(nil),
    +    Field:         215,
    +    Name:          "testdata.x215",
    +    Tag:           "bytes,215,opt,name=x215",
    +}
    + + +
    var E_X216 = &proto.ExtensionDesc{
    +    ExtendedType:  (*MyMessageSet)(nil),
    +    ExtensionType: (*Empty)(nil),
    +    Field:         216,
    +    Name:          "testdata.x216",
    +    Tag:           "bytes,216,opt,name=x216",
    +}
    + + +
    var E_X217 = &proto.ExtensionDesc{
    +    ExtendedType:  (*MyMessageSet)(nil),
    +    ExtensionType: (*Empty)(nil),
    +    Field:         217,
    +    Name:          "testdata.x217",
    +    Tag:           "bytes,217,opt,name=x217",
    +}
    + + +
    var E_X218 = &proto.ExtensionDesc{
    +    ExtendedType:  (*MyMessageSet)(nil),
    +    ExtensionType: (*Empty)(nil),
    +    Field:         218,
    +    Name:          "testdata.x218",
    +    Tag:           "bytes,218,opt,name=x218",
    +}
    + + +
    var E_X219 = &proto.ExtensionDesc{
    +    ExtendedType:  (*MyMessageSet)(nil),
    +    ExtensionType: (*Empty)(nil),
    +    Field:         219,
    +    Name:          "testdata.x219",
    +    Tag:           "bytes,219,opt,name=x219",
    +}
    + + +
    var E_X220 = &proto.ExtensionDesc{
    +    ExtendedType:  (*MyMessageSet)(nil),
    +    ExtensionType: (*Empty)(nil),
    +    Field:         220,
    +    Name:          "testdata.x220",
    +    Tag:           "bytes,220,opt,name=x220",
    +}
    + + +
    var E_X221 = &proto.ExtensionDesc{
    +    ExtendedType:  (*MyMessageSet)(nil),
    +    ExtensionType: (*Empty)(nil),
    +    Field:         221,
    +    Name:          "testdata.x221",
    +    Tag:           "bytes,221,opt,name=x221",
    +}
    + + +
    var E_X222 = &proto.ExtensionDesc{
    +    ExtendedType:  (*MyMessageSet)(nil),
    +    ExtensionType: (*Empty)(nil),
    +    Field:         222,
    +    Name:          "testdata.x222",
    +    Tag:           "bytes,222,opt,name=x222",
    +}
    + + +
    var E_X223 = &proto.ExtensionDesc{
    +    ExtendedType:  (*MyMessageSet)(nil),
    +    ExtensionType: (*Empty)(nil),
    +    Field:         223,
    +    Name:          "testdata.x223",
    +    Tag:           "bytes,223,opt,name=x223",
    +}
    + + +
    var E_X224 = &proto.ExtensionDesc{
    +    ExtendedType:  (*MyMessageSet)(nil),
    +    ExtensionType: (*Empty)(nil),
    +    Field:         224,
    +    Name:          "testdata.x224",
    +    Tag:           "bytes,224,opt,name=x224",
    +}
    + + +
    var E_X225 = &proto.ExtensionDesc{
    +    ExtendedType:  (*MyMessageSet)(nil),
    +    ExtensionType: (*Empty)(nil),
    +    Field:         225,
    +    Name:          "testdata.x225",
    +    Tag:           "bytes,225,opt,name=x225",
    +}
    + + +
    var E_X226 = &proto.ExtensionDesc{
    +    ExtendedType:  (*MyMessageSet)(nil),
    +    ExtensionType: (*Empty)(nil),
    +    Field:         226,
    +    Name:          "testdata.x226",
    +    Tag:           "bytes,226,opt,name=x226",
    +}
    + + +
    var E_X227 = &proto.ExtensionDesc{
    +    ExtendedType:  (*MyMessageSet)(nil),
    +    ExtensionType: (*Empty)(nil),
    +    Field:         227,
    +    Name:          "testdata.x227",
    +    Tag:           "bytes,227,opt,name=x227",
    +}
    + + +
    var E_X228 = &proto.ExtensionDesc{
    +    ExtendedType:  (*MyMessageSet)(nil),
    +    ExtensionType: (*Empty)(nil),
    +    Field:         228,
    +    Name:          "testdata.x228",
    +    Tag:           "bytes,228,opt,name=x228",
    +}
    + + +
    var E_X229 = &proto.ExtensionDesc{
    +    ExtendedType:  (*MyMessageSet)(nil),
    +    ExtensionType: (*Empty)(nil),
    +    Field:         229,
    +    Name:          "testdata.x229",
    +    Tag:           "bytes,229,opt,name=x229",
    +}
    + + +
    var E_X230 = &proto.ExtensionDesc{
    +    ExtendedType:  (*MyMessageSet)(nil),
    +    ExtensionType: (*Empty)(nil),
    +    Field:         230,
    +    Name:          "testdata.x230",
    +    Tag:           "bytes,230,opt,name=x230",
    +}
    + + +
    var E_X231 = &proto.ExtensionDesc{
    +    ExtendedType:  (*MyMessageSet)(nil),
    +    ExtensionType: (*Empty)(nil),
    +    Field:         231,
    +    Name:          "testdata.x231",
    +    Tag:           "bytes,231,opt,name=x231",
    +}
    + + +
    var E_X232 = &proto.ExtensionDesc{
    +    ExtendedType:  (*MyMessageSet)(nil),
    +    ExtensionType: (*Empty)(nil),
    +    Field:         232,
    +    Name:          "testdata.x232",
    +    Tag:           "bytes,232,opt,name=x232",
    +}
    + + +
    var E_X233 = &proto.ExtensionDesc{
    +    ExtendedType:  (*MyMessageSet)(nil),
    +    ExtensionType: (*Empty)(nil),
    +    Field:         233,
    +    Name:          "testdata.x233",
    +    Tag:           "bytes,233,opt,name=x233",
    +}
    + + +
    var E_X234 = &proto.ExtensionDesc{
    +    ExtendedType:  (*MyMessageSet)(nil),
    +    ExtensionType: (*Empty)(nil),
    +    Field:         234,
    +    Name:          "testdata.x234",
    +    Tag:           "bytes,234,opt,name=x234",
    +}
    + + +
    var E_X235 = &proto.ExtensionDesc{
    +    ExtendedType:  (*MyMessageSet)(nil),
    +    ExtensionType: (*Empty)(nil),
    +    Field:         235,
    +    Name:          "testdata.x235",
    +    Tag:           "bytes,235,opt,name=x235",
    +}
    + + +
    var E_X236 = &proto.ExtensionDesc{
    +    ExtendedType:  (*MyMessageSet)(nil),
    +    ExtensionType: (*Empty)(nil),
    +    Field:         236,
    +    Name:          "testdata.x236",
    +    Tag:           "bytes,236,opt,name=x236",
    +}
    + + +
    var E_X237 = &proto.ExtensionDesc{
    +    ExtendedType:  (*MyMessageSet)(nil),
    +    ExtensionType: (*Empty)(nil),
    +    Field:         237,
    +    Name:          "testdata.x237",
    +    Tag:           "bytes,237,opt,name=x237",
    +}
    + + +
    var E_X238 = &proto.ExtensionDesc{
    +    ExtendedType:  (*MyMessageSet)(nil),
    +    ExtensionType: (*Empty)(nil),
    +    Field:         238,
    +    Name:          "testdata.x238",
    +    Tag:           "bytes,238,opt,name=x238",
    +}
    + + +
    var E_X239 = &proto.ExtensionDesc{
    +    ExtendedType:  (*MyMessageSet)(nil),
    +    ExtensionType: (*Empty)(nil),
    +    Field:         239,
    +    Name:          "testdata.x239",
    +    Tag:           "bytes,239,opt,name=x239",
    +}
    + + +
    var E_X240 = &proto.ExtensionDesc{
    +    ExtendedType:  (*MyMessageSet)(nil),
    +    ExtensionType: (*Empty)(nil),
    +    Field:         240,
    +    Name:          "testdata.x240",
    +    Tag:           "bytes,240,opt,name=x240",
    +}
    + + +
    var E_X241 = &proto.ExtensionDesc{
    +    ExtendedType:  (*MyMessageSet)(nil),
    +    ExtensionType: (*Empty)(nil),
    +    Field:         241,
    +    Name:          "testdata.x241",
    +    Tag:           "bytes,241,opt,name=x241",
    +}
    + + +
    var E_X242 = &proto.ExtensionDesc{
    +    ExtendedType:  (*MyMessageSet)(nil),
    +    ExtensionType: (*Empty)(nil),
    +    Field:         242,
    +    Name:          "testdata.x242",
    +    Tag:           "bytes,242,opt,name=x242",
    +}
    + + +
    var E_X243 = &proto.ExtensionDesc{
    +    ExtendedType:  (*MyMessageSet)(nil),
    +    ExtensionType: (*Empty)(nil),
    +    Field:         243,
    +    Name:          "testdata.x243",
    +    Tag:           "bytes,243,opt,name=x243",
    +}
    + + +
    var E_X244 = &proto.ExtensionDesc{
    +    ExtendedType:  (*MyMessageSet)(nil),
    +    ExtensionType: (*Empty)(nil),
    +    Field:         244,
    +    Name:          "testdata.x244",
    +    Tag:           "bytes,244,opt,name=x244",
    +}
    + + +
    var E_X245 = &proto.ExtensionDesc{
    +    ExtendedType:  (*MyMessageSet)(nil),
    +    ExtensionType: (*Empty)(nil),
    +    Field:         245,
    +    Name:          "testdata.x245",
    +    Tag:           "bytes,245,opt,name=x245",
    +}
    + + +
    var E_X246 = &proto.ExtensionDesc{
    +    ExtendedType:  (*MyMessageSet)(nil),
    +    ExtensionType: (*Empty)(nil),
    +    Field:         246,
    +    Name:          "testdata.x246",
    +    Tag:           "bytes,246,opt,name=x246",
    +}
    + + +
    var E_X247 = &proto.ExtensionDesc{
    +    ExtendedType:  (*MyMessageSet)(nil),
    +    ExtensionType: (*Empty)(nil),
    +    Field:         247,
    +    Name:          "testdata.x247",
    +    Tag:           "bytes,247,opt,name=x247",
    +}
    + + +
    var E_X248 = &proto.ExtensionDesc{
    +    ExtendedType:  (*MyMessageSet)(nil),
    +    ExtensionType: (*Empty)(nil),
    +    Field:         248,
    +    Name:          "testdata.x248",
    +    Tag:           "bytes,248,opt,name=x248",
    +}
    + + +
    var E_X249 = &proto.ExtensionDesc{
    +    ExtendedType:  (*MyMessageSet)(nil),
    +    ExtensionType: (*Empty)(nil),
    +    Field:         249,
    +    Name:          "testdata.x249",
    +    Tag:           "bytes,249,opt,name=x249",
    +}
    + + +
    var E_X250 = &proto.ExtensionDesc{
    +    ExtendedType:  (*MyMessageSet)(nil),
    +    ExtensionType: (*Empty)(nil),
    +    Field:         250,
    +    Name:          "testdata.x250",
    +    Tag:           "bytes,250,opt,name=x250",
    +}
    + + +
    var FOO_name = map[int32]string{
    +    1: "FOO1",
    +}
    + + +
    var FOO_value = map[string]int32{
    +    "FOO1": 1,
    +}
    + + +
    var GoTest_KIND_name = map[int32]string{
    +    0:  "VOID",
    +    1:  "BOOL",
    +    2:  "BYTES",
    +    3:  "FINGERPRINT",
    +    4:  "FLOAT",
    +    5:  "INT",
    +    6:  "STRING",
    +    7:  "TIME",
    +    8:  "TUPLE",
    +    9:  "ARRAY",
    +    10: "MAP",
    +    11: "TABLE",
    +    12: "FUNCTION",
    +}
    + + +
    var GoTest_KIND_value = map[string]int32{
    +    "VOID":        0,
    +    "BOOL":        1,
    +    "BYTES":       2,
    +    "FINGERPRINT": 3,
    +    "FLOAT":       4,
    +    "INT":         5,
    +    "STRING":      6,
    +    "TIME":        7,
    +    "TUPLE":       8,
    +    "ARRAY":       9,
    +    "MAP":         10,
    +    "TABLE":       11,
    +    "FUNCTION":    12,
    +}
    + + +
    var MyMessage_Color_name = map[int32]string{
    +    0: "RED",
    +    1: "GREEN",
    +    2: "BLUE",
    +}
    + + +
    var MyMessage_Color_value = map[string]int32{
    +    "RED":   0,
    +    "GREEN": 1,
    +    "BLUE":  2,
    +}
    + + +
    var RepeatedEnum_Color_name = map[int32]string{
    +    1: "RED",
    +}
    + + +
    var RepeatedEnum_Color_value = map[string]int32{
    +    "RED": 1,
    +}
    + + + + + + + +

    type Communique

    +
    type Communique struct {
    +    MakeMeCry *bool `protobuf:"varint,1,opt,name=make_me_cry,json=makeMeCry" json:"make_me_cry,omitempty"`
    +    // This is a oneof, called "union".
    +    //
    +    // Types that are valid to be assigned to Union:
    +    //	*Communique_Number
    +    //	*Communique_Name
    +    //	*Communique_Data
    +    //	*Communique_TempC
    +    //	*Communique_Col
    +    //	*Communique_Msg
    +    Union            isCommunique_Union `protobuf_oneof:"union"`
    +    XXX_unrecognized []byte             `json:"-"`
    +}
    + + + + + + + + + + + + + + +

    func (*Communique) Descriptor

    +
    func (*Communique) Descriptor() ([]byte, []int)
    + + + + + + +

    func (*Communique) GetCol

    +
    func (m *Communique) GetCol() MyMessage_Color
    + + + + + + +

    func (*Communique) GetData

    +
    func (m *Communique) GetData() []byte
    + + + + + + +

    func (*Communique) GetMakeMeCry

    +
    func (m *Communique) GetMakeMeCry() bool
    + + + + + + +

    func (*Communique) GetMsg

    +
    func (m *Communique) GetMsg() *Strings
    + + + + + + +

    func (*Communique) GetName

    +
    func (m *Communique) GetName() string
    + + + + + + +

    func (*Communique) GetNumber

    +
    func (m *Communique) GetNumber() int32
    + + + + + + +

    func (*Communique) GetTempC

    +
    func (m *Communique) GetTempC() float64
    + + + + + + +

    func (*Communique) GetUnion

    +
    func (m *Communique) GetUnion() isCommunique_Union
    + + + + + + +

    func (*Communique) ProtoMessage

    +
    func (*Communique) ProtoMessage()
    + + + + + + +

    func (*Communique) Reset

    +
    func (m *Communique) Reset()
    + + + + + + +

    func (*Communique) String

    +
    func (m *Communique) String() string
    + + + + + + +

    func (*Communique) XXX_OneofFuncs

    +
    func (*Communique) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{})
    +

    +XXX_OneofFuncs is for the internal use of the proto package. +

    + + + + + + + + +

    type Communique_Col

    +
    type Communique_Col struct {
    +    Col MyMessage_Color `protobuf:"varint,9,opt,name=col,enum=testdata.MyMessage_Color,oneof"`
    +}
    + + + + + + + + + + + + + + + + +

    type Communique_Data

    +
    type Communique_Data struct {
    +    Data []byte `protobuf:"bytes,7,opt,name=data,oneof"`
    +}
    + + + + + + + + + + + + + + + + +

    type Communique_Msg

    +
    type Communique_Msg struct {
    +    Msg *Strings `protobuf:"bytes,10,opt,name=msg,oneof"`
    +}
    + + + + + + + + + + + + + + + + +

    type Communique_Name

    +
    type Communique_Name struct {
    +    Name string `protobuf:"bytes,6,opt,name=name,oneof"`
    +}
    + + + + + + + + + + + + + + + + +

    type Communique_Number

    +
    type Communique_Number struct {
    +    Number int32 `protobuf:"varint,5,opt,name=number,oneof"`
    +}
    + + + + + + + + + + + + + + + + +

    type Communique_TempC

    +
    type Communique_TempC struct {
    +    TempC float64 `protobuf:"fixed64,8,opt,name=temp_c,json=tempC,oneof"`
    +}
    + + + + + + + + + + + + + + + + +

    type ComplexExtension

    +
    type ComplexExtension struct {
    +    First            *int32  `protobuf:"varint,1,opt,name=first" json:"first,omitempty"`
    +    Second           *int32  `protobuf:"varint,2,opt,name=second" json:"second,omitempty"`
    +    Third            []int32 `protobuf:"varint,3,rep,name=third" json:"third,omitempty"`
    +    XXX_unrecognized []byte  `json:"-"`
    +}
    + + + + + + + + + + + + + + +

    func (*ComplexExtension) Descriptor

    +
    func (*ComplexExtension) Descriptor() ([]byte, []int)
    + + + + + + +

    func (*ComplexExtension) GetFirst

    +
    func (m *ComplexExtension) GetFirst() int32
    + + + + + + +

    func (*ComplexExtension) GetSecond

    +
    func (m *ComplexExtension) GetSecond() int32
    + + + + + + +

    func (*ComplexExtension) GetThird

    +
    func (m *ComplexExtension) GetThird() []int32
    + + + + + + +

    func (*ComplexExtension) ProtoMessage

    +
    func (*ComplexExtension) ProtoMessage()
    + + + + + + +

    func (*ComplexExtension) Reset

    +
    func (m *ComplexExtension) Reset()
    + + + + + + +

    func (*ComplexExtension) String

    +
    func (m *ComplexExtension) String() string
    + + + + + + + + +

    type Defaults

    +
    type Defaults struct {
    +    // Default-valued fields of all basic types.
    +    // Same as GoTest, but copied here to make testing easier.
    +    F_Bool    *bool           `protobuf:"varint,1,opt,name=F_Bool,json=fBool,def=1" json:"F_Bool,omitempty"`
    +    F_Int32   *int32          `protobuf:"varint,2,opt,name=F_Int32,json=fInt32,def=32" json:"F_Int32,omitempty"`
    +    F_Int64   *int64          `protobuf:"varint,3,opt,name=F_Int64,json=fInt64,def=64" json:"F_Int64,omitempty"`
    +    F_Fixed32 *uint32         `protobuf:"fixed32,4,opt,name=F_Fixed32,json=fFixed32,def=320" json:"F_Fixed32,omitempty"`
    +    F_Fixed64 *uint64         `protobuf:"fixed64,5,opt,name=F_Fixed64,json=fFixed64,def=640" json:"F_Fixed64,omitempty"`
    +    F_Uint32  *uint32         `protobuf:"varint,6,opt,name=F_Uint32,json=fUint32,def=3200" json:"F_Uint32,omitempty"`
    +    F_Uint64  *uint64         `protobuf:"varint,7,opt,name=F_Uint64,json=fUint64,def=6400" json:"F_Uint64,omitempty"`
    +    F_Float   *float32        `protobuf:"fixed32,8,opt,name=F_Float,json=fFloat,def=314159" json:"F_Float,omitempty"`
    +    F_Double  *float64        `protobuf:"fixed64,9,opt,name=F_Double,json=fDouble,def=271828" json:"F_Double,omitempty"`
    +    F_String  *string         `protobuf:"bytes,10,opt,name=F_String,json=fString,def=hello, \"world!\"\n" json:"F_String,omitempty"`
    +    F_Bytes   []byte          `protobuf:"bytes,11,opt,name=F_Bytes,json=fBytes,def=Bignose" json:"F_Bytes,omitempty"`
    +    F_Sint32  *int32          `protobuf:"zigzag32,12,opt,name=F_Sint32,json=fSint32,def=-32" json:"F_Sint32,omitempty"`
    +    F_Sint64  *int64          `protobuf:"zigzag64,13,opt,name=F_Sint64,json=fSint64,def=-64" json:"F_Sint64,omitempty"`
    +    F_Enum    *Defaults_Color `protobuf:"varint,14,opt,name=F_Enum,json=fEnum,enum=testdata.Defaults_Color,def=1" json:"F_Enum,omitempty"`
    +    // More fields with crazy defaults.
    +    F_Pinf *float32 `protobuf:"fixed32,15,opt,name=F_Pinf,json=fPinf,def=inf" json:"F_Pinf,omitempty"`
    +    F_Ninf *float32 `protobuf:"fixed32,16,opt,name=F_Ninf,json=fNinf,def=-inf" json:"F_Ninf,omitempty"`
    +    F_Nan  *float32 `protobuf:"fixed32,17,opt,name=F_Nan,json=fNan,def=nan" json:"F_Nan,omitempty"`
    +    // Sub-message.
    +    Sub *SubDefaults `protobuf:"bytes,18,opt,name=sub" json:"sub,omitempty"`
    +    // Redundant but explicit defaults.
    +    StrZero          *string `protobuf:"bytes,19,opt,name=str_zero,json=strZero,def=" json:"str_zero,omitempty"`
    +    XXX_unrecognized []byte  `json:"-"`
    +}
    + + + + + + + + + + + + + + +

    func (*Defaults) Descriptor

    +
    func (*Defaults) Descriptor() ([]byte, []int)
    + + + + + + +

    func (*Defaults) GetF_Bool

    +
    func (m *Defaults) GetF_Bool() bool
    + + + + + + +

    func (*Defaults) GetF_Bytes

    +
    func (m *Defaults) GetF_Bytes() []byte
    + + + + + + +

    func (*Defaults) GetF_Double

    +
    func (m *Defaults) GetF_Double() float64
    + + + + + + +

    func (*Defaults) GetF_Enum

    +
    func (m *Defaults) GetF_Enum() Defaults_Color
    + + + + + + +

    func (*Defaults) GetF_Fixed32

    +
    func (m *Defaults) GetF_Fixed32() uint32
    + + + + + + +

    func (*Defaults) GetF_Fixed64

    +
    func (m *Defaults) GetF_Fixed64() uint64
    + + + + + + +

    func (*Defaults) GetF_Float

    +
    func (m *Defaults) GetF_Float() float32
    + + + + + + +

    func (*Defaults) GetF_Int32

    +
    func (m *Defaults) GetF_Int32() int32
    + + + + + + +

    func (*Defaults) GetF_Int64

    +
    func (m *Defaults) GetF_Int64() int64
    + + + + + + +

    func (*Defaults) GetF_Nan

    +
    func (m *Defaults) GetF_Nan() float32
    + + + + + + +

    func (*Defaults) GetF_Ninf

    +
    func (m *Defaults) GetF_Ninf() float32
    + + + + + + +

    func (*Defaults) GetF_Pinf

    +
    func (m *Defaults) GetF_Pinf() float32
    + + + + + + +

    func (*Defaults) GetF_Sint32

    +
    func (m *Defaults) GetF_Sint32() int32
    + + + + + + +

    func (*Defaults) GetF_Sint64

    +
    func (m *Defaults) GetF_Sint64() int64
    + + + + + + +

    func (*Defaults) GetF_String

    +
    func (m *Defaults) GetF_String() string
    + + + + + + +

    func (*Defaults) GetF_Uint32

    +
    func (m *Defaults) GetF_Uint32() uint32
    + + + + + + +

    func (*Defaults) GetF_Uint64

    +
    func (m *Defaults) GetF_Uint64() uint64
    + + + + + + +

    func (*Defaults) GetStrZero

    +
    func (m *Defaults) GetStrZero() string
    + + + + + + +

    func (*Defaults) GetSub

    +
    func (m *Defaults) GetSub() *SubDefaults
    + + + + + + +

    func (*Defaults) ProtoMessage

    +
    func (*Defaults) ProtoMessage()
    + + + + + + +

    func (*Defaults) Reset

    +
    func (m *Defaults) Reset()
    + + + + + + +

    func (*Defaults) String

    +
    func (m *Defaults) String() string
    + + + + + + + + +

    type DefaultsMessage

    +
    type DefaultsMessage struct {
    +    proto.XXX_InternalExtensions `json:"-"`
    +    XXX_unrecognized             []byte `json:"-"`
    +}
    + + + + + + + + + + + + + + +

    func (*DefaultsMessage) Descriptor

    +
    func (*DefaultsMessage) Descriptor() ([]byte, []int)
    + + + + + + +

    func (*DefaultsMessage) ExtensionRangeArray

    +
    func (*DefaultsMessage) ExtensionRangeArray() []proto.ExtensionRange
    + + + + + + +

    func (*DefaultsMessage) ProtoMessage

    +
    func (*DefaultsMessage) ProtoMessage()
    + + + + + + +

    func (*DefaultsMessage) Reset

    +
    func (m *DefaultsMessage) Reset()
    + + + + + + +

    func (*DefaultsMessage) String

    +
    func (m *DefaultsMessage) String() string
    + + + + + + + + +

    type DefaultsMessage_DefaultsEnum

    +
    type DefaultsMessage_DefaultsEnum int32
    + + + +
    const (
    +    DefaultsMessage_ZERO DefaultsMessage_DefaultsEnum = 0
    +    DefaultsMessage_ONE  DefaultsMessage_DefaultsEnum = 1
    +    DefaultsMessage_TWO  DefaultsMessage_DefaultsEnum = 2
    +)
    + + + + + + + + + + + + + +

    func (DefaultsMessage_DefaultsEnum) Enum

    +
    func (x DefaultsMessage_DefaultsEnum) Enum() *DefaultsMessage_DefaultsEnum
    + + + + + + +

    func (DefaultsMessage_DefaultsEnum) EnumDescriptor

    +
    func (DefaultsMessage_DefaultsEnum) EnumDescriptor() ([]byte, []int)
    + + + + + + +

    func (DefaultsMessage_DefaultsEnum) String

    +
    func (x DefaultsMessage_DefaultsEnum) String() string
    + + + + + + +

    func (*DefaultsMessage_DefaultsEnum) UnmarshalJSON

    +
    func (x *DefaultsMessage_DefaultsEnum) UnmarshalJSON(data []byte) error
    + + + + + + + + +

    type Defaults_Color

    +
    type Defaults_Color int32
    + + + +
    const (
    +    Defaults_RED   Defaults_Color = 0
    +    Defaults_GREEN Defaults_Color = 1
    +    Defaults_BLUE  Defaults_Color = 2
    +)
    + + +
    const Default_Defaults_F_Enum Defaults_Color = Defaults_GREEN
    + + + + + + + + + + + + + +

    func (Defaults_Color) Enum

    +
    func (x Defaults_Color) Enum() *Defaults_Color
    + + + + + + +

    func (Defaults_Color) EnumDescriptor

    +
    func (Defaults_Color) EnumDescriptor() ([]byte, []int)
    + + + + + + +

    func (Defaults_Color) String

    +
    func (x Defaults_Color) String() string
    + + + + + + +

    func (*Defaults_Color) UnmarshalJSON

    +
    func (x *Defaults_Color) UnmarshalJSON(data []byte) error
    + + + + + + + + +

    type Empty

    +
    type Empty struct {
    +    XXX_unrecognized []byte `json:"-"`
    +}
    + + + + + + + + + + + + + + +

    func (*Empty) Descriptor

    +
    func (*Empty) Descriptor() ([]byte, []int)
    + + + + + + +

    func (*Empty) ProtoMessage

    +
    func (*Empty) ProtoMessage()
    + + + + + + +

    func (*Empty) Reset

    +
    func (m *Empty) Reset()
    + + + + + + +

    func (*Empty) String

    +
    func (m *Empty) String() string
    + + + + + + + + +

    type Ext

    +
    type Ext struct {
    +    Data             *string `protobuf:"bytes,1,opt,name=data" json:"data,omitempty"`
    +    XXX_unrecognized []byte  `json:"-"`
    +}
    + + + + + + + + + + + + + + +

    func (*Ext) Descriptor

    +
    func (*Ext) Descriptor() ([]byte, []int)
    + + + + + + +

    func (*Ext) GetData

    +
    func (m *Ext) GetData() string
    + + + + + + +

    func (*Ext) ProtoMessage

    +
    func (*Ext) ProtoMessage()
    + + + + + + +

    func (*Ext) Reset

    +
    func (m *Ext) Reset()
    + + + + + + +

    func (*Ext) String

    +
    func (m *Ext) String() string
    + + + + + + + + +

    type FOO

    +
    type FOO int32
    + + + +
    const (
    +    FOO_FOO1 FOO = 1
    +)
    + + + + + + + + + + + + + +

    func (FOO) Enum

    +
    func (x FOO) Enum() *FOO
    + + + + + + +

    func (FOO) EnumDescriptor

    +
    func (FOO) EnumDescriptor() ([]byte, []int)
    + + + + + + +

    func (FOO) String

    +
    func (x FOO) String() string
    + + + + + + +

    func (*FOO) UnmarshalJSON

    +
    func (x *FOO) UnmarshalJSON(data []byte) error
    + + + + + + + + +

    type FloatingPoint

    +
    type FloatingPoint struct {
    +    F                *float64 `protobuf:"fixed64,1,req,name=f" json:"f,omitempty"`
    +    Exact            *bool    `protobuf:"varint,2,opt,name=exact" json:"exact,omitempty"`
    +    XXX_unrecognized []byte   `json:"-"`
    +}
    + + + + + + + + + + + + + + +

    func (*FloatingPoint) Descriptor

    +
    func (*FloatingPoint) Descriptor() ([]byte, []int)
    + + + + + + +

    func (*FloatingPoint) GetExact

    +
    func (m *FloatingPoint) GetExact() bool
    + + + + + + +

    func (*FloatingPoint) GetF

    +
    func (m *FloatingPoint) GetF() float64
    + + + + + + +

    func (*FloatingPoint) ProtoMessage

    +
    func (*FloatingPoint) ProtoMessage()
    + + + + + + +

    func (*FloatingPoint) Reset

    +
    func (m *FloatingPoint) Reset()
    + + + + + + +

    func (*FloatingPoint) String

    +
    func (m *FloatingPoint) String() string
    + + + + + + + + +

    type GoEnum

    +
    type GoEnum struct {
    +    Foo              *FOO   `protobuf:"varint,1,req,name=foo,enum=testdata.FOO" json:"foo,omitempty"`
    +    XXX_unrecognized []byte `json:"-"`
    +}
    + + + + + + + + + + + + + + +

    func (*GoEnum) Descriptor

    +
    func (*GoEnum) Descriptor() ([]byte, []int)
    + + + + + + +

    func (*GoEnum) GetFoo

    +
    func (m *GoEnum) GetFoo() FOO
    + + + + + + +

    func (*GoEnum) ProtoMessage

    +
    func (*GoEnum) ProtoMessage()
    + + + + + + +

    func (*GoEnum) Reset

    +
    func (m *GoEnum) Reset()
    + + + + + + +

    func (*GoEnum) String

    +
    func (m *GoEnum) String() string
    + + + + + + + + +

    type GoSkipTest

    +
    type GoSkipTest struct {
    +    SkipInt32        *int32                `protobuf:"varint,11,req,name=skip_int32,json=skipInt32" json:"skip_int32,omitempty"`
    +    SkipFixed32      *uint32               `protobuf:"fixed32,12,req,name=skip_fixed32,json=skipFixed32" json:"skip_fixed32,omitempty"`
    +    SkipFixed64      *uint64               `protobuf:"fixed64,13,req,name=skip_fixed64,json=skipFixed64" json:"skip_fixed64,omitempty"`
    +    SkipString       *string               `protobuf:"bytes,14,req,name=skip_string,json=skipString" json:"skip_string,omitempty"`
    +    Skipgroup        *GoSkipTest_SkipGroup `protobuf:"group,15,req,name=SkipGroup,json=skipgroup" json:"skipgroup,omitempty"`
    +    XXX_unrecognized []byte                `json:"-"`
    +}
    +

    +For testing skipping of unrecognized fields. +Numbers are all big, larger than tag numbers in GoTestField, +the message used in the corresponding test. +

    + + + + + + + + + + + + + + +

    func (*GoSkipTest) Descriptor

    +
    func (*GoSkipTest) Descriptor() ([]byte, []int)
    + + + + + + +

    func (*GoSkipTest) GetSkipFixed32

    +
    func (m *GoSkipTest) GetSkipFixed32() uint32
    + + + + + + +

    func (*GoSkipTest) GetSkipFixed64

    +
    func (m *GoSkipTest) GetSkipFixed64() uint64
    + + + + + + +

    func (*GoSkipTest) GetSkipInt32

    +
    func (m *GoSkipTest) GetSkipInt32() int32
    + + + + + + +

    func (*GoSkipTest) GetSkipString

    +
    func (m *GoSkipTest) GetSkipString() string
    + + + + + + +

    func (*GoSkipTest) GetSkipgroup

    +
    func (m *GoSkipTest) GetSkipgroup() *GoSkipTest_SkipGroup
    + + + + + + +

    func (*GoSkipTest) ProtoMessage

    +
    func (*GoSkipTest) ProtoMessage()
    + + + + + + +

    func (*GoSkipTest) Reset

    +
    func (m *GoSkipTest) Reset()
    + + + + + + +

    func (*GoSkipTest) String

    +
    func (m *GoSkipTest) String() string
    + + + + + + + + +

    type GoSkipTest_SkipGroup

    +
    type GoSkipTest_SkipGroup struct {
    +    GroupInt32       *int32  `protobuf:"varint,16,req,name=group_int32,json=groupInt32" json:"group_int32,omitempty"`
    +    GroupString      *string `protobuf:"bytes,17,req,name=group_string,json=groupString" json:"group_string,omitempty"`
    +    XXX_unrecognized []byte  `json:"-"`
    +}
    + + + + + + + + + + + + + + +

    func (*GoSkipTest_SkipGroup) Descriptor

    +
    func (*GoSkipTest_SkipGroup) Descriptor() ([]byte, []int)
    + + + + + + +

    func (*GoSkipTest_SkipGroup) GetGroupInt32

    +
    func (m *GoSkipTest_SkipGroup) GetGroupInt32() int32
    + + + + + + +

    func (*GoSkipTest_SkipGroup) GetGroupString

    +
    func (m *GoSkipTest_SkipGroup) GetGroupString() string
    + + + + + + +

    func (*GoSkipTest_SkipGroup) ProtoMessage

    +
    func (*GoSkipTest_SkipGroup) ProtoMessage()
    + + + + + + +

    func (*GoSkipTest_SkipGroup) Reset

    +
    func (m *GoSkipTest_SkipGroup) Reset()
    + + + + + + +

    func (*GoSkipTest_SkipGroup) String

    +
    func (m *GoSkipTest_SkipGroup) String() string
    + + + + + + + + +

    type GoTest

    +
    type GoTest struct {
    +    // Some typical parameters
    +    Kind  *GoTest_KIND `protobuf:"varint,1,req,name=Kind,json=kind,enum=testdata.GoTest_KIND" json:"Kind,omitempty"`
    +    Table *string      `protobuf:"bytes,2,opt,name=Table,json=table" json:"Table,omitempty"`
    +    Param *int32       `protobuf:"varint,3,opt,name=Param,json=param" json:"Param,omitempty"`
    +    // Required, repeated and optional foreign fields.
    +    RequiredField *GoTestField   `protobuf:"bytes,4,req,name=RequiredField,json=requiredField" json:"RequiredField,omitempty"`
    +    RepeatedField []*GoTestField `protobuf:"bytes,5,rep,name=RepeatedField,json=repeatedField" json:"RepeatedField,omitempty"`
    +    OptionalField *GoTestField   `protobuf:"bytes,6,opt,name=OptionalField,json=optionalField" json:"OptionalField,omitempty"`
    +    // Required fields of all basic types
    +    F_BoolRequired    *bool    `protobuf:"varint,10,req,name=F_Bool_required,json=fBoolRequired" json:"F_Bool_required,omitempty"`
    +    F_Int32Required   *int32   `protobuf:"varint,11,req,name=F_Int32_required,json=fInt32Required" json:"F_Int32_required,omitempty"`
    +    F_Int64Required   *int64   `protobuf:"varint,12,req,name=F_Int64_required,json=fInt64Required" json:"F_Int64_required,omitempty"`
    +    F_Fixed32Required *uint32  `protobuf:"fixed32,13,req,name=F_Fixed32_required,json=fFixed32Required" json:"F_Fixed32_required,omitempty"`
    +    F_Fixed64Required *uint64  `protobuf:"fixed64,14,req,name=F_Fixed64_required,json=fFixed64Required" json:"F_Fixed64_required,omitempty"`
    +    F_Uint32Required  *uint32  `protobuf:"varint,15,req,name=F_Uint32_required,json=fUint32Required" json:"F_Uint32_required,omitempty"`
    +    F_Uint64Required  *uint64  `protobuf:"varint,16,req,name=F_Uint64_required,json=fUint64Required" json:"F_Uint64_required,omitempty"`
    +    F_FloatRequired   *float32 `protobuf:"fixed32,17,req,name=F_Float_required,json=fFloatRequired" json:"F_Float_required,omitempty"`
    +    F_DoubleRequired  *float64 `protobuf:"fixed64,18,req,name=F_Double_required,json=fDoubleRequired" json:"F_Double_required,omitempty"`
    +    F_StringRequired  *string  `protobuf:"bytes,19,req,name=F_String_required,json=fStringRequired" json:"F_String_required,omitempty"`
    +    F_BytesRequired   []byte   `protobuf:"bytes,101,req,name=F_Bytes_required,json=fBytesRequired" json:"F_Bytes_required,omitempty"`
    +    F_Sint32Required  *int32   `protobuf:"zigzag32,102,req,name=F_Sint32_required,json=fSint32Required" json:"F_Sint32_required,omitempty"`
    +    F_Sint64Required  *int64   `protobuf:"zigzag64,103,req,name=F_Sint64_required,json=fSint64Required" json:"F_Sint64_required,omitempty"`
    +    // Repeated fields of all basic types
    +    F_BoolRepeated    []bool    `protobuf:"varint,20,rep,name=F_Bool_repeated,json=fBoolRepeated" json:"F_Bool_repeated,omitempty"`
    +    F_Int32Repeated   []int32   `protobuf:"varint,21,rep,name=F_Int32_repeated,json=fInt32Repeated" json:"F_Int32_repeated,omitempty"`
    +    F_Int64Repeated   []int64   `protobuf:"varint,22,rep,name=F_Int64_repeated,json=fInt64Repeated" json:"F_Int64_repeated,omitempty"`
    +    F_Fixed32Repeated []uint32  `protobuf:"fixed32,23,rep,name=F_Fixed32_repeated,json=fFixed32Repeated" json:"F_Fixed32_repeated,omitempty"`
    +    F_Fixed64Repeated []uint64  `protobuf:"fixed64,24,rep,name=F_Fixed64_repeated,json=fFixed64Repeated" json:"F_Fixed64_repeated,omitempty"`
    +    F_Uint32Repeated  []uint32  `protobuf:"varint,25,rep,name=F_Uint32_repeated,json=fUint32Repeated" json:"F_Uint32_repeated,omitempty"`
    +    F_Uint64Repeated  []uint64  `protobuf:"varint,26,rep,name=F_Uint64_repeated,json=fUint64Repeated" json:"F_Uint64_repeated,omitempty"`
    +    F_FloatRepeated   []float32 `protobuf:"fixed32,27,rep,name=F_Float_repeated,json=fFloatRepeated" json:"F_Float_repeated,omitempty"`
    +    F_DoubleRepeated  []float64 `protobuf:"fixed64,28,rep,name=F_Double_repeated,json=fDoubleRepeated" json:"F_Double_repeated,omitempty"`
    +    F_StringRepeated  []string  `protobuf:"bytes,29,rep,name=F_String_repeated,json=fStringRepeated" json:"F_String_repeated,omitempty"`
    +    F_BytesRepeated   [][]byte  `protobuf:"bytes,201,rep,name=F_Bytes_repeated,json=fBytesRepeated" json:"F_Bytes_repeated,omitempty"`
    +    F_Sint32Repeated  []int32   `protobuf:"zigzag32,202,rep,name=F_Sint32_repeated,json=fSint32Repeated" json:"F_Sint32_repeated,omitempty"`
    +    F_Sint64Repeated  []int64   `protobuf:"zigzag64,203,rep,name=F_Sint64_repeated,json=fSint64Repeated" json:"F_Sint64_repeated,omitempty"`
    +    // Optional fields of all basic types
    +    F_BoolOptional    *bool    `protobuf:"varint,30,opt,name=F_Bool_optional,json=fBoolOptional" json:"F_Bool_optional,omitempty"`
    +    F_Int32Optional   *int32   `protobuf:"varint,31,opt,name=F_Int32_optional,json=fInt32Optional" json:"F_Int32_optional,omitempty"`
    +    F_Int64Optional   *int64   `protobuf:"varint,32,opt,name=F_Int64_optional,json=fInt64Optional" json:"F_Int64_optional,omitempty"`
    +    F_Fixed32Optional *uint32  `protobuf:"fixed32,33,opt,name=F_Fixed32_optional,json=fFixed32Optional" json:"F_Fixed32_optional,omitempty"`
    +    F_Fixed64Optional *uint64  `protobuf:"fixed64,34,opt,name=F_Fixed64_optional,json=fFixed64Optional" json:"F_Fixed64_optional,omitempty"`
    +    F_Uint32Optional  *uint32  `protobuf:"varint,35,opt,name=F_Uint32_optional,json=fUint32Optional" json:"F_Uint32_optional,omitempty"`
    +    F_Uint64Optional  *uint64  `protobuf:"varint,36,opt,name=F_Uint64_optional,json=fUint64Optional" json:"F_Uint64_optional,omitempty"`
    +    F_FloatOptional   *float32 `protobuf:"fixed32,37,opt,name=F_Float_optional,json=fFloatOptional" json:"F_Float_optional,omitempty"`
    +    F_DoubleOptional  *float64 `protobuf:"fixed64,38,opt,name=F_Double_optional,json=fDoubleOptional" json:"F_Double_optional,omitempty"`
    +    F_StringOptional  *string  `protobuf:"bytes,39,opt,name=F_String_optional,json=fStringOptional" json:"F_String_optional,omitempty"`
    +    F_BytesOptional   []byte   `protobuf:"bytes,301,opt,name=F_Bytes_optional,json=fBytesOptional" json:"F_Bytes_optional,omitempty"`
    +    F_Sint32Optional  *int32   `protobuf:"zigzag32,302,opt,name=F_Sint32_optional,json=fSint32Optional" json:"F_Sint32_optional,omitempty"`
    +    F_Sint64Optional  *int64   `protobuf:"zigzag64,303,opt,name=F_Sint64_optional,json=fSint64Optional" json:"F_Sint64_optional,omitempty"`
    +    // Default-valued fields of all basic types
    +    F_BoolDefaulted    *bool    `protobuf:"varint,40,opt,name=F_Bool_defaulted,json=fBoolDefaulted,def=1" json:"F_Bool_defaulted,omitempty"`
    +    F_Int32Defaulted   *int32   `protobuf:"varint,41,opt,name=F_Int32_defaulted,json=fInt32Defaulted,def=32" json:"F_Int32_defaulted,omitempty"`
    +    F_Int64Defaulted   *int64   `protobuf:"varint,42,opt,name=F_Int64_defaulted,json=fInt64Defaulted,def=64" json:"F_Int64_defaulted,omitempty"`
    +    F_Fixed32Defaulted *uint32  `protobuf:"fixed32,43,opt,name=F_Fixed32_defaulted,json=fFixed32Defaulted,def=320" json:"F_Fixed32_defaulted,omitempty"`
    +    F_Fixed64Defaulted *uint64  `protobuf:"fixed64,44,opt,name=F_Fixed64_defaulted,json=fFixed64Defaulted,def=640" json:"F_Fixed64_defaulted,omitempty"`
    +    F_Uint32Defaulted  *uint32  `protobuf:"varint,45,opt,name=F_Uint32_defaulted,json=fUint32Defaulted,def=3200" json:"F_Uint32_defaulted,omitempty"`
    +    F_Uint64Defaulted  *uint64  `protobuf:"varint,46,opt,name=F_Uint64_defaulted,json=fUint64Defaulted,def=6400" json:"F_Uint64_defaulted,omitempty"`
    +    F_FloatDefaulted   *float32 `protobuf:"fixed32,47,opt,name=F_Float_defaulted,json=fFloatDefaulted,def=314159" json:"F_Float_defaulted,omitempty"`
    +    F_DoubleDefaulted  *float64 `protobuf:"fixed64,48,opt,name=F_Double_defaulted,json=fDoubleDefaulted,def=271828" json:"F_Double_defaulted,omitempty"`
    +    F_StringDefaulted  *string  `protobuf:"bytes,49,opt,name=F_String_defaulted,json=fStringDefaulted,def=hello, \"world!\"\n" json:"F_String_defaulted,omitempty"`
    +    F_BytesDefaulted   []byte   `protobuf:"bytes,401,opt,name=F_Bytes_defaulted,json=fBytesDefaulted,def=Bignose" json:"F_Bytes_defaulted,omitempty"`
    +    F_Sint32Defaulted  *int32   `protobuf:"zigzag32,402,opt,name=F_Sint32_defaulted,json=fSint32Defaulted,def=-32" json:"F_Sint32_defaulted,omitempty"`
    +    F_Sint64Defaulted  *int64   `protobuf:"zigzag64,403,opt,name=F_Sint64_defaulted,json=fSint64Defaulted,def=-64" json:"F_Sint64_defaulted,omitempty"`
    +    // Packed repeated fields (no string or bytes).
    +    F_BoolRepeatedPacked    []bool                  `protobuf:"varint,50,rep,packed,name=F_Bool_repeated_packed,json=fBoolRepeatedPacked" json:"F_Bool_repeated_packed,omitempty"`
    +    F_Int32RepeatedPacked   []int32                 `protobuf:"varint,51,rep,packed,name=F_Int32_repeated_packed,json=fInt32RepeatedPacked" json:"F_Int32_repeated_packed,omitempty"`
    +    F_Int64RepeatedPacked   []int64                 `protobuf:"varint,52,rep,packed,name=F_Int64_repeated_packed,json=fInt64RepeatedPacked" json:"F_Int64_repeated_packed,omitempty"`
    +    F_Fixed32RepeatedPacked []uint32                `protobuf:"fixed32,53,rep,packed,name=F_Fixed32_repeated_packed,json=fFixed32RepeatedPacked" json:"F_Fixed32_repeated_packed,omitempty"`
    +    F_Fixed64RepeatedPacked []uint64                `protobuf:"fixed64,54,rep,packed,name=F_Fixed64_repeated_packed,json=fFixed64RepeatedPacked" json:"F_Fixed64_repeated_packed,omitempty"`
    +    F_Uint32RepeatedPacked  []uint32                `protobuf:"varint,55,rep,packed,name=F_Uint32_repeated_packed,json=fUint32RepeatedPacked" json:"F_Uint32_repeated_packed,omitempty"`
    +    F_Uint64RepeatedPacked  []uint64                `protobuf:"varint,56,rep,packed,name=F_Uint64_repeated_packed,json=fUint64RepeatedPacked" json:"F_Uint64_repeated_packed,omitempty"`
    +    F_FloatRepeatedPacked   []float32               `protobuf:"fixed32,57,rep,packed,name=F_Float_repeated_packed,json=fFloatRepeatedPacked" json:"F_Float_repeated_packed,omitempty"`
    +    F_DoubleRepeatedPacked  []float64               `protobuf:"fixed64,58,rep,packed,name=F_Double_repeated_packed,json=fDoubleRepeatedPacked" json:"F_Double_repeated_packed,omitempty"`
    +    F_Sint32RepeatedPacked  []int32                 `protobuf:"zigzag32,502,rep,packed,name=F_Sint32_repeated_packed,json=fSint32RepeatedPacked" json:"F_Sint32_repeated_packed,omitempty"`
    +    F_Sint64RepeatedPacked  []int64                 `protobuf:"zigzag64,503,rep,packed,name=F_Sint64_repeated_packed,json=fSint64RepeatedPacked" json:"F_Sint64_repeated_packed,omitempty"`
    +    Requiredgroup           *GoTest_RequiredGroup   `protobuf:"group,70,req,name=RequiredGroup,json=requiredgroup" json:"requiredgroup,omitempty"`
    +    Repeatedgroup           []*GoTest_RepeatedGroup `protobuf:"group,80,rep,name=RepeatedGroup,json=repeatedgroup" json:"repeatedgroup,omitempty"`
    +    Optionalgroup           *GoTest_OptionalGroup   `protobuf:"group,90,opt,name=OptionalGroup,json=optionalgroup" json:"optionalgroup,omitempty"`
    +    XXX_unrecognized        []byte                  `json:"-"`
    +}
    + + + + + + + + + + + + + + +

    func (*GoTest) Descriptor

    +
    func (*GoTest) Descriptor() ([]byte, []int)
    + + + + + + +

    func (*GoTest) GetF_BoolDefaulted

    +
    func (m *GoTest) GetF_BoolDefaulted() bool
    + + + + + + +

    func (*GoTest) GetF_BoolOptional

    +
    func (m *GoTest) GetF_BoolOptional() bool
    + + + + + + +

    func (*GoTest) GetF_BoolRepeated

    +
    func (m *GoTest) GetF_BoolRepeated() []bool
    + + + + + + +

    func (*GoTest) GetF_BoolRepeatedPacked

    +
    func (m *GoTest) GetF_BoolRepeatedPacked() []bool
    + + + + + + +

    func (*GoTest) GetF_BoolRequired

    +
    func (m *GoTest) GetF_BoolRequired() bool
    + + + + + + +

    func (*GoTest) GetF_BytesDefaulted

    +
    func (m *GoTest) GetF_BytesDefaulted() []byte
    + + + + + + +

    func (*GoTest) GetF_BytesOptional

    +
    func (m *GoTest) GetF_BytesOptional() []byte
    + + + + + + +

    func (*GoTest) GetF_BytesRepeated

    +
    func (m *GoTest) GetF_BytesRepeated() [][]byte
    + + + + + + +

    func (*GoTest) GetF_BytesRequired

    +
    func (m *GoTest) GetF_BytesRequired() []byte
    + + + + + + +

    func (*GoTest) GetF_DoubleDefaulted

    +
    func (m *GoTest) GetF_DoubleDefaulted() float64
    + + + + + + +

    func (*GoTest) GetF_DoubleOptional

    +
    func (m *GoTest) GetF_DoubleOptional() float64
    + + + + + + +

    func (*GoTest) GetF_DoubleRepeated

    +
    func (m *GoTest) GetF_DoubleRepeated() []float64
    + + + + + + +

    func (*GoTest) GetF_DoubleRepeatedPacked

    +
    func (m *GoTest) GetF_DoubleRepeatedPacked() []float64
    + + + + + + +

    func (*GoTest) GetF_DoubleRequired

    +
    func (m *GoTest) GetF_DoubleRequired() float64
    + + + + + + +

    func (*GoTest) GetF_Fixed32Defaulted

    +
    func (m *GoTest) GetF_Fixed32Defaulted() uint32
    + + + + + + +

    func (*GoTest) GetF_Fixed32Optional

    +
    func (m *GoTest) GetF_Fixed32Optional() uint32
    + + + + + + +

    func (*GoTest) GetF_Fixed32Repeated

    +
    func (m *GoTest) GetF_Fixed32Repeated() []uint32
    + + + + + + +

    func (*GoTest) GetF_Fixed32RepeatedPacked

    +
    func (m *GoTest) GetF_Fixed32RepeatedPacked() []uint32
    + + + + + + +

    func (*GoTest) GetF_Fixed32Required

    +
    func (m *GoTest) GetF_Fixed32Required() uint32
    + + + + + + +

    func (*GoTest) GetF_Fixed64Defaulted

    +
    func (m *GoTest) GetF_Fixed64Defaulted() uint64
    + + + + + + +

    func (*GoTest) GetF_Fixed64Optional

    +
    func (m *GoTest) GetF_Fixed64Optional() uint64
    + + + + + + +

    func (*GoTest) GetF_Fixed64Repeated

    +
    func (m *GoTest) GetF_Fixed64Repeated() []uint64
    + + + + + + +

    func (*GoTest) GetF_Fixed64RepeatedPacked

    +
    func (m *GoTest) GetF_Fixed64RepeatedPacked() []uint64
    + + + + + + +

    func (*GoTest) GetF_Fixed64Required

    +
    func (m *GoTest) GetF_Fixed64Required() uint64
    + + + + + + +

    func (*GoTest) GetF_FloatDefaulted

    +
    func (m *GoTest) GetF_FloatDefaulted() float32
    + + + + + + +

    func (*GoTest) GetF_FloatOptional

    +
    func (m *GoTest) GetF_FloatOptional() float32
    + + + + + + +

    func (*GoTest) GetF_FloatRepeated

    +
    func (m *GoTest) GetF_FloatRepeated() []float32
    + + + + + + +

    func (*GoTest) GetF_FloatRepeatedPacked

    +
    func (m *GoTest) GetF_FloatRepeatedPacked() []float32
    + + + + + + +

    func (*GoTest) GetF_FloatRequired

    +
    func (m *GoTest) GetF_FloatRequired() float32
    + + + + + + +

    func (*GoTest) GetF_Int32Defaulted

    +
    func (m *GoTest) GetF_Int32Defaulted() int32
    + + + + + + +

    func (*GoTest) GetF_Int32Optional

    +
    func (m *GoTest) GetF_Int32Optional() int32
    + + + + + + +

    func (*GoTest) GetF_Int32Repeated

    +
    func (m *GoTest) GetF_Int32Repeated() []int32
    + + + + + + +

    func (*GoTest) GetF_Int32RepeatedPacked

    +
    func (m *GoTest) GetF_Int32RepeatedPacked() []int32
    + + + + + + +

    func (*GoTest) GetF_Int32Required

    +
    func (m *GoTest) GetF_Int32Required() int32
    + + + + + + +

    func (*GoTest) GetF_Int64Defaulted

    +
    func (m *GoTest) GetF_Int64Defaulted() int64
    + + + + + + +

    func (*GoTest) GetF_Int64Optional

    +
    func (m *GoTest) GetF_Int64Optional() int64
    + + + + + + +

    func (*GoTest) GetF_Int64Repeated

    +
    func (m *GoTest) GetF_Int64Repeated() []int64
    + + + + + + +

    func (*GoTest) GetF_Int64RepeatedPacked

    +
    func (m *GoTest) GetF_Int64RepeatedPacked() []int64
    + + + + + + +

    func (*GoTest) GetF_Int64Required

    +
    func (m *GoTest) GetF_Int64Required() int64
    + + + + + + +

    func (*GoTest) GetF_Sint32Defaulted

    +
    func (m *GoTest) GetF_Sint32Defaulted() int32
    + + + + + + +

    func (*GoTest) GetF_Sint32Optional

    +
    func (m *GoTest) GetF_Sint32Optional() int32
    + + + + + + +

    func (*GoTest) GetF_Sint32Repeated

    +
    func (m *GoTest) GetF_Sint32Repeated() []int32
    + + + + + + +

    func (*GoTest) GetF_Sint32RepeatedPacked

    +
    func (m *GoTest) GetF_Sint32RepeatedPacked() []int32
    + + + + + + +

    func (*GoTest) GetF_Sint32Required

    +
    func (m *GoTest) GetF_Sint32Required() int32
    + + + + + + +

    func (*GoTest) GetF_Sint64Defaulted

    +
    func (m *GoTest) GetF_Sint64Defaulted() int64
    + + + + + + +

    func (*GoTest) GetF_Sint64Optional

    +
    func (m *GoTest) GetF_Sint64Optional() int64
    + + + + + + +

    func (*GoTest) GetF_Sint64Repeated

    +
    func (m *GoTest) GetF_Sint64Repeated() []int64
    + + + + + + +

    func (*GoTest) GetF_Sint64RepeatedPacked

    +
    func (m *GoTest) GetF_Sint64RepeatedPacked() []int64
    + + + + + + +

    func (*GoTest) GetF_Sint64Required

    +
    func (m *GoTest) GetF_Sint64Required() int64
    + + + + + + +

    func (*GoTest) GetF_StringDefaulted

    +
    func (m *GoTest) GetF_StringDefaulted() string
    + + + + + + +

    func (*GoTest) GetF_StringOptional

    +
    func (m *GoTest) GetF_StringOptional() string
    + + + + + + +

    func (*GoTest) GetF_StringRepeated

    +
    func (m *GoTest) GetF_StringRepeated() []string
    + + + + + + +

    func (*GoTest) GetF_StringRequired

    +
    func (m *GoTest) GetF_StringRequired() string
    + + + + + + +

    func (*GoTest) GetF_Uint32Defaulted

    +
    func (m *GoTest) GetF_Uint32Defaulted() uint32
    + + + + + + +

    func (*GoTest) GetF_Uint32Optional

    +
    func (m *GoTest) GetF_Uint32Optional() uint32
    + + + + + + +

    func (*GoTest) GetF_Uint32Repeated

    +
    func (m *GoTest) GetF_Uint32Repeated() []uint32
    + + + + + + +

    func (*GoTest) GetF_Uint32RepeatedPacked

    +
    func (m *GoTest) GetF_Uint32RepeatedPacked() []uint32
    + + + + + + +

    func (*GoTest) GetF_Uint32Required

    +
    func (m *GoTest) GetF_Uint32Required() uint32
    + + + + + + +

    func (*GoTest) GetF_Uint64Defaulted

    +
    func (m *GoTest) GetF_Uint64Defaulted() uint64
    + + + + + + +

    func (*GoTest) GetF_Uint64Optional

    +
    func (m *GoTest) GetF_Uint64Optional() uint64
    + + + + + + +

    func (*GoTest) GetF_Uint64Repeated

    +
    func (m *GoTest) GetF_Uint64Repeated() []uint64
    + + + + + + +

    func (*GoTest) GetF_Uint64RepeatedPacked

    +
    func (m *GoTest) GetF_Uint64RepeatedPacked() []uint64
    + + + + + + +

    func (*GoTest) GetF_Uint64Required

    +
    func (m *GoTest) GetF_Uint64Required() uint64
    + + + + + + +

    func (*GoTest) GetKind

    +
    func (m *GoTest) GetKind() GoTest_KIND
    + + + + + + +

    func (*GoTest) GetOptionalField

    +
    func (m *GoTest) GetOptionalField() *GoTestField
    + + + + + + +

    func (*GoTest) GetOptionalgroup

    +
    func (m *GoTest) GetOptionalgroup() *GoTest_OptionalGroup
    + + + + + + +

    func (*GoTest) GetParam

    +
    func (m *GoTest) GetParam() int32
    + + + + + + +

    func (*GoTest) GetRepeatedField

    +
    func (m *GoTest) GetRepeatedField() []*GoTestField
    + + + + + + +

    func (*GoTest) GetRepeatedgroup

    +
    func (m *GoTest) GetRepeatedgroup() []*GoTest_RepeatedGroup
    + + + + + + +

    func (*GoTest) GetRequiredField

    +
    func (m *GoTest) GetRequiredField() *GoTestField
    + + + + + + +

    func (*GoTest) GetRequiredgroup

    +
    func (m *GoTest) GetRequiredgroup() *GoTest_RequiredGroup
    + + + + + + +

    func (*GoTest) GetTable

    +
    func (m *GoTest) GetTable() string
    + + + + + + +

    func (*GoTest) ProtoMessage

    +
    func (*GoTest) ProtoMessage()
    + + + + + + +

    func (*GoTest) Reset

    +
    func (m *GoTest) Reset()
    + + + + + + +

    func (*GoTest) String

    +
    func (m *GoTest) String() string
    + + + + + + + + +

    type GoTestField

    +
    type GoTestField struct {
    +    Label            *string `protobuf:"bytes,1,req,name=Label,json=label" json:"Label,omitempty"`
    +    Type             *string `protobuf:"bytes,2,req,name=Type,json=type" json:"Type,omitempty"`
    +    XXX_unrecognized []byte  `json:"-"`
    +}
    + + + + + + + + + + + + + + +

    func (*GoTestField) Descriptor

    +
    func (*GoTestField) Descriptor() ([]byte, []int)
    + + + + + + +

    func (*GoTestField) GetLabel

    +
    func (m *GoTestField) GetLabel() string
    + + + + + + +

    func (*GoTestField) GetType

    +
    func (m *GoTestField) GetType() string
    + + + + + + +

    func (*GoTestField) ProtoMessage

    +
    func (*GoTestField) ProtoMessage()
    + + + + + + +

    func (*GoTestField) Reset

    +
    func (m *GoTestField) Reset()
    + + + + + + +

    func (*GoTestField) String

    +
    func (m *GoTestField) String() string
    + + + + + + + + +

    type GoTestRequiredGroupField

    +
    type GoTestRequiredGroupField struct {
    +    Group            *GoTestRequiredGroupField_Group `protobuf:"group,1,req,name=Group,json=group" json:"group,omitempty"`
    +    XXX_unrecognized []byte                          `json:"-"`
    +}
    +

    +For testing a group containing a required field. +

    + + + + + + + + + + + + + + +

    func (*GoTestRequiredGroupField) Descriptor

    +
    func (*GoTestRequiredGroupField) Descriptor() ([]byte, []int)
    + + + + + + +

    func (*GoTestRequiredGroupField) GetGroup

    +
    func (m *GoTestRequiredGroupField) GetGroup() *GoTestRequiredGroupField_Group
    + + + + + + +

    func (*GoTestRequiredGroupField) ProtoMessage

    +
    func (*GoTestRequiredGroupField) ProtoMessage()
    + + + + + + +

    func (*GoTestRequiredGroupField) Reset

    +
    func (m *GoTestRequiredGroupField) Reset()
    + + + + + + +

    func (*GoTestRequiredGroupField) String

    +
    func (m *GoTestRequiredGroupField) String() string
    + + + + + + + + +

    type GoTestRequiredGroupField_Group

    +
    type GoTestRequiredGroupField_Group struct {
    +    Field            *int32 `protobuf:"varint,2,req,name=Field,json=field" json:"Field,omitempty"`
    +    XXX_unrecognized []byte `json:"-"`
    +}
    + + + + + + + + + + + + + + +

    func (*GoTestRequiredGroupField_Group) Descriptor

    +
    func (*GoTestRequiredGroupField_Group) Descriptor() ([]byte, []int)
    + + + + + + +

    func (*GoTestRequiredGroupField_Group) GetField

    +
    func (m *GoTestRequiredGroupField_Group) GetField() int32
    + + + + + + +

    func (*GoTestRequiredGroupField_Group) ProtoMessage

    +
    func (*GoTestRequiredGroupField_Group) ProtoMessage()
    + + + + + + +

    func (*GoTestRequiredGroupField_Group) Reset

    +
    func (m *GoTestRequiredGroupField_Group) Reset()
    + + + + + + +

    func (*GoTestRequiredGroupField_Group) String

    +
    func (m *GoTestRequiredGroupField_Group) String() string
    + + + + + + + + +

    type GoTest_KIND

    +
    type GoTest_KIND int32
    +

    +An enum, for completeness. +

    + + + +
    const (
    +    GoTest_VOID GoTest_KIND = 0
    +    // Basic types
    +    GoTest_BOOL        GoTest_KIND = 1
    +    GoTest_BYTES       GoTest_KIND = 2
    +    GoTest_FINGERPRINT GoTest_KIND = 3
    +    GoTest_FLOAT       GoTest_KIND = 4
    +    GoTest_INT         GoTest_KIND = 5
    +    GoTest_STRING      GoTest_KIND = 6
    +    GoTest_TIME        GoTest_KIND = 7
    +    // Groupings
    +    GoTest_TUPLE GoTest_KIND = 8
    +    GoTest_ARRAY GoTest_KIND = 9
    +    GoTest_MAP   GoTest_KIND = 10
    +    // Table types
    +    GoTest_TABLE GoTest_KIND = 11
    +    // Functions
    +    GoTest_FUNCTION GoTest_KIND = 12
    +)
    + + + + + + + + + + + + + +

    func (GoTest_KIND) Enum

    +
    func (x GoTest_KIND) Enum() *GoTest_KIND
    + + + + + + +

    func (GoTest_KIND) EnumDescriptor

    +
    func (GoTest_KIND) EnumDescriptor() ([]byte, []int)
    + + + + + + +

    func (GoTest_KIND) String

    +
    func (x GoTest_KIND) String() string
    + + + + + + +

    func (*GoTest_KIND) UnmarshalJSON

    +
    func (x *GoTest_KIND) UnmarshalJSON(data []byte) error
    + + + + + + + + +

    type GoTest_OptionalGroup

    +
    type GoTest_OptionalGroup struct {
    +    RequiredField    *string `protobuf:"bytes,91,req,name=RequiredField,json=requiredField" json:"RequiredField,omitempty"`
    +    XXX_unrecognized []byte  `json:"-"`
    +}
    + + + + + + + + + + + + + + +

    func (*GoTest_OptionalGroup) Descriptor

    +
    func (*GoTest_OptionalGroup) Descriptor() ([]byte, []int)
    + + + + + + +

    func (*GoTest_OptionalGroup) GetRequiredField

    +
    func (m *GoTest_OptionalGroup) GetRequiredField() string
    + + + + + + +

    func (*GoTest_OptionalGroup) ProtoMessage

    +
    func (*GoTest_OptionalGroup) ProtoMessage()
    + + + + + + +

    func (*GoTest_OptionalGroup) Reset

    +
    func (m *GoTest_OptionalGroup) Reset()
    + + + + + + +

    func (*GoTest_OptionalGroup) String

    +
    func (m *GoTest_OptionalGroup) String() string
    + + + + + + + + +

    type GoTest_RepeatedGroup

    +
    type GoTest_RepeatedGroup struct {
    +    RequiredField    *string `protobuf:"bytes,81,req,name=RequiredField,json=requiredField" json:"RequiredField,omitempty"`
    +    XXX_unrecognized []byte  `json:"-"`
    +}
    + + + + + + + + + + + + + + +

    func (*GoTest_RepeatedGroup) Descriptor

    +
    func (*GoTest_RepeatedGroup) Descriptor() ([]byte, []int)
    + + + + + + +

    func (*GoTest_RepeatedGroup) GetRequiredField

    +
    func (m *GoTest_RepeatedGroup) GetRequiredField() string
    + + + + + + +

    func (*GoTest_RepeatedGroup) ProtoMessage

    +
    func (*GoTest_RepeatedGroup) ProtoMessage()
    + + + + + + +

    func (*GoTest_RepeatedGroup) Reset

    +
    func (m *GoTest_RepeatedGroup) Reset()
    + + + + + + +

    func (*GoTest_RepeatedGroup) String

    +
    func (m *GoTest_RepeatedGroup) String() string
    + + + + + + + + +

    type GoTest_RequiredGroup

    +
    type GoTest_RequiredGroup struct {
    +    RequiredField    *string `protobuf:"bytes,71,req,name=RequiredField,json=requiredField" json:"RequiredField,omitempty"`
    +    XXX_unrecognized []byte  `json:"-"`
    +}
    +

    +Required, repeated, and optional groups. +

    + + + + + + + + + + + + + + +

    func (*GoTest_RequiredGroup) Descriptor

    +
    func (*GoTest_RequiredGroup) Descriptor() ([]byte, []int)
    + + + + + + +

    func (*GoTest_RequiredGroup) GetRequiredField

    +
    func (m *GoTest_RequiredGroup) GetRequiredField() string
    + + + + + + +

    func (*GoTest_RequiredGroup) ProtoMessage

    +
    func (*GoTest_RequiredGroup) ProtoMessage()
    + + + + + + +

    func (*GoTest_RequiredGroup) Reset

    +
    func (m *GoTest_RequiredGroup) Reset()
    + + + + + + +

    func (*GoTest_RequiredGroup) String

    +
    func (m *GoTest_RequiredGroup) String() string
    + + + + + + + + +

    type GroupNew

    +
    type GroupNew struct {
    +    G                *GroupNew_G `protobuf:"group,101,opt,name=G,json=g" json:"g,omitempty"`
    +    XXX_unrecognized []byte      `json:"-"`
    +}
    + + + + + + + + + + + + + + +

    func (*GroupNew) Descriptor

    +
    func (*GroupNew) Descriptor() ([]byte, []int)
    + + + + + + +

    func (*GroupNew) GetG

    +
    func (m *GroupNew) GetG() *GroupNew_G
    + + + + + + +

    func (*GroupNew) ProtoMessage

    +
    func (*GroupNew) ProtoMessage()
    + + + + + + +

    func (*GroupNew) Reset

    +
    func (m *GroupNew) Reset()
    + + + + + + +

    func (*GroupNew) String

    +
    func (m *GroupNew) String() string
    + + + + + + + + +

    type GroupNew_G

    +
    type GroupNew_G struct {
    +    X                *int32 `protobuf:"varint,2,opt,name=x" json:"x,omitempty"`
    +    Y                *int32 `protobuf:"varint,3,opt,name=y" json:"y,omitempty"`
    +    XXX_unrecognized []byte `json:"-"`
    +}
    + + + + + + + + + + + + + + +

    func (*GroupNew_G) Descriptor

    +
    func (*GroupNew_G) Descriptor() ([]byte, []int)
    + + + + + + +

    func (*GroupNew_G) GetX

    +
    func (m *GroupNew_G) GetX() int32
    + + + + + + +

    func (*GroupNew_G) GetY

    +
    func (m *GroupNew_G) GetY() int32
    + + + + + + +

    func (*GroupNew_G) ProtoMessage

    +
    func (*GroupNew_G) ProtoMessage()
    + + + + + + +

    func (*GroupNew_G) Reset

    +
    func (m *GroupNew_G) Reset()
    + + + + + + +

    func (*GroupNew_G) String

    +
    func (m *GroupNew_G) String() string
    + + + + + + + + +

    type GroupOld

    +
    type GroupOld struct {
    +    G                *GroupOld_G `protobuf:"group,101,opt,name=G,json=g" json:"g,omitempty"`
    +    XXX_unrecognized []byte      `json:"-"`
    +}
    + + + + + + + + + + + + + + +

    func (*GroupOld) Descriptor

    +
    func (*GroupOld) Descriptor() ([]byte, []int)
    + + + + + + +

    func (*GroupOld) GetG

    +
    func (m *GroupOld) GetG() *GroupOld_G
    + + + + + + +

    func (*GroupOld) ProtoMessage

    +
    func (*GroupOld) ProtoMessage()
    + + + + + + +

    func (*GroupOld) Reset

    +
    func (m *GroupOld) Reset()
    + + + + + + +

    func (*GroupOld) String

    +
    func (m *GroupOld) String() string
    + + + + + + + + +

    type GroupOld_G

    +
    type GroupOld_G struct {
    +    X                *int32 `protobuf:"varint,2,opt,name=x" json:"x,omitempty"`
    +    XXX_unrecognized []byte `json:"-"`
    +}
    + + + + + + + + + + + + + + +

    func (*GroupOld_G) Descriptor

    +
    func (*GroupOld_G) Descriptor() ([]byte, []int)
    + + + + + + +

    func (*GroupOld_G) GetX

    +
    func (m *GroupOld_G) GetX() int32
    + + + + + + +

    func (*GroupOld_G) ProtoMessage

    +
    func (*GroupOld_G) ProtoMessage()
    + + + + + + +

    func (*GroupOld_G) Reset

    +
    func (m *GroupOld_G) Reset()
    + + + + + + +

    func (*GroupOld_G) String

    +
    func (m *GroupOld_G) String() string
    + + + + + + + + +

    type InnerMessage

    +
    type InnerMessage struct {
    +    Host             *string `protobuf:"bytes,1,req,name=host" json:"host,omitempty"`
    +    Port             *int32  `protobuf:"varint,2,opt,name=port,def=4000" json:"port,omitempty"`
    +    Connected        *bool   `protobuf:"varint,3,opt,name=connected" json:"connected,omitempty"`
    +    XXX_unrecognized []byte  `json:"-"`
    +}
    + + + + + + + + + + + + + + +

    func (*InnerMessage) Descriptor

    +
    func (*InnerMessage) Descriptor() ([]byte, []int)
    + + + + + + +

    func (*InnerMessage) GetConnected

    +
    func (m *InnerMessage) GetConnected() bool
    + + + + + + +

    func (*InnerMessage) GetHost

    +
    func (m *InnerMessage) GetHost() string
    + + + + + + +

    func (*InnerMessage) GetPort

    +
    func (m *InnerMessage) GetPort() int32
    + + + + + + +

    func (*InnerMessage) ProtoMessage

    +
    func (*InnerMessage) ProtoMessage()
    + + + + + + +

    func (*InnerMessage) Reset

    +
    func (m *InnerMessage) Reset()
    + + + + + + +

    func (*InnerMessage) String

    +
    func (m *InnerMessage) String() string
    + + + + + + + + +

    type MaxTag

    +
    type MaxTag struct {
    +    // Maximum possible tag number.
    +    LastField        *string `protobuf:"bytes,536870911,opt,name=last_field,json=lastField" json:"last_field,omitempty"`
    +    XXX_unrecognized []byte  `json:"-"`
    +}
    + + + + + + + + + + + + + + +

    func (*MaxTag) Descriptor

    +
    func (*MaxTag) Descriptor() ([]byte, []int)
    + + + + + + +

    func (*MaxTag) GetLastField

    +
    func (m *MaxTag) GetLastField() string
    + + + + + + +

    func (*MaxTag) ProtoMessage

    +
    func (*MaxTag) ProtoMessage()
    + + + + + + +

    func (*MaxTag) Reset

    +
    func (m *MaxTag) Reset()
    + + + + + + +

    func (*MaxTag) String

    +
    func (m *MaxTag) String() string
    + + + + + + + + +

    type MessageList

    +
    type MessageList struct {
    +    Message          []*MessageList_Message `protobuf:"group,1,rep,name=Message,json=message" json:"message,omitempty"`
    +    XXX_unrecognized []byte                 `json:"-"`
    +}
    + + + + + + + + + + + + + + +

    func (*MessageList) Descriptor

    +
    func (*MessageList) Descriptor() ([]byte, []int)
    + + + + + + +

    func (*MessageList) GetMessage

    +
    func (m *MessageList) GetMessage() []*MessageList_Message
    + + + + + + +

    func (*MessageList) ProtoMessage

    +
    func (*MessageList) ProtoMessage()
    + + + + + + +

    func (*MessageList) Reset

    +
    func (m *MessageList) Reset()
    + + + + + + +

    func (*MessageList) String

    +
    func (m *MessageList) String() string
    + + + + + + + + +

    type MessageList_Message

    +
    type MessageList_Message struct {
    +    Name             *string `protobuf:"bytes,2,req,name=name" json:"name,omitempty"`
    +    Count            *int32  `protobuf:"varint,3,req,name=count" json:"count,omitempty"`
    +    XXX_unrecognized []byte  `json:"-"`
    +}
    + + + + + + + + + + + + + + +

    func (*MessageList_Message) Descriptor

    +
    func (*MessageList_Message) Descriptor() ([]byte, []int)
    + + + + + + +

    func (*MessageList_Message) GetCount

    +
    func (m *MessageList_Message) GetCount() int32
    + + + + + + +

    func (*MessageList_Message) GetName

    +
    func (m *MessageList_Message) GetName() string
    + + + + + + +

    func (*MessageList_Message) ProtoMessage

    +
    func (*MessageList_Message) ProtoMessage()
    + + + + + + +

    func (*MessageList_Message) Reset

    +
    func (m *MessageList_Message) Reset()
    + + + + + + +

    func (*MessageList_Message) String

    +
    func (m *MessageList_Message) String() string
    + + + + + + + + +

    type MessageWithMap

    +
    type MessageWithMap struct {
    +    NameMapping      map[int32]string         `protobuf:"bytes,1,rep,name=name_mapping,json=nameMapping" json:"name_mapping,omitempty" protobuf_key:"varint,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"`
    +    MsgMapping       map[int64]*FloatingPoint `protobuf:"bytes,2,rep,name=msg_mapping,json=msgMapping" json:"msg_mapping,omitempty" protobuf_key:"zigzag64,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"`
    +    ByteMapping      map[bool][]byte          `protobuf:"bytes,3,rep,name=byte_mapping,json=byteMapping" json:"byte_mapping,omitempty" protobuf_key:"varint,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"`
    +    StrToStr         map[string]string        `protobuf:"bytes,4,rep,name=str_to_str,json=strToStr" json:"str_to_str,omitempty" protobuf_key:"bytes,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"`
    +    XXX_unrecognized []byte                   `json:"-"`
    +}
    + + + + + + + + + + + + + + +

    func (*MessageWithMap) Descriptor

    +
    func (*MessageWithMap) Descriptor() ([]byte, []int)
    + + + + + + +

    func (*MessageWithMap) GetByteMapping

    +
    func (m *MessageWithMap) GetByteMapping() map[bool][]byte
    + + + + + + +

    func (*MessageWithMap) GetMsgMapping

    +
    func (m *MessageWithMap) GetMsgMapping() map[int64]*FloatingPoint
    + + + + + + +

    func (*MessageWithMap) GetNameMapping

    +
    func (m *MessageWithMap) GetNameMapping() map[int32]string
    + + + + + + +

    func (*MessageWithMap) GetStrToStr

    +
    func (m *MessageWithMap) GetStrToStr() map[string]string
    + + + + + + +

    func (*MessageWithMap) ProtoMessage

    +
    func (*MessageWithMap) ProtoMessage()
    + + + + + + +

    func (*MessageWithMap) Reset

    +
    func (m *MessageWithMap) Reset()
    + + + + + + +

    func (*MessageWithMap) String

    +
    func (m *MessageWithMap) String() string
    + + + + + + + + +

    type MoreRepeated

    +
    type MoreRepeated struct {
    +    Bools            []bool   `protobuf:"varint,1,rep,name=bools" json:"bools,omitempty"`
    +    BoolsPacked      []bool   `protobuf:"varint,2,rep,packed,name=bools_packed,json=boolsPacked" json:"bools_packed,omitempty"`
    +    Ints             []int32  `protobuf:"varint,3,rep,name=ints" json:"ints,omitempty"`
    +    IntsPacked       []int32  `protobuf:"varint,4,rep,packed,name=ints_packed,json=intsPacked" json:"ints_packed,omitempty"`
    +    Int64SPacked     []int64  `protobuf:"varint,7,rep,packed,name=int64s_packed,json=int64sPacked" json:"int64s_packed,omitempty"`
    +    Strings          []string `protobuf:"bytes,5,rep,name=strings" json:"strings,omitempty"`
    +    Fixeds           []uint32 `protobuf:"fixed32,6,rep,name=fixeds" json:"fixeds,omitempty"`
    +    XXX_unrecognized []byte   `json:"-"`
    +}
    + + + + + + + + + + + + + + +

    func (*MoreRepeated) Descriptor

    +
    func (*MoreRepeated) Descriptor() ([]byte, []int)
    + + + + + + +

    func (*MoreRepeated) GetBools

    +
    func (m *MoreRepeated) GetBools() []bool
    + + + + + + +

    func (*MoreRepeated) GetBoolsPacked

    +
    func (m *MoreRepeated) GetBoolsPacked() []bool
    + + + + + + +

    func (*MoreRepeated) GetFixeds

    +
    func (m *MoreRepeated) GetFixeds() []uint32
    + + + + + + +

    func (*MoreRepeated) GetInt64SPacked

    +
    func (m *MoreRepeated) GetInt64SPacked() []int64
    + + + + + + +

    func (*MoreRepeated) GetInts

    +
    func (m *MoreRepeated) GetInts() []int32
    + + + + + + +

    func (*MoreRepeated) GetIntsPacked

    +
    func (m *MoreRepeated) GetIntsPacked() []int32
    + + + + + + +

    func (*MoreRepeated) GetStrings

    +
    func (m *MoreRepeated) GetStrings() []string
    + + + + + + +

    func (*MoreRepeated) ProtoMessage

    +
    func (*MoreRepeated) ProtoMessage()
    + + + + + + +

    func (*MoreRepeated) Reset

    +
    func (m *MoreRepeated) Reset()
    + + + + + + +

    func (*MoreRepeated) String

    +
    func (m *MoreRepeated) String() string
    + + + + + + + + +

    type MyMessage

    +
    type MyMessage struct {
    +    Count          *int32                `protobuf:"varint,1,req,name=count" json:"count,omitempty"`
    +    Name           *string               `protobuf:"bytes,2,opt,name=name" json:"name,omitempty"`
    +    Quote          *string               `protobuf:"bytes,3,opt,name=quote" json:"quote,omitempty"`
    +    Pet            []string              `protobuf:"bytes,4,rep,name=pet" json:"pet,omitempty"`
    +    Inner          *InnerMessage         `protobuf:"bytes,5,opt,name=inner" json:"inner,omitempty"`
    +    Others         []*OtherMessage       `protobuf:"bytes,6,rep,name=others" json:"others,omitempty"`
    +    WeMustGoDeeper *RequiredInnerMessage `protobuf:"bytes,13,opt,name=we_must_go_deeper,json=weMustGoDeeper" json:"we_must_go_deeper,omitempty"`
    +    RepInner       []*InnerMessage       `protobuf:"bytes,12,rep,name=rep_inner,json=repInner" json:"rep_inner,omitempty"`
    +    Bikeshed       *MyMessage_Color      `protobuf:"varint,7,opt,name=bikeshed,enum=testdata.MyMessage_Color" json:"bikeshed,omitempty"`
    +    Somegroup      *MyMessage_SomeGroup  `protobuf:"group,8,opt,name=SomeGroup,json=somegroup" json:"somegroup,omitempty"`
    +    // This field becomes [][]byte in the generated code.
    +    RepBytes                     [][]byte `protobuf:"bytes,10,rep,name=rep_bytes,json=repBytes" json:"rep_bytes,omitempty"`
    +    Bigfloat                     *float64 `protobuf:"fixed64,11,opt,name=bigfloat" json:"bigfloat,omitempty"`
    +    proto.XXX_InternalExtensions `json:"-"`
    +    XXX_unrecognized             []byte `json:"-"`
    +}
    + + + + + + + + + + + + + + +

    func (*MyMessage) Descriptor

    +
    func (*MyMessage) Descriptor() ([]byte, []int)
    + + + + + + +

    func (*MyMessage) ExtensionRangeArray

    +
    func (*MyMessage) ExtensionRangeArray() []proto.ExtensionRange
    + + + + + + +

    func (*MyMessage) GetBigfloat

    +
    func (m *MyMessage) GetBigfloat() float64
    + + + + + + +

    func (*MyMessage) GetBikeshed

    +
    func (m *MyMessage) GetBikeshed() MyMessage_Color
    + + + + + + +

    func (*MyMessage) GetCount

    +
    func (m *MyMessage) GetCount() int32
    + + + + + + +

    func (*MyMessage) GetInner

    +
    func (m *MyMessage) GetInner() *InnerMessage
    + + + + + + +

    func (*MyMessage) GetName

    +
    func (m *MyMessage) GetName() string
    + + + + + + +

    func (*MyMessage) GetOthers

    +
    func (m *MyMessage) GetOthers() []*OtherMessage
    + + + + + + +

    func (*MyMessage) GetPet

    +
    func (m *MyMessage) GetPet() []string
    + + + + + + +

    func (*MyMessage) GetQuote

    +
    func (m *MyMessage) GetQuote() string
    + + + + + + +

    func (*MyMessage) GetRepBytes

    +
    func (m *MyMessage) GetRepBytes() [][]byte
    + + + + + + +

    func (*MyMessage) GetRepInner

    +
    func (m *MyMessage) GetRepInner() []*InnerMessage
    + + + + + + +

    func (*MyMessage) GetSomegroup

    +
    func (m *MyMessage) GetSomegroup() *MyMessage_SomeGroup
    + + + + + + +

    func (*MyMessage) GetWeMustGoDeeper

    +
    func (m *MyMessage) GetWeMustGoDeeper() *RequiredInnerMessage
    + + + + + + +

    func (*MyMessage) ProtoMessage

    +
    func (*MyMessage) ProtoMessage()
    + + + + + + +

    func (*MyMessage) Reset

    +
    func (m *MyMessage) Reset()
    + + + + + + +

    func (*MyMessage) String

    +
    func (m *MyMessage) String() string
    + + + + + + + + +

    type MyMessageSet

    +
    type MyMessageSet struct {
    +    proto.XXX_InternalExtensions `json:"-"`
    +    XXX_unrecognized             []byte `json:"-"`
    +}
    + + + + + + + + + + + + + + +

    func (*MyMessageSet) Descriptor

    +
    func (*MyMessageSet) Descriptor() ([]byte, []int)
    + + + + + + +

    func (*MyMessageSet) ExtensionRangeArray

    +
    func (*MyMessageSet) ExtensionRangeArray() []proto.ExtensionRange
    + + + + + + +

    func (*MyMessageSet) Marshal

    +
    func (m *MyMessageSet) Marshal() ([]byte, error)
    + + + + + + +

    func (*MyMessageSet) MarshalJSON

    +
    func (m *MyMessageSet) MarshalJSON() ([]byte, error)
    + + + + + + +

    func (*MyMessageSet) ProtoMessage

    +
    func (*MyMessageSet) ProtoMessage()
    + + + + + + +

    func (*MyMessageSet) Reset

    +
    func (m *MyMessageSet) Reset()
    + + + + + + +

    func (*MyMessageSet) String

    +
    func (m *MyMessageSet) String() string
    + + + + + + +

    func (*MyMessageSet) Unmarshal

    +
    func (m *MyMessageSet) Unmarshal(buf []byte) error
    + + + + + + +

    func (*MyMessageSet) UnmarshalJSON

    +
    func (m *MyMessageSet) UnmarshalJSON(buf []byte) error
    + + + + + + + + +

    type MyMessage_Color

    +
    type MyMessage_Color int32
    + + + +
    const (
    +    MyMessage_RED   MyMessage_Color = 0
    +    MyMessage_GREEN MyMessage_Color = 1
    +    MyMessage_BLUE  MyMessage_Color = 2
    +)
    + + + + + + + + + + + + + +

    func (MyMessage_Color) Enum

    +
    func (x MyMessage_Color) Enum() *MyMessage_Color
    + + + + + + +

    func (MyMessage_Color) EnumDescriptor

    +
    func (MyMessage_Color) EnumDescriptor() ([]byte, []int)
    + + + + + + +

    func (MyMessage_Color) String

    +
    func (x MyMessage_Color) String() string
    + + + + + + +

    func (*MyMessage_Color) UnmarshalJSON

    +
    func (x *MyMessage_Color) UnmarshalJSON(data []byte) error
    + + + + + + + + +

    type MyMessage_SomeGroup

    +
    type MyMessage_SomeGroup struct {
    +    GroupField       *int32 `protobuf:"varint,9,opt,name=group_field,json=groupField" json:"group_field,omitempty"`
    +    XXX_unrecognized []byte `json:"-"`
    +}
    + + + + + + + + + + + + + + +

    func (*MyMessage_SomeGroup) Descriptor

    +
    func (*MyMessage_SomeGroup) Descriptor() ([]byte, []int)
    + + + + + + +

    func (*MyMessage_SomeGroup) GetGroupField

    +
    func (m *MyMessage_SomeGroup) GetGroupField() int32
    + + + + + + +

    func (*MyMessage_SomeGroup) ProtoMessage

    +
    func (*MyMessage_SomeGroup) ProtoMessage()
    + + + + + + +

    func (*MyMessage_SomeGroup) Reset

    +
    func (m *MyMessage_SomeGroup) Reset()
    + + + + + + +

    func (*MyMessage_SomeGroup) String

    +
    func (m *MyMessage_SomeGroup) String() string
    + + + + + + + + +

    type NewMessage

    +
    type NewMessage struct {
    +    Nested *NewMessage_Nested `protobuf:"bytes,1,opt,name=nested" json:"nested,omitempty"`
    +    // This is an int32 in OldMessage.
    +    Num              *int64 `protobuf:"varint,2,opt,name=num" json:"num,omitempty"`
    +    XXX_unrecognized []byte `json:"-"`
    +}
    +

    +NewMessage is wire compatible with OldMessage; +imagine it as a future version. +

    + + + + + + + + + + + + + + +

    func (*NewMessage) Descriptor

    +
    func (*NewMessage) Descriptor() ([]byte, []int)
    + + + + + + +

    func (*NewMessage) GetNested

    +
    func (m *NewMessage) GetNested() *NewMessage_Nested
    + + + + + + +

    func (*NewMessage) GetNum

    +
    func (m *NewMessage) GetNum() int64
    + + + + + + +

    func (*NewMessage) ProtoMessage

    +
    func (*NewMessage) ProtoMessage()
    + + + + + + +

    func (*NewMessage) Reset

    +
    func (m *NewMessage) Reset()
    + + + + + + +

    func (*NewMessage) String

    +
    func (m *NewMessage) String() string
    + + + + + + + + +

    type NewMessage_Nested

    +
    type NewMessage_Nested struct {
    +    Name             *string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"`
    +    FoodGroup        *string `protobuf:"bytes,2,opt,name=food_group,json=foodGroup" json:"food_group,omitempty"`
    +    XXX_unrecognized []byte  `json:"-"`
    +}
    + + + + + + + + + + + + + + +

    func (*NewMessage_Nested) Descriptor

    +
    func (*NewMessage_Nested) Descriptor() ([]byte, []int)
    + + + + + + +

    func (*NewMessage_Nested) GetFoodGroup

    +
    func (m *NewMessage_Nested) GetFoodGroup() string
    + + + + + + +

    func (*NewMessage_Nested) GetName

    +
    func (m *NewMessage_Nested) GetName() string
    + + + + + + +

    func (*NewMessage_Nested) ProtoMessage

    +
    func (*NewMessage_Nested) ProtoMessage()
    + + + + + + +

    func (*NewMessage_Nested) Reset

    +
    func (m *NewMessage_Nested) Reset()
    + + + + + + +

    func (*NewMessage_Nested) String

    +
    func (m *NewMessage_Nested) String() string
    + + + + + + + + +

    type NonPackedTest

    +
    type NonPackedTest struct {
    +    A                []int32 `protobuf:"varint,1,rep,name=a" json:"a,omitempty"`
    +    XXX_unrecognized []byte  `json:"-"`
    +}
    +

    +For testing packed/non-packed decoder switching. +A serialized instance of one should be deserializable as the other. +

    + + + + + + + + + + + + + + +

    func (*NonPackedTest) Descriptor

    +
    func (*NonPackedTest) Descriptor() ([]byte, []int)
    + + + + + + +

    func (*NonPackedTest) GetA

    +
    func (m *NonPackedTest) GetA() []int32
    + + + + + + +

    func (*NonPackedTest) ProtoMessage

    +
    func (*NonPackedTest) ProtoMessage()
    + + + + + + +

    func (*NonPackedTest) Reset

    +
    func (m *NonPackedTest) Reset()
    + + + + + + +

    func (*NonPackedTest) String

    +
    func (m *NonPackedTest) String() string
    + + + + + + + + +

    type OldMessage

    +
    type OldMessage struct {
    +    Nested           *OldMessage_Nested `protobuf:"bytes,1,opt,name=nested" json:"nested,omitempty"`
    +    Num              *int32             `protobuf:"varint,2,opt,name=num" json:"num,omitempty"`
    +    XXX_unrecognized []byte             `json:"-"`
    +}
    + + + + + + + + + + + + + + +

    func (*OldMessage) Descriptor

    +
    func (*OldMessage) Descriptor() ([]byte, []int)
    + + + + + + +

    func (*OldMessage) GetNested

    +
    func (m *OldMessage) GetNested() *OldMessage_Nested
    + + + + + + +

    func (*OldMessage) GetNum

    +
    func (m *OldMessage) GetNum() int32
    + + + + + + +

    func (*OldMessage) ProtoMessage

    +
    func (*OldMessage) ProtoMessage()
    + + + + + + +

    func (*OldMessage) Reset

    +
    func (m *OldMessage) Reset()
    + + + + + + +

    func (*OldMessage) String

    +
    func (m *OldMessage) String() string
    + + + + + + + + +

    type OldMessage_Nested

    +
    type OldMessage_Nested struct {
    +    Name             *string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"`
    +    XXX_unrecognized []byte  `json:"-"`
    +}
    + + + + + + + + + + + + + + +

    func (*OldMessage_Nested) Descriptor

    +
    func (*OldMessage_Nested) Descriptor() ([]byte, []int)
    + + + + + + +

    func (*OldMessage_Nested) GetName

    +
    func (m *OldMessage_Nested) GetName() string
    + + + + + + +

    func (*OldMessage_Nested) ProtoMessage

    +
    func (*OldMessage_Nested) ProtoMessage()
    + + + + + + +

    func (*OldMessage_Nested) Reset

    +
    func (m *OldMessage_Nested) Reset()
    + + + + + + +

    func (*OldMessage_Nested) String

    +
    func (m *OldMessage_Nested) String() string
    + + + + + + + + +

    type Oneof

    +
    type Oneof struct {
    +    // Types that are valid to be assigned to Union:
    +    //	*Oneof_F_Bool
    +    //	*Oneof_F_Int32
    +    //	*Oneof_F_Int64
    +    //	*Oneof_F_Fixed32
    +    //	*Oneof_F_Fixed64
    +    //	*Oneof_F_Uint32
    +    //	*Oneof_F_Uint64
    +    //	*Oneof_F_Float
    +    //	*Oneof_F_Double
    +    //	*Oneof_F_String
    +    //	*Oneof_F_Bytes
    +    //	*Oneof_F_Sint32
    +    //	*Oneof_F_Sint64
    +    //	*Oneof_F_Enum
    +    //	*Oneof_F_Message
    +    //	*Oneof_FGroup
    +    //	*Oneof_F_Largest_Tag
    +    Union isOneof_Union `protobuf_oneof:"union"`
    +    // Types that are valid to be assigned to Tormato:
    +    //	*Oneof_Value
    +    Tormato          isOneof_Tormato `protobuf_oneof:"tormato"`
    +    XXX_unrecognized []byte          `json:"-"`
    +}
    + + + + + + + + + + + + + + +

    func (*Oneof) Descriptor

    +
    func (*Oneof) Descriptor() ([]byte, []int)
    + + + + + + +

    func (*Oneof) GetFGroup

    +
    func (m *Oneof) GetFGroup() *Oneof_F_Group
    + + + + + + +

    func (*Oneof) GetF_Bool

    +
    func (m *Oneof) GetF_Bool() bool
    + + + + + + +

    func (*Oneof) GetF_Bytes

    +
    func (m *Oneof) GetF_Bytes() []byte
    + + + + + + +

    func (*Oneof) GetF_Double

    +
    func (m *Oneof) GetF_Double() float64
    + + + + + + +

    func (*Oneof) GetF_Enum

    +
    func (m *Oneof) GetF_Enum() MyMessage_Color
    + + + + + + +

    func (*Oneof) GetF_Fixed32

    +
    func (m *Oneof) GetF_Fixed32() uint32
    + + + + + + +

    func (*Oneof) GetF_Fixed64

    +
    func (m *Oneof) GetF_Fixed64() uint64
    + + + + + + +

    func (*Oneof) GetF_Float

    +
    func (m *Oneof) GetF_Float() float32
    + + + + + + +

    func (*Oneof) GetF_Int32

    +
    func (m *Oneof) GetF_Int32() int32
    + + + + + + +

    func (*Oneof) GetF_Int64

    +
    func (m *Oneof) GetF_Int64() int64
    + + + + + + +

    func (*Oneof) GetF_Largest_Tag

    +
    func (m *Oneof) GetF_Largest_Tag() int32
    + + + + + + +

    func (*Oneof) GetF_Message

    +
    func (m *Oneof) GetF_Message() *GoTestField
    + + + + + + +

    func (*Oneof) GetF_Sint32

    +
    func (m *Oneof) GetF_Sint32() int32
    + + + + + + +

    func (*Oneof) GetF_Sint64

    +
    func (m *Oneof) GetF_Sint64() int64
    + + + + + + +

    func (*Oneof) GetF_String

    +
    func (m *Oneof) GetF_String() string
    + + + + + + +

    func (*Oneof) GetF_Uint32

    +
    func (m *Oneof) GetF_Uint32() uint32
    + + + + + + +

    func (*Oneof) GetF_Uint64

    +
    func (m *Oneof) GetF_Uint64() uint64
    + + + + + + +

    func (*Oneof) GetTormato

    +
    func (m *Oneof) GetTormato() isOneof_Tormato
    + + + + + + +

    func (*Oneof) GetUnion

    +
    func (m *Oneof) GetUnion() isOneof_Union
    + + + + + + +

    func (*Oneof) GetValue

    +
    func (m *Oneof) GetValue() int32
    + + + + + + +

    func (*Oneof) ProtoMessage

    +
    func (*Oneof) ProtoMessage()
    + + + + + + +

    func (*Oneof) Reset

    +
    func (m *Oneof) Reset()
    + + + + + + +

    func (*Oneof) String

    +
    func (m *Oneof) String() string
    + + + + + + +

    func (*Oneof) XXX_OneofFuncs

    +
    func (*Oneof) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{})
    +

    +XXX_OneofFuncs is for the internal use of the proto package. +

    + + + + + + + + +

    type Oneof_FGroup

    +
    type Oneof_FGroup struct {
    +    FGroup *Oneof_F_Group `protobuf:"group,16,opt,name=F_Group,json=fGroup,oneof"`
    +}
    + + + + + + + + + + + + + + + + +

    type Oneof_F_Bool

    +
    type Oneof_F_Bool struct {
    +    F_Bool bool `protobuf:"varint,1,opt,name=F_Bool,json=fBool,oneof"`
    +}
    + + + + + + + + + + + + + + + + +

    type Oneof_F_Bytes

    +
    type Oneof_F_Bytes struct {
    +    F_Bytes []byte `protobuf:"bytes,11,opt,name=F_Bytes,json=fBytes,oneof"`
    +}
    + + + + + + + + + + + + + + + + +

    type Oneof_F_Double

    +
    type Oneof_F_Double struct {
    +    F_Double float64 `protobuf:"fixed64,9,opt,name=F_Double,json=fDouble,oneof"`
    +}
    + + + + + + + + + + + + + + + + +

    type Oneof_F_Enum

    +
    type Oneof_F_Enum struct {
    +    F_Enum MyMessage_Color `protobuf:"varint,14,opt,name=F_Enum,json=fEnum,enum=testdata.MyMessage_Color,oneof"`
    +}
    + + + + + + + + + + + + + + + + +

    type Oneof_F_Fixed32

    +
    type Oneof_F_Fixed32 struct {
    +    F_Fixed32 uint32 `protobuf:"fixed32,4,opt,name=F_Fixed32,json=fFixed32,oneof"`
    +}
    + + + + + + + + + + + + + + + + +

    type Oneof_F_Fixed64

    +
    type Oneof_F_Fixed64 struct {
    +    F_Fixed64 uint64 `protobuf:"fixed64,5,opt,name=F_Fixed64,json=fFixed64,oneof"`
    +}
    + + + + + + + + + + + + + + + + +

    type Oneof_F_Float

    +
    type Oneof_F_Float struct {
    +    F_Float float32 `protobuf:"fixed32,8,opt,name=F_Float,json=fFloat,oneof"`
    +}
    + + + + + + + + + + + + + + + + +

    type Oneof_F_Group

    +
    type Oneof_F_Group struct {
    +    X                *int32 `protobuf:"varint,17,opt,name=x" json:"x,omitempty"`
    +    XXX_unrecognized []byte `json:"-"`
    +}
    + + + + + + + + + + + + + + +

    func (*Oneof_F_Group) Descriptor

    +
    func (*Oneof_F_Group) Descriptor() ([]byte, []int)
    + + + + + + +

    func (*Oneof_F_Group) GetX

    +
    func (m *Oneof_F_Group) GetX() int32
    + + + + + + +

    func (*Oneof_F_Group) ProtoMessage

    +
    func (*Oneof_F_Group) ProtoMessage()
    + + + + + + +

    func (*Oneof_F_Group) Reset

    +
    func (m *Oneof_F_Group) Reset()
    + + + + + + +

    func (*Oneof_F_Group) String

    +
    func (m *Oneof_F_Group) String() string
    + + + + + + + + +

    type Oneof_F_Int32

    +
    type Oneof_F_Int32 struct {
    +    F_Int32 int32 `protobuf:"varint,2,opt,name=F_Int32,json=fInt32,oneof"`
    +}
    + + + + + + + + + + + + + + + + +

    type Oneof_F_Int64

    +
    type Oneof_F_Int64 struct {
    +    F_Int64 int64 `protobuf:"varint,3,opt,name=F_Int64,json=fInt64,oneof"`
    +}
    + + + + + + + + + + + + + + + + +

    type Oneof_F_Largest_Tag

    +
    type Oneof_F_Largest_Tag struct {
    +    F_Largest_Tag int32 `protobuf:"varint,536870911,opt,name=F_Largest_Tag,json=fLargestTag,oneof"`
    +}
    + + + + + + + + + + + + + + + + +

    type Oneof_F_Message

    +
    type Oneof_F_Message struct {
    +    F_Message *GoTestField `protobuf:"bytes,15,opt,name=F_Message,json=fMessage,oneof"`
    +}
    + + + + + + + + + + + + + + + + +

    type Oneof_F_Sint32

    +
    type Oneof_F_Sint32 struct {
    +    F_Sint32 int32 `protobuf:"zigzag32,12,opt,name=F_Sint32,json=fSint32,oneof"`
    +}
    + + + + + + + + + + + + + + + + +

    type Oneof_F_Sint64

    +
    type Oneof_F_Sint64 struct {
    +    F_Sint64 int64 `protobuf:"zigzag64,13,opt,name=F_Sint64,json=fSint64,oneof"`
    +}
    + + + + + + + + + + + + + + + + +

    type Oneof_F_String

    +
    type Oneof_F_String struct {
    +    F_String string `protobuf:"bytes,10,opt,name=F_String,json=fString,oneof"`
    +}
    + + + + + + + + + + + + + + + + +

    type Oneof_F_Uint32

    +
    type Oneof_F_Uint32 struct {
    +    F_Uint32 uint32 `protobuf:"varint,6,opt,name=F_Uint32,json=fUint32,oneof"`
    +}
    + + + + + + + + + + + + + + + + +

    type Oneof_F_Uint64

    +
    type Oneof_F_Uint64 struct {
    +    F_Uint64 uint64 `protobuf:"varint,7,opt,name=F_Uint64,json=fUint64,oneof"`
    +}
    + + + + + + + + + + + + + + + + +

    type Oneof_Value

    +
    type Oneof_Value struct {
    +    Value int32 `protobuf:"varint,100,opt,name=value,oneof"`
    +}
    + + + + + + + + + + + + + + + + +

    type OtherMessage

    +
    type OtherMessage struct {
    +    Key                          *int64        `protobuf:"varint,1,opt,name=key" json:"key,omitempty"`
    +    Value                        []byte        `protobuf:"bytes,2,opt,name=value" json:"value,omitempty"`
    +    Weight                       *float32      `protobuf:"fixed32,3,opt,name=weight" json:"weight,omitempty"`
    +    Inner                        *InnerMessage `protobuf:"bytes,4,opt,name=inner" json:"inner,omitempty"`
    +    proto.XXX_InternalExtensions `json:"-"`
    +    XXX_unrecognized             []byte `json:"-"`
    +}
    + + + + + + + + + + + + + + +

    func (*OtherMessage) Descriptor

    +
    func (*OtherMessage) Descriptor() ([]byte, []int)
    + + + + + + +

    func (*OtherMessage) ExtensionRangeArray

    +
    func (*OtherMessage) ExtensionRangeArray() []proto.ExtensionRange
    + + + + + + +

    func (*OtherMessage) GetInner

    +
    func (m *OtherMessage) GetInner() *InnerMessage
    + + + + + + +

    func (*OtherMessage) GetKey

    +
    func (m *OtherMessage) GetKey() int64
    + + + + + + +

    func (*OtherMessage) GetValue

    +
    func (m *OtherMessage) GetValue() []byte
    + + + + + + +

    func (*OtherMessage) GetWeight

    +
    func (m *OtherMessage) GetWeight() float32
    + + + + + + +

    func (*OtherMessage) ProtoMessage

    +
    func (*OtherMessage) ProtoMessage()
    + + + + + + +

    func (*OtherMessage) Reset

    +
    func (m *OtherMessage) Reset()
    + + + + + + +

    func (*OtherMessage) String

    +
    func (m *OtherMessage) String() string
    + + + + + + + + +

    type PackedTest

    +
    type PackedTest struct {
    +    B                []int32 `protobuf:"varint,1,rep,packed,name=b" json:"b,omitempty"`
    +    XXX_unrecognized []byte  `json:"-"`
    +}
    + + + + + + + + + + + + + + +

    func (*PackedTest) Descriptor

    +
    func (*PackedTest) Descriptor() ([]byte, []int)
    + + + + + + +

    func (*PackedTest) GetB

    +
    func (m *PackedTest) GetB() []int32
    + + + + + + +

    func (*PackedTest) ProtoMessage

    +
    func (*PackedTest) ProtoMessage()
    + + + + + + +

    func (*PackedTest) Reset

    +
    func (m *PackedTest) Reset()
    + + + + + + +

    func (*PackedTest) String

    +
    func (m *PackedTest) String() string
    + + + + + + + + +

    type RepeatedEnum

    +
    type RepeatedEnum struct {
    +    Color            []RepeatedEnum_Color `protobuf:"varint,1,rep,name=color,enum=testdata.RepeatedEnum_Color" json:"color,omitempty"`
    +    XXX_unrecognized []byte               `json:"-"`
    +}
    + + + + + + + + + + + + + + +

    func (*RepeatedEnum) Descriptor

    +
    func (*RepeatedEnum) Descriptor() ([]byte, []int)
    + + + + + + +

    func (*RepeatedEnum) GetColor

    +
    func (m *RepeatedEnum) GetColor() []RepeatedEnum_Color
    + + + + + + +

    func (*RepeatedEnum) ProtoMessage

    +
    func (*RepeatedEnum) ProtoMessage()
    + + + + + + +

    func (*RepeatedEnum) Reset

    +
    func (m *RepeatedEnum) Reset()
    + + + + + + +

    func (*RepeatedEnum) String

    +
    func (m *RepeatedEnum) String() string
    + + + + + + + + +

    type RepeatedEnum_Color

    +
    type RepeatedEnum_Color int32
    + + + +
    const (
    +    RepeatedEnum_RED RepeatedEnum_Color = 1
    +)
    + + + + + + + + + + + + + +

    func (RepeatedEnum_Color) Enum

    +
    func (x RepeatedEnum_Color) Enum() *RepeatedEnum_Color
    + + + + + + +

    func (RepeatedEnum_Color) EnumDescriptor

    +
    func (RepeatedEnum_Color) EnumDescriptor() ([]byte, []int)
    + + + + + + +

    func (RepeatedEnum_Color) String

    +
    func (x RepeatedEnum_Color) String() string
    + + + + + + +

    func (*RepeatedEnum_Color) UnmarshalJSON

    +
    func (x *RepeatedEnum_Color) UnmarshalJSON(data []byte) error
    + + + + + + + + +

    type RequiredInnerMessage

    +
    type RequiredInnerMessage struct {
    +    LeoFinallyWonAnOscar *InnerMessage `protobuf:"bytes,1,req,name=leo_finally_won_an_oscar,json=leoFinallyWonAnOscar" json:"leo_finally_won_an_oscar,omitempty"`
    +    XXX_unrecognized     []byte        `json:"-"`
    +}
    + + + + + + + + + + + + + + +

    func (*RequiredInnerMessage) Descriptor

    +
    func (*RequiredInnerMessage) Descriptor() ([]byte, []int)
    + + + + + + +

    func (*RequiredInnerMessage) GetLeoFinallyWonAnOscar

    +
    func (m *RequiredInnerMessage) GetLeoFinallyWonAnOscar() *InnerMessage
    + + + + + + +

    func (*RequiredInnerMessage) ProtoMessage

    +
    func (*RequiredInnerMessage) ProtoMessage()
    + + + + + + +

    func (*RequiredInnerMessage) Reset

    +
    func (m *RequiredInnerMessage) Reset()
    + + + + + + +

    func (*RequiredInnerMessage) String

    +
    func (m *RequiredInnerMessage) String() string
    + + + + + + + + +

    type Strings

    +
    type Strings struct {
    +    StringField      *string `protobuf:"bytes,1,opt,name=string_field,json=stringField" json:"string_field,omitempty"`
    +    BytesField       []byte  `protobuf:"bytes,2,opt,name=bytes_field,json=bytesField" json:"bytes_field,omitempty"`
    +    XXX_unrecognized []byte  `json:"-"`
    +}
    + + + + + + + + + + + + + + +

    func (*Strings) Descriptor

    +
    func (*Strings) Descriptor() ([]byte, []int)
    + + + + + + +

    func (*Strings) GetBytesField

    +
    func (m *Strings) GetBytesField() []byte
    + + + + + + +

    func (*Strings) GetStringField

    +
    func (m *Strings) GetStringField() string
    + + + + + + +

    func (*Strings) ProtoMessage

    +
    func (*Strings) ProtoMessage()
    + + + + + + +

    func (*Strings) Reset

    +
    func (m *Strings) Reset()
    + + + + + + +

    func (*Strings) String

    +
    func (m *Strings) String() string
    + + + + + + + + +

    type SubDefaults

    +
    type SubDefaults struct {
    +    N                *int64 `protobuf:"varint,1,opt,name=n,def=7" json:"n,omitempty"`
    +    XXX_unrecognized []byte `json:"-"`
    +}
    + + + + + + + + + + + + + + +

    func (*SubDefaults) Descriptor

    +
    func (*SubDefaults) Descriptor() ([]byte, []int)
    + + + + + + +

    func (*SubDefaults) GetN

    +
    func (m *SubDefaults) GetN() int64
    + + + + + + +

    func (*SubDefaults) ProtoMessage

    +
    func (*SubDefaults) ProtoMessage()
    + + + + + + +

    func (*SubDefaults) Reset

    +
    func (m *SubDefaults) Reset()
    + + + + + + +

    func (*SubDefaults) String

    +
    func (m *SubDefaults) String() string
    + + + + + + + + + + + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/github.com/golang/snappy/index.html b/pkg/github.com/golang/snappy/index.html new file mode 100644 index 0000000..3c2fe37 --- /dev/null +++ b/pkg/github.com/golang/snappy/index.html @@ -0,0 +1,507 @@ + + + + + + + + snappy - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Package snappy

    + + + + + + + + + + + + + + +
    +
    +
    import "github.com/golang/snappy"
    +
    +
    +
    Overview
    +
    Index
    + + +
    +
    + +
    + +
    +

    Overview ▾

    +

    +Package snappy implements the snappy block-based compression format. +It aims for very high speeds and reasonable compression. +

    +

    +The C++ snappy implementation is at https://github.com/google/snappy +

    + +
    +
    + + + + + + + + +

    Variables

    + +
    var (
    +    // ErrCorrupt reports that the input is invalid.
    +    ErrCorrupt = errors.New("snappy: corrupt input")
    +    // ErrTooLarge reports that the uncompressed length is too large.
    +    ErrTooLarge = errors.New("snappy: decoded block is too large")
    +    // ErrUnsupported reports that the input isn't supported.
    +    ErrUnsupported = errors.New("snappy: unsupported input")
    +)
    + + + + + + +

    func Decode

    +
    func Decode(dst, src []byte) ([]byte, error)
    +

    +Decode returns the decoded form of src. The returned slice may be a sub- +slice of dst if dst was large enough to hold the entire decoded block. +Otherwise, a newly allocated slice will be returned. +

    +

    +The dst and src must not overlap. It is valid to pass a nil dst. +

    + + + + + + + +

    func DecodedLen

    +
    func DecodedLen(src []byte) (int, error)
    +

    +DecodedLen returns the length of the decoded block. +

    + + + + + + + +

    func Encode

    +
    func Encode(dst, src []byte) []byte
    +

    +Encode returns the encoded form of src. The returned slice may be a sub- +slice of dst if dst was large enough to hold the entire encoded block. +Otherwise, a newly allocated slice will be returned. +

    +

    +The dst and src must not overlap. It is valid to pass a nil dst. +

    + + + + + + + +

    func MaxEncodedLen

    +
    func MaxEncodedLen(srcLen int) int
    +

    +MaxEncodedLen returns the maximum length of a snappy block, given its +uncompressed length. +

    +

    +It will return a negative value if srcLen is too large to encode. +

    + + + + + + + + +

    type Reader

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

    +Reader is an io.Reader that can read Snappy-compressed bytes. +

    + + + + + + + + + + + + +

    func NewReader

    +
    func NewReader(r io.Reader) *Reader
    +

    +NewReader returns a new Reader that decompresses from r, using the framing +format described at +https://github.com/google/snappy/blob/master/framing_format.txt +

    + + + + + + + +

    func (*Reader) Read

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

    +Read satisfies the io.Reader interface. +

    + + + + + + +

    func (*Reader) Reset

    +
    func (r *Reader) Reset(reader io.Reader)
    +

    +Reset discards any buffered data, resets all state, and switches the Snappy +reader to read from r. This permits reusing a Reader rather than allocating +a new one. +

    + + + + + + + + +

    type Writer

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

    +Writer is an io.Writer than can write Snappy-compressed bytes. +

    + + + + + + + + + + + + +

    func NewBufferedWriter

    +
    func NewBufferedWriter(w io.Writer) *Writer
    +

    +NewBufferedWriter returns a new Writer that compresses to w, using the +framing format described at +https://github.com/google/snappy/blob/master/framing_format.txt +

    +

    +The Writer returned buffers writes. Users must call Close to guarantee all +data has been forwarded to the underlying io.Writer. They may also call +Flush zero or more times before calling Close. +

    + + + + + +

    func NewWriter

    +
    func NewWriter(w io.Writer) *Writer
    +

    +NewWriter returns a new Writer that compresses to w. +

    +

    +The Writer returned does not buffer writes. There is no need to Flush or +Close such a Writer. +

    +

    +Deprecated: the Writer returned is not suitable for many small writes, only +for few large writes. Use NewBufferedWriter instead, which is efficient +regardless of the frequency and shape of the writes, and remember to Close +that Writer when done. +

    + + + + + + + +

    func (*Writer) Close

    +
    func (w *Writer) Close() error
    +

    +Close calls Flush and then closes the Writer. +

    + + + + + + +

    func (*Writer) Flush

    +
    func (w *Writer) Flush() error
    +

    +Flush flushes the Writer to its underlying io.Writer. +

    + + + + + + +

    func (*Writer) Reset

    +
    func (w *Writer) Reset(writer io.Writer)
    +

    +Reset discards the writer's state and switches the Snappy writer to write to +w. This permits reusing a Writer rather than allocating a new one. +

    + + + + + + +

    func (*Writer) Write

    +
    func (w *Writer) Write(p []byte) (nRet int, errRet error)
    +

    +Write satisfies the io.Writer interface. +

    + + + + + + + + + + + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/github.com/google/btree/index.html b/pkg/github.com/google/btree/index.html new file mode 100644 index 0000000..fc0471d --- /dev/null +++ b/pkg/github.com/google/btree/index.html @@ -0,0 +1,781 @@ + + + + + + + + btree - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Package btree

    + + + + + + + + + + + + + + +
    +
    +
    import "github.com/google/btree"
    +
    +
    +
    Overview
    +
    Index
    + +
    Examples
    + + +
    +
    + +
    + +
    +

    Overview ▾

    +

    +Package btree implements in-memory B-Trees of arbitrary degree. +

    +

    +btree implements an in-memory B-Tree for use as an ordered data structure. +It is not meant for persistent storage solutions. +

    +

    +It has a flatter structure than an equivalent red-black or other binary tree, +which in some cases yields better memory usage and/or performance. +See some discussion on the matter here: +

    +
    http://google-opensource.blogspot.com/2013/01/c-containers-that-save-memory-and-time.html
    +
    +

    +Note, though, that this project is in no way related to the C++ B-Tree +implementation written about there. +

    +

    +Within this tree, each node contains a slice of items and a (possibly nil) +slice of children. For basic numeric values or raw structs, this can cause +efficiency differences when compared to equivalent C++ template code that +stores values in arrays within the node: +

    +
    * Due to the overhead of storing values as interfaces (each
    +  value needs to be stored as the value itself, then 2 words for the
    +  interface pointing to that value and its type), resulting in higher
    +  memory use.
    +* Since interfaces can point to values anywhere in memory, values are
    +  most likely not stored in contiguous blocks, resulting in a higher
    +  number of cache misses.
    +
    +

    +These issues don't tend to matter, though, when working with strings or other +heap-allocated structures, since C++-equivalent structures also must store +pointers and also distribute their values across the heap. +

    +

    +This implementation is designed to be a drop-in replacement to gollrb.LLRB +trees, (http://github.com/petar/gollrb), an excellent and probably the most +widely used ordered tree implementation in the Go ecosystem currently. +Its functions, therefore, exactly mirror those of +llrb.LLRB where possible. Unlike gollrb, though, we currently don't +support storing multiple equivalent values. +

    + +
    +
    + + +
    + + +
    + + + + +

    Constants

    + +
    const (
    +    DefaultFreeListSize = 32
    +)
    + + + + + + + + +

    type BTree

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

    +BTree is an implementation of a B-Tree. +

    +

    +BTree stores Item instances in an ordered structure, allowing easy insertion, +removal, and iteration. +

    +

    +Write operations are not safe for concurrent mutation by multiple +goroutines, but Read operations are. +

    + + + + + + +
    + +
    +

    Example

    + + + +

    Code:

    +
    tr := New(*btreeDegree)
    +for i := Int(0); i < 10; i++ {
    +    tr.ReplaceOrInsert(i)
    +}
    +fmt.Println("len:       ", tr.Len())
    +fmt.Println("get3:      ", tr.Get(Int(3)))
    +fmt.Println("get100:    ", tr.Get(Int(100)))
    +fmt.Println("del4:      ", tr.Delete(Int(4)))
    +fmt.Println("del100:    ", tr.Delete(Int(100)))
    +fmt.Println("replace5:  ", tr.ReplaceOrInsert(Int(5)))
    +fmt.Println("replace100:", tr.ReplaceOrInsert(Int(100)))
    +fmt.Println("min:       ", tr.Min())
    +fmt.Println("delmin:    ", tr.DeleteMin())
    +fmt.Println("max:       ", tr.Max())
    +fmt.Println("delmax:    ", tr.DeleteMax())
    +fmt.Println("len:       ", tr.Len())
    +
    + +

    Output:

    +
    len:        10
    +get3:       3
    +get100:     <nil>
    +del4:       4
    +del100:     <nil>
    +replace5:   5
    +replace100: <nil>
    +min:        0
    +delmin:     0
    +max:        100
    +delmax:     100
    +len:        8
    +
    + + +
    +
    + + + + + + +

    func New

    +
    func New(degree int) *BTree
    +

    +New creates a new B-Tree with the given degree. +

    +

    +New(2), for example, will create a 2-3-4 tree (each node contains 1-3 items +and 2-4 children). +

    + + + + + +

    func NewWithFreeList

    +
    func NewWithFreeList(degree int, f *FreeList) *BTree
    +

    +NewWithFreeList creates a new B-Tree that uses the given node free list. +

    + + + + + + + +

    func (*BTree) Ascend

    +
    func (t *BTree) Ascend(iterator ItemIterator)
    +

    +Ascend calls the iterator for every value in the tree within the range +[first, last], until iterator returns false. +

    + + + + + + +

    func (*BTree) AscendGreaterOrEqual

    +
    func (t *BTree) AscendGreaterOrEqual(pivot Item, iterator ItemIterator)
    +

    +AscendGreaterOrEqual calls the iterator for every value in the tree within +the range [pivot, last], until iterator returns false. +

    + + + + + + +

    func (*BTree) AscendLessThan

    +
    func (t *BTree) AscendLessThan(pivot Item, iterator ItemIterator)
    +

    +AscendLessThan calls the iterator for every value in the tree within the range +[first, pivot), until iterator returns false. +

    + + + + + + +

    func (*BTree) AscendRange

    +
    func (t *BTree) AscendRange(greaterOrEqual, lessThan Item, iterator ItemIterator)
    +

    +AscendRange calls the iterator for every value in the tree within the range +[greaterOrEqual, lessThan), until iterator returns false. +

    + + + + + + +

    func (*BTree) Delete

    +
    func (t *BTree) Delete(item Item) Item
    +

    +Delete removes an item equal to the passed in item from the tree, returning +it. If no such item exists, returns nil. +

    + + + + + + +

    func (*BTree) DeleteMax

    +
    func (t *BTree) DeleteMax() Item
    +

    +DeleteMax removes the largest item in the tree and returns it. +If no such item exists, returns nil. +

    + + + + + + +

    func (*BTree) DeleteMin

    +
    func (t *BTree) DeleteMin() Item
    +

    +DeleteMin removes the smallest item in the tree and returns it. +If no such item exists, returns nil. +

    + + + + + + +

    func (*BTree) Descend

    +
    func (t *BTree) Descend(iterator ItemIterator)
    +

    +Descend calls the iterator for every value in the tree within the range +[last, first], until iterator returns false. +

    + + + + + + +

    func (*BTree) DescendGreaterThan

    +
    func (t *BTree) DescendGreaterThan(pivot Item, iterator ItemIterator)
    +

    +DescendGreaterThan calls the iterator for every value in the tree within +the range (pivot, last], until iterator returns false. +

    + + + + + + +

    func (*BTree) DescendLessOrEqual

    +
    func (t *BTree) DescendLessOrEqual(pivot Item, iterator ItemIterator)
    +

    +DescendLessOrEqual calls the iterator for every value in the tree within the range +[pivot, first], until iterator returns false. +

    + + + + + + +

    func (*BTree) DescendRange

    +
    func (t *BTree) DescendRange(lessOrEqual, greaterThan Item, iterator ItemIterator)
    +

    +DescendRange calls the iterator for every value in the tree within the range +[lessOrEqual, greaterThan), until iterator returns false. +

    + + + + + + +

    func (*BTree) Get

    +
    func (t *BTree) Get(key Item) Item
    +

    +Get looks for the key item in the tree, returning it. It returns nil if +unable to find that item. +

    + + + + + + +

    func (*BTree) Has

    +
    func (t *BTree) Has(key Item) bool
    +

    +Has returns true if the given key is in the tree. +

    + + + + + + +

    func (*BTree) Len

    +
    func (t *BTree) Len() int
    +

    +Len returns the number of items currently in the tree. +

    + + + + + + +

    func (*BTree) Max

    +
    func (t *BTree) Max() Item
    +

    +Max returns the largest item in the tree, or nil if the tree is empty. +

    + + + + + + +

    func (*BTree) Min

    +
    func (t *BTree) Min() Item
    +

    +Min returns the smallest item in the tree, or nil if the tree is empty. +

    + + + + + + +

    func (*BTree) ReplaceOrInsert

    +
    func (t *BTree) ReplaceOrInsert(item Item) Item
    +

    +ReplaceOrInsert adds the given item to the tree. If an item in the tree +already equals the given one, it is removed from the tree and returned. +Otherwise, nil is returned. +

    +

    +nil cannot be added to the tree (will panic). +

    + + + + + + + + +

    type FreeList

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

    +FreeList represents a free list of btree nodes. By default each +BTree has its own FreeList, but multiple BTrees can share the same +FreeList. +Two Btrees using the same freelist are not safe for concurrent write access. +

    + + + + + + + + + + + + +

    func NewFreeList

    +
    func NewFreeList(size int) *FreeList
    +

    +NewFreeList creates a new free list. +size is the maximum size of the returned free list. +

    + + + + + + + + + +

    type Int

    +
    type Int int
    +

    +Int implements the Item interface for integers. +

    + + + + + + + + + + + + + + +

    func (Int) Less

    +
    func (a Int) Less(b Item) bool
    +

    +Less returns true if int(a) < int(b). +

    + + + + + + + + +

    type Item

    +
    type Item interface {
    +    // Less tests whether the current item is less than the given argument.
    +    //
    +    // This must provide a strict weak ordering.
    +    // If !a.Less(b) && !b.Less(a), we treat this to mean a == b (i.e. we can only
    +    // hold one of either a or b in the tree).
    +    Less(than Item) bool
    +}
    +

    +Item represents a single object in the tree. +

    + + + + + + + + + + + + + + + + +

    type ItemIterator

    +
    type ItemIterator func(i Item) bool
    +

    +ItemIterator allows callers of Ascend* to iterate in-order over portions of +the tree. When this function returns false, iteration will stop and the +associated Ascend* function will immediately return. +

    + + + + + + + + + + + + + + + + + + + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/github.com/google/go-github/github/index.html b/pkg/github.com/google/go-github/github/index.html new file mode 100644 index 0000000..1bd23f0 --- /dev/null +++ b/pkg/github.com/google/go-github/github/index.html @@ -0,0 +1,14559 @@ + + + + + + + + github - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Package github

    + + + + + + + + + + + + + + +
    +
    +
    import "github.com/google/go-github/github"
    +
    +
    +
    Overview
    +
    Index
    + +
    Examples
    + + +
    +
    + +
    + +
    +

    Overview ▾

    +

    +Package github provides a client for using the GitHub API. +

    +

    +Usage: +

    +
    import "github.com/google/go-github/github"
    +
    +

    +Construct a new GitHub client, then use the various services on the client to +access different parts of the GitHub API. For example: +

    +
    client := github.NewClient(nil)
    +
    +// list all organizations for user "willnorris"
    +orgs, _, err := client.Organizations.List("willnorris", nil)
    +
    +

    +Some API methods have optional parameters that can be passed. For example: +

    +
    client := github.NewClient(nil)
    +
    +// list recently updated repositories for org "github"
    +opt := &github.RepositoryListByOrgOptions{Sort: "updated"}
    +repos, _, err := client.Repositories.ListByOrg("github", opt)
    +
    +

    +The services of a client divide the API into logical chunks and correspond to +the structure of the GitHub API documentation at +http://developer.github.com/v3/. +

    +

    Authentication

    +

    +The go-github library does not directly handle authentication. Instead, when +creating a new client, pass an http.Client that can handle authentication for +you. The easiest and recommended way to do this is using the golang.org/x/oauth2 +library, but you can always use any other library that provides an http.Client. +If you have an OAuth2 access token (for example, a personal API token), you can +use it with the oauth2 library using: +

    +
    import "golang.org/x/oauth2"
    +
    +func main() {
    +	ts := oauth2.StaticTokenSource(
    +		&oauth2.Token{AccessToken: "... your access token ..."},
    +	)
    +	tc := oauth2.NewClient(oauth2.NoContext, ts)
    +
    +	client := github.NewClient(tc)
    +
    +	// list all repositories for the authenticated user
    +	repos, _, err := client.Repositories.List("", nil)
    +}
    +
    +

    +Note that when using an authenticated Client, all calls made by the client will +include the specified OAuth token. Therefore, authenticated clients should +almost never be shared between different users. +

    +

    +See the oauth2 docs for complete instructions on using that library. +

    +

    +For API methods that require HTTP Basic Authentication, use the +BasicAuthTransport. +

    +

    Rate Limiting

    +

    +GitHub imposes a rate limit on all API clients. Unauthenticated clients are +limited to 60 requests per hour, while authenticated clients can make up to +5,000 requests per hour. To receive the higher rate limit when making calls +that are not issued on behalf of a user, use the +UnauthenticatedRateLimitedTransport. +

    +

    +The Rate method on a client returns the rate limit information based on the most +recent API call. This is updated on every call, but may be out of date if it's +been some time since the last API call and other clients have made subsequent +requests since then. You can always call RateLimits() directly to get the most +up-to-date rate limit data for the client. +

    +

    +To detect an API rate limit error, you can check if its type is *github.RateLimitError: +

    +
    repos, _, err := client.Repositories.List("", nil)
    +if _, ok := err.(*github.RateLimitError); ok {
    +	log.Println("hit rate limit")
    +}
    +
    +

    +Learn more about GitHub rate limiting at +http://developer.github.com/v3/#rate-limiting. +

    +

    Conditional Requests

    +

    +The GitHub API has good support for conditional requests which will help +prevent you from burning through your rate limit, as well as help speed up your +application. go-github does not handle conditional requests directly, but is +instead designed to work with a caching http.Transport. We recommend using +https://github.com/gregjones/httpcache for that. +

    +

    +Learn more about GitHub conditional requests at +https://developer.github.com/v3/#conditional-requests. +

    +

    Creating and Updating Resources

    +

    +All structs for GitHub resources use pointer values for all non-repeated fields. +This allows distinguishing between unset fields and those set to a zero-value. +Helper functions have been provided to easily create these pointers for string, +bool, and int values. For example: +

    +
    // create a new private repository named "foo"
    +repo := &github.Repository{
    +	Name:    github.String("foo"),
    +	Private: github.Bool(true),
    +}
    +client.Repositories.Create("", repo)
    +
    +

    +Users who have worked with protocol buffers should find this pattern familiar. +

    +

    Pagination

    +

    +All requests for resource collections (repos, pull requests, issues, etc.) +support pagination. Pagination options are described in the +github.ListOptions struct and passed to the list methods directly or as an +embedded type of a more specific list options struct (for example +github.PullRequestListOptions). Pages information is available via the +github.Response struct. +

    +
    client := github.NewClient(nil)
    +
    +opt := &github.RepositoryListByOrgOptions{
    +	ListOptions: github.ListOptions{PerPage: 10},
    +}
    +// get all pages of results
    +var allRepos []*github.Repository
    +for {
    +	repos, resp, err := client.Repositories.ListByOrg("github", opt)
    +	if err != nil {
    +		return err
    +	}
    +	allRepos = append(allRepos, repos...)
    +	if resp.NextPage == 0 {
    +		break
    +	}
    +	opt.ListOptions.Page = resp.NextPage
    +}
    +
    + +
    +
    + + +
    + +
    +

    Index ▾

    + + +
    +
    + +
    Constants
    + + + + +
    func Bool(v bool) *bool
    + + +
    func CheckResponse(r *http.Response) error
    + + +
    func Int(v int) *int
    + + +
    func String(v string) *string
    + + +
    func Stringify(message interface{}) string
    + + +
    func ValidatePayload(r *http.Request, secretKey []byte) (payload []byte, err error)
    + + + +
    type APIMeta
    + + + + +
    type ActivityListStarredOptions
    + + + + +
    type ActivityService
    + + + +
        func (s *ActivityService) DeleteRepositorySubscription(owner, repo string) (*Response, error)
    + + +
        func (s *ActivityService) DeleteThreadSubscription(id string) (*Response, error)
    + + +
        func (s *ActivityService) GetRepositorySubscription(owner, repo string) (*Subscription, *Response, error)
    + + +
        func (s *ActivityService) GetThread(id string) (*Notification, *Response, error)
    + + +
        func (s *ActivityService) GetThreadSubscription(id string) (*Subscription, *Response, error)
    + + +
        func (s *ActivityService) IsStarred(owner, repo string) (bool, *Response, error)
    + + +
        func (s *ActivityService) ListEvents(opt *ListOptions) ([]*Event, *Response, error)
    + + +
        func (s *ActivityService) ListEventsForOrganization(org string, opt *ListOptions) ([]*Event, *Response, error)
    + + +
        func (s *ActivityService) ListEventsForRepoNetwork(owner, repo string, opt *ListOptions) ([]*Event, *Response, error)
    + + +
        func (s *ActivityService) ListEventsPerformedByUser(user string, publicOnly bool, opt *ListOptions) ([]*Event, *Response, error)
    + + +
        func (s *ActivityService) ListEventsReceivedByUser(user string, publicOnly bool, opt *ListOptions) ([]*Event, *Response, error)
    + + +
        func (s *ActivityService) ListFeeds() (*Feeds, *Response, error)
    + + +
        func (s *ActivityService) ListIssueEventsForRepository(owner, repo string, opt *ListOptions) ([]*Event, *Response, error)
    + + +
        func (s *ActivityService) ListNotifications(opt *NotificationListOptions) ([]*Notification, *Response, error)
    + + +
        func (s *ActivityService) ListRepositoryEvents(owner, repo string, opt *ListOptions) ([]*Event, *Response, error)
    + + +
        func (s *ActivityService) ListRepositoryNotifications(owner, repo string, opt *NotificationListOptions) ([]*Notification, *Response, error)
    + + +
        func (s *ActivityService) ListStargazers(owner, repo string, opt *ListOptions) ([]*Stargazer, *Response, error)
    + + +
        func (s *ActivityService) ListStarred(user string, opt *ActivityListStarredOptions) ([]*StarredRepository, *Response, error)
    + + +
        func (s *ActivityService) ListUserEventsForOrganization(org, user string, opt *ListOptions) ([]*Event, *Response, error)
    + + +
        func (s *ActivityService) ListWatched(user string, opt *ListOptions) ([]*Repository, *Response, error)
    + + +
        func (s *ActivityService) ListWatchers(owner, repo string, opt *ListOptions) ([]*User, *Response, error)
    + + +
        func (s *ActivityService) MarkNotificationsRead(lastRead time.Time) (*Response, error)
    + + +
        func (s *ActivityService) MarkRepositoryNotificationsRead(owner, repo string, lastRead time.Time) (*Response, error)
    + + +
        func (s *ActivityService) MarkThreadRead(id string) (*Response, error)
    + + +
        func (s *ActivityService) SetRepositorySubscription(owner, repo string, subscription *Subscription) (*Subscription, *Response, error)
    + + +
        func (s *ActivityService) SetThreadSubscription(id string, subscription *Subscription) (*Subscription, *Response, error)
    + + +
        func (s *ActivityService) Star(owner, repo string) (*Response, error)
    + + +
        func (s *ActivityService) Unstar(owner, repo string) (*Response, error)
    + + + +
    type Authorization
    + + + +
        func (a Authorization) String() string
    + + + +
    type AuthorizationApp
    + + + +
        func (a AuthorizationApp) String() string
    + + + +
    type AuthorizationRequest
    + + + +
        func (a AuthorizationRequest) String() string
    + + + +
    type AuthorizationUpdateRequest
    + + + +
        func (a AuthorizationUpdateRequest) String() string
    + + + +
    type AuthorizationsService
    + + + +
        func (s *AuthorizationsService) Check(clientID string, token string) (*Authorization, *Response, error)
    + + +
        func (s *AuthorizationsService) Create(auth *AuthorizationRequest) (*Authorization, *Response, error)
    + + +
        func (s *AuthorizationsService) CreateImpersonation(username string, authReq *AuthorizationRequest) (*Authorization, *Response, error)
    + + +
        func (s *AuthorizationsService) Delete(id int) (*Response, error)
    + + +
        func (s *AuthorizationsService) DeleteGrant(id int) (*Response, error)
    + + +
        func (s *AuthorizationsService) DeleteImpersonation(username string) (*Response, error)
    + + +
        func (s *AuthorizationsService) Edit(id int, auth *AuthorizationUpdateRequest) (*Authorization, *Response, error)
    + + +
        func (s *AuthorizationsService) Get(id int) (*Authorization, *Response, error)
    + + +
        func (s *AuthorizationsService) GetGrant(id int) (*Grant, *Response, error)
    + + +
        func (s *AuthorizationsService) GetOrCreateForApp(clientID string, auth *AuthorizationRequest) (*Authorization, *Response, error)
    + + +
        func (s *AuthorizationsService) List(opt *ListOptions) ([]*Authorization, *Response, error)
    + + +
        func (s *AuthorizationsService) ListGrants() ([]*Grant, *Response, error)
    + + +
        func (s *AuthorizationsService) Reset(clientID string, token string) (*Authorization, *Response, error)
    + + +
        func (s *AuthorizationsService) Revoke(clientID string, token string) (*Response, error)
    + + + +
    type BasicAuthTransport
    + + + +
        func (t *BasicAuthTransport) Client() *http.Client
    + + +
        func (t *BasicAuthTransport) RoundTrip(req *http.Request) (*http.Response, error)
    + + + +
    type Blob
    + + + + +
    type Branch
    + + + + +
    type Client
    + + +
        func NewClient(httpClient *http.Client) *Client
    + + + +
        func (c *Client) APIMeta() (*APIMeta, *Response, error)
    + + +
        func (c *Client) Do(req *http.Request, v interface{}) (*Response, error)
    + + +
        func (c *Client) ListEmojis() (map[string]string, *Response, error)
    + + +
        func (c *Client) ListServiceHooks() ([]*ServiceHook, *Response, error)
    + + +
        func (c *Client) Markdown(text string, opt *MarkdownOptions) (string, *Response, error)
    + + +
        func (c *Client) NewRequest(method, urlStr string, body interface{}) (*http.Request, error)
    + + +
        func (c *Client) NewUploadRequest(urlStr string, reader io.Reader, size int64, mediaType string) (*http.Request, error)
    + + +
        func (c *Client) Octocat(message string) (string, *Response, error)
    + + +
        func (c *Client) Rate() Rate
    + + +
        func (c *Client) RateLimit() (*Rate, *Response, error)
    + + +
        func (c *Client) RateLimits() (*RateLimits, *Response, error)
    + + +
        func (c *Client) Zen() (string, *Response, error)
    + + + +
    type CodeResult
    + + + +
        func (c CodeResult) String() string
    + + + +
    type CodeSearchResult
    + + + + +
    type CombinedStatus
    + + + +
        func (s CombinedStatus) String() string
    + + + +
    type Commit
    + + + +
        func (c Commit) String() string
    + + + +
    type CommitAuthor
    + + + +
        func (c CommitAuthor) String() string
    + + + +
    type CommitCommentEvent
    + + + + +
    type CommitFile
    + + + +
        func (c CommitFile) String() string
    + + + +
    type CommitStats
    + + + +
        func (c CommitStats) String() string
    + + + +
    type CommitsComparison
    + + + +
        func (c CommitsComparison) String() string
    + + + +
    type CommitsListOptions
    + + + + +
    type Contributor
    + + + + +
    type ContributorStats
    + + + +
        func (c ContributorStats) String() string
    + + + +
    type CreateEvent
    + + + + +
    type DeleteEvent
    + + + + +
    type Deployment
    + + + + +
    type DeploymentEvent
    + + + + +
    type DeploymentRequest
    + + + + +
    type DeploymentStatus
    + + + + +
    type DeploymentStatusEvent
    + + + + +
    type DeploymentStatusRequest
    + + + + +
    type DeploymentsListOptions
    + + + + +
    type EditChange
    + + + + +
    type Error
    + + + +
        func (e *Error) Error() string
    + + + +
    type ErrorResponse
    + + + +
        func (r *ErrorResponse) Error() string
    + + + +
    type Event
    + + + +
        func (e *Event) Payload() (payload interface{})
    + + +
        func (e Event) String() string
    + + + +
    type FeedLink
    + + + + +
    type Feeds
    + + + + +
    type ForkEvent
    + + + + +
    type GPGEmail
    + + + + +
    type GPGKey
    + + + +
        func (k GPGKey) String() string
    + + + +
    type Gist
    + + + +
        func (g Gist) String() string
    + + + +
    type GistComment
    + + + +
        func (g GistComment) String() string
    + + + +
    type GistCommit
    + + + +
        func (gc GistCommit) String() string
    + + + +
    type GistFile
    + + + +
        func (g GistFile) String() string
    + + + +
    type GistFilename
    + + + + +
    type GistFork
    + + + +
        func (gf GistFork) String() string
    + + + +
    type GistListOptions
    + + + + +
    type GistsService
    + + + +
        func (s *GistsService) Create(gist *Gist) (*Gist, *Response, error)
    + + +
        func (s *GistsService) CreateComment(gistID string, comment *GistComment) (*GistComment, *Response, error)
    + + +
        func (s *GistsService) Delete(id string) (*Response, error)
    + + +
        func (s *GistsService) DeleteComment(gistID string, commentID int) (*Response, error)
    + + +
        func (s *GistsService) Edit(id string, gist *Gist) (*Gist, *Response, error)
    + + +
        func (s *GistsService) EditComment(gistID string, commentID int, comment *GistComment) (*GistComment, *Response, error)
    + + +
        func (s *GistsService) Fork(id string) (*Gist, *Response, error)
    + + +
        func (s *GistsService) Get(id string) (*Gist, *Response, error)
    + + +
        func (s *GistsService) GetComment(gistID string, commentID int) (*GistComment, *Response, error)
    + + +
        func (s *GistsService) GetRevision(id, sha string) (*Gist, *Response, error)
    + + +
        func (s *GistsService) IsStarred(id string) (bool, *Response, error)
    + + +
        func (s *GistsService) List(user string, opt *GistListOptions) ([]*Gist, *Response, error)
    + + +
        func (s *GistsService) ListAll(opt *GistListOptions) ([]*Gist, *Response, error)
    + + +
        func (s *GistsService) ListComments(gistID string, opt *ListOptions) ([]*GistComment, *Response, error)
    + + +
        func (s *GistsService) ListCommits(id string) ([]*GistCommit, *Response, error)
    + + +
        func (s *GistsService) ListForks(id string) ([]*GistFork, *Response, error)
    + + +
        func (s *GistsService) ListStarred(opt *GistListOptions) ([]*Gist, *Response, error)
    + + +
        func (s *GistsService) Star(id string) (*Response, error)
    + + +
        func (s *GistsService) Unstar(id string) (*Response, error)
    + + + +
    type GitObject
    + + + +
        func (o GitObject) String() string
    + + + +
    type GitService
    + + + +
        func (s *GitService) CreateBlob(owner string, repo string, blob *Blob) (*Blob, *Response, error)
    + + +
        func (s *GitService) CreateCommit(owner string, repo string, commit *Commit) (*Commit, *Response, error)
    + + +
        func (s *GitService) CreateRef(owner string, repo string, ref *Reference) (*Reference, *Response, error)
    + + +
        func (s *GitService) CreateTag(owner string, repo string, tag *Tag) (*Tag, *Response, error)
    + + +
        func (s *GitService) CreateTree(owner string, repo string, baseTree string, entries []TreeEntry) (*Tree, *Response, error)
    + + +
        func (s *GitService) DeleteRef(owner string, repo string, ref string) (*Response, error)
    + + +
        func (s *GitService) GetBlob(owner string, repo string, sha string) (*Blob, *Response, error)
    + + +
        func (s *GitService) GetCommit(owner string, repo string, sha string) (*Commit, *Response, error)
    + + +
        func (s *GitService) GetRef(owner string, repo string, ref string) (*Reference, *Response, error)
    + + +
        func (s *GitService) GetTag(owner string, repo string, sha string) (*Tag, *Response, error)
    + + +
        func (s *GitService) GetTree(owner string, repo string, sha string, recursive bool) (*Tree, *Response, error)
    + + +
        func (s *GitService) ListRefs(owner, repo string, opt *ReferenceListOptions) ([]*Reference, *Response, error)
    + + +
        func (s *GitService) UpdateRef(owner string, repo string, ref *Reference, force bool) (*Reference, *Response, error)
    + + + +
    type Gitignore
    + + + +
        func (g Gitignore) String() string
    + + + +
    type GitignoresService
    + + + +
        func (s GitignoresService) Get(name string) (*Gitignore, *Response, error)
    + + +
        func (s GitignoresService) List() ([]string, *Response, error)
    + + + +
    type GollumEvent
    + + + + +
    type Grant
    + + + +
        func (g Grant) String() string
    + + + +
    type Hook
    + + + +
        func (h Hook) String() string
    + + + +
    type Import
    + + + +
        func (i Import) String() string
    + + + +
    type Issue
    + + + +
        func (i Issue) String() string
    + + + +
    type IssueActivityEvent
    + + + + +
    type IssueComment
    + + + +
        func (i IssueComment) String() string
    + + + +
    type IssueCommentEvent
    + + + + +
    type IssueEvent
    + + + + +
    type IssueListByRepoOptions
    + + + + +
    type IssueListCommentsOptions
    + + + + +
    type IssueListOptions
    + + + + +
    type IssueRequest
    + + + + +
    type IssuesEvent
    + + + + +
    type IssuesSearchResult
    + + + + +
    type IssuesService
    + + + +
        func (s *IssuesService) AddAssignees(owner, repo string, number int, assignees []string) (*Issue, *Response, error)
    + + +
        func (s *IssuesService) AddLabelsToIssue(owner string, repo string, number int, labels []string) ([]*Label, *Response, error)
    + + +
        func (s *IssuesService) Create(owner string, repo string, issue *IssueRequest) (*Issue, *Response, error)
    + + +
        func (s *IssuesService) CreateComment(owner string, repo string, number int, comment *IssueComment) (*IssueComment, *Response, error)
    + + +
        func (s *IssuesService) CreateLabel(owner string, repo string, label *Label) (*Label, *Response, error)
    + + +
        func (s *IssuesService) CreateMilestone(owner string, repo string, milestone *Milestone) (*Milestone, *Response, error)
    + + +
        func (s *IssuesService) DeleteComment(owner string, repo string, id int) (*Response, error)
    + + +
        func (s *IssuesService) DeleteLabel(owner string, repo string, name string) (*Response, error)
    + + +
        func (s *IssuesService) DeleteMilestone(owner string, repo string, number int) (*Response, error)
    + + +
        func (s *IssuesService) Edit(owner string, repo string, number int, issue *IssueRequest) (*Issue, *Response, error)
    + + +
        func (s *IssuesService) EditComment(owner string, repo string, id int, comment *IssueComment) (*IssueComment, *Response, error)
    + + +
        func (s *IssuesService) EditLabel(owner string, repo string, name string, label *Label) (*Label, *Response, error)
    + + +
        func (s *IssuesService) EditMilestone(owner string, repo string, number int, milestone *Milestone) (*Milestone, *Response, error)
    + + +
        func (s *IssuesService) Get(owner string, repo string, number int) (*Issue, *Response, error)
    + + +
        func (s *IssuesService) GetComment(owner string, repo string, id int) (*IssueComment, *Response, error)
    + + +
        func (s *IssuesService) GetEvent(owner, repo string, id int) (*IssueEvent, *Response, error)
    + + +
        func (s *IssuesService) GetLabel(owner string, repo string, name string) (*Label, *Response, error)
    + + +
        func (s *IssuesService) GetMilestone(owner string, repo string, number int) (*Milestone, *Response, error)
    + + +
        func (s *IssuesService) IsAssignee(owner, repo, user string) (bool, *Response, error)
    + + +
        func (s *IssuesService) List(all bool, opt *IssueListOptions) ([]*Issue, *Response, error)
    + + +
        func (s *IssuesService) ListAssignees(owner, repo string, opt *ListOptions) ([]*User, *Response, error)
    + + +
        func (s *IssuesService) ListByOrg(org string, opt *IssueListOptions) ([]*Issue, *Response, error)
    + + +
        func (s *IssuesService) ListByRepo(owner string, repo string, opt *IssueListByRepoOptions) ([]*Issue, *Response, error)
    + + +
        func (s *IssuesService) ListComments(owner string, repo string, number int, opt *IssueListCommentsOptions) ([]*IssueComment, *Response, error)
    + + +
        func (s *IssuesService) ListIssueEvents(owner, repo string, number int, opt *ListOptions) ([]*IssueEvent, *Response, error)
    + + +
        func (s *IssuesService) ListIssueTimeline(owner, repo string, number int, opt *ListOptions) ([]*Timeline, *Response, error)
    + + +
        func (s *IssuesService) ListLabels(owner string, repo string, opt *ListOptions) ([]*Label, *Response, error)
    + + +
        func (s *IssuesService) ListLabelsByIssue(owner string, repo string, number int, opt *ListOptions) ([]*Label, *Response, error)
    + + +
        func (s *IssuesService) ListLabelsForMilestone(owner string, repo string, number int, opt *ListOptions) ([]*Label, *Response, error)
    + + +
        func (s *IssuesService) ListMilestones(owner string, repo string, opt *MilestoneListOptions) ([]*Milestone, *Response, error)
    + + +
        func (s *IssuesService) ListRepositoryEvents(owner, repo string, opt *ListOptions) ([]*IssueEvent, *Response, error)
    + + +
        func (s *IssuesService) Lock(owner string, repo string, number int) (*Response, error)
    + + +
        func (s *IssuesService) RemoveAssignees(owner, repo string, number int, assignees []string) (*Issue, *Response, error)
    + + +
        func (s *IssuesService) RemoveLabelForIssue(owner string, repo string, number int, label string) (*Response, error)
    + + +
        func (s *IssuesService) RemoveLabelsForIssue(owner string, repo string, number int) (*Response, error)
    + + +
        func (s *IssuesService) ReplaceLabelsForIssue(owner string, repo string, number int, labels []string) ([]*Label, *Response, error)
    + + +
        func (s *IssuesService) Unlock(owner string, repo string, number int) (*Response, error)
    + + + +
    type Key
    + + + +
        func (k Key) String() string
    + + + +
    type Label
    + + + +
        func (l Label) String() string
    + + + +
    type LargeFile
    + + + +
        func (f LargeFile) String() string
    + + + +
    type License
    + + + +
        func (l License) String() string
    + + + +
    type LicensesService
    + + + +
        func (s *LicensesService) Get(licenseName string) (*License, *Response, error)
    + + +
        func (s *LicensesService) List() ([]*License, *Response, error)
    + + + +
    type ListContributorsOptions
    + + + + +
    type ListMembersOptions
    + + + + +
    type ListOptions
    + + + + +
    type ListOrgMembershipsOptions
    + + + + +
    type MarkdownOptions
    + + + + +
    type Match
    + + + + +
    type MemberEvent
    + + + + +
    type Membership
    + + + +
        func (m Membership) String() string
    + + + +
    type MembershipEvent
    + + + + +
    type Migration
    + + + +
        func (m Migration) String() string
    + + + +
    type MigrationOptions
    + + + + +
    type MigrationService
    + + + +
        func (s *MigrationService) CancelImport(owner, repo string) (*Response, error)
    + + +
        func (s *MigrationService) CommitAuthors(owner, repo string) ([]*SourceImportAuthor, *Response, error)
    + + +
        func (s *MigrationService) DeleteMigration(org string, id int) (*Response, error)
    + + +
        func (s *MigrationService) ImportProgress(owner, repo string) (*Import, *Response, error)
    + + +
        func (s *MigrationService) LargeFiles(owner, repo string) ([]*LargeFile, *Response, error)
    + + +
        func (s *MigrationService) ListMigrations(org string) ([]*Migration, *Response, error)
    + + +
        func (s *MigrationService) MapCommitAuthor(owner, repo string, id int, author *SourceImportAuthor) (*SourceImportAuthor, *Response, error)
    + + +
        func (s *MigrationService) MigrationArchiveURL(org string, id int) (url string, err error)
    + + +
        func (s *MigrationService) MigrationStatus(org string, id int) (*Migration, *Response, error)
    + + +
        func (s *MigrationService) SetLFSPreference(owner, repo string, in *Import) (*Import, *Response, error)
    + + +
        func (s *MigrationService) StartImport(owner, repo string, in *Import) (*Import, *Response, error)
    + + +
        func (s *MigrationService) StartMigration(org string, repos []string, opt *MigrationOptions) (*Migration, *Response, error)
    + + +
        func (s *MigrationService) UnlockRepo(org string, id int, repo string) (*Response, error)
    + + +
        func (s *MigrationService) UpdateImport(owner, repo string, in *Import) (*Import, *Response, error)
    + + + +
    type Milestone
    + + + +
        func (m Milestone) String() string
    + + + +
    type MilestoneListOptions
    + + + + +
    type NewPullRequest
    + + + + +
    type Notification
    + + + + +
    type NotificationListOptions
    + + + + +
    type NotificationSubject
    + + + + +
    type Organization
    + + + +
        func (o Organization) String() string
    + + + +
    type OrganizationAddTeamMembershipOptions
    + + + + +
    type OrganizationAddTeamRepoOptions
    + + + + +
    type OrganizationListTeamMembersOptions
    + + + + +
    type OrganizationsListOptions
    + + + + +
    type OrganizationsService
    + + + +
        func (s *OrganizationsService) AddTeamMembership(team int, user string, opt *OrganizationAddTeamMembershipOptions) (*Membership, *Response, error)
    + + +
        func (s *OrganizationsService) AddTeamRepo(team int, owner string, repo string, opt *OrganizationAddTeamRepoOptions) (*Response, error)
    + + +
        func (s *OrganizationsService) ConcealMembership(org, user string) (*Response, error)
    + + +
        func (s *OrganizationsService) CreateHook(org string, hook *Hook) (*Hook, *Response, error)
    + + +
        func (s *OrganizationsService) CreateTeam(org string, team *Team) (*Team, *Response, error)
    + + +
        func (s *OrganizationsService) DeleteHook(org string, id int) (*Response, error)
    + + +
        func (s *OrganizationsService) DeleteTeam(team int) (*Response, error)
    + + +
        func (s *OrganizationsService) Edit(name string, org *Organization) (*Organization, *Response, error)
    + + +
        func (s *OrganizationsService) EditHook(org string, id int, hook *Hook) (*Hook, *Response, error)
    + + +
        func (s *OrganizationsService) EditOrgMembership(user, org string, membership *Membership) (*Membership, *Response, error)
    + + +
        func (s *OrganizationsService) EditTeam(id int, team *Team) (*Team, *Response, error)
    + + +
        func (s *OrganizationsService) Get(org string) (*Organization, *Response, error)
    + + +
        func (s *OrganizationsService) GetHook(org string, id int) (*Hook, *Response, error)
    + + +
        func (s *OrganizationsService) GetOrgMembership(user, org string) (*Membership, *Response, error)
    + + +
        func (s *OrganizationsService) GetTeam(team int) (*Team, *Response, error)
    + + +
        func (s *OrganizationsService) GetTeamMembership(team int, user string) (*Membership, *Response, error)
    + + +
        func (s *OrganizationsService) IsMember(org, user string) (bool, *Response, error)
    + + +
        func (s *OrganizationsService) IsPublicMember(org, user string) (bool, *Response, error)
    + + +
        func (s *OrganizationsService) IsTeamMember(team int, user string) (bool, *Response, error)
    + + +
        func (s *OrganizationsService) IsTeamRepo(team int, owner string, repo string) (*Repository, *Response, error)
    + + +
        func (s *OrganizationsService) List(user string, opt *ListOptions) ([]*Organization, *Response, error)
    + + +
        func (s *OrganizationsService) ListAll(opt *OrganizationsListOptions) ([]*Organization, *Response, error)
    + + +
        func (s *OrganizationsService) ListHooks(org string, opt *ListOptions) ([]*Hook, *Response, error)
    + + +
        func (s *OrganizationsService) ListMembers(org string, opt *ListMembersOptions) ([]*User, *Response, error)
    + + +
        func (s *OrganizationsService) ListOrgMemberships(opt *ListOrgMembershipsOptions) ([]*Membership, *Response, error)
    + + +
        func (s *OrganizationsService) ListTeamMembers(team int, opt *OrganizationListTeamMembersOptions) ([]*User, *Response, error)
    + + +
        func (s *OrganizationsService) ListTeamRepos(team int, opt *ListOptions) ([]*Repository, *Response, error)
    + + +
        func (s *OrganizationsService) ListTeams(org string, opt *ListOptions) ([]*Team, *Response, error)
    + + +
        func (s *OrganizationsService) ListUserTeams(opt *ListOptions) ([]*Team, *Response, error)
    + + +
        func (s *OrganizationsService) PingHook(org string, id int) (*Response, error)
    + + +
        func (s *OrganizationsService) PublicizeMembership(org, user string) (*Response, error)
    + + +
        func (s *OrganizationsService) RemoveMember(org, user string) (*Response, error)
    + + +
        func (s *OrganizationsService) RemoveOrgMembership(user, org string) (*Response, error)
    + + +
        func (s *OrganizationsService) RemoveTeamMembership(team int, user string) (*Response, error)
    + + +
        func (s *OrganizationsService) RemoveTeamRepo(team int, owner string, repo string) (*Response, error)
    + + + +
    type Page
    + + + + +
    type PageBuildEvent
    + + + + +
    type Pages
    + + + + +
    type PagesBuild
    + + + + +
    type PagesError
    + + + + +
    type Plan
    + + + +
        func (p Plan) String() string
    + + + +
    type Protection
    + + + + +
    type PublicEvent
    + + + + +
    type PullRequest
    + + + +
        func (p PullRequest) String() string
    + + + +
    type PullRequestBranch
    + + + + +
    type PullRequestComment
    + + + +
        func (p PullRequestComment) String() string
    + + + +
    type PullRequestEvent
    + + + + +
    type PullRequestLinks
    + + + + +
    type PullRequestListCommentsOptions
    + + + + +
    type PullRequestListOptions
    + + + + +
    type PullRequestMergeResult
    + + + + +
    type PullRequestOptions
    + + + + +
    type PullRequestReviewCommentEvent
    + + + + +
    type PullRequestsService
    + + + +
        func (s *PullRequestsService) Create(owner string, repo string, pull *NewPullRequest) (*PullRequest, *Response, error)
    + + +
        func (s *PullRequestsService) CreateComment(owner string, repo string, number int, comment *PullRequestComment) (*PullRequestComment, *Response, error)
    + + +
        func (s *PullRequestsService) DeleteComment(owner string, repo string, number int) (*Response, error)
    + + +
        func (s *PullRequestsService) Edit(owner string, repo string, number int, pull *PullRequest) (*PullRequest, *Response, error)
    + + +
        func (s *PullRequestsService) EditComment(owner string, repo string, number int, comment *PullRequestComment) (*PullRequestComment, *Response, error)
    + + +
        func (s *PullRequestsService) Get(owner string, repo string, number int) (*PullRequest, *Response, error)
    + + +
        func (s *PullRequestsService) GetComment(owner string, repo string, number int) (*PullRequestComment, *Response, error)
    + + +
        func (s *PullRequestsService) IsMerged(owner string, repo string, number int) (bool, *Response, error)
    + + +
        func (s *PullRequestsService) List(owner string, repo string, opt *PullRequestListOptions) ([]*PullRequest, *Response, error)
    + + +
        func (s *PullRequestsService) ListComments(owner string, repo string, number int, opt *PullRequestListCommentsOptions) ([]*PullRequestComment, *Response, error)
    + + +
        func (s *PullRequestsService) ListCommits(owner string, repo string, number int, opt *ListOptions) ([]*RepositoryCommit, *Response, error)
    + + +
        func (s *PullRequestsService) ListFiles(owner string, repo string, number int, opt *ListOptions) ([]*CommitFile, *Response, error)
    + + +
        func (s *PullRequestsService) Merge(owner string, repo string, number int, commitMessage string, options *PullRequestOptions) (*PullRequestMergeResult, *Response, error)
    + + + +
    type PunchCard
    + + + + +
    type PushEvent
    + + + +
        func (p PushEvent) String() string
    + + + +
    type PushEventCommit
    + + + +
        func (p PushEventCommit) String() string
    + + + +
    type PushEventRepoOwner
    + + + + +
    type PushEventRepository
    + + + + +
    type Rate
    + + + +
        func (r Rate) String() string
    + + + +
    type RateLimitError
    + + + +
        func (r *RateLimitError) Error() string
    + + + +
    type RateLimits
    + + + +
        func (r RateLimits) String() string
    + + + +
    type Reaction
    + + + +
        func (r Reaction) String() string
    + + + +
    type Reactions
    + + + + +
    type ReactionsService
    + + + +
        func (s ReactionsService) CreateCommentReaction(owner, repo string, id int, content string) (*Reaction, *Response, error)
    + + +
        func (s ReactionsService) CreateIssueCommentReaction(owner, repo string, id int, content string) (*Reaction, *Response, error)
    + + +
        func (s ReactionsService) CreateIssueReaction(owner, repo string, number int, content string) (*Reaction, *Response, error)
    + + +
        func (s ReactionsService) CreatePullRequestCommentReaction(owner, repo string, id int, content string) (*Reaction, *Response, error)
    + + +
        func (s *ReactionsService) DeleteReaction(id int) (*Response, error)
    + + +
        func (s *ReactionsService) ListCommentReactions(owner, repo string, id int, opt *ListOptions) ([]*Reaction, *Response, error)
    + + +
        func (s *ReactionsService) ListIssueCommentReactions(owner, repo string, id int, opt *ListOptions) ([]*Reaction, *Response, error)
    + + +
        func (s *ReactionsService) ListIssueReactions(owner, repo string, number int, opt *ListOptions) ([]*Reaction, *Response, error)
    + + +
        func (s *ReactionsService) ListPullRequestCommentReactions(owner, repo string, id int, opt *ListOptions) ([]*Reaction, *Response, error)
    + + + +
    type Reference
    + + + +
        func (r Reference) String() string
    + + + +
    type ReferenceListOptions
    + + + + +
    type ReleaseAsset
    + + + +
        func (r ReleaseAsset) String() string
    + + + +
    type ReleaseEvent
    + + + + +
    type Rename
    + + + +
        func (r Rename) String() string
    + + + +
    type RepoStatus
    + + + +
        func (r RepoStatus) String() string
    + + + +
    type RepositoriesSearchResult
    + + + + +
    type RepositoriesService
    + + + +
        func (s *RepositoriesService) AddCollaborator(owner, repo, user string, opt *RepositoryAddCollaboratorOptions) (*Response, error)
    + + +
        func (s *RepositoriesService) CompareCommits(owner, repo string, base, head string) (*CommitsComparison, *Response, error)
    + + +
        func (s *RepositoriesService) Create(org string, repo *Repository) (*Repository, *Response, error)
    + + +
        func (s *RepositoriesService) CreateComment(owner, repo, sha string, comment *RepositoryComment) (*RepositoryComment, *Response, error)
    + + +
        func (s *RepositoriesService) CreateDeployment(owner, repo string, request *DeploymentRequest) (*Deployment, *Response, error)
    + + +
        func (s *RepositoriesService) CreateDeploymentStatus(owner, repo string, deployment int, request *DeploymentStatusRequest) (*DeploymentStatus, *Response, error)
    + + +
        func (s *RepositoriesService) CreateFile(owner, repo, path string, opt *RepositoryContentFileOptions) (*RepositoryContentResponse, *Response, error)
    + + +
        func (s *RepositoriesService) CreateFork(owner, repo string, opt *RepositoryCreateForkOptions) (*Repository, *Response, error)
    + + +
        func (s *RepositoriesService) CreateHook(owner, repo string, hook *Hook) (*Hook, *Response, error)
    + + +
        func (s *RepositoriesService) CreateKey(owner string, repo string, key *Key) (*Key, *Response, error)
    + + +
        func (s *RepositoriesService) CreateRelease(owner, repo string, release *RepositoryRelease) (*RepositoryRelease, *Response, error)
    + + +
        func (s *RepositoriesService) CreateStatus(owner, repo, ref string, status *RepoStatus) (*RepoStatus, *Response, error)
    + + +
        func (s *RepositoriesService) Delete(owner, repo string) (*Response, error)
    + + +
        func (s *RepositoriesService) DeleteComment(owner, repo string, id int) (*Response, error)
    + + +
        func (s *RepositoriesService) DeleteFile(owner, repo, path string, opt *RepositoryContentFileOptions) (*RepositoryContentResponse, *Response, error)
    + + +
        func (s *RepositoriesService) DeleteHook(owner, repo string, id int) (*Response, error)
    + + +
        func (s *RepositoriesService) DeleteInvitation(repoID, invitationID int) (*Response, error)
    + + +
        func (s *RepositoriesService) DeleteKey(owner string, repo string, id int) (*Response, error)
    + + +
        func (s *RepositoriesService) DeleteRelease(owner, repo string, id int) (*Response, error)
    + + +
        func (s *RepositoriesService) DeleteReleaseAsset(owner, repo string, id int) (*Response, error)
    + + +
        func (s *RepositoriesService) DownloadContents(owner, repo, filepath string, opt *RepositoryContentGetOptions) (io.ReadCloser, error)
    + + +
        func (s *RepositoriesService) DownloadReleaseAsset(owner, repo string, id int) (rc io.ReadCloser, redirectURL string, err error)
    + + +
        func (s *RepositoriesService) Edit(owner, repo string, repository *Repository) (*Repository, *Response, error)
    + + +
        func (s *RepositoriesService) EditBranch(owner, repo, branchName string, branch *Branch) (*Branch, *Response, error)
    + + +
        func (s *RepositoriesService) EditHook(owner, repo string, id int, hook *Hook) (*Hook, *Response, error)
    + + +
        func (s *RepositoriesService) EditKey(owner string, repo string, id int, key *Key) (*Key, *Response, error)
    + + +
        func (s *RepositoriesService) EditRelease(owner, repo string, id int, release *RepositoryRelease) (*RepositoryRelease, *Response, error)
    + + +
        func (s *RepositoriesService) EditReleaseAsset(owner, repo string, id int, release *ReleaseAsset) (*ReleaseAsset, *Response, error)
    + + +
        func (s *RepositoriesService) Get(owner, repo string) (*Repository, *Response, error)
    + + +
        func (s *RepositoriesService) GetArchiveLink(owner, repo string, archiveformat archiveFormat, opt *RepositoryContentGetOptions) (*url.URL, *Response, error)
    + + +
        func (s *RepositoriesService) GetBranch(owner, repo, branch string) (*Branch, *Response, error)
    + + +
        func (s *RepositoriesService) GetByID(id int) (*Repository, *Response, error)
    + + +
        func (s *RepositoriesService) GetCombinedStatus(owner, repo, ref string, opt *ListOptions) (*CombinedStatus, *Response, error)
    + + +
        func (s *RepositoriesService) GetComment(owner, repo string, id int) (*RepositoryComment, *Response, error)
    + + +
        func (s *RepositoriesService) GetCommit(owner, repo, sha string) (*RepositoryCommit, *Response, error)
    + + +
        func (s *RepositoriesService) GetCommitSHA1(owner, repo, ref, lastSHA string) (string, *Response, error)
    + + +
        func (s *RepositoriesService) GetContents(owner, repo, path string, opt *RepositoryContentGetOptions) (fileContent *RepositoryContent, directoryContent []*RepositoryContent, resp *Response, err error)
    + + +
        func (s *RepositoriesService) GetHook(owner, repo string, id int) (*Hook, *Response, error)
    + + +
        func (s *RepositoriesService) GetKey(owner string, repo string, id int) (*Key, *Response, error)
    + + +
        func (s *RepositoriesService) GetLatestPagesBuild(owner string, repo string) (*PagesBuild, *Response, error)
    + + +
        func (s *RepositoriesService) GetLatestRelease(owner, repo string) (*RepositoryRelease, *Response, error)
    + + +
        func (s *RepositoriesService) GetPagesInfo(owner string, repo string) (*Pages, *Response, error)
    + + +
        func (s *RepositoriesService) GetReadme(owner, repo string, opt *RepositoryContentGetOptions) (*RepositoryContent, *Response, error)
    + + +
        func (s *RepositoriesService) GetRelease(owner, repo string, id int) (*RepositoryRelease, *Response, error)
    + + +
        func (s *RepositoriesService) GetReleaseAsset(owner, repo string, id int) (*ReleaseAsset, *Response, error)
    + + +
        func (s *RepositoriesService) GetReleaseByTag(owner, repo, tag string) (*RepositoryRelease, *Response, error)
    + + +
        func (s *RepositoriesService) IsCollaborator(owner, repo, user string) (bool, *Response, error)
    + + +
        func (s *RepositoriesService) License(owner, repo string) (*License, *Response, error)
    + + +
        func (s *RepositoriesService) List(user string, opt *RepositoryListOptions) ([]*Repository, *Response, error)
    + + +
        func (s *RepositoriesService) ListAll(opt *RepositoryListAllOptions) ([]*Repository, *Response, error)
    + + +
        func (s *RepositoriesService) ListBranches(owner string, repo string, opt *ListOptions) ([]*Branch, *Response, error)
    + + +
        func (s *RepositoriesService) ListByOrg(org string, opt *RepositoryListByOrgOptions) ([]*Repository, *Response, error)
    + + +
        func (s *RepositoriesService) ListCodeFrequency(owner, repo string) ([]*WeeklyStats, *Response, error)
    + + +
        func (s *RepositoriesService) ListCollaborators(owner, repo string, opt *ListOptions) ([]*User, *Response, error)
    + + +
        func (s *RepositoriesService) ListComments(owner, repo string, opt *ListOptions) ([]*RepositoryComment, *Response, error)
    + + +
        func (s *RepositoriesService) ListCommitActivity(owner, repo string) ([]*WeeklyCommitActivity, *Response, error)
    + + +
        func (s *RepositoriesService) ListCommitComments(owner, repo, sha string, opt *ListOptions) ([]*RepositoryComment, *Response, error)
    + + +
        func (s *RepositoriesService) ListCommits(owner, repo string, opt *CommitsListOptions) ([]*RepositoryCommit, *Response, error)
    + + +
        func (s *RepositoriesService) ListContributors(owner string, repository string, opt *ListContributorsOptions) ([]*Contributor, *Response, error)
    + + +
        func (s *RepositoriesService) ListContributorsStats(owner, repo string) ([]*ContributorStats, *Response, error)
    + + +
        func (s *RepositoriesService) ListDeploymentStatuses(owner, repo string, deployment int, opt *ListOptions) ([]*DeploymentStatus, *Response, error)
    + + +
        func (s *RepositoriesService) ListDeployments(owner, repo string, opt *DeploymentsListOptions) ([]*Deployment, *Response, error)
    + + +
        func (s *RepositoriesService) ListForks(owner, repo string, opt *RepositoryListForksOptions) ([]*Repository, *Response, error)
    + + +
        func (s *RepositoriesService) ListHooks(owner, repo string, opt *ListOptions) ([]*Hook, *Response, error)
    + + +
        func (s *RepositoriesService) ListInvitations(repoID int, opt *ListOptions) ([]*RepositoryInvitation, *Response, error)
    + + +
        func (s *RepositoriesService) ListKeys(owner string, repo string, opt *ListOptions) ([]*Key, *Response, error)
    + + +
        func (s *RepositoriesService) ListLanguages(owner string, repo string) (map[string]int, *Response, error)
    + + +
        func (s *RepositoriesService) ListPagesBuilds(owner string, repo string) ([]*PagesBuild, *Response, error)
    + + +
        func (s *RepositoriesService) ListParticipation(owner, repo string) (*RepositoryParticipation, *Response, error)
    + + +
        func (s *RepositoriesService) ListPunchCard(owner, repo string) ([]*PunchCard, *Response, error)
    + + +
        func (s *RepositoriesService) ListReleaseAssets(owner, repo string, id int, opt *ListOptions) ([]*ReleaseAsset, *Response, error)
    + + +
        func (s *RepositoriesService) ListReleases(owner, repo string, opt *ListOptions) ([]*RepositoryRelease, *Response, error)
    + + +
        func (s *RepositoriesService) ListServiceHooks() ([]*ServiceHook, *Response, error)
    + + +
        func (s *RepositoriesService) ListStatuses(owner, repo, ref string, opt *ListOptions) ([]*RepoStatus, *Response, error)
    + + +
        func (s *RepositoriesService) ListTags(owner string, repo string, opt *ListOptions) ([]*RepositoryTag, *Response, error)
    + + +
        func (s *RepositoriesService) ListTeams(owner string, repo string, opt *ListOptions) ([]*Team, *Response, error)
    + + +
        func (s *RepositoriesService) Merge(owner, repo string, request *RepositoryMergeRequest) (*RepositoryCommit, *Response, error)
    + + +
        func (s *RepositoriesService) PingHook(owner, repo string, id int) (*Response, error)
    + + +
        func (s *RepositoriesService) RemoveCollaborator(owner, repo, user string) (*Response, error)
    + + +
        func (s *RepositoriesService) RequestPageBuild(owner string, repo string) (*PagesBuild, *Response, error)
    + + +
        func (s *RepositoriesService) TestHook(owner, repo string, id int) (*Response, error)
    + + +
        func (s *RepositoriesService) UpdateComment(owner, repo string, id int, comment *RepositoryComment) (*RepositoryComment, *Response, error)
    + + +
        func (s *RepositoriesService) UpdateFile(owner, repo, path string, opt *RepositoryContentFileOptions) (*RepositoryContentResponse, *Response, error)
    + + +
        func (s *RepositoriesService) UpdateInvitation(repoID, invitationID int, permissions string) (*RepositoryInvitation, *Response, error)
    + + +
        func (s *RepositoriesService) UploadReleaseAsset(owner, repo string, id int, opt *UploadOptions, file *os.File) (*ReleaseAsset, *Response, error)
    + + + +
    type Repository
    + + + +
        func (r Repository) String() string
    + + + +
    type RepositoryAddCollaboratorOptions
    + + + + +
    type RepositoryComment
    + + + +
        func (r RepositoryComment) String() string
    + + + +
    type RepositoryCommit
    + + + +
        func (r RepositoryCommit) String() string
    + + + +
    type RepositoryContent
    + + + +
        func (r *RepositoryContent) Decode() ([]byte, error)
    + + +
        func (r *RepositoryContent) GetContent() (string, error)
    + + +
        func (r RepositoryContent) String() string
    + + + +
    type RepositoryContentFileOptions
    + + + + +
    type RepositoryContentGetOptions
    + + + + +
    type RepositoryContentResponse
    + + + + +
    type RepositoryCreateForkOptions
    + + + + +
    type RepositoryEvent
    + + + + +
    type RepositoryInvitation
    + + + + +
    type RepositoryListAllOptions
    + + + + +
    type RepositoryListByOrgOptions
    + + + + +
    type RepositoryListForksOptions
    + + + + +
    type RepositoryListOptions
    + + + + +
    type RepositoryMergeRequest
    + + + + +
    type RepositoryParticipation
    + + + +
        func (r RepositoryParticipation) String() string
    + + + +
    type RepositoryRelease
    + + + +
        func (r RepositoryRelease) String() string
    + + + +
    type RepositoryTag
    + + + + +
    type RequiredStatusChecks
    + + + + +
    type Response
    + + + + +
    type Scope
    + + + + +
    type SearchOptions
    + + + + +
    type SearchService
    + + + +
        func (s *SearchService) Code(query string, opt *SearchOptions) (*CodeSearchResult, *Response, error)
    + + +
        func (s *SearchService) Issues(query string, opt *SearchOptions) (*IssuesSearchResult, *Response, error)
    + + +
        func (s *SearchService) Repositories(query string, opt *SearchOptions) (*RepositoriesSearchResult, *Response, error)
    + + +
        func (s *SearchService) Users(query string, opt *SearchOptions) (*UsersSearchResult, *Response, error)
    + + + +
    type ServiceHook
    + + + +
        func (s *ServiceHook) String() string
    + + + +
    type SignatureVerification
    + + + + +
    type Source
    + + + + +
    type SourceImportAuthor
    + + + +
        func (a SourceImportAuthor) String() string
    + + + +
    type Stargazer
    + + + + +
    type StarredRepository
    + + + + +
    type StatusEvent
    + + + + +
    type Subscription
    + + + + +
    type Tag
    + + + + +
    type Team
    + + + +
        func (t Team) String() string
    + + + +
    type TeamAddEvent
    + + + + +
    type TextMatch
    + + + +
        func (tm TextMatch) String() string
    + + + +
    type Timeline
    + + + + +
    type Timestamp
    + + + +
        func (t Timestamp) Equal(u Timestamp) bool
    + + +
        func (t Timestamp) String() string
    + + +
        func (t *Timestamp) UnmarshalJSON(data []byte) (err error)
    + + + +
    type Tree
    + + + +
        func (t Tree) String() string
    + + + +
    type TreeEntry
    + + + +
        func (t TreeEntry) String() string
    + + + +
    type TwoFactorAuthError
    + + + +
        func (r *TwoFactorAuthError) Error() string
    + + + +
    type UnauthenticatedRateLimitedTransport
    + + + +
        func (t *UnauthenticatedRateLimitedTransport) Client() *http.Client
    + + +
        func (t *UnauthenticatedRateLimitedTransport) RoundTrip(req *http.Request) (*http.Response, error)
    + + + +
    type UploadOptions
    + + + + +
    type User
    + + + +
        func (u User) String() string
    + + + +
    type UserEmail
    + + + + +
    type UserListOptions
    + + + + +
    type UsersSearchResult
    + + + + +
    type UsersService
    + + + +
        func (s *UsersService) AcceptInvitation(invitationID int) (*Response, error)
    + + +
        func (s *UsersService) AddEmails(emails []string) ([]*UserEmail, *Response, error)
    + + +
        func (s *UsersService) CreateGPGKey(armoredPublicKey string) (*GPGKey, *Response, error)
    + + +
        func (s *UsersService) CreateKey(key *Key) (*Key, *Response, error)
    + + +
        func (s *UsersService) DeclineInvitation(invitationID int) (*Response, error)
    + + +
        func (s *UsersService) DeleteEmails(emails []string) (*Response, error)
    + + +
        func (s *UsersService) DeleteGPGKey(id int) (*Response, error)
    + + +
        func (s *UsersService) DeleteKey(id int) (*Response, error)
    + + +
        func (s *UsersService) DemoteSiteAdmin(user string) (*Response, error)
    + + +
        func (s *UsersService) Edit(user *User) (*User, *Response, error)
    + + +
        func (s *UsersService) Follow(user string) (*Response, error)
    + + +
        func (s *UsersService) Get(user string) (*User, *Response, error)
    + + +
        func (s *UsersService) GetByID(id int) (*User, *Response, error)
    + + +
        func (s *UsersService) GetGPGKey(id int) (*GPGKey, *Response, error)
    + + +
        func (s *UsersService) GetKey(id int) (*Key, *Response, error)
    + + +
        func (s *UsersService) IsFollowing(user, target string) (bool, *Response, error)
    + + +
        func (s *UsersService) ListAll(opt *UserListOptions) ([]*User, *Response, error)
    + + +
        func (s *UsersService) ListEmails(opt *ListOptions) ([]*UserEmail, *Response, error)
    + + +
        func (s *UsersService) ListFollowers(user string, opt *ListOptions) ([]*User, *Response, error)
    + + +
        func (s *UsersService) ListFollowing(user string, opt *ListOptions) ([]*User, *Response, error)
    + + +
        func (s *UsersService) ListGPGKeys() ([]*GPGKey, *Response, error)
    + + +
        func (s *UsersService) ListInvitations() ([]*RepositoryInvitation, *Response, error)
    + + +
        func (s *UsersService) ListKeys(user string, opt *ListOptions) ([]*Key, *Response, error)
    + + +
        func (s *UsersService) PromoteSiteAdmin(user string) (*Response, error)
    + + +
        func (s *UsersService) Suspend(user string) (*Response, error)
    + + +
        func (s *UsersService) Unfollow(user string) (*Response, error)
    + + +
        func (s *UsersService) Unsuspend(user string) (*Response, error)
    + + + +
    type WatchEvent
    + + + + +
    type WebHookAuthor
    + + + +
        func (w WebHookAuthor) String() string
    + + + +
    type WebHookCommit
    + + + +
        func (w WebHookCommit) String() string
    + + + +
    type WebHookPayload
    + + + +
        func (w WebHookPayload) String() string
    + + + +
    type WeeklyCommitActivity
    + + + +
        func (w WeeklyCommitActivity) String() string
    + + + +
    type WeeklyStats
    + + + +
        func (w WeeklyStats) String() string
    + + + +
    +
    + + + + + + +

    Package files

    +

    + + + activity.go + + activity_events.go + + activity_notifications.go + + activity_star.go + + activity_watching.go + + authorizations.go + + doc.go + + event_types.go + + gists.go + + gists_comments.go + + git.go + + git_blobs.go + + git_commits.go + + git_refs.go + + git_tags.go + + git_trees.go + + github.go + + gitignore.go + + issues.go + + issues_assignees.go + + issues_comments.go + + issues_events.go + + issues_labels.go + + issues_milestones.go + + issues_timeline.go + + licenses.go + + messages.go + + migrations.go + + migrations_source_import.go + + misc.go + + orgs.go + + orgs_hooks.go + + orgs_members.go + + orgs_teams.go + + pulls.go + + pulls_comments.go + + reactions.go + + repos.go + + repos_collaborators.go + + repos_comments.go + + repos_commits.go + + repos_contents.go + + repos_deployments.go + + repos_forks.go + + repos_hooks.go + + repos_invitations.go + + repos_keys.go + + repos_merging.go + + repos_pages.go + + repos_releases.go + + repos_stats.go + + repos_statuses.go + + search.go + + strings.go + + timestamp.go + + users.go + + users_administration.go + + users_emails.go + + users_followers.go + + users_gpg_keys.go + + users_keys.go + + +

    + +
    +
    + + + + +

    Constants

    + +
    const (
    +    // Tarball specifies an archive in gzipped tar format.
    +    Tarball archiveFormat = "tarball"
    +
    +    // Zipball specifies an archive in zip format.
    +    Zipball archiveFormat = "zipball"
    +)
    + + +
    const (
    +    // StatusUnprocessableEntity is the status code returned when sending a request with invalid fields.
    +    StatusUnprocessableEntity = 422
    +)
    + + + + + + + +

    func Bool

    +
    func Bool(v bool) *bool
    +

    +Bool is a helper routine that allocates a new bool value +to store v and returns a pointer to it. +

    + + + + + + + +

    func CheckResponse

    +
    func CheckResponse(r *http.Response) error
    +

    +CheckResponse checks the API response for errors, and returns them if +present. A response is considered an error if it has a status code outside +the 200 range. API error responses are expected to have either no response +body, or a JSON response body that maps to ErrorResponse. Any other +response body will be silently ignored. +

    +

    +The error type will be *RateLimitError for rate limit exceeded errors, +and *TwoFactorAuthError for two-factor authentication errors. +

    + + + + + + + +

    func Int

    +
    func Int(v int) *int
    +

    +Int is a helper routine that allocates a new int value +to store v and returns a pointer to it. +

    + + + + + + + +

    func String

    +
    func String(v string) *string
    +

    +String is a helper routine that allocates a new string value +to store v and returns a pointer to it. +

    + + + + + + + +

    func Stringify

    +
    func Stringify(message interface{}) string
    +

    +Stringify attempts to create a reasonable string representation of types in +the GitHub library. It does things like resolve pointers to their values +and omits struct fields with nil values. +

    + + + + + + + +

    func ValidatePayload

    +
    func ValidatePayload(r *http.Request, secretKey []byte) (payload []byte, err error)
    +

    +ValidatePayload validates an incoming GitHub Webhook event request +and returns the (JSON) payload. +secretKey is the GitHub Webhook secret message. +

    +

    +Example usage: +

    +
    func (s *GitHubEventMonitor) ServeHTTP(w http.ResponseWriter, r *http.Request) {
    +  payload, err := github.ValidatePayload(r, s.webhookSecretKey)
    +  if err != nil { ... }
    +  // Process payload...
    +}
    +
    + + + + + + + + +

    type APIMeta

    +
    type APIMeta struct {
    +    // An Array of IP addresses in CIDR format specifying the addresses
    +    // that incoming service hooks will originate from on GitHub.com.
    +    Hooks []string `json:"hooks,omitempty"`
    +
    +    // An Array of IP addresses in CIDR format specifying the Git servers
    +    // for GitHub.com.
    +    Git []string `json:"git,omitempty"`
    +
    +    // Whether authentication with username and password is supported.
    +    // (GitHub Enterprise instances using CAS or OAuth for authentication
    +    // will return false. Features like Basic Authentication with a
    +    // username and password, sudo mode, and two-factor authentication are
    +    // not supported on these servers.)
    +    VerifiablePasswordAuthentication *bool `json:"verifiable_password_authentication,omitempty"`
    +
    +    // An array of IP addresses in CIDR format specifying the addresses
    +    // which serve GitHub Pages websites.
    +    Pages []string `json:"pages,omitempty"`
    +}
    +

    +APIMeta represents metadata about the GitHub API. +

    + + + + + + + + + + + + + + + + +

    type ActivityListStarredOptions

    +
    type ActivityListStarredOptions struct {
    +    // How to sort the repository list.  Possible values are: created, updated,
    +    // pushed, full_name.  Default is "full_name".
    +    Sort string `url:"sort,omitempty"`
    +
    +    // Direction in which to sort repositories.  Possible values are: asc, desc.
    +    // Default is "asc" when sort is "full_name", otherwise default is "desc".
    +    Direction string `url:"direction,omitempty"`
    +
    +    ListOptions
    +}
    +

    +ActivityListStarredOptions specifies the optional parameters to the +ActivityService.ListStarred method. +

    + + + + + + + + + + + + + + + + +

    type ActivityService

    +
    type ActivityService service
    +

    +ActivityService handles communication with the activity related +methods of the GitHub API. +

    +

    +GitHub API docs: http://developer.github.com/v3/activity/ +

    + + + + + + + + + + + + + + +

    func (*ActivityService) DeleteRepositorySubscription

    +
    func (s *ActivityService) DeleteRepositorySubscription(owner, repo string) (*Response, error)
    +

    +DeleteRepositorySubscription deletes the subscription for the specified +repository for the authenticated user. +

    +

    +GitHub API Docs: https://developer.github.com/v3/activity/watching/#delete-a-repository-subscription +

    + + + + + + +

    func (*ActivityService) DeleteThreadSubscription

    +
    func (s *ActivityService) DeleteThreadSubscription(id string) (*Response, error)
    +

    +DeleteThreadSubscription deletes the subscription for the specified thread +for the authenticated user. +

    +

    +GitHub API Docs: https://developer.github.com/v3/activity/notifications/#delete-a-thread-subscription +

    + + + + + + +

    func (*ActivityService) GetRepositorySubscription

    +
    func (s *ActivityService) GetRepositorySubscription(owner, repo string) (*Subscription, *Response, error)
    +

    +GetRepositorySubscription returns the subscription for the specified +repository for the authenticated user. If the authenticated user is not +watching the repository, a nil Subscription is returned. +

    +

    +GitHub API Docs: https://developer.github.com/v3/activity/watching/#get-a-repository-subscription +

    + + + + + + +

    func (*ActivityService) GetThread

    +
    func (s *ActivityService) GetThread(id string) (*Notification, *Response, error)
    +

    +GetThread gets the specified notification thread. +

    +

    +GitHub API Docs: https://developer.github.com/v3/activity/notifications/#view-a-single-thread +

    + + + + + + +

    func (*ActivityService) GetThreadSubscription

    +
    func (s *ActivityService) GetThreadSubscription(id string) (*Subscription, *Response, error)
    +

    +GetThreadSubscription checks to see if the authenticated user is subscribed +to a thread. +

    +

    +GitHub API Docs: https://developer.github.com/v3/activity/notifications/#get-a-thread-subscription +

    + + + + + + +

    func (*ActivityService) IsStarred

    +
    func (s *ActivityService) IsStarred(owner, repo string) (bool, *Response, error)
    +

    +IsStarred checks if a repository is starred by authenticated user. +

    +

    +GitHub API docs: https://developer.github.com/v3/activity/starring/#check-if-you-are-starring-a-repository +

    + + + + + + +

    func (*ActivityService) ListEvents

    +
    func (s *ActivityService) ListEvents(opt *ListOptions) ([]*Event, *Response, error)
    +

    +ListEvents drinks from the firehose of all public events across GitHub. +

    +

    +GitHub API docs: http://developer.github.com/v3/activity/events/#list-public-events +

    + + + + + + +

    func (*ActivityService) ListEventsForOrganization

    +
    func (s *ActivityService) ListEventsForOrganization(org string, opt *ListOptions) ([]*Event, *Response, error)
    +

    +ListEventsForOrganization lists public events for an organization. +

    +

    +GitHub API docs: http://developer.github.com/v3/activity/events/#list-public-events-for-an-organization +

    + + + + + + +

    func (*ActivityService) ListEventsForRepoNetwork

    +
    func (s *ActivityService) ListEventsForRepoNetwork(owner, repo string, opt *ListOptions) ([]*Event, *Response, error)
    +

    +ListEventsForRepoNetwork lists public events for a network of repositories. +

    +

    +GitHub API docs: http://developer.github.com/v3/activity/events/#list-public-events-for-a-network-of-repositories +

    + + + + + + +

    func (*ActivityService) ListEventsPerformedByUser

    +
    func (s *ActivityService) ListEventsPerformedByUser(user string, publicOnly bool, opt *ListOptions) ([]*Event, *Response, error)
    +

    +ListEventsPerformedByUser lists the events performed by a user. If publicOnly is +true, only public events will be returned. +

    +

    +GitHub API docs: http://developer.github.com/v3/activity/events/#list-events-performed-by-a-user +

    + + + + + + +

    func (*ActivityService) ListEventsReceivedByUser

    +
    func (s *ActivityService) ListEventsReceivedByUser(user string, publicOnly bool, opt *ListOptions) ([]*Event, *Response, error)
    +

    +ListEventsReceivedByUser lists the events received by a user. If publicOnly is +true, only public events will be returned. +

    +

    +GitHub API docs: http://developer.github.com/v3/activity/events/#list-events-that-a-user-has-received +

    + + + + + + +

    func (*ActivityService) ListFeeds

    +
    func (s *ActivityService) ListFeeds() (*Feeds, *Response, error)
    +

    +ListFeeds lists all the feeds available to the authenticated user. +

    +

    +GitHub provides several timeline resources in Atom format: +

    +
    Timeline: The GitHub global public timeline
    +User: The public timeline for any user, using URI template
    +Current user public: The public timeline for the authenticated user
    +Current user: The private timeline for the authenticated user
    +Current user actor: The private timeline for activity created by the
    +    authenticated user
    +Current user organizations: The private timeline for the organizations
    +    the authenticated user is a member of.
    +
    +

    +Note: Private feeds are only returned when authenticating via Basic Auth +since current feed URIs use the older, non revocable auth tokens. +

    + + + + + + +

    func (*ActivityService) ListIssueEventsForRepository

    +
    func (s *ActivityService) ListIssueEventsForRepository(owner, repo string, opt *ListOptions) ([]*Event, *Response, error)
    +

    +ListIssueEventsForRepository lists issue events for a repository. +

    +

    +GitHub API docs: http://developer.github.com/v3/activity/events/#list-issue-events-for-a-repository +

    + + + + + + +

    func (*ActivityService) ListNotifications

    +
    func (s *ActivityService) ListNotifications(opt *NotificationListOptions) ([]*Notification, *Response, error)
    +

    +ListNotifications lists all notifications for the authenticated user. +

    +

    +GitHub API Docs: https://developer.github.com/v3/activity/notifications/#list-your-notifications +

    + + + + + + +

    func (*ActivityService) ListRepositoryEvents

    +
    func (s *ActivityService) ListRepositoryEvents(owner, repo string, opt *ListOptions) ([]*Event, *Response, error)
    +

    +ListRepositoryEvents lists events for a repository. +

    +

    +GitHub API docs: http://developer.github.com/v3/activity/events/#list-repository-events +

    + + + + + + +

    func (*ActivityService) ListRepositoryNotifications

    +
    func (s *ActivityService) ListRepositoryNotifications(owner, repo string, opt *NotificationListOptions) ([]*Notification, *Response, error)
    +

    +ListRepositoryNotifications lists all notifications in a given repository +for the authenticated user. +

    +

    +GitHub API Docs: https://developer.github.com/v3/activity/notifications/#list-your-notifications-in-a-repository +

    + + + + + + +

    func (*ActivityService) ListStargazers

    +
    func (s *ActivityService) ListStargazers(owner, repo string, opt *ListOptions) ([]*Stargazer, *Response, error)
    +

    +ListStargazers lists people who have starred the specified repo. +

    +

    +GitHub API Docs: https://developer.github.com/v3/activity/starring/#list-stargazers +

    + + + + + + +

    func (*ActivityService) ListStarred

    +
    func (s *ActivityService) ListStarred(user string, opt *ActivityListStarredOptions) ([]*StarredRepository, *Response, error)
    +

    +ListStarred lists all the repos starred by a user. Passing the empty string +will list the starred repositories for the authenticated user. +

    +

    +GitHub API docs: http://developer.github.com/v3/activity/starring/#list-repositories-being-starred +

    + + + + + + +

    func (*ActivityService) ListUserEventsForOrganization

    +
    func (s *ActivityService) ListUserEventsForOrganization(org, user string, opt *ListOptions) ([]*Event, *Response, error)
    +

    +ListUserEventsForOrganization provides the user’s organization dashboard. You +must be authenticated as the user to view this. +

    +

    +GitHub API docs: http://developer.github.com/v3/activity/events/#list-events-for-an-organization +

    + + + + + + +

    func (*ActivityService) ListWatched

    +
    func (s *ActivityService) ListWatched(user string, opt *ListOptions) ([]*Repository, *Response, error)
    +

    +ListWatched lists the repositories the specified user is watching. Passing +the empty string will fetch watched repos for the authenticated user. +

    +

    +GitHub API Docs: https://developer.github.com/v3/activity/watching/#list-repositories-being-watched +

    + + + + + + +

    func (*ActivityService) ListWatchers

    +
    func (s *ActivityService) ListWatchers(owner, repo string, opt *ListOptions) ([]*User, *Response, error)
    +

    +ListWatchers lists watchers of a particular repo. +

    +

    +GitHub API Docs: http://developer.github.com/v3/activity/watching/#list-watchers +

    + + + + + + +

    func (*ActivityService) MarkNotificationsRead

    +
    func (s *ActivityService) MarkNotificationsRead(lastRead time.Time) (*Response, error)
    +

    +MarkNotificationsRead marks all notifications up to lastRead as read. +

    +

    +GitHub API Docs: https://developer.github.com/v3/activity/notifications/#mark-as-read +

    + + + + + + +

    func (*ActivityService) MarkRepositoryNotificationsRead

    +
    func (s *ActivityService) MarkRepositoryNotificationsRead(owner, repo string, lastRead time.Time) (*Response, error)
    +

    +MarkRepositoryNotificationsRead marks all notifications up to lastRead in +the specified repository as read. +

    +

    +GitHub API Docs: https://developer.github.com/v3/activity/notifications/#mark-notifications-as-read-in-a-repository +

    + + + + + + +

    func (*ActivityService) MarkThreadRead

    +
    func (s *ActivityService) MarkThreadRead(id string) (*Response, error)
    +

    +MarkThreadRead marks the specified thread as read. +

    +

    +GitHub API Docs: https://developer.github.com/v3/activity/notifications/#mark-a-thread-as-read +

    + + + + + + +

    func (*ActivityService) SetRepositorySubscription

    +
    func (s *ActivityService) SetRepositorySubscription(owner, repo string, subscription *Subscription) (*Subscription, *Response, error)
    +

    +SetRepositorySubscription sets the subscription for the specified repository +for the authenticated user. +

    +

    +GitHub API Docs: https://developer.github.com/v3/activity/watching/#set-a-repository-subscription +

    + + + + + + +

    func (*ActivityService) SetThreadSubscription

    +
    func (s *ActivityService) SetThreadSubscription(id string, subscription *Subscription) (*Subscription, *Response, error)
    +

    +SetThreadSubscription sets the subscription for the specified thread for the +authenticated user. +

    +

    +GitHub API Docs: https://developer.github.com/v3/activity/notifications/#set-a-thread-subscription +

    + + + + + + +

    func (*ActivityService) Star

    +
    func (s *ActivityService) Star(owner, repo string) (*Response, error)
    +

    +Star a repository as the authenticated user. +

    +

    +GitHub API docs: https://developer.github.com/v3/activity/starring/#star-a-repository +

    + + + + + + +

    func (*ActivityService) Unstar

    +
    func (s *ActivityService) Unstar(owner, repo string) (*Response, error)
    +

    +Unstar a repository as the authenticated user. +

    +

    +GitHub API docs: https://developer.github.com/v3/activity/starring/#unstar-a-repository +

    + + + + + + + + +

    type Authorization

    +
    type Authorization struct {
    +    ID             *int              `json:"id,omitempty"`
    +    URL            *string           `json:"url,omitempty"`
    +    Scopes         []Scope           `json:"scopes,omitempty"`
    +    Token          *string           `json:"token,omitempty"`
    +    TokenLastEight *string           `json:"token_last_eight,omitempty"`
    +    HashedToken    *string           `json:"hashed_token,omitempty"`
    +    App            *AuthorizationApp `json:"app,omitempty"`
    +    Note           *string           `json:"note,omitempty"`
    +    NoteURL        *string           `json:"note_url,omitempty"`
    +    UpdateAt       *Timestamp        `json:"updated_at,omitempty"`
    +    CreatedAt      *Timestamp        `json:"created_at,omitempty"`
    +    Fingerprint    *string           `json:"fingerprint,omitempty"`
    +
    +    // User is only populated by the Check and Reset methods.
    +    User *User `json:"user,omitempty"`
    +}
    +

    +Authorization represents an individual GitHub authorization. +

    + + + + + + + + + + + + + + +

    func (Authorization) String

    +
    func (a Authorization) String() string
    + + + + + + + + +

    type AuthorizationApp

    +
    type AuthorizationApp struct {
    +    URL      *string `json:"url,omitempty"`
    +    Name     *string `json:"name,omitempty"`
    +    ClientID *string `json:"client_id,omitempty"`
    +}
    +

    +AuthorizationApp represents an individual GitHub app (in the context of authorization). +

    + + + + + + + + + + + + + + +

    func (AuthorizationApp) String

    +
    func (a AuthorizationApp) String() string
    + + + + + + + + +

    type AuthorizationRequest

    +
    type AuthorizationRequest struct {
    +    Scopes       []Scope `json:"scopes,omitempty"`
    +    Note         *string `json:"note,omitempty"`
    +    NoteURL      *string `json:"note_url,omitempty"`
    +    ClientID     *string `json:"client_id,omitempty"`
    +    ClientSecret *string `json:"client_secret,omitempty"`
    +    Fingerprint  *string `json:"fingerprint,omitempty"`
    +}
    +

    +AuthorizationRequest represents a request to create an authorization. +

    + + + + + + + + + + + + + + +

    func (AuthorizationRequest) String

    +
    func (a AuthorizationRequest) String() string
    + + + + + + + + +

    type AuthorizationUpdateRequest

    +
    type AuthorizationUpdateRequest struct {
    +    Scopes       []string `json:"scopes,omitempty"`
    +    AddScopes    []string `json:"add_scopes,omitempty"`
    +    RemoveScopes []string `json:"remove_scopes,omitempty"`
    +    Note         *string  `json:"note,omitempty"`
    +    NoteURL      *string  `json:"note_url,omitempty"`
    +    Fingerprint  *string  `json:"fingerprint,omitempty"`
    +}
    +

    +AuthorizationUpdateRequest represents a request to update an authorization. +

    +

    +Note that for any one update, you must only provide one of the "scopes" +fields. That is, you may provide only one of "Scopes", or "AddScopes", or +"RemoveScopes". +

    +

    +GitHub API docs: https://developer.github.com/v3/oauth_authorizations/#update-an-existing-authorization +

    + + + + + + + + + + + + + + +

    func (AuthorizationUpdateRequest) String

    +
    func (a AuthorizationUpdateRequest) String() string
    + + + + + + + + +

    type AuthorizationsService

    +
    type AuthorizationsService service
    +

    +AuthorizationsService handles communication with the authorization related +methods of the GitHub API. +

    +

    +This service requires HTTP Basic Authentication; it cannot be accessed using +an OAuth token. +

    +

    +GitHub API docs: https://developer.github.com/v3/oauth_authorizations/ +

    + + + + + + + + + + + + + + +

    func (*AuthorizationsService) Check

    +
    func (s *AuthorizationsService) Check(clientID string, token string) (*Authorization, *Response, error)
    +

    +Check if an OAuth token is valid for a specific app. +

    +

    +Note that this operation requires the use of BasicAuth, but where the +username is the OAuth application clientID, and the password is its +clientSecret. Invalid tokens will return a 404 Not Found. +

    +

    +The returned Authorization.User field will be populated. +

    +

    +GitHub API docs: https://developer.github.com/v3/oauth_authorizations/#check-an-authorization +

    + + + + + + +

    func (*AuthorizationsService) Create

    +
    func (s *AuthorizationsService) Create(auth *AuthorizationRequest) (*Authorization, *Response, error)
    +

    +Create a new authorization for the specified OAuth application. +

    +

    +GitHub API docs: https://developer.github.com/v3/oauth_authorizations/#create-a-new-authorization +

    + + + + + + +

    func (*AuthorizationsService) CreateImpersonation

    +
    func (s *AuthorizationsService) CreateImpersonation(username string, authReq *AuthorizationRequest) (*Authorization, *Response, error)
    +

    +Create an impersonation OAuth token. +

    +

    +This requires admin permissions. With the returned Authorization.Token +you can e.g. create or delete a user's public SSH key. NOTE: creating a +new token automatically revokes an existing one. +

    +

    +GitHub API docs: https://developer.github.com/enterprise/2.5/v3/users/administration/#create-an-impersonation-oauth-token +

    + + + + + + +

    func (*AuthorizationsService) Delete

    +
    func (s *AuthorizationsService) Delete(id int) (*Response, error)
    +

    +Delete a single authorization. +

    +

    +GitHub API docs: https://developer.github.com/v3/oauth_authorizations/#delete-an-authorization +

    + + + + + + +

    func (*AuthorizationsService) DeleteGrant

    +
    func (s *AuthorizationsService) DeleteGrant(id int) (*Response, error)
    +

    +DeleteGrant deletes an OAuth application grant. Deleting an application's +grant will also delete all OAuth tokens associated with the application for +the user. +

    +

    +GitHub API docs: https://developer.github.com/v3/oauth_authorizations/#delete-a-grant +

    + + + + + + +

    func (*AuthorizationsService) DeleteImpersonation

    +
    func (s *AuthorizationsService) DeleteImpersonation(username string) (*Response, error)
    +

    +Delete an impersonation OAuth token. +

    +

    +NOTE: there can be only one at a time. +

    +

    +GitHub API docs: https://developer.github.com/enterprise/2.5/v3/users/administration/#delete-an-impersonation-oauth-token +

    + + + + + + +

    func (*AuthorizationsService) Edit

    +
    func (s *AuthorizationsService) Edit(id int, auth *AuthorizationUpdateRequest) (*Authorization, *Response, error)
    +

    +Edit a single authorization. +

    +

    +GitHub API docs: https://developer.github.com/v3/oauth_authorizations/#update-an-existing-authorization +

    + + + + + + +

    func (*AuthorizationsService) Get

    +
    func (s *AuthorizationsService) Get(id int) (*Authorization, *Response, error)
    +

    +Get a single authorization. +

    +

    +GitHub API docs: https://developer.github.com/v3/oauth_authorizations/#get-a-single-authorization +

    + + + + + + +

    func (*AuthorizationsService) GetGrant

    +
    func (s *AuthorizationsService) GetGrant(id int) (*Grant, *Response, error)
    +

    +GetGrant gets a single OAuth application grant. +

    +

    +GitHub API docs: https://developer.github.com/v3/oauth_authorizations/#get-a-single-grant +

    + + + + + + +

    func (*AuthorizationsService) GetOrCreateForApp

    +
    func (s *AuthorizationsService) GetOrCreateForApp(clientID string, auth *AuthorizationRequest) (*Authorization, *Response, error)
    +

    +GetOrCreateForApp creates a new authorization for the specified OAuth +application, only if an authorization for that application doesn’t already +exist for the user. +

    +

    +If a new token is created, the HTTP status code will be "201 Created", and +the returned Authorization.Token field will be populated. If an existing +token is returned, the status code will be "200 OK" and the +Authorization.Token field will be empty. +

    +

    +clientID is the OAuth Client ID with which to create the token. +

    +

    +GitHub API docs: +- https://developer.github.com/v3/oauth_authorizations/#get-or-create-an-authorization-for-a-specific-app +- https://developer.github.com/v3/oauth_authorizations/#get-or-create-an-authorization-for-a-specific-app-and-fingerprint +

    + + + + + + +

    func (*AuthorizationsService) List

    +
    func (s *AuthorizationsService) List(opt *ListOptions) ([]*Authorization, *Response, error)
    +

    +List the authorizations for the authenticated user. +

    +

    +GitHub API docs: https://developer.github.com/v3/oauth_authorizations/#list-your-authorizations +

    + + + + + + +

    func (*AuthorizationsService) ListGrants

    +
    func (s *AuthorizationsService) ListGrants() ([]*Grant, *Response, error)
    +

    +ListGrants lists the set of OAuth applications that have been granted +access to a user's account. This will return one entry for each application +that has been granted access to the account, regardless of the number of +tokens an application has generated for the user. +

    +

    +GitHub API docs: https://developer.github.com/v3/oauth_authorizations/#list-your-grants +

    + + + + + + +

    func (*AuthorizationsService) Reset

    +
    func (s *AuthorizationsService) Reset(clientID string, token string) (*Authorization, *Response, error)
    +

    +Reset is used to reset a valid OAuth token without end user involvement. +Applications must save the "token" property in the response, because changes +take effect immediately. +

    +

    +Note that this operation requires the use of BasicAuth, but where the +username is the OAuth application clientID, and the password is its +clientSecret. Invalid tokens will return a 404 Not Found. +

    +

    +The returned Authorization.User field will be populated. +

    +

    +GitHub API docs: https://developer.github.com/v3/oauth_authorizations/#reset-an-authorization +

    + + + + + + +

    func (*AuthorizationsService) Revoke

    +
    func (s *AuthorizationsService) Revoke(clientID string, token string) (*Response, error)
    +

    +Revoke an authorization for an application. +

    +

    +Note that this operation requires the use of BasicAuth, but where the +username is the OAuth application clientID, and the password is its +clientSecret. Invalid tokens will return a 404 Not Found. +

    +

    +GitHub API docs: https://developer.github.com/v3/oauth_authorizations/#revoke-an-authorization-for-an-application +

    + + + + + + + + +

    type BasicAuthTransport

    +
    type BasicAuthTransport struct {
    +    Username string // GitHub username
    +    Password string // GitHub password
    +    OTP      string // one-time password for users with two-factor auth enabled
    +
    +    // Transport is the underlying HTTP transport to use when making requests.
    +    // It will default to http.DefaultTransport if nil.
    +    Transport http.RoundTripper
    +}
    +

    +BasicAuthTransport is an http.RoundTripper that authenticates all requests +using HTTP Basic Authentication with the provided username and password. It +additionally supports users who have two-factor authentication enabled on +their GitHub account. +

    + + + + + + + + + + + + + + +

    func (*BasicAuthTransport) Client

    +
    func (t *BasicAuthTransport) Client() *http.Client
    +

    +Client returns an *http.Client that makes requests that are authenticated +using HTTP Basic Authentication. +

    + + + + + + +

    func (*BasicAuthTransport) RoundTrip

    +
    func (t *BasicAuthTransport) RoundTrip(req *http.Request) (*http.Response, error)
    +

    +RoundTrip implements the RoundTripper interface. +

    + + + + + + + + +

    type Blob

    +
    type Blob struct {
    +    Content  *string `json:"content,omitempty"`
    +    Encoding *string `json:"encoding,omitempty"`
    +    SHA      *string `json:"sha,omitempty"`
    +    Size     *int    `json:"size,omitempty"`
    +    URL      *string `json:"url,omitempty"`
    +}
    +

    +Blob represents a blob object. +

    + + + + + + + + + + + + + + + + +

    type Branch

    +
    type Branch struct {
    +    Name       *string     `json:"name,omitempty"`
    +    Commit     *Commit     `json:"commit,omitempty"`
    +    Protection *Protection `json:"protection,omitempty"`
    +}
    +

    +Branch represents a repository branch +

    + + + + + + + + + + + + + + + + +

    type Client

    +
    type Client struct {
    +
    +    // Base URL for API requests.  Defaults to the public GitHub API, but can be
    +    // set to a domain endpoint to use with GitHub Enterprise.  BaseURL should
    +    // always be specified with a trailing slash.
    +    BaseURL *url.URL
    +
    +    // Base URL for uploading files.
    +    UploadURL *url.URL
    +
    +    // User agent used when communicating with the GitHub API.
    +    UserAgent string
    +
    +    // Services used for talking to different parts of the GitHub API.
    +    Activity       *ActivityService
    +    Authorizations *AuthorizationsService
    +    Gists          *GistsService
    +    Git            *GitService
    +    Gitignores     *GitignoresService
    +    Issues         *IssuesService
    +    Organizations  *OrganizationsService
    +    PullRequests   *PullRequestsService
    +    Repositories   *RepositoriesService
    +    Search         *SearchService
    +    Users          *UsersService
    +    Licenses       *LicensesService
    +    Migrations     *MigrationService
    +    Reactions      *ReactionsService
    +    // contains filtered or unexported fields
    +}
    +

    +A Client manages communication with the GitHub API. +

    + + + + + + + + + + + + +

    func NewClient

    +
    func NewClient(httpClient *http.Client) *Client
    +

    +NewClient returns a new GitHub API client. If a nil httpClient is +provided, http.DefaultClient will be used. To use API methods which require +authentication, provide an http.Client that will perform the authentication +for you (such as that provided by the golang.org/x/oauth2 library). +

    + + + + + + + +

    func (*Client) APIMeta

    +
    func (c *Client) APIMeta() (*APIMeta, *Response, error)
    +

    +APIMeta returns information about GitHub.com, the service. Or, if you access +this endpoint on your organization’s GitHub Enterprise installation, this +endpoint provides information about that installation. +

    +

    +GitHub API docs: https://developer.github.com/v3/meta/ +

    + + + + + + +

    func (*Client) Do

    +
    func (c *Client) Do(req *http.Request, v interface{}) (*Response, error)
    +

    +Do sends an API request and returns the API response. The API response is +JSON decoded and stored in the value pointed to by v, or returned as an +error if an API error has occurred. If v implements the io.Writer +interface, the raw response body will be written to v, without attempting to +first decode it. If rate limit is exceeded and reset time is in the future, +Do returns *RateLimitError immediately without making a network API call. +

    + + + + + + +

    func (*Client) ListEmojis

    +
    func (c *Client) ListEmojis() (map[string]string, *Response, error)
    +

    +ListEmojis returns the emojis available to use on GitHub. +

    +

    +GitHub API docs: https://developer.github.com/v3/emojis/ +

    + + + + + + +

    func (*Client) ListServiceHooks

    +
    func (c *Client) ListServiceHooks() ([]*ServiceHook, *Response, error)
    +

    +ListServiceHooks lists all of the available service hooks. +

    +

    +GitHub API docs: https://developer.github.com/webhooks/#services +

    + + + + + + +

    func (*Client) Markdown

    +
    func (c *Client) Markdown(text string, opt *MarkdownOptions) (string, *Response, error)
    +

    +Markdown renders an arbitrary Markdown document. +

    +

    +GitHub API docs: https://developer.github.com/v3/markdown/ +

    + + +
    + +
    +

    Example

    + + + +

    Code:

    +
    +client := github.NewClient(nil)
    +
    +input := "# heading #\n\nLink to issue #1"
    +opt := &github.MarkdownOptions{Mode: "gfm", Context: "google/go-github"}
    +
    +output, _, err := client.Markdown(input, opt)
    +if err != nil {
    +    fmt.Println(err)
    +}
    +
    +fmt.Println(output)
    +
    + + +
    +
    + + + + +

    func (*Client) NewRequest

    +
    func (c *Client) NewRequest(method, urlStr string, body interface{}) (*http.Request, error)
    +

    +NewRequest creates an API request. A relative URL can be provided in urlStr, +in which case it is resolved relative to the BaseURL of the Client. +Relative URLs should always be specified without a preceding slash. If +specified, the value pointed to by body is JSON encoded and included as the +request body. +

    + + + + + + +

    func (*Client) NewUploadRequest

    +
    func (c *Client) NewUploadRequest(urlStr string, reader io.Reader, size int64, mediaType string) (*http.Request, error)
    +

    +NewUploadRequest creates an upload request. A relative URL can be provided in +urlStr, in which case it is resolved relative to the UploadURL of the Client. +Relative URLs should always be specified without a preceding slash. +

    + + + + + + +

    func (*Client) Octocat

    +
    func (c *Client) Octocat(message string) (string, *Response, error)
    +

    +Octocat returns an ASCII art octocat with the specified message in a speech +bubble. If message is empty, a random zen phrase is used. +

    + + + + + + +

    func (*Client) Rate

    +
    func (c *Client) Rate() Rate
    +

    +Rate specifies the current rate limit for the client as determined by the +most recent API call. If the client is used in a multi-user application, +this rate may not always be up-to-date. +

    +

    +Deprecated: Use the Response.Rate returned from most recent API call instead. +Call RateLimits() to check the current rate. +

    + + + + + + +

    func (*Client) RateLimit

    +
    func (c *Client) RateLimit() (*Rate, *Response, error)
    +

    +Deprecated: RateLimit is deprecated, use RateLimits instead. +

    + + + + + + +

    func (*Client) RateLimits

    +
    func (c *Client) RateLimits() (*RateLimits, *Response, error)
    +

    +RateLimits returns the rate limits for the current client. +

    + + + + + + +

    func (*Client) Zen

    +
    func (c *Client) Zen() (string, *Response, error)
    +

    +Zen returns a random line from The Zen of GitHub. +

    +

    +see also: http://warpspire.com/posts/taste/ +

    + + + + + + + + +

    type CodeResult

    +
    type CodeResult struct {
    +    Name        *string     `json:"name,omitempty"`
    +    Path        *string     `json:"path,omitempty"`
    +    SHA         *string     `json:"sha,omitempty"`
    +    HTMLURL     *string     `json:"html_url,omitempty"`
    +    Repository  *Repository `json:"repository,omitempty"`
    +    TextMatches []TextMatch `json:"text_matches,omitempty"`
    +}
    +

    +CodeResult represents a single search result. +

    + + + + + + + + + + + + + + +

    func (CodeResult) String

    +
    func (c CodeResult) String() string
    + + + + + + + + +

    type CodeSearchResult

    +
    type CodeSearchResult struct {
    +    Total       *int         `json:"total_count,omitempty"`
    +    CodeResults []CodeResult `json:"items,omitempty"`
    +}
    +

    +CodeSearchResult represents the result of an code search. +

    + + + + + + + + + + + + + + + + +

    type CombinedStatus

    +
    type CombinedStatus struct {
    +    // State is the combined state of the repository.  Possible values are:
    +    // failure, pending, or success.
    +    State *string `json:"state,omitempty"`
    +
    +    Name       *string      `json:"name,omitempty"`
    +    SHA        *string      `json:"sha,omitempty"`
    +    TotalCount *int         `json:"total_count,omitempty"`
    +    Statuses   []RepoStatus `json:"statuses,omitempty"`
    +
    +    CommitURL     *string `json:"commit_url,omitempty"`
    +    RepositoryURL *string `json:"repository_url,omitempty"`
    +}
    +

    +CombinedStatus represents the combined status of a repository at a particular reference. +

    + + + + + + + + + + + + + + +

    func (CombinedStatus) String

    +
    func (s CombinedStatus) String() string
    + + + + + + + + +

    type Commit

    +
    type Commit struct {
    +    SHA          *string                `json:"sha,omitempty"`
    +    Author       *CommitAuthor          `json:"author,omitempty"`
    +    Committer    *CommitAuthor          `json:"committer,omitempty"`
    +    Message      *string                `json:"message,omitempty"`
    +    Tree         *Tree                  `json:"tree,omitempty"`
    +    Parents      []Commit               `json:"parents,omitempty"`
    +    Stats        *CommitStats           `json:"stats,omitempty"`
    +    URL          *string                `json:"url,omitempty"`
    +    Verification *SignatureVerification `json:"verification,omitempty"`
    +
    +    // CommentCount is the number of GitHub comments on the commit.  This
    +    // is only populated for requests that fetch GitHub data like
    +    // Pulls.ListCommits, Repositories.ListCommits, etc.
    +    CommentCount *int `json:"comment_count,omitempty"`
    +}
    +

    +Commit represents a GitHub commit. +

    + + + + + + + + + + + + + + +

    func (Commit) String

    +
    func (c Commit) String() string
    + + + + + + + + +

    type CommitAuthor

    +
    type CommitAuthor struct {
    +    Date  *time.Time `json:"date,omitempty"`
    +    Name  *string    `json:"name,omitempty"`
    +    Email *string    `json:"email,omitempty"`
    +
    +    // The following fields are only populated by Webhook events.
    +    Login *string `json:"username,omitempty"` // Renamed for go-github consistency.
    +}
    +

    +CommitAuthor represents the author or committer of a commit. The commit +author may not correspond to a GitHub User. +

    + + + + + + + + + + + + + + +

    func (CommitAuthor) String

    +
    func (c CommitAuthor) String() string
    + + + + + + + + +

    type CommitCommentEvent

    +
    type CommitCommentEvent struct {
    +    Comment *RepositoryComment `json:"comment,omitempty"`
    +
    +    // The following fields are only populated by Webhook events.
    +    Action *string     `json:"action,omitempty"`
    +    Repo   *Repository `json:"repository,omitempty"`
    +    Sender *User       `json:"sender,omitempty"`
    +}
    +

    +CommitCommentEvent is triggered when a commit comment is created. +The Webhook event name is "commit_comment". +

    +

    +GitHub docs: https://developer.github.com/v3/activity/events/types/#commitcommentevent +

    + + + + + + + + + + + + + + + + +

    type CommitFile

    +
    type CommitFile struct {
    +    SHA       *string `json:"sha,omitempty"`
    +    Filename  *string `json:"filename,omitempty"`
    +    Additions *int    `json:"additions,omitempty"`
    +    Deletions *int    `json:"deletions,omitempty"`
    +    Changes   *int    `json:"changes,omitempty"`
    +    Status    *string `json:"status,omitempty"`
    +    Patch     *string `json:"patch,omitempty"`
    +}
    +

    +CommitFile represents a file modified in a commit. +

    + + + + + + + + + + + + + + +

    func (CommitFile) String

    +
    func (c CommitFile) String() string
    + + + + + + + + +

    type CommitStats

    +
    type CommitStats struct {
    +    Additions *int `json:"additions,omitempty"`
    +    Deletions *int `json:"deletions,omitempty"`
    +    Total     *int `json:"total,omitempty"`
    +}
    +

    +CommitStats represents the number of additions / deletions from a file in a given RepositoryCommit or GistCommit. +

    + + + + + + + + + + + + + + +

    func (CommitStats) String

    +
    func (c CommitStats) String() string
    + + + + + + + + +

    type CommitsComparison

    +
    type CommitsComparison struct {
    +    BaseCommit      *RepositoryCommit `json:"base_commit,omitempty"`
    +    MergeBaseCommit *RepositoryCommit `json:"merge_base_commit,omitempty"`
    +
    +    // Head can be 'behind' or 'ahead'
    +    Status       *string `json:"status,omitempty"`
    +    AheadBy      *int    `json:"ahead_by,omitempty"`
    +    BehindBy     *int    `json:"behind_by,omitempty"`
    +    TotalCommits *int    `json:"total_commits,omitempty"`
    +
    +    Commits []RepositoryCommit `json:"commits,omitempty"`
    +
    +    Files []CommitFile `json:"files,omitempty"`
    +}
    +

    +CommitsComparison is the result of comparing two commits. +See CompareCommits() for details. +

    + + + + + + + + + + + + + + +

    func (CommitsComparison) String

    +
    func (c CommitsComparison) String() string
    + + + + + + + + +

    type CommitsListOptions

    +
    type CommitsListOptions struct {
    +    // SHA or branch to start listing Commits from.
    +    SHA string `url:"sha,omitempty"`
    +
    +    // Path that should be touched by the returned Commits.
    +    Path string `url:"path,omitempty"`
    +
    +    // Author of by which to filter Commits.
    +    Author string `url:"author,omitempty"`
    +
    +    // Since when should Commits be included in the response.
    +    Since time.Time `url:"since,omitempty"`
    +
    +    // Until when should Commits be included in the response.
    +    Until time.Time `url:"until,omitempty"`
    +
    +    ListOptions
    +}
    +

    +CommitsListOptions specifies the optional parameters to the +RepositoriesService.ListCommits method. +

    + + + + + + + + + + + + + + + + +

    type Contributor

    +
    type Contributor struct {
    +    Login             *string `json:"login,omitempty"`
    +    ID                *int    `json:"id,omitempty"`
    +    AvatarURL         *string `json:"avatar_url,omitempty"`
    +    GravatarID        *string `json:"gravatar_id,omitempty"`
    +    URL               *string `json:"url,omitempty"`
    +    HTMLURL           *string `json:"html_url,omitempty"`
    +    FollowersURL      *string `json:"followers_url,omitempty"`
    +    FollowingURL      *string `json:"following_url,omitempty"`
    +    GistsURL          *string `json:"gists_url,omitempty"`
    +    StarredURL        *string `json:"starred_url,omitempty"`
    +    SubscriptionsURL  *string `json:"subscriptions_url,omitempty"`
    +    OrganizationsURL  *string `json:"organizations_url,omitempty"`
    +    ReposURL          *string `json:"repos_url,omitempty"`
    +    EventsURL         *string `json:"events_url,omitempty"`
    +    ReceivedEventsURL *string `json:"received_events_url,omitempty"`
    +    Type              *string `json:"type,omitempty"`
    +    SiteAdmin         *bool   `json:"site_admin"`
    +    Contributions     *int    `json:"contributions,omitempty"`
    +}
    +

    +Contributor represents a repository contributor +

    + + + + + + + + + + + + + + + + +

    type ContributorStats

    +
    type ContributorStats struct {
    +    Author *Contributor  `json:"author,omitempty"`
    +    Total  *int          `json:"total,omitempty"`
    +    Weeks  []WeeklyStats `json:"weeks,omitempty"`
    +}
    +

    +ContributorStats represents a contributor to a repository and their +weekly contributions to a given repo. +

    + + + + + + + + + + + + + + +

    func (ContributorStats) String

    +
    func (c ContributorStats) String() string
    + + + + + + + + +

    type CreateEvent

    +
    type CreateEvent struct {
    +    Ref *string `json:"ref,omitempty"`
    +    // RefType is the object that was created. Possible values are: "repository", "branch", "tag".
    +    RefType      *string `json:"ref_type,omitempty"`
    +    MasterBranch *string `json:"master_branch,omitempty"`
    +    Description  *string `json:"description,omitempty"`
    +
    +    // The following fields are only populated by Webhook events.
    +    PusherType *string     `json:"pusher_type,omitempty"`
    +    Repo       *Repository `json:"repository,omitempty"`
    +    Sender     *User       `json:"sender,omitempty"`
    +}
    +

    +CreateEvent represents a created repository, branch, or tag. +The Webhook event name is "create". +

    +

    +Note: webhooks will not receive this event for created repositories. +Additionally, webhooks will not receive this event for tags if more +than three tags are pushed at once. +

    +

    +GitHub docs: https://developer.github.com/v3/activity/events/types/#createevent +

    + + + + + + + + + + + + + + + + +

    type DeleteEvent

    +
    type DeleteEvent struct {
    +    Ref *string `json:"ref,omitempty"`
    +    // RefType is the object that was deleted. Possible values are: "branch", "tag".
    +    RefType *string `json:"ref_type,omitempty"`
    +
    +    // The following fields are only populated by Webhook events.
    +    PusherType *string     `json:"pusher_type,omitempty"`
    +    Repo       *Repository `json:"repository,omitempty"`
    +    Sender     *User       `json:"sender,omitempty"`
    +}
    +

    +DeleteEvent represents a deleted branch or tag. +The Webhook event name is "delete". +

    +

    +Note: webhooks will not receive this event for tags if more than three tags +are deleted at once. +

    +

    +GitHub docs: https://developer.github.com/v3/activity/events/types/#deleteevent +

    + + + + + + + + + + + + + + + + +

    type Deployment

    +
    type Deployment struct {
    +    URL           *string         `json:"url,omitempty"`
    +    ID            *int            `json:"id,omitempty"`
    +    SHA           *string         `json:"sha,omitempty"`
    +    Ref           *string         `json:"ref,omitempty"`
    +    Task          *string         `json:"task,omitempty"`
    +    Payload       json.RawMessage `json:"payload,omitempty"`
    +    Environment   *string         `json:"environment,omitempty"`
    +    Description   *string         `json:"description,omitempty"`
    +    Creator       *User           `json:"creator,omitempty"`
    +    CreatedAt     *Timestamp      `json:"created_at,omitempty"`
    +    UpdatedAt     *Timestamp      `json:"pushed_at,omitempty"`
    +    StatusesURL   *string         `json:"statuses_url,omitempty"`
    +    RepositoryURL *string         `json:"repository_url,omitempty"`
    +}
    +

    +Deployment represents a deployment in a repo +

    + + + + + + + + + + + + + + + + +

    type DeploymentEvent

    +
    type DeploymentEvent struct {
    +    Deployment *Deployment `json:"deployment,omitempty"`
    +    Repo       *Repository `json:"repository,omitempty"`
    +
    +    // The following fields are only populated by Webhook events.
    +    Sender *User `json:"sender,omitempty"`
    +}
    +

    +DeploymentEvent represents a deployment. +The Webhook event name is "deployment". +

    +

    +Events of this type are not visible in timelines, they are only used to trigger hooks. +

    +

    +GitHub docs: https://developer.github.com/v3/activity/events/types/#deploymentevent +

    + + + + + + + + + + + + + + + + +

    type DeploymentRequest

    +
    type DeploymentRequest struct {
    +    Ref                   *string   `json:"ref,omitempty"`
    +    Task                  *string   `json:"task,omitempty"`
    +    AutoMerge             *bool     `json:"auto_merge,omitempty"`
    +    RequiredContexts      *[]string `json:"required_contexts,omitempty"`
    +    Payload               *string   `json:"payload,omitempty"`
    +    Environment           *string   `json:"environment,omitempty"`
    +    Description           *string   `json:"description,omitempty"`
    +    TransientEnvironment  *bool     `json:"transient_environment,omitempty"`
    +    ProductionEnvironment *bool     `json:"production_environment,omitempty"`
    +}
    +

    +DeploymentRequest represents a deployment request +

    + + + + + + + + + + + + + + + + +

    type DeploymentStatus

    +
    type DeploymentStatus struct {
    +    ID *int `json:"id,omitempty"`
    +    // State is the deployment state.
    +    // Possible values are: "pending", "success", "failure", "error", "inactive".
    +    State         *string    `json:"state,omitempty"`
    +    Creator       *User      `json:"creator,omitempty"`
    +    Description   *string    `json:"description,omitempty"`
    +    TargetURL     *string    `json:"target_url,omitempty"`
    +    CreatedAt     *Timestamp `json:"created_at,omitempty"`
    +    UpdatedAt     *Timestamp `json:"pushed_at,omitempty"`
    +    DeploymentURL *string    `json:"deployment_url,omitempty"`
    +    RepositoryURL *string    `json:"repository_url,omitempty"`
    +}
    +

    +DeploymentStatus represents the status of a +particular deployment. +

    + + + + + + + + + + + + + + + + +

    type DeploymentStatusEvent

    +
    type DeploymentStatusEvent struct {
    +    Deployment       *Deployment       `json:"deployment,omitempty"`
    +    DeploymentStatus *DeploymentStatus `json:"deployment_status,omitempty"`
    +    Repo             *Repository       `json:"repository,omitempty"`
    +
    +    // The following fields are only populated by Webhook events.
    +    Sender *User `json:"sender,omitempty"`
    +}
    +

    +DeploymentStatusEvent represents a deployment status. +The Webhook event name is "deployment_status". +

    +

    +Events of this type are not visible in timelines, they are only used to trigger hooks. +

    +

    +GitHub docs: https://developer.github.com/v3/activity/events/types/#deploymentstatusevent +

    + + + + + + + + + + + + + + + + +

    type DeploymentStatusRequest

    +
    type DeploymentStatusRequest struct {
    +    State          *string `json:"state,omitempty"`
    +    TargetURL      *string `json:"target_url,omitempty"` // Deprecated. Use LogURL instead.
    +    LogURL         *string `json:"log_url,omitempty"`
    +    Description    *string `json:"description,omitempty"`
    +    EnvironmentURL *string `json:"environment_url,omitempty"`
    +    AutoInactive   *bool   `json:"auto_inactive,omitempty"`
    +}
    +

    +DeploymentStatusRequest represents a deployment request +

    + + + + + + + + + + + + + + + + +

    type DeploymentsListOptions

    +
    type DeploymentsListOptions struct {
    +    // SHA of the Deployment.
    +    SHA string `url:"sha,omitempty"`
    +
    +    // List deployments for a given ref.
    +    Ref string `url:"ref,omitempty"`
    +
    +    // List deployments for a given task.
    +    Task string `url:"task,omitempty"`
    +
    +    // List deployments for a given environment.
    +    Environment string `url:"environment,omitempty"`
    +
    +    ListOptions
    +}
    +

    +DeploymentsListOptions specifies the optional parameters to the +RepositoriesService.ListDeployments method. +

    + + + + + + + + + + + + + + + + +

    type EditChange

    +
    type EditChange struct {
    +    Title *struct {
    +        From *string `json:"from,omitempty"`
    +    } `json:"title,omitempty"`
    +    Body *struct {
    +        From *string `json:"from,omitempty"`
    +    } `json:"body,omitempty"`
    +}
    +

    +EditChange represents the changes when an issue, pull request, or comment has +been edited. +

    + + + + + + + + + + + + + + + + +

    type Error

    +
    type Error struct {
    +    Resource string `json:"resource"` // resource on which the error occurred
    +    Field    string `json:"field"`    // field on which the error occurred
    +    Code     string `json:"code"`     // validation error code
    +    Message  string `json:"message"`  // Message describing the error. Errors with Code == "custom" will always have this set.
    +}
    +

    +An Error reports more details on an individual error in an ErrorResponse. +These are the possible validation error codes: +

    +
    missing:
    +    resource does not exist
    +missing_field:
    +    a required field on a resource has not been set
    +invalid:
    +    the formatting of a field is invalid
    +already_exists:
    +    another resource has the same valid as this field
    +custom:
    +    some resources return this (e.g. github.User.CreateKey()), additional
    +    information is set in the Message field of the Error
    +
    +

    +GitHub API docs: http://developer.github.com/v3/#client-errors +

    + + + + + + + + + + + + + + +

    func (*Error) Error

    +
    func (e *Error) Error() string
    + + + + + + + + +

    type ErrorResponse

    +
    type ErrorResponse struct {
    +    Response *http.Response // HTTP response that caused this error
    +    Message  string         `json:"message"` // error message
    +    Errors   []Error        `json:"errors"`  // more detail on individual errors
    +    // Block is only populated on certain types of errors such as code 451.
    +    // See https://developer.github.com/changes/2016-03-17-the-451-status-code-is-now-supported/
    +    // for more information.
    +    Block *struct {
    +        Reason    string     `json:"reason,omitempty"`
    +        CreatedAt *Timestamp `json:"created_at,omitempty"`
    +    } `json:"block,omitempty"`
    +    // Most errors will also include a documentation_url field pointing
    +    // to some content that might help you resolve the error, see
    +    // https://developer.github.com/v3/#client-errors
    +    DocumentationURL string `json:"documentation_url,omitempty"`
    +}
    +

    +An ErrorResponse reports one or more errors caused by an API request. +

    +

    +GitHub API docs: http://developer.github.com/v3/#client-errors +

    + + + + + + + + + + + + + + +

    func (*ErrorResponse) Error

    +
    func (r *ErrorResponse) Error() string
    + + + + + + + + +

    type Event

    +
    type Event struct {
    +    Type       *string          `json:"type,omitempty"`
    +    Public     *bool            `json:"public"`
    +    RawPayload *json.RawMessage `json:"payload,omitempty"`
    +    Repo       *Repository      `json:"repo,omitempty"`
    +    Actor      *User            `json:"actor,omitempty"`
    +    Org        *Organization    `json:"org,omitempty"`
    +    CreatedAt  *time.Time       `json:"created_at,omitempty"`
    +    ID         *string          `json:"id,omitempty"`
    +}
    +

    +Event represents a GitHub event. +

    + + + + + + + + + + + + + + +

    func (*Event) Payload

    +
    func (e *Event) Payload() (payload interface{})
    +

    +Payload returns the parsed event payload. For recognized event types, +a value of the corresponding struct type will be returned. +

    + + + + + + +

    func (Event) String

    +
    func (e Event) String() string
    + + + + + + + + + +
    type FeedLink struct {
    +    HRef *string `json:"href,omitempty"`
    +    Type *string `json:"type,omitempty"`
    +}
    +

    +FeedLink represents a link to a related resource. +

    + + + + + + + + + + + + + + + + +

    type Feeds

    +
    type Feeds struct {
    +    TimelineURL                 *string  `json:"timeline_url,omitempty"`
    +    UserURL                     *string  `json:"user_url,omitempty"`
    +    CurrentUserPublicURL        *string  `json:"current_user_public_url,omitempty"`
    +    CurrentUserURL              *string  `json:"current_user_url,omitempty"`
    +    CurrentUserActorURL         *string  `json:"current_user_actor_url,omitempty"`
    +    CurrentUserOrganizationURL  *string  `json:"current_user_organization_url,omitempty"`
    +    CurrentUserOrganizationURLs []string `json:"current_user_organization_urls,omitempty"`
    +    Links                       *struct {
    +        Timeline                 *FeedLink  `json:"timeline,omitempty"`
    +        User                     *FeedLink  `json:"user,omitempty"`
    +        CurrentUserPublic        *FeedLink  `json:"current_user_public,omitempty"`
    +        CurrentUser              *FeedLink  `json:"current_user,omitempty"`
    +        CurrentUserActor         *FeedLink  `json:"current_user_actor,omitempty"`
    +        CurrentUserOrganization  *FeedLink  `json:"current_user_organization,omitempty"`
    +        CurrentUserOrganizations []FeedLink `json:"current_user_organizations,omitempty"`
    +    } `json:"_links,omitempty"`
    +}
    +

    +Feeds represents timeline resources in Atom format. +

    + + + + + + + + + + + + + + + + +

    type ForkEvent

    +
    type ForkEvent struct {
    +    // Forkee is the created repository.
    +    Forkee *Repository `json:"forkee,omitempty"`
    +
    +    // The following fields are only populated by Webhook events.
    +    Repo   *Repository `json:"repository,omitempty"`
    +    Sender *User       `json:"sender,omitempty"`
    +}
    +

    +ForkEvent is triggered when a user forks a repository. +The Webhook event name is "fork". +

    +

    +GitHub docs: https://developer.github.com/v3/activity/events/types/#forkevent +

    + + + + + + + + + + + + + + + + +

    type GPGEmail

    +
    type GPGEmail struct {
    +    Email    *string `json:"email,omitempty"`
    +    Verified *bool   `json:"verified,omitempty"`
    +}
    +

    +GPGEmail represents an email address associated to a GPG key. +

    + + + + + + + + + + + + + + + + +

    type GPGKey

    +
    type GPGKey struct {
    +    ID                *int       `json:"id,omitempty"`
    +    PrimaryKeyID      *int       `json:"primary_key_id,omitempty"`
    +    KeyID             *string    `json:"key_id,omitempty"`
    +    PublicKey         *string    `json:"public_key,omitempty"`
    +    Emails            []GPGEmail `json:"emails,omitempty"`
    +    Subkeys           []GPGKey   `json:"subkeys,omitempty"`
    +    CanSign           *bool      `json:"can_sign,omitempty"`
    +    CanEncryptComms   *bool      `json:"can_encrypt_comms,omitempty"`
    +    CanEncryptStorage *bool      `json:"can_encrypt_storage,omitempty"`
    +    CanCertify        *bool      `json:"can_certify,omitempty"`
    +    CreatedAt         *time.Time `json:"created_at,omitempty"`
    +    ExpiresAt         *time.Time `json:"expires_at,omitempty"`
    +}
    +

    +GPGKey represents a GitHub user's public GPG key used to verify GPG signed commits and tags. +

    +

    +https://developer.github.com/changes/2016-04-04-git-signing-api-preview/ +

    + + + + + + + + + + + + + + +

    func (GPGKey) String

    +
    func (k GPGKey) String() string
    +

    +String stringifies a GPGKey. +

    + + + + + + + + +

    type Gist

    +
    type Gist struct {
    +    ID          *string                   `json:"id,omitempty"`
    +    Description *string                   `json:"description,omitempty"`
    +    Public      *bool                     `json:"public,omitempty"`
    +    Owner       *User                     `json:"owner,omitempty"`
    +    Files       map[GistFilename]GistFile `json:"files,omitempty"`
    +    Comments    *int                      `json:"comments,omitempty"`
    +    HTMLURL     *string                   `json:"html_url,omitempty"`
    +    GitPullURL  *string                   `json:"git_pull_url,omitempty"`
    +    GitPushURL  *string                   `json:"git_push_url,omitempty"`
    +    CreatedAt   *time.Time                `json:"created_at,omitempty"`
    +    UpdatedAt   *time.Time                `json:"updated_at,omitempty"`
    +}
    +

    +Gist represents a GitHub's gist. +

    + + + + + + + + + + + + + + +

    func (Gist) String

    +
    func (g Gist) String() string
    + + + + + + + + +

    type GistComment

    +
    type GistComment struct {
    +    ID        *int       `json:"id,omitempty"`
    +    URL       *string    `json:"url,omitempty"`
    +    Body      *string    `json:"body,omitempty"`
    +    User      *User      `json:"user,omitempty"`
    +    CreatedAt *time.Time `json:"created_at,omitempty"`
    +}
    +

    +GistComment represents a Gist comment. +

    + + + + + + + + + + + + + + +

    func (GistComment) String

    +
    func (g GistComment) String() string
    + + + + + + + + +

    type GistCommit

    +
    type GistCommit struct {
    +    URL          *string      `json:"url,omitempty"`
    +    Version      *string      `json:"version,omitempty"`
    +    User         *User        `json:"user,omitempty"`
    +    ChangeStatus *CommitStats `json:"change_status,omitempty"`
    +    CommitedAt   *Timestamp   `json:"commited_at,omitempty"`
    +}
    +

    +GistCommit represents a commit on a gist. +

    + + + + + + + + + + + + + + +

    func (GistCommit) String

    +
    func (gc GistCommit) String() string
    + + + + + + + + +

    type GistFile

    +
    type GistFile struct {
    +    Size     *int    `json:"size,omitempty"`
    +    Filename *string `json:"filename,omitempty"`
    +    RawURL   *string `json:"raw_url,omitempty"`
    +    Content  *string `json:"content,omitempty"`
    +}
    +

    +GistFile represents a file on a gist. +

    + + + + + + + + + + + + + + +

    func (GistFile) String

    +
    func (g GistFile) String() string
    + + + + + + + + +

    type GistFilename

    +
    type GistFilename string
    +

    +GistFilename represents filename on a gist. +

    + + + + + + + + + + + + + + + + +

    type GistFork

    +
    type GistFork struct {
    +    URL       *string    `json:"url,omitempty"`
    +    User      *User      `json:"user,omitempty"`
    +    ID        *string    `json:"id,omitempty"`
    +    CreatedAt *Timestamp `json:"created_at,omitempty"`
    +    UpdatedAt *Timestamp `json:"updated_at,omitempty"`
    +}
    +

    +GistFork represents a fork of a gist. +

    + + + + + + + + + + + + + + +

    func (GistFork) String

    +
    func (gf GistFork) String() string
    + + + + + + + + +

    type GistListOptions

    +
    type GistListOptions struct {
    +    // Since filters Gists by time.
    +    Since time.Time `url:"since,omitempty"`
    +
    +    ListOptions
    +}
    +

    +GistListOptions specifies the optional parameters to the +GistsService.List, GistsService.ListAll, and GistsService.ListStarred methods. +

    + + + + + + + + + + + + + + + + +

    type GistsService

    +
    type GistsService service
    +

    +GistsService handles communication with the Gist related +methods of the GitHub API. +

    +

    +GitHub API docs: http://developer.github.com/v3/gists/ +

    + + + + + + + + + + + + + + +

    func (*GistsService) Create

    +
    func (s *GistsService) Create(gist *Gist) (*Gist, *Response, error)
    +

    +Create a gist for authenticated user. +

    +

    +GitHub API docs: http://developer.github.com/v3/gists/#create-a-gist +

    + + + + + + +

    func (*GistsService) CreateComment

    +
    func (s *GistsService) CreateComment(gistID string, comment *GistComment) (*GistComment, *Response, error)
    +

    +CreateComment creates a comment for a gist. +

    +

    +GitHub API docs: http://developer.github.com/v3/gists/comments/#create-a-comment +

    + + + + + + +

    func (*GistsService) Delete

    +
    func (s *GistsService) Delete(id string) (*Response, error)
    +

    +Delete a gist. +

    +

    +GitHub API docs: http://developer.github.com/v3/gists/#delete-a-gist +

    + + + + + + +

    func (*GistsService) DeleteComment

    +
    func (s *GistsService) DeleteComment(gistID string, commentID int) (*Response, error)
    +

    +DeleteComment deletes a gist comment. +

    +

    +GitHub API docs: http://developer.github.com/v3/gists/comments/#delete-a-comment +

    + + + + + + +

    func (*GistsService) Edit

    +
    func (s *GistsService) Edit(id string, gist *Gist) (*Gist, *Response, error)
    +

    +Edit a gist. +

    +

    +GitHub API docs: http://developer.github.com/v3/gists/#edit-a-gist +

    + + + + + + +

    func (*GistsService) EditComment

    +
    func (s *GistsService) EditComment(gistID string, commentID int, comment *GistComment) (*GistComment, *Response, error)
    +

    +EditComment edits an existing gist comment. +

    +

    +GitHub API docs: http://developer.github.com/v3/gists/comments/#edit-a-comment +

    + + + + + + +

    func (*GistsService) Fork

    +
    func (s *GistsService) Fork(id string) (*Gist, *Response, error)
    +

    +Fork a gist. +

    +

    +GitHub API docs: http://developer.github.com/v3/gists/#fork-a-gist +

    + + + + + + +

    func (*GistsService) Get

    +
    func (s *GistsService) Get(id string) (*Gist, *Response, error)
    +

    +Get a single gist. +

    +

    +GitHub API docs: http://developer.github.com/v3/gists/#get-a-single-gist +

    + + + + + + +

    func (*GistsService) GetComment

    +
    func (s *GistsService) GetComment(gistID string, commentID int) (*GistComment, *Response, error)
    +

    +GetComment retrieves a single comment from a gist. +

    +

    +GitHub API docs: http://developer.github.com/v3/gists/comments/#get-a-single-comment +

    + + + + + + +

    func (*GistsService) GetRevision

    +
    func (s *GistsService) GetRevision(id, sha string) (*Gist, *Response, error)
    +

    +GetRevision gets a specific revision of a gist. +

    +

    +GitHub API docs: https://developer.github.com/v3/gists/#get-a-specific-revision-of-a-gist +

    + + + + + + +

    func (*GistsService) IsStarred

    +
    func (s *GistsService) IsStarred(id string) (bool, *Response, error)
    +

    +IsStarred checks if a gist is starred by authenticated user. +

    +

    +GitHub API docs: http://developer.github.com/v3/gists/#check-if-a-gist-is-starred +

    + + + + + + +

    func (*GistsService) List

    +
    func (s *GistsService) List(user string, opt *GistListOptions) ([]*Gist, *Response, error)
    +

    +List gists for a user. Passing the empty string will list +all public gists if called anonymously. However, if the call +is authenticated, it will returns all gists for the authenticated +user. +

    +

    +GitHub API docs: http://developer.github.com/v3/gists/#list-gists +

    + + + + + + +

    func (*GistsService) ListAll

    +
    func (s *GistsService) ListAll(opt *GistListOptions) ([]*Gist, *Response, error)
    +

    +ListAll lists all public gists. +

    +

    +GitHub API docs: http://developer.github.com/v3/gists/#list-gists +

    + + + + + + +

    func (*GistsService) ListComments

    +
    func (s *GistsService) ListComments(gistID string, opt *ListOptions) ([]*GistComment, *Response, error)
    +

    +ListComments lists all comments for a gist. +

    +

    +GitHub API docs: http://developer.github.com/v3/gists/comments/#list-comments-on-a-gist +

    + + + + + + +

    func (*GistsService) ListCommits

    +
    func (s *GistsService) ListCommits(id string) ([]*GistCommit, *Response, error)
    +

    +ListCommits lists commits of a gist. +

    +

    +Github API docs: https://developer.github.com/v3/gists/#list-gist-commits +

    + + + + + + +

    func (*GistsService) ListForks

    +
    func (s *GistsService) ListForks(id string) ([]*GistFork, *Response, error)
    +

    +ListForks lists forks of a gist. +

    +

    +Github API docs: https://developer.github.com/v3/gists/#list-gist-forks +

    + + + + + + +

    func (*GistsService) ListStarred

    +
    func (s *GistsService) ListStarred(opt *GistListOptions) ([]*Gist, *Response, error)
    +

    +ListStarred lists starred gists of authenticated user. +

    +

    +GitHub API docs: http://developer.github.com/v3/gists/#list-gists +

    + + + + + + +

    func (*GistsService) Star

    +
    func (s *GistsService) Star(id string) (*Response, error)
    +

    +Star a gist on behalf of authenticated user. +

    +

    +GitHub API docs: http://developer.github.com/v3/gists/#star-a-gist +

    + + + + + + +

    func (*GistsService) Unstar

    +
    func (s *GistsService) Unstar(id string) (*Response, error)
    +

    +Unstar a gist on a behalf of authenticated user. +

    +

    +Github API docs: http://developer.github.com/v3/gists/#unstar-a-gist +

    + + + + + + + + +

    type GitObject

    +
    type GitObject struct {
    +    Type *string `json:"type"`
    +    SHA  *string `json:"sha"`
    +    URL  *string `json:"url"`
    +}
    +

    +GitObject represents a Git object. +

    + + + + + + + + + + + + + + +

    func (GitObject) String

    +
    func (o GitObject) String() string
    + + + + + + + + +

    type GitService

    +
    type GitService service
    +

    +GitService handles communication with the git data related +methods of the GitHub API. +

    +

    +GitHub API docs: http://developer.github.com/v3/git/ +

    + + + + + + + + + + + + + + +

    func (*GitService) CreateBlob

    +
    func (s *GitService) CreateBlob(owner string, repo string, blob *Blob) (*Blob, *Response, error)
    +

    +CreateBlob creates a blob object. +

    +

    +GitHub API docs: https://developer.github.com/v3/git/blobs/#create-a-blob +

    + + + + + + +

    func (*GitService) CreateCommit

    +
    func (s *GitService) CreateCommit(owner string, repo string, commit *Commit) (*Commit, *Response, error)
    +

    +CreateCommit creates a new commit in a repository. +

    +

    +The commit.Committer is optional and will be filled with the commit.Author +data if omitted. If the commit.Author is omitted, it will be filled in with +the authenticated user’s information and the current date. +

    +

    +GitHub API docs: http://developer.github.com/v3/git/commits/#create-a-commit +

    + + + + + + +

    func (*GitService) CreateRef

    +
    func (s *GitService) CreateRef(owner string, repo string, ref *Reference) (*Reference, *Response, error)
    +

    +CreateRef creates a new ref in a repository. +

    +

    +GitHub API docs: http://developer.github.com/v3/git/refs/#create-a-reference +

    + + + + + + +

    func (*GitService) CreateTag

    +
    func (s *GitService) CreateTag(owner string, repo string, tag *Tag) (*Tag, *Response, error)
    +

    +CreateTag creates a tag object. +

    +

    +GitHub API docs: http://developer.github.com/v3/git/tags/#create-a-tag-object +

    + + + + + + +

    func (*GitService) CreateTree

    +
    func (s *GitService) CreateTree(owner string, repo string, baseTree string, entries []TreeEntry) (*Tree, *Response, error)
    +

    +CreateTree creates a new tree in a repository. If both a tree and a nested +path modifying that tree are specified, it will overwrite the contents of +that tree with the new path contents and write a new tree out. +

    +

    +GitHub API docs: http://developer.github.com/v3/git/trees/#create-a-tree +

    + + + + + + +

    func (*GitService) DeleteRef

    +
    func (s *GitService) DeleteRef(owner string, repo string, ref string) (*Response, error)
    +

    +DeleteRef deletes a ref from a repository. +

    +

    +GitHub API docs: http://developer.github.com/v3/git/refs/#delete-a-reference +

    + + + + + + +

    func (*GitService) GetBlob

    +
    func (s *GitService) GetBlob(owner string, repo string, sha string) (*Blob, *Response, error)
    +

    +GetBlob fetchs a blob from a repo given a SHA. +

    +

    +GitHub API docs: http://developer.github.com/v3/git/blobs/#get-a-blob +

    + + + + + + +

    func (*GitService) GetCommit

    +
    func (s *GitService) GetCommit(owner string, repo string, sha string) (*Commit, *Response, error)
    +

    +GetCommit fetchs the Commit object for a given SHA. +

    +

    +GitHub API docs: http://developer.github.com/v3/git/commits/#get-a-commit +

    + + + + + + +

    func (*GitService) GetRef

    +
    func (s *GitService) GetRef(owner string, repo string, ref string) (*Reference, *Response, error)
    +

    +GetRef fetches the Reference object for a given Git ref. +

    +

    +GitHub API docs: http://developer.github.com/v3/git/refs/#get-a-reference +

    + + + + + + +

    func (*GitService) GetTag

    +
    func (s *GitService) GetTag(owner string, repo string, sha string) (*Tag, *Response, error)
    +

    +GetTag fetchs a tag from a repo given a SHA. +

    +

    +GitHub API docs: http://developer.github.com/v3/git/tags/#get-a-tag +

    + + + + + + +

    func (*GitService) GetTree

    +
    func (s *GitService) GetTree(owner string, repo string, sha string, recursive bool) (*Tree, *Response, error)
    +

    +GetTree fetches the Tree object for a given sha hash from a repository. +

    +

    +GitHub API docs: http://developer.github.com/v3/git/trees/#get-a-tree +

    + + + + + + +

    func (*GitService) ListRefs

    +
    func (s *GitService) ListRefs(owner, repo string, opt *ReferenceListOptions) ([]*Reference, *Response, error)
    +

    +ListRefs lists all refs in a repository. +

    +

    +GitHub API docs: http://developer.github.com/v3/git/refs/#get-all-references +

    + + + + + + +

    func (*GitService) UpdateRef

    +
    func (s *GitService) UpdateRef(owner string, repo string, ref *Reference, force bool) (*Reference, *Response, error)
    +

    +UpdateRef updates an existing ref in a repository. +

    +

    +GitHub API docs: http://developer.github.com/v3/git/refs/#update-a-reference +

    + + + + + + + + +

    type Gitignore

    +
    type Gitignore struct {
    +    Name   *string `json:"name,omitempty"`
    +    Source *string `json:"source,omitempty"`
    +}
    +

    +Gitignore represents a .gitignore file as returned by the GitHub API. +

    + + + + + + + + + + + + + + +

    func (Gitignore) String

    +
    func (g Gitignore) String() string
    + + + + + + + + +

    type GitignoresService

    +
    type GitignoresService service
    +

    +GitignoresService provides access to the gitignore related functions in the +GitHub API. +

    +

    +GitHub API docs: http://developer.github.com/v3/gitignore/ +

    + + + + + + + + + + + + + + +

    func (GitignoresService) Get

    +
    func (s GitignoresService) Get(name string) (*Gitignore, *Response, error)
    +

    +Get a Gitignore by name. +

    +

    +http://developer.github.com/v3/gitignore/#get-a-single-template +

    + + + + + + +

    func (GitignoresService) List

    +
    func (s GitignoresService) List() ([]string, *Response, error)
    +

    +List all available Gitignore templates. +

    +

    +http://developer.github.com/v3/gitignore/#listing-available-templates +

    + + + + + + + + +

    type GollumEvent

    +
    type GollumEvent struct {
    +    Pages []*Page `json:"pages,omitempty"`
    +
    +    // The following fields are only populated by Webhook events.
    +    Repo   *Repository `json:"repository,omitempty"`
    +    Sender *User       `json:"sender,omitempty"`
    +}
    +

    +GollumEvent is triggered when a Wiki page is created or updated. +The Webhook event name is "gollum". +

    +

    +GitHub docs: https://developer.github.com/v3/activity/events/types/#gollumevent +

    + + + + + + + + + + + + + + + + +

    type Grant

    +
    type Grant struct {
    +    ID        *int              `json:"id,omitempty"`
    +    URL       *string           `json:"url,omitempty"`
    +    App       *AuthorizationApp `json:"app,omitempty"`
    +    CreatedAt *Timestamp        `json:"created_at,omitempty"`
    +    UpdatedAt *Timestamp        `json:"updated_at,omitempty"`
    +    Scopes    []string          `json:"scopes,omitempty"`
    +}
    +

    +Grant represents an OAuth application that has been granted access to an account. +

    + + + + + + + + + + + + + + +

    func (Grant) String

    +
    func (g Grant) String() string
    + + + + + + + + +

    type Hook

    +
    type Hook struct {
    +    CreatedAt *time.Time             `json:"created_at,omitempty"`
    +    UpdatedAt *time.Time             `json:"updated_at,omitempty"`
    +    Name      *string                `json:"name,omitempty"`
    +    URL       *string                `json:"url,omitempty"`
    +    Events    []string               `json:"events,omitempty"`
    +    Active    *bool                  `json:"active,omitempty"`
    +    Config    map[string]interface{} `json:"config,omitempty"`
    +    ID        *int                   `json:"id,omitempty"`
    +}
    +

    +Hook represents a GitHub (web and service) hook for a repository. +

    + + + + + + + + + + + + + + +

    func (Hook) String

    +
    func (h Hook) String() string
    + + + + + + + + +

    type Import

    +
    type Import struct {
    +    // The URL of the originating repository.
    +    VCSURL *string `json:"vcs_url,omitempty"`
    +    // The originating VCS type. Can be one of 'subversion', 'git',
    +    // 'mercurial', or 'tfvc'. Without this parameter, the import job will
    +    // take additional time to detect the VCS type before beginning the
    +    // import. This detection step will be reflected in the response.
    +    VCS *string `json:"vcs,omitempty"`
    +    // VCSUsername and VCSPassword are only used for StartImport calls that
    +    // are importing a password-protected repository.
    +    VCSUsername *string `json:"vcs_username,omitempty"`
    +    VCSPassword *string `json:"vcs_password,omitempty"`
    +    // For a tfvc import, the name of the project that is being imported.
    +    TFVCProject *string `json:"tfvc_project,omitempty"`
    +
    +    // Describes whether the import has been opted in or out of using Git
    +    // LFS. The value can be 'opt_in', 'opt_out', or 'undecided' if no
    +    // action has been taken.
    +    UseLFS *string `json:"use_lfs,omitempty"`
    +    // Describes whether files larger than 100MB were found during the
    +    // importing step.
    +    HasLargeFiles *bool `json:"has_large_files,omitempty"`
    +    // The total size in gigabytes of files larger than 100MB found in the
    +    // originating repository.
    +    LargeFilesSize *int `json:"large_files_size,omitempty"`
    +    // The total number of files larger than 100MB found in the originating
    +    // repository. To see a list of these files, call LargeFiles.
    +    LargeFilesCount *int `json:"large_files_count,omitempty"`
    +
    +    // Identifies the current status of an import.  An import that does not
    +    // have errors will progress through these steps:
    +    //
    +    //     detecting - the "detection" step of the import is in progress
    +    //         because the request did not include a VCS parameter. The
    +    //         import is identifying the type of source control present at
    +    //         the URL.
    +    //     importing - the "raw" step of the import is in progress. This is
    +    //         where commit data is fetched from the original repository.
    +    //         The import progress response will include CommitCount (the
    +    //         total number of raw commits that will be imported) and
    +    //         Percent (0 - 100, the current progress through the import).
    +    //     mapping - the "rewrite" step of the import is in progress. This
    +    //         is where SVN branches are converted to Git branches, and
    +    //         where author updates are applied. The import progress
    +    //         response does not include progress information.
    +    //     pushing - the "push" step of the import is in progress. This is
    +    //         where the importer updates the repository on GitHub. The
    +    //         import progress response will include PushPercent, which is
    +    //         the percent value reported by git push when it is "Writing
    +    //         objects".
    +    //     complete - the import is complete, and the repository is ready
    +    //         on GitHub.
    +    //
    +    // If there are problems, you will see one of these in the status field:
    +    //
    +    //     auth_failed - the import requires authentication in order to
    +    //         connect to the original repository. Make an UpdateImport
    +    //         request, and include VCSUsername and VCSPassword.
    +    //     error - the import encountered an error. The import progress
    +    //         response will include the FailedStep and an error message.
    +    //         Contact GitHub support for more information.
    +    //     detection_needs_auth - the importer requires authentication for
    +    //         the originating repository to continue detection. Make an
    +    //         UpdatImport request, and include VCSUsername and
    +    //         VCSPassword.
    +    //     detection_found_nothing - the importer didn't recognize any
    +    //         source control at the URL.
    +    //     detection_found_multiple - the importer found several projects
    +    //         or repositories at the provided URL. When this is the case,
    +    //         the Import Progress response will also include a
    +    //         ProjectChoices field with the possible project choices as
    +    //         values. Make an UpdateImport request, and include VCS and
    +    //         (if applicable) TFVCProject.
    +    Status        *string `json:"status,omitempty"`
    +    CommitCount   *int    `json:"commit_count,omitempty"`
    +    StatusText    *string `json:"status_text,omitempty"`
    +    AuthorsCount  *int    `json:"authors_count,omitempty"`
    +    Percent       *int    `json:"percent,omitempty"`
    +    PushPercent   *int    `json:"push_percent,omitempty"`
    +    URL           *string `json:"url,omitempty"`
    +    HTMLURL       *string `json:"html_url,omitempty"`
    +    AuthorsURL    *string `json:"authors_url,omitempty"`
    +    RepositoryURL *string `json:"repository_url,omitempty"`
    +    Message       *string `json:"message,omitempty"`
    +    FailedStep    *string `json:"failed_step,omitempty"`
    +
    +    // Human readable display name, provided when the Import appears as
    +    // part of ProjectChoices.
    +    HumanName *string `json:"human_name,omitempty"`
    +
    +    // When the importer finds several projects or repositories at the
    +    // provided URLs, this will identify the available choices.  Call
    +    // UpdateImport with the selected Import value.
    +    ProjectChoices []Import `json:"project_choices,omitempty"`
    +}
    +

    +Import represents a repository import request. +

    + + + + + + + + + + + + + + +

    func (Import) String

    +
    func (i Import) String() string
    + + + + + + + + +

    type Issue

    +
    type Issue struct {
    +    ID               *int              `json:"id,omitempty"`
    +    Number           *int              `json:"number,omitempty"`
    +    State            *string           `json:"state,omitempty"`
    +    Title            *string           `json:"title,omitempty"`
    +    Body             *string           `json:"body,omitempty"`
    +    User             *User             `json:"user,omitempty"`
    +    Labels           []Label           `json:"labels,omitempty"`
    +    Assignee         *User             `json:"assignee,omitempty"`
    +    Comments         *int              `json:"comments,omitempty"`
    +    ClosedAt         *time.Time        `json:"closed_at,omitempty"`
    +    CreatedAt        *time.Time        `json:"created_at,omitempty"`
    +    UpdatedAt        *time.Time        `json:"updated_at,omitempty"`
    +    URL              *string           `json:"url,omitempty"`
    +    HTMLURL          *string           `json:"html_url,omitempty"`
    +    Milestone        *Milestone        `json:"milestone,omitempty"`
    +    PullRequestLinks *PullRequestLinks `json:"pull_request,omitempty"`
    +    Repository       *Repository       `json:"repository,omitempty"`
    +    Reactions        *Reactions        `json:"reactions,omitempty"`
    +    Assignees        []*User           `json:"assignees,omitempty"`
    +
    +    // TextMatches is only populated from search results that request text matches
    +    // See: search.go and https://developer.github.com/v3/search/#text-match-metadata
    +    TextMatches []TextMatch `json:"text_matches,omitempty"`
    +}
    +

    +Issue represents a GitHub issue on a repository. +

    + + + + + + + + + + + + + + +

    func (Issue) String

    +
    func (i Issue) String() string
    + + + + + + + + +

    type IssueActivityEvent

    +
    type IssueActivityEvent struct {
    +    Action *string `json:"action,omitempty"`
    +    Issue  *Issue  `json:"issue,omitempty"`
    +
    +    // The following fields are only populated by Webhook events.
    +    Repo   *Repository `json:"repository,omitempty"`
    +    Sender *User       `json:"sender,omitempty"`
    +}
    +

    +DEPRECATED: IssueActivityEvent represents the payload delivered by Issue webhook +Use IssuesEvent instead. +

    + + + + + + + + + + + + + + + + +

    type IssueComment

    +
    type IssueComment struct {
    +    ID        *int       `json:"id,omitempty"`
    +    Body      *string    `json:"body,omitempty"`
    +    User      *User      `json:"user,omitempty"`
    +    Reactions *Reactions `json:"reactions,omitempty"`
    +    CreatedAt *time.Time `json:"created_at,omitempty"`
    +    UpdatedAt *time.Time `json:"updated_at,omitempty"`
    +    URL       *string    `json:"url,omitempty"`
    +    HTMLURL   *string    `json:"html_url,omitempty"`
    +    IssueURL  *string    `json:"issue_url,omitempty"`
    +}
    +

    +IssueComment represents a comment left on an issue. +

    + + + + + + + + + + + + + + +

    func (IssueComment) String

    +
    func (i IssueComment) String() string
    + + + + + + + + +

    type IssueCommentEvent

    +
    type IssueCommentEvent struct {
    +    // Action is the action that was performed on the comment.
    +    // Possible values are: "created", "edited", "deleted".
    +    Action  *string       `json:"action,omitempty"`
    +    Issue   *Issue        `json:"issue,omitempty"`
    +    Comment *IssueComment `json:"comment,omitempty"`
    +
    +    // The following fields are only populated by Webhook events.
    +    Changes *EditChange `json:"changes,omitempty"`
    +    Repo    *Repository `json:"repository,omitempty"`
    +    Sender  *User       `json:"sender,omitempty"`
    +}
    +

    +IssueCommentEvent is triggered when an issue comment is created on an issue +or pull request. +The Webhook event name is "issue_comment". +

    +

    +GitHub docs: https://developer.github.com/v3/activity/events/types/#issuecommentevent +

    + + + + + + + + + + + + + + + + +

    type IssueEvent

    +
    type IssueEvent struct {
    +    ID  *int    `json:"id,omitempty"`
    +    URL *string `json:"url,omitempty"`
    +
    +    // The User that generated this event.
    +    Actor *User `json:"actor,omitempty"`
    +
    +    // Event identifies the actual type of Event that occurred.  Possible
    +    // values are:
    +    //
    +    //     closed
    +    //       The Actor closed the issue.
    +    //       If the issue was closed by commit message, CommitID holds the SHA1 hash of the commit.
    +    //
    +    //     merged
    +    //       The Actor merged into master a branch containing a commit mentioning the issue.
    +    //       CommitID holds the SHA1 of the merge commit.
    +    //
    +    //     referenced
    +    //       The Actor committed to master a commit mentioning the issue in its commit message.
    +    //       CommitID holds the SHA1 of the commit.
    +    //
    +    //     reopened, locked, unlocked
    +    //       The Actor did that to the issue.
    +    //
    +    //     renamed
    +    //       The Actor changed the issue title from Rename.From to Rename.To.
    +    //
    +    //     mentioned
    +    //       Someone unspecified @mentioned the Actor [sic] in an issue comment body.
    +    //
    +    //     assigned, unassigned
    +    //       The Actor assigned the issue to or removed the assignment from the Assignee.
    +    //
    +    //     labeled, unlabeled
    +    //       The Actor added or removed the Label from the issue.
    +    //
    +    //     milestoned, demilestoned
    +    //       The Actor added or removed the issue from the Milestone.
    +    //
    +    //     subscribed, unsubscribed
    +    //       The Actor subscribed to or unsubscribed from notifications for an issue.
    +    //
    +    //     head_ref_deleted, head_ref_restored
    +    //       The pull request’s branch was deleted or restored.
    +    //
    +    Event *string `json:"event,omitempty"`
    +
    +    CreatedAt *time.Time `json:"created_at,omitempty"`
    +    Issue     *Issue     `json:"issue,omitempty"`
    +
    +    // Only present on certain events; see above.
    +    Assignee  *User      `json:"assignee,omitempty"`
    +    CommitID  *string    `json:"commit_id,omitempty"`
    +    Milestone *Milestone `json:"milestone,omitempty"`
    +    Label     *Label     `json:"label,omitempty"`
    +    Rename    *Rename    `json:"rename,omitempty"`
    +}
    +

    +IssueEvent represents an event that occurred around an Issue or Pull Request. +

    + + + + + + + + + + + + + + + + +

    type IssueListByRepoOptions

    +
    type IssueListByRepoOptions struct {
    +    // Milestone limits issues for the specified milestone.  Possible values are
    +    // a milestone number, "none" for issues with no milestone, "*" for issues
    +    // with any milestone.
    +    Milestone string `url:"milestone,omitempty"`
    +
    +    // State filters issues based on their state.  Possible values are: open,
    +    // closed, all.  Default is "open".
    +    State string `url:"state,omitempty"`
    +
    +    // Assignee filters issues based on their assignee.  Possible values are a
    +    // user name, "none" for issues that are not assigned, "*" for issues with
    +    // any assigned user.
    +    Assignee string `url:"assignee,omitempty"`
    +
    +    // Creator filters issues based on their creator.
    +    Creator string `url:"creator,omitempty"`
    +
    +    // Mentioned filters issues to those mentioned a specific user.
    +    Mentioned string `url:"mentioned,omitempty"`
    +
    +    // Labels filters issues based on their label.
    +    Labels []string `url:"labels,omitempty,comma"`
    +
    +    // Sort specifies how to sort issues.  Possible values are: created, updated,
    +    // and comments.  Default value is "created".
    +    Sort string `url:"sort,omitempty"`
    +
    +    // Direction in which to sort issues.  Possible values are: asc, desc.
    +    // Default is "desc".
    +    Direction string `url:"direction,omitempty"`
    +
    +    // Since filters issues by time.
    +    Since time.Time `url:"since,omitempty"`
    +
    +    ListOptions
    +}
    +

    +IssueListByRepoOptions specifies the optional parameters to the +IssuesService.ListByRepo method. +

    + + + + + + + + + + + + + + + + +

    type IssueListCommentsOptions

    +
    type IssueListCommentsOptions struct {
    +    // Sort specifies how to sort comments.  Possible values are: created, updated.
    +    Sort string `url:"sort,omitempty"`
    +
    +    // Direction in which to sort comments.  Possible values are: asc, desc.
    +    Direction string `url:"direction,omitempty"`
    +
    +    // Since filters comments by time.
    +    Since time.Time `url:"since,omitempty"`
    +
    +    ListOptions
    +}
    +

    +IssueListCommentsOptions specifies the optional parameters to the +IssuesService.ListComments method. +

    + + + + + + + + + + + + + + + + +

    type IssueListOptions

    +
    type IssueListOptions struct {
    +    // Filter specifies which issues to list.  Possible values are: assigned,
    +    // created, mentioned, subscribed, all.  Default is "assigned".
    +    Filter string `url:"filter,omitempty"`
    +
    +    // State filters issues based on their state.  Possible values are: open,
    +    // closed, all.  Default is "open".
    +    State string `url:"state,omitempty"`
    +
    +    // Labels filters issues based on their label.
    +    Labels []string `url:"labels,comma,omitempty"`
    +
    +    // Sort specifies how to sort issues.  Possible values are: created, updated,
    +    // and comments.  Default value is "created".
    +    Sort string `url:"sort,omitempty"`
    +
    +    // Direction in which to sort issues.  Possible values are: asc, desc.
    +    // Default is "desc".
    +    Direction string `url:"direction,omitempty"`
    +
    +    // Since filters issues by time.
    +    Since time.Time `url:"since,omitempty"`
    +
    +    ListOptions
    +}
    +

    +IssueListOptions specifies the optional parameters to the IssuesService.List +and IssuesService.ListByOrg methods. +

    + + + + + + + + + + + + + + + + +

    type IssueRequest

    +
    type IssueRequest struct {
    +    Title     *string   `json:"title,omitempty"`
    +    Body      *string   `json:"body,omitempty"`
    +    Labels    *[]string `json:"labels,omitempty"`
    +    Assignee  *string   `json:"assignee,omitempty"`
    +    State     *string   `json:"state,omitempty"`
    +    Milestone *int      `json:"milestone,omitempty"`
    +    Assignees *[]string `json:"assignees,omitempty"`
    +}
    +

    +IssueRequest represents a request to create/edit an issue. +It is separate from Issue above because otherwise Labels +and Assignee fail to serialize to the correct JSON. +

    + + + + + + + + + + + + + + + + +

    type IssuesEvent

    +
    type IssuesEvent struct {
    +    // Action is the action that was performed. Possible values are: "assigned",
    +    // "unassigned", "labeled", "unlabeled", "opened", "closed", "reopened", "edited".
    +    Action   *string `json:"action,omitempty"`
    +    Issue    *Issue  `json:"issue,omitempty"`
    +    Assignee *User   `json:"assignee,omitempty"`
    +    Label    *Label  `json:"label,omitempty"`
    +
    +    // The following fields are only populated by Webhook events.
    +    Changes *EditChange `json:"changes,omitempty"`
    +    Repo    *Repository `json:"repository,omitempty"`
    +    Sender  *User       `json:"sender,omitempty"`
    +}
    +

    +IssuesEvent is triggered when an issue is assigned, unassigned, labeled, +unlabeled, opened, closed, or reopened. +The Webhook event name is "issues". +

    +

    +GitHub docs: https://developer.github.com/v3/activity/events/types/#issuesevent +

    + + + + + + + + + + + + + + + + +

    type IssuesSearchResult

    +
    type IssuesSearchResult struct {
    +    Total  *int    `json:"total_count,omitempty"`
    +    Issues []Issue `json:"items,omitempty"`
    +}
    +

    +IssuesSearchResult represents the result of an issues search. +

    + + + + + + + + + + + + + + + + +

    type IssuesService

    +
    type IssuesService service
    +

    +IssuesService handles communication with the issue related +methods of the GitHub API. +

    +

    +GitHub API docs: http://developer.github.com/v3/issues/ +

    + + + + + + + + + + + + + + +

    func (*IssuesService) AddAssignees

    +
    func (s *IssuesService) AddAssignees(owner, repo string, number int, assignees []string) (*Issue, *Response, error)
    +

    +AddAssignees adds the provided GitHub users as assignees to the issue. +

    +

    +GitHub API docs: https://developer.github.com/v3/issues/assignees/#add-assignees-to-an-issue +

    + + + + + + +

    func (*IssuesService) AddLabelsToIssue

    +
    func (s *IssuesService) AddLabelsToIssue(owner string, repo string, number int, labels []string) ([]*Label, *Response, error)
    +

    +AddLabelsToIssue adds labels to an issue. +

    +

    +GitHub API docs: http://developer.github.com/v3/issues/labels/#list-all-labels-for-this-repository +

    + + + + + + +

    func (*IssuesService) Create

    +
    func (s *IssuesService) Create(owner string, repo string, issue *IssueRequest) (*Issue, *Response, error)
    +

    +Create a new issue on the specified repository. +

    +

    +GitHub API docs: http://developer.github.com/v3/issues/#create-an-issue +

    + + + + + + +

    func (*IssuesService) CreateComment

    +
    func (s *IssuesService) CreateComment(owner string, repo string, number int, comment *IssueComment) (*IssueComment, *Response, error)
    +

    +CreateComment creates a new comment on the specified issue. +

    +

    +GitHub API docs: http://developer.github.com/v3/issues/comments/#create-a-comment +

    + + + + + + +

    func (*IssuesService) CreateLabel

    +
    func (s *IssuesService) CreateLabel(owner string, repo string, label *Label) (*Label, *Response, error)
    +

    +CreateLabel creates a new label on the specified repository. +

    +

    +GitHub API docs: http://developer.github.com/v3/issues/labels/#create-a-label +

    + + + + + + +

    func (*IssuesService) CreateMilestone

    +
    func (s *IssuesService) CreateMilestone(owner string, repo string, milestone *Milestone) (*Milestone, *Response, error)
    +

    +CreateMilestone creates a new milestone on the specified repository. +

    +

    +GitHub API docs: https://developer.github.com/v3/issues/milestones/#create-a-milestone +

    + + + + + + +

    func (*IssuesService) DeleteComment

    +
    func (s *IssuesService) DeleteComment(owner string, repo string, id int) (*Response, error)
    +

    +DeleteComment deletes an issue comment. +

    +

    +GitHub API docs: http://developer.github.com/v3/issues/comments/#delete-a-comment +

    + + + + + + +

    func (*IssuesService) DeleteLabel

    +
    func (s *IssuesService) DeleteLabel(owner string, repo string, name string) (*Response, error)
    +

    +DeleteLabel deletes a label. +

    +

    +GitHub API docs: http://developer.github.com/v3/issues/labels/#delete-a-label +

    + + + + + + +

    func (*IssuesService) DeleteMilestone

    +
    func (s *IssuesService) DeleteMilestone(owner string, repo string, number int) (*Response, error)
    +

    +DeleteMilestone deletes a milestone. +

    +

    +GitHub API docs: https://developer.github.com/v3/issues/milestones/#delete-a-milestone +

    + + + + + + +

    func (*IssuesService) Edit

    +
    func (s *IssuesService) Edit(owner string, repo string, number int, issue *IssueRequest) (*Issue, *Response, error)
    +

    +Edit an issue. +

    +

    +GitHub API docs: http://developer.github.com/v3/issues/#edit-an-issue +

    + + + + + + +

    func (*IssuesService) EditComment

    +
    func (s *IssuesService) EditComment(owner string, repo string, id int, comment *IssueComment) (*IssueComment, *Response, error)
    +

    +EditComment updates an issue comment. +

    +

    +GitHub API docs: http://developer.github.com/v3/issues/comments/#edit-a-comment +

    + + + + + + +

    func (*IssuesService) EditLabel

    +
    func (s *IssuesService) EditLabel(owner string, repo string, name string, label *Label) (*Label, *Response, error)
    +

    +EditLabel edits a label. +

    +

    +GitHub API docs: http://developer.github.com/v3/issues/labels/#update-a-label +

    + + + + + + +

    func (*IssuesService) EditMilestone

    +
    func (s *IssuesService) EditMilestone(owner string, repo string, number int, milestone *Milestone) (*Milestone, *Response, error)
    +

    +EditMilestone edits a milestone. +

    +

    +GitHub API docs: https://developer.github.com/v3/issues/milestones/#update-a-milestone +

    + + + + + + +

    func (*IssuesService) Get

    +
    func (s *IssuesService) Get(owner string, repo string, number int) (*Issue, *Response, error)
    +

    +Get a single issue. +

    +

    +GitHub API docs: http://developer.github.com/v3/issues/#get-a-single-issue +

    + + + + + + +

    func (*IssuesService) GetComment

    +
    func (s *IssuesService) GetComment(owner string, repo string, id int) (*IssueComment, *Response, error)
    +

    +GetComment fetches the specified issue comment. +

    +

    +GitHub API docs: http://developer.github.com/v3/issues/comments/#get-a-single-comment +

    + + + + + + +

    func (*IssuesService) GetEvent

    +
    func (s *IssuesService) GetEvent(owner, repo string, id int) (*IssueEvent, *Response, error)
    +

    +GetEvent returns the specified issue event. +

    +

    +GitHub API docs: https://developer.github.com/v3/issues/events/#get-a-single-event +

    + + + + + + +

    func (*IssuesService) GetLabel

    +
    func (s *IssuesService) GetLabel(owner string, repo string, name string) (*Label, *Response, error)
    +

    +GetLabel gets a single label. +

    +

    +GitHub API docs: http://developer.github.com/v3/issues/labels/#get-a-single-label +

    + + + + + + +

    func (*IssuesService) GetMilestone

    +
    func (s *IssuesService) GetMilestone(owner string, repo string, number int) (*Milestone, *Response, error)
    +

    +GetMilestone gets a single milestone. +

    +

    +GitHub API docs: https://developer.github.com/v3/issues/milestones/#get-a-single-milestone +

    + + + + + + +

    func (*IssuesService) IsAssignee

    +
    func (s *IssuesService) IsAssignee(owner, repo, user string) (bool, *Response, error)
    +

    +IsAssignee checks if a user is an assignee for the specified repository. +

    +

    +GitHub API docs: http://developer.github.com/v3/issues/assignees/#check-assignee +

    + + + + + + +

    func (*IssuesService) List

    +
    func (s *IssuesService) List(all bool, opt *IssueListOptions) ([]*Issue, *Response, error)
    +

    +List the issues for the authenticated user. If all is true, list issues +across all the user's visible repositories including owned, member, and +organization repositories; if false, list only owned and member +repositories. +

    +

    +GitHub API docs: http://developer.github.com/v3/issues/#list-issues +

    + + + + + + +

    func (*IssuesService) ListAssignees

    +
    func (s *IssuesService) ListAssignees(owner, repo string, opt *ListOptions) ([]*User, *Response, error)
    +

    +ListAssignees fetches all available assignees (owners and collaborators) to +which issues may be assigned. +

    +

    +GitHub API docs: http://developer.github.com/v3/issues/assignees/#list-assignees +

    + + + + + + +

    func (*IssuesService) ListByOrg

    +
    func (s *IssuesService) ListByOrg(org string, opt *IssueListOptions) ([]*Issue, *Response, error)
    +

    +ListByOrg fetches the issues in the specified organization for the +authenticated user. +

    +

    +GitHub API docs: http://developer.github.com/v3/issues/#list-issues +

    + + + + + + +

    func (*IssuesService) ListByRepo

    +
    func (s *IssuesService) ListByRepo(owner string, repo string, opt *IssueListByRepoOptions) ([]*Issue, *Response, error)
    +

    +ListByRepo lists the issues for the specified repository. +

    +

    +GitHub API docs: http://developer.github.com/v3/issues/#list-issues-for-a-repository +

    + + + + + + +

    func (*IssuesService) ListComments

    +
    func (s *IssuesService) ListComments(owner string, repo string, number int, opt *IssueListCommentsOptions) ([]*IssueComment, *Response, error)
    +

    +ListComments lists all comments on the specified issue. Specifying an issue +number of 0 will return all comments on all issues for the repository. +

    +

    +GitHub API docs: http://developer.github.com/v3/issues/comments/#list-comments-on-an-issue +

    + + + + + + +

    func (*IssuesService) ListIssueEvents

    +
    func (s *IssuesService) ListIssueEvents(owner, repo string, number int, opt *ListOptions) ([]*IssueEvent, *Response, error)
    +

    +ListIssueEvents lists events for the specified issue. +

    +

    +GitHub API docs: https://developer.github.com/v3/issues/events/#list-events-for-an-issue +

    + + + + + + +

    func (*IssuesService) ListIssueTimeline

    +
    func (s *IssuesService) ListIssueTimeline(owner, repo string, number int, opt *ListOptions) ([]*Timeline, *Response, error)
    +

    +ListIssueTimeline lists events for the specified issue. +

    +

    +GitHub API docs: https://developer.github.com/v3/issues/timeline/#list-events-for-an-issue +

    + + + + + + +

    func (*IssuesService) ListLabels

    +
    func (s *IssuesService) ListLabels(owner string, repo string, opt *ListOptions) ([]*Label, *Response, error)
    +

    +ListLabels lists all labels for a repository. +

    +

    +GitHub API docs: http://developer.github.com/v3/issues/labels/#list-all-labels-for-this-repository +

    + + + + + + +

    func (*IssuesService) ListLabelsByIssue

    +
    func (s *IssuesService) ListLabelsByIssue(owner string, repo string, number int, opt *ListOptions) ([]*Label, *Response, error)
    +

    +ListLabelsByIssue lists all labels for an issue. +

    +

    +GitHub API docs: http://developer.github.com/v3/issues/labels/#list-all-labels-for-this-repository +

    + + + + + + +

    func (*IssuesService) ListLabelsForMilestone

    +
    func (s *IssuesService) ListLabelsForMilestone(owner string, repo string, number int, opt *ListOptions) ([]*Label, *Response, error)
    +

    +ListLabelsForMilestone lists labels for every issue in a milestone. +

    +

    +GitHub API docs: http://developer.github.com/v3/issues/labels/#get-labels-for-every-issue-in-a-milestone +

    + + + + + + +

    func (*IssuesService) ListMilestones

    +
    func (s *IssuesService) ListMilestones(owner string, repo string, opt *MilestoneListOptions) ([]*Milestone, *Response, error)
    +

    +ListMilestones lists all milestones for a repository. +

    +

    +GitHub API docs: https://developer.github.com/v3/issues/milestones/#list-milestones-for-a-repository +

    + + + + + + +

    func (*IssuesService) ListRepositoryEvents

    +
    func (s *IssuesService) ListRepositoryEvents(owner, repo string, opt *ListOptions) ([]*IssueEvent, *Response, error)
    +

    +ListRepositoryEvents lists events for the specified repository. +

    +

    +GitHub API docs: https://developer.github.com/v3/issues/events/#list-events-for-a-repository +

    + + + + + + +

    func (*IssuesService) Lock

    +
    func (s *IssuesService) Lock(owner string, repo string, number int) (*Response, error)
    +

    +Lock an issue's conversation. +

    +

    +GitHub API docs: https://developer.github.com/v3/issues/#lock-an-issue +

    + + + + + + +

    func (*IssuesService) RemoveAssignees

    +
    func (s *IssuesService) RemoveAssignees(owner, repo string, number int, assignees []string) (*Issue, *Response, error)
    +

    +RemoveAssignees removes the provided GitHub users as assignees from the issue. +

    +

    +GitHub API docs: https://developer.github.com/v3/issues/assignees/#remove-assignees-from-an-issue +

    + + + + + + +

    func (*IssuesService) RemoveLabelForIssue

    +
    func (s *IssuesService) RemoveLabelForIssue(owner string, repo string, number int, label string) (*Response, error)
    +

    +RemoveLabelForIssue removes a label for an issue. +

    +

    +GitHub API docs: http://developer.github.com/v3/issues/labels/#remove-a-label-from-an-issue +

    + + + + + + +

    func (*IssuesService) RemoveLabelsForIssue

    +
    func (s *IssuesService) RemoveLabelsForIssue(owner string, repo string, number int) (*Response, error)
    +

    +RemoveLabelsForIssue removes all labels for an issue. +

    +

    +GitHub API docs: http://developer.github.com/v3/issues/labels/#remove-all-labels-from-an-issue +

    + + + + + + +

    func (*IssuesService) ReplaceLabelsForIssue

    +
    func (s *IssuesService) ReplaceLabelsForIssue(owner string, repo string, number int, labels []string) ([]*Label, *Response, error)
    +

    +ReplaceLabelsForIssue replaces all labels for an issue. +

    +

    +GitHub API docs: http://developer.github.com/v3/issues/labels/#replace-all-labels-for-an-issue +

    + + + + + + +

    func (*IssuesService) Unlock

    +
    func (s *IssuesService) Unlock(owner string, repo string, number int) (*Response, error)
    +

    +Unlock an issue's conversation. +

    +

    +GitHub API docs: https://developer.github.com/v3/issues/#unlock-an-issue +

    + + + + + + + + +

    type Key

    +
    type Key struct {
    +    ID       *int    `json:"id,omitempty"`
    +    Key      *string `json:"key,omitempty"`
    +    URL      *string `json:"url,omitempty"`
    +    Title    *string `json:"title,omitempty"`
    +    ReadOnly *bool   `json:"read_only,omitempty"`
    +}
    +

    +Key represents a public SSH key used to authenticate a user or deploy script. +

    + + + + + + + + + + + + + + +

    func (Key) String

    +
    func (k Key) String() string
    + + + + + + + + +

    type Label

    +
    type Label struct {
    +    URL   *string `json:"url,omitempty"`
    +    Name  *string `json:"name,omitempty"`
    +    Color *string `json:"color,omitempty"`
    +}
    +

    +Label represents a GitHub label on an Issue +

    + + + + + + + + + + + + + + +

    func (Label) String

    +
    func (l Label) String() string
    + + + + + + + + +

    type LargeFile

    +
    type LargeFile struct {
    +    RefName *string `json:"ref_name,omitempty"`
    +    Path    *string `json:"path,omitempty"`
    +    OID     *string `json:"oid,omitempty"`
    +    Size    *int    `json:"size,omitempty"`
    +}
    +

    +LargeFile identifies a file larger than 100MB found during a repository import. +

    +

    +GitHub API docs: https://developer.github.com/v3/migration/source_imports/#get-large-files +

    + + + + + + + + + + + + + + +

    func (LargeFile) String

    +
    func (f LargeFile) String() string
    + + + + + + + + +

    type License

    +
    type License struct {
    +    Key  *string `json:"key,omitempty"`
    +    Name *string `json:"name,omitempty"`
    +    URL  *string `json:"url,omitempty"`
    +
    +    HTMLURL        *string   `json:"html_url,omitempty"`
    +    Featured       *bool     `json:"featured,omitempty"`
    +    Description    *string   `json:"description,omitempty"`
    +    Category       *string   `json:"category,omitempty"`
    +    Implementation *string   `json:"implementation,omitempty"`
    +    Required       *[]string `json:"required,omitempty"`
    +    Permitted      *[]string `json:"permitted,omitempty"`
    +    Forbidden      *[]string `json:"forbidden,omitempty"`
    +    Body           *string   `json:"body,omitempty"`
    +}
    +

    +License represents an open source license. +

    + + + + + + + + + + + + + + +

    func (License) String

    +
    func (l License) String() string
    + + + + + + + + +

    type LicensesService

    +
    type LicensesService service
    +

    +LicensesService handles communication with the license related +methods of the GitHub API. +

    +

    +GitHub API docs: http://developer.github.com/v3/pulls/ +

    + + + + + + + + + + + + + + +

    func (*LicensesService) Get

    +
    func (s *LicensesService) Get(licenseName string) (*License, *Response, error)
    +

    +Get extended metadata for one license. +

    +

    +GitHub API docs: https://developer.github.com/v3/licenses/#get-an-individual-license +

    + + + + + + +

    func (*LicensesService) List

    +
    func (s *LicensesService) List() ([]*License, *Response, error)
    +

    +List popular open source licenses. +

    +

    +GitHub API docs: https://developer.github.com/v3/licenses/#list-all-licenses +

    + + + + + + + + +

    type ListContributorsOptions

    +
    type ListContributorsOptions struct {
    +    // Include anonymous contributors in results or not
    +    Anon string `url:"anon,omitempty"`
    +
    +    ListOptions
    +}
    +

    +ListContributorsOptions specifies the optional parameters to the +RepositoriesService.ListContributors method. +

    + + + + + + + + + + + + + + + + +

    type ListMembersOptions

    +
    type ListMembersOptions struct {
    +    // If true (or if the authenticated user is not an owner of the
    +    // organization), list only publicly visible members.
    +    PublicOnly bool `url:"-"`
    +
    +    // Filter members returned in the list.  Possible values are:
    +    // 2fa_disabled, all.  Default is "all".
    +    Filter string `url:"filter,omitempty"`
    +
    +    // Role filters members returned by their role in the organization.
    +    // Possible values are:
    +    //     all - all members of the organization, regardless of role
    +    //     admin - organization owners
    +    //     member - non-organization members
    +    //
    +    // Default is "all".
    +    Role string `url:"role,omitempty"`
    +
    +    ListOptions
    +}
    +

    +ListMembersOptions specifies optional parameters to the +OrganizationsService.ListMembers method. +

    + + + + + + + + + + + + + + + + +

    type ListOptions

    +
    type ListOptions struct {
    +    // For paginated result sets, page of results to retrieve.
    +    Page int `url:"page,omitempty"`
    +
    +    // For paginated result sets, the number of results to include per page.
    +    PerPage int `url:"per_page,omitempty"`
    +}
    +

    +ListOptions specifies the optional parameters to various List methods that +support pagination. +

    + + + + + + + + + + + + + + + + +

    type ListOrgMembershipsOptions

    +
    type ListOrgMembershipsOptions struct {
    +    // Filter memberships to include only those with the specified state.
    +    // Possible values are: "active", "pending".
    +    State string `url:"state,omitempty"`
    +
    +    ListOptions
    +}
    +

    +ListOrgMembershipsOptions specifies optional parameters to the +OrganizationsService.ListOrgMemberships method. +

    + + + + + + + + + + + + + + + + +

    type MarkdownOptions

    +
    type MarkdownOptions struct {
    +    // Mode identifies the rendering mode.  Possible values are:
    +    //   markdown - render a document as plain Markdown, just like
    +    //   README files are rendered.
    +    //
    +    //   gfm - to render a document as user-content, e.g. like user
    +    //   comments or issues are rendered. In GFM mode, hard line breaks are
    +    //   always taken into account, and issue and user mentions are linked
    +    //   accordingly.
    +    //
    +    // Default is "markdown".
    +    Mode string
    +
    +    // Context identifies the repository context.  Only taken into account
    +    // when rendering as "gfm".
    +    Context string
    +}
    +

    +MarkdownOptions specifies optional parameters to the Markdown method. +

    + + + + + + + + + + + + + + + + +

    type Match

    +
    type Match struct {
    +    Text    *string `json:"text,omitempty"`
    +    Indices []int   `json:"indices,omitempty"`
    +}
    +

    +Match represents a single text match. +

    + + + + + + + + + + + + + + + + +

    type MemberEvent

    +
    type MemberEvent struct {
    +    // Action is the action that was performed. Possible value is: "added".
    +    Action *string `json:"action,omitempty"`
    +    Member *User   `json:"member,omitempty"`
    +
    +    // The following fields are only populated by Webhook events.
    +    Repo   *Repository `json:"repository,omitempty"`
    +    Sender *User       `json:"sender,omitempty"`
    +}
    +

    +MemberEvent is triggered when a user is added as a collaborator to a repository. +The Webhook event name is "member". +

    +

    +GitHub docs: https://developer.github.com/v3/activity/events/types/#memberevent +

    + + + + + + + + + + + + + + + + +

    type Membership

    +
    type Membership struct {
    +    URL *string `json:"url,omitempty"`
    +
    +    // State is the user's status within the organization or team.
    +    // Possible values are: "active", "pending"
    +    State *string `json:"state,omitempty"`
    +
    +    // Role identifies the user's role within the organization or team.
    +    // Possible values for organization membership:
    +    //     member - non-owner organization member
    +    //     admin - organization owner
    +    //
    +    // Possible values for team membership are:
    +    //     member - a normal member of the team
    +    //     maintainer - a team maintainer. Able to add/remove other team
    +    //                  members, promote other team members to team
    +    //                  maintainer, and edit the team’s name and description
    +    Role *string `json:"role,omitempty"`
    +
    +    // For organization membership, the API URL of the organization.
    +    OrganizationURL *string `json:"organization_url,omitempty"`
    +
    +    // For organization membership, the organization the membership is for.
    +    Organization *Organization `json:"organization,omitempty"`
    +
    +    // For organization membership, the user the membership is for.
    +    User *User `json:"user,omitempty"`
    +}
    +

    +Membership represents the status of a user's membership in an organization or team. +

    + + + + + + + + + + + + + + +

    func (Membership) String

    +
    func (m Membership) String() string
    + + + + + + + + +

    type MembershipEvent

    +
    type MembershipEvent struct {
    +    // Action is the action that was performed. Possible values are: "added", "removed".
    +    Action *string `json:"action,omitempty"`
    +    // Scope is the scope of the membership. Possible value is: "team".
    +    Scope  *string `json:"scope,omitempty"`
    +    Member *User   `json:"member,omitempty"`
    +    Team   *Team   `json:"team,omitempty"`
    +
    +    // The following fields are only populated by Webhook events.
    +    Org    *Organization `json:"organization,omitempty"`
    +    Sender *User         `json:"sender,omitempty"`
    +}
    +

    +MembershipEvent is triggered when a user is added or removed from a team. +The Webhook event name is "membership". +

    +

    +Events of this type are not visible in timelines, they are only used to +trigger organization webhooks. +

    +

    +GitHub docs: https://developer.github.com/v3/activity/events/types/#membershipevent +

    + + + + + + + + + + + + + + + + +

    type Migration

    +
    type Migration struct {
    +    ID   *int    `json:"id,omitempty"`
    +    GUID *string `json:"guid,omitempty"`
    +    // State is the current state of a migration.
    +    // Possible values are:
    +    //     "pending" which means the migration hasn't started yet,
    +    //     "exporting" which means the migration is in progress,
    +    //     "exported" which means the migration finished successfully, or
    +    //     "failed" which means the migration failed.
    +    State *string `json:"state,omitempty"`
    +    // LockRepositories indicates whether repositories are locked (to prevent
    +    // manipulation) while migrating data.
    +    LockRepositories *bool `json:"lock_repositories,omitempty"`
    +    // ExcludeAttachments indicates whether attachments should be excluded from
    +    // the migration (to reduce migration archive file size).
    +    ExcludeAttachments *bool         `json:"exclude_attachments,omitempty"`
    +    URL                *string       `json:"url,omitempty"`
    +    CreatedAt          *string       `json:"created_at,omitempty"`
    +    UpdatedAt          *string       `json:"updated_at,omitempty"`
    +    Repositories       []*Repository `json:"repositories,omitempty"`
    +}
    +

    +Migration represents a GitHub migration (archival). +

    + + + + + + + + + + + + + + +

    func (Migration) String

    +
    func (m Migration) String() string
    + + + + + + + + +

    type MigrationOptions

    +
    type MigrationOptions struct {
    +    // LockRepositories indicates whether repositories should be locked (to prevent
    +    // manipulation) while migrating data.
    +    LockRepositories bool
    +
    +    // ExcludeAttachments indicates whether attachments should be excluded from
    +    // the migration (to reduce migration archive file size).
    +    ExcludeAttachments bool
    +}
    +

    +MigrationOptions specifies the optional parameters to Migration methods. +

    + + + + + + + + + + + + + + + + +

    type MigrationService

    +
    type MigrationService service
    +

    +MigrationService provides access to the migration related functions +in the GitHub API. +

    +

    +GitHub API docs: https://developer.github.com/v3/migration/ +

    + + + + + + + + + + + + + + +

    func (*MigrationService) CancelImport

    +
    func (s *MigrationService) CancelImport(owner, repo string) (*Response, error)
    +

    +CancelImport stops an import for a repository. +

    +

    +GitHub API docs: https://developer.github.com/v3/migration/source_imports/#cancel-an-import +

    + + + + + + +

    func (*MigrationService) CommitAuthors

    +
    func (s *MigrationService) CommitAuthors(owner, repo string) ([]*SourceImportAuthor, *Response, error)
    +

    +CommitAuthors gets the authors mapped from the original repository. +

    +

    +Each type of source control system represents authors in a different way. +For example, a Git commit author has a display name and an email address, +but a Subversion commit author just has a username. The GitHub Importer will +make the author information valid, but the author might not be correct. For +example, it will change the bare Subversion username "hubot" into something +like "hubot <hubot@12341234-abab-fefe-8787-fedcba987654>". +

    +

    +This method and MapCommitAuthor allow you to provide correct Git author +information. +

    +

    +GitHub API docs: https://developer.github.com/v3/migration/source_imports/#get-commit-authors +

    + + + + + + +

    func (*MigrationService) DeleteMigration

    +
    func (s *MigrationService) DeleteMigration(org string, id int) (*Response, error)
    +

    +DeleteMigration deletes a previous migration archive. +id is the migration ID. +

    +

    +GitHub API docs: https://developer.github.com/v3/migration/migrations/#delete-a-migration-archive +

    + + + + + + +

    func (*MigrationService) ImportProgress

    +
    func (s *MigrationService) ImportProgress(owner, repo string) (*Import, *Response, error)
    +

    +QueryImport queries for the status and progress of an ongoing repository import. +

    +

    +GitHub API docs: https://developer.github.com/v3/migration/source_imports/#get-import-progress +

    + + + + + + +

    func (*MigrationService) LargeFiles

    +
    func (s *MigrationService) LargeFiles(owner, repo string) ([]*LargeFile, *Response, error)
    +

    +LargeFiles lists files larger than 100MB found during the import. +

    +

    +GitHub API docs: https://developer.github.com/v3/migration/source_imports/#get-large-files +

    + + + + + + +

    func (*MigrationService) ListMigrations

    +
    func (s *MigrationService) ListMigrations(org string) ([]*Migration, *Response, error)
    +

    +ListMigrations lists the most recent migrations. +

    +

    +GitHub API docs: https://developer.github.com/v3/migration/migrations/#get-a-list-of-migrations +

    + + + + + + +

    func (*MigrationService) MapCommitAuthor

    +
    func (s *MigrationService) MapCommitAuthor(owner, repo string, id int, author *SourceImportAuthor) (*SourceImportAuthor, *Response, error)
    +

    +MapCommitAuthor updates an author's identity for the import. Your +application can continue updating authors any time before you push new +commits to the repository. +

    +

    +GitHub API docs: https://developer.github.com/v3/migration/source_imports/#map-a-commit-author +

    + + + + + + +

    func (*MigrationService) MigrationArchiveURL

    +
    func (s *MigrationService) MigrationArchiveURL(org string, id int) (url string, err error)
    +

    +MigrationArchiveURL fetches a migration archive URL. +id is the migration ID. +

    +

    +GitHub API docs: https://developer.github.com/v3/migration/migrations/#download-a-migration-archive +

    + + + + + + +

    func (*MigrationService) MigrationStatus

    +
    func (s *MigrationService) MigrationStatus(org string, id int) (*Migration, *Response, error)
    +

    +MigrationStatus gets the status of a specific migration archive. +id is the migration ID. +

    +

    +GitHub API docs: https://developer.github.com/v3/migration/migrations/#get-the-status-of-a-migration +

    + + + + + + +

    func (*MigrationService) SetLFSPreference

    +
    func (s *MigrationService) SetLFSPreference(owner, repo string, in *Import) (*Import, *Response, error)
    +

    +SetLFSPreference sets whether imported repositories should use Git LFS for +files larger than 100MB. Only the UseLFS field on the provided Import is +used. +

    +

    +GitHub API docs: https://developer.github.com/v3/migration/source_imports/#set-git-lfs-preference +

    + + + + + + +

    func (*MigrationService) StartImport

    +
    func (s *MigrationService) StartImport(owner, repo string, in *Import) (*Import, *Response, error)
    +

    +StartImport initiates a repository import. +

    +

    +GitHub API docs: https://developer.github.com/v3/migration/source_imports/#start-an-import +

    + + + + + + +

    func (*MigrationService) StartMigration

    +
    func (s *MigrationService) StartMigration(org string, repos []string, opt *MigrationOptions) (*Migration, *Response, error)
    +

    +StartMigration starts the generation of a migration archive. +repos is a slice of repository names to migrate. +

    +

    +GitHub API docs: https://developer.github.com/v3/migration/migrations/#start-a-migration +

    + + + + + + +

    func (*MigrationService) UnlockRepo

    +
    func (s *MigrationService) UnlockRepo(org string, id int, repo string) (*Response, error)
    +

    +UnlockRepo unlocks a repository that was locked for migration. +id is the migration ID. +You should unlock each migrated repository and delete them when the migration +is complete and you no longer need the source data. +

    +

    +GitHub API docs: https://developer.github.com/v3/migration/migrations/#unlock-a-repository +

    + + + + + + +

    func (*MigrationService) UpdateImport

    +
    func (s *MigrationService) UpdateImport(owner, repo string, in *Import) (*Import, *Response, error)
    +

    +UpdateImport initiates a repository import. +

    +

    +GitHub API docs: https://developer.github.com/v3/migration/source_imports/#update-existing-import +

    + + + + + + + + +

    type Milestone

    +
    type Milestone struct {
    +    URL          *string    `json:"url,omitempty"`
    +    HTMLURL      *string    `json:"html_url,omitempty"`
    +    LabelsURL    *string    `json:"labels_url,omitempty"`
    +    ID           *int       `json:"id,omitempty"`
    +    Number       *int       `json:"number,omitempty"`
    +    State        *string    `json:"state,omitempty"`
    +    Title        *string    `json:"title,omitempty"`
    +    Description  *string    `json:"description,omitempty"`
    +    Creator      *User      `json:"creator,omitempty"`
    +    OpenIssues   *int       `json:"open_issues,omitempty"`
    +    ClosedIssues *int       `json:"closed_issues,omitempty"`
    +    CreatedAt    *time.Time `json:"created_at,omitempty"`
    +    UpdatedAt    *time.Time `json:"updated_at,omitempty"`
    +    ClosedAt     *time.Time `json:"closed_at,omitempty"`
    +    DueOn        *time.Time `json:"due_on,omitempty"`
    +}
    +

    +Milestone represents a Github repository milestone. +

    + + + + + + + + + + + + + + +

    func (Milestone) String

    +
    func (m Milestone) String() string
    + + + + + + + + +

    type MilestoneListOptions

    +
    type MilestoneListOptions struct {
    +    // State filters milestones based on their state. Possible values are:
    +    // open, closed. Default is "open".
    +    State string `url:"state,omitempty"`
    +
    +    // Sort specifies how to sort milestones. Possible values are: due_date, completeness.
    +    // Default value is "due_date".
    +    Sort string `url:"sort,omitempty"`
    +
    +    // Direction in which to sort milestones. Possible values are: asc, desc.
    +    // Default is "asc".
    +    Direction string `url:"direction,omitempty"`
    +
    +    ListOptions
    +}
    +

    +MilestoneListOptions specifies the optional parameters to the +IssuesService.ListMilestones method. +

    + + + + + + + + + + + + + + + + +

    type NewPullRequest

    +
    type NewPullRequest struct {
    +    Title *string `json:"title,omitempty"`
    +    Head  *string `json:"head,omitempty"`
    +    Base  *string `json:"base,omitempty"`
    +    Body  *string `json:"body,omitempty"`
    +    Issue *int    `json:"issue,omitempty"`
    +}
    +

    +NewPullRequest represents a new pull request to be created. +

    + + + + + + + + + + + + + + + + +

    type Notification

    +
    type Notification struct {
    +    ID         *string              `json:"id,omitempty"`
    +    Repository *Repository          `json:"repository,omitempty"`
    +    Subject    *NotificationSubject `json:"subject,omitempty"`
    +
    +    // Reason identifies the event that triggered the notification.
    +    //
    +    // GitHub API Docs: https://developer.github.com/v3/activity/notifications/#notification-reasons
    +    Reason *string `json:"reason,omitempty"`
    +
    +    Unread     *bool      `json:"unread,omitempty"`
    +    UpdatedAt  *time.Time `json:"updated_at,omitempty"`
    +    LastReadAt *time.Time `json:"last_read_at,omitempty"`
    +    URL        *string    `json:"url,omitempty"`
    +}
    +

    +Notification identifies a GitHub notification for a user. +

    + + + + + + + + + + + + + + + + +

    type NotificationListOptions

    +
    type NotificationListOptions struct {
    +    All           bool      `url:"all,omitempty"`
    +    Participating bool      `url:"participating,omitempty"`
    +    Since         time.Time `url:"since,omitempty"`
    +    Before        time.Time `url:"before,omitempty"`
    +
    +    ListOptions
    +}
    +

    +NotificationListOptions specifies the optional parameters to the +ActivityService.ListNotifications method. +

    + + + + + + + + + + + + + + + + +

    type NotificationSubject

    +
    type NotificationSubject struct {
    +    Title            *string `json:"title,omitempty"`
    +    URL              *string `json:"url,omitempty"`
    +    LatestCommentURL *string `json:"latest_comment_url,omitempty"`
    +    Type             *string `json:"type,omitempty"`
    +}
    +

    +NotificationSubject identifies the subject of a notification. +

    + + + + + + + + + + + + + + + + +

    type Organization

    +
    type Organization struct {
    +    Login             *string    `json:"login,omitempty"`
    +    ID                *int       `json:"id,omitempty"`
    +    AvatarURL         *string    `json:"avatar_url,omitempty"`
    +    HTMLURL           *string    `json:"html_url,omitempty"`
    +    Name              *string    `json:"name,omitempty"`
    +    Company           *string    `json:"company,omitempty"`
    +    Blog              *string    `json:"blog,omitempty"`
    +    Location          *string    `json:"location,omitempty"`
    +    Email             *string    `json:"email,omitempty"`
    +    PublicRepos       *int       `json:"public_repos,omitempty"`
    +    PublicGists       *int       `json:"public_gists,omitempty"`
    +    Followers         *int       `json:"followers,omitempty"`
    +    Following         *int       `json:"following,omitempty"`
    +    CreatedAt         *time.Time `json:"created_at,omitempty"`
    +    UpdatedAt         *time.Time `json:"updated_at,omitempty"`
    +    TotalPrivateRepos *int       `json:"total_private_repos,omitempty"`
    +    OwnedPrivateRepos *int       `json:"owned_private_repos,omitempty"`
    +    PrivateGists      *int       `json:"private_gists,omitempty"`
    +    DiskUsage         *int       `json:"disk_usage,omitempty"`
    +    Collaborators     *int       `json:"collaborators,omitempty"`
    +    BillingEmail      *string    `json:"billing_email,omitempty"`
    +    Type              *string    `json:"type,omitempty"`
    +    Plan              *Plan      `json:"plan,omitempty"`
    +
    +    // API URLs
    +    URL              *string `json:"url,omitempty"`
    +    EventsURL        *string `json:"events_url,omitempty"`
    +    MembersURL       *string `json:"members_url,omitempty"`
    +    PublicMembersURL *string `json:"public_members_url,omitempty"`
    +    ReposURL         *string `json:"repos_url,omitempty"`
    +}
    +

    +Organization represents a GitHub organization account. +

    + + + + + + + + + + + + + + +

    func (Organization) String

    +
    func (o Organization) String() string
    + + + + + + + + +

    type OrganizationAddTeamMembershipOptions

    +
    type OrganizationAddTeamMembershipOptions struct {
    +    // Role specifies the role the user should have in the team.  Possible
    +    // values are:
    +    //     member - a normal member of the team
    +    //     maintainer - a team maintainer. Able to add/remove other team
    +    //                  members, promote other team members to team
    +    //                  maintainer, and edit the team’s name and description
    +    //
    +    // Default value is "member".
    +    Role string `json:"role,omitempty"`
    +}
    +

    +OrganizationAddTeamMembershipOptions does stuff specifies the optional +parameters to the OrganizationsService.AddTeamMembership method. +

    + + + + + + + + + + + + + + + + +

    type OrganizationAddTeamRepoOptions

    +
    type OrganizationAddTeamRepoOptions struct {
    +    // Permission specifies the permission to grant the team on this repository.
    +    // Possible values are:
    +    //     pull - team members can pull, but not push to or administer this repository
    +    //     push - team members can pull and push, but not administer this repository
    +    //     admin - team members can pull, push and administer this repository
    +    //
    +    // If not specified, the team's permission attribute will be used.
    +    Permission string `json:"permission,omitempty"`
    +}
    +

    +OrganizationAddTeamRepoOptions specifies the optional parameters to the +OrganizationsService.AddTeamRepo method. +

    + + + + + + + + + + + + + + + + +

    type OrganizationListTeamMembersOptions

    +
    type OrganizationListTeamMembersOptions struct {
    +    // Role filters members returned by their role in the team.  Possible
    +    // values are "all", "member", "maintainer".  Default is "all".
    +    Role string `url:"role,omitempty"`
    +
    +    ListOptions
    +}
    +

    +OrganizationListTeamMembersOptions specifies the optional parameters to the +OrganizationsService.ListTeamMembers method. +

    + + + + + + + + + + + + + + + + +

    type OrganizationsListOptions

    +
    type OrganizationsListOptions struct {
    +    // Since filters Organizations by ID.
    +    Since int `url:"since,omitempty"`
    +
    +    ListOptions
    +}
    +

    +OrganizationsListOptions specifies the optional parameters to the +OrganizationsService.ListAll method. +

    + + + + + + + + + + + + + + + + +

    type OrganizationsService

    +
    type OrganizationsService service
    +

    +OrganizationsService provides access to the organization related functions +in the GitHub API. +

    +

    +GitHub API docs: http://developer.github.com/v3/orgs/ +

    + + + + + + + + + + + + + + +

    func (*OrganizationsService) AddTeamMembership

    +
    func (s *OrganizationsService) AddTeamMembership(team int, user string, opt *OrganizationAddTeamMembershipOptions) (*Membership, *Response, error)
    +

    +AddTeamMembership adds or invites a user to a team. +

    +

    +In order to add a membership between a user and a team, the authenticated +user must have 'admin' permissions to the team or be an owner of the +organization that the team is associated with. +

    +

    +If the user is already a part of the team's organization (meaning they're on +at least one other team in the organization), this endpoint will add the +user to the team. +

    +

    +If the user is completely unaffiliated with the team's organization (meaning +they're on none of the organization's teams), this endpoint will send an +invitation to the user via email. This newly-created membership will be in +the "pending" state until the user accepts the invitation, at which point +the membership will transition to the "active" state and the user will be +added as a member of the team. +

    +

    +GitHub API docs: https://developer.github.com/v3/orgs/teams/#add-team-membership +

    + + + + + + +

    func (*OrganizationsService) AddTeamRepo

    +
    func (s *OrganizationsService) AddTeamRepo(team int, owner string, repo string, opt *OrganizationAddTeamRepoOptions) (*Response, error)
    +

    +AddTeamRepo adds a repository to be managed by the specified team. The +specified repository must be owned by the organization to which the team +belongs, or a direct fork of a repository owned by the organization. +

    +

    +GitHub API docs: http://developer.github.com/v3/orgs/teams/#add-team-repo +

    + + + + + + +

    func (*OrganizationsService) ConcealMembership

    +
    func (s *OrganizationsService) ConcealMembership(org, user string) (*Response, error)
    +

    +ConcealMembership conceals a user's membership in an organization. +

    +

    +GitHub API docs: http://developer.github.com/v3/orgs/members/#conceal-a-users-membership +

    + + + + + + +

    func (*OrganizationsService) CreateHook

    +
    func (s *OrganizationsService) CreateHook(org string, hook *Hook) (*Hook, *Response, error)
    +

    +CreateHook creates a Hook for the specified org. +Name and Config are required fields. +

    +

    +GitHub API docs: https://developer.github.com/v3/orgs/hooks/#create-a-hook +

    + + + + + + +

    func (*OrganizationsService) CreateTeam

    +
    func (s *OrganizationsService) CreateTeam(org string, team *Team) (*Team, *Response, error)
    +

    +CreateTeam creates a new team within an organization. +

    +

    +GitHub API docs: http://developer.github.com/v3/orgs/teams/#create-team +

    + + + + + + +

    func (*OrganizationsService) DeleteHook

    +
    func (s *OrganizationsService) DeleteHook(org string, id int) (*Response, error)
    +

    +DeleteHook deletes a specified Hook. +

    +

    +GitHub API docs: https://developer.github.com/v3/orgs/hooks/#delete-a-hook +

    + + + + + + +

    func (*OrganizationsService) DeleteTeam

    +
    func (s *OrganizationsService) DeleteTeam(team int) (*Response, error)
    +

    +DeleteTeam deletes a team. +

    +

    +GitHub API docs: http://developer.github.com/v3/orgs/teams/#delete-team +

    + + + + + + +

    func (*OrganizationsService) Edit

    +
    func (s *OrganizationsService) Edit(name string, org *Organization) (*Organization, *Response, error)
    +

    +Edit an organization. +

    +

    +GitHub API docs: http://developer.github.com/v3/orgs/#edit-an-organization +

    + + + + + + +

    func (*OrganizationsService) EditHook

    +
    func (s *OrganizationsService) EditHook(org string, id int, hook *Hook) (*Hook, *Response, error)
    +

    +EditHook updates a specified Hook. +

    +

    +GitHub API docs: https://developer.github.com/v3/orgs/hooks/#edit-a-hook +

    + + + + + + +

    func (*OrganizationsService) EditOrgMembership

    +
    func (s *OrganizationsService) EditOrgMembership(user, org string, membership *Membership) (*Membership, *Response, error)
    +

    +EditOrgMembership edits the membership for user in specified organization. +Passing an empty string for user will edit the membership for the +authenticated user. +

    +

    +GitHub API docs: https://developer.github.com/v3/orgs/members/#add-or-update-organization-membership +GitHub API docs: https://developer.github.com/v3/orgs/members/#edit-your-organization-membership +

    + + + + + + +

    func (*OrganizationsService) EditTeam

    +
    func (s *OrganizationsService) EditTeam(id int, team *Team) (*Team, *Response, error)
    +

    +EditTeam edits a team. +

    +

    +GitHub API docs: http://developer.github.com/v3/orgs/teams/#edit-team +

    + + + + + + +

    func (*OrganizationsService) Get

    +
    func (s *OrganizationsService) Get(org string) (*Organization, *Response, error)
    +

    +Get fetches an organization by name. +

    +

    +GitHub API docs: http://developer.github.com/v3/orgs/#get-an-organization +

    + + + + + + +

    func (*OrganizationsService) GetHook

    +
    func (s *OrganizationsService) GetHook(org string, id int) (*Hook, *Response, error)
    +

    +GetHook returns a single specified Hook. +

    +

    +GitHub API docs: https://developer.github.com/v3/orgs/hooks/#get-single-hook +

    + + + + + + +

    func (*OrganizationsService) GetOrgMembership

    +
    func (s *OrganizationsService) GetOrgMembership(user, org string) (*Membership, *Response, error)
    +

    +GetOrgMembership gets the membership for a user in a specified organization. +Passing an empty string for user will get the membership for the +authenticated user. +

    +

    +GitHub API docs: https://developer.github.com/v3/orgs/members/#get-organization-membership +GitHub API docs: https://developer.github.com/v3/orgs/members/#get-your-organization-membership +

    + + + + + + +

    func (*OrganizationsService) GetTeam

    +
    func (s *OrganizationsService) GetTeam(team int) (*Team, *Response, error)
    +

    +GetTeam fetches a team by ID. +

    +

    +GitHub API docs: http://developer.github.com/v3/orgs/teams/#get-team +

    + + + + + + +

    func (*OrganizationsService) GetTeamMembership

    +
    func (s *OrganizationsService) GetTeamMembership(team int, user string) (*Membership, *Response, error)
    +

    +GetTeamMembership returns the membership status for a user in a team. +

    +

    +GitHub API docs: https://developer.github.com/v3/orgs/teams/#get-team-membership +

    + + + + + + +

    func (*OrganizationsService) IsMember

    +
    func (s *OrganizationsService) IsMember(org, user string) (bool, *Response, error)
    +

    +IsMember checks if a user is a member of an organization. +

    +

    +GitHub API docs: http://developer.github.com/v3/orgs/members/#check-membership +

    + + + + + + +

    func (*OrganizationsService) IsPublicMember

    +
    func (s *OrganizationsService) IsPublicMember(org, user string) (bool, *Response, error)
    +

    +IsPublicMember checks if a user is a public member of an organization. +

    +

    +GitHub API docs: http://developer.github.com/v3/orgs/members/#check-public-membership +

    + + + + + + +

    func (*OrganizationsService) IsTeamMember

    +
    func (s *OrganizationsService) IsTeamMember(team int, user string) (bool, *Response, error)
    +

    +IsTeamMember checks if a user is a member of the specified team. +

    +

    +GitHub API docs: http://developer.github.com/v3/orgs/teams/#get-team-member +

    + + + + + + +

    func (*OrganizationsService) IsTeamRepo

    +
    func (s *OrganizationsService) IsTeamRepo(team int, owner string, repo string) (*Repository, *Response, error)
    +

    +IsTeamRepo checks if a team manages the specified repository. If the +repository is managed by team, a Repository is returned which includes the +permissions team has for that repo. +

    +

    +GitHub API docs: https://developer.github.com/v3/orgs/teams/#check-if-a-team-manages-a-repository +

    + + + + + + +

    func (*OrganizationsService) List

    +
    func (s *OrganizationsService) List(user string, opt *ListOptions) ([]*Organization, *Response, error)
    +

    +List the organizations for a user. Passing the empty string will list +organizations for the authenticated user. +

    +

    +GitHub API docs: http://developer.github.com/v3/orgs/#list-user-organizations +

    + + + + + + +

    func (*OrganizationsService) ListAll

    +
    func (s *OrganizationsService) ListAll(opt *OrganizationsListOptions) ([]*Organization, *Response, error)
    +

    +ListAll lists all organizations, in the order that they were created on GitHub. +

    +

    +Note: Pagination is powered exclusively by the since parameter. To continue +listing the next set of organizations, use the ID of the last-returned organization +as the opts.Since parameter for the next call. +

    +

    +GitHub API docs: https://developer.github.com/v3/orgs/#list-all-organizations +

    + + + + + + +

    func (*OrganizationsService) ListHooks

    +
    func (s *OrganizationsService) ListHooks(org string, opt *ListOptions) ([]*Hook, *Response, error)
    +

    +ListHooks lists all Hooks for the specified organization. +

    +

    +GitHub API docs: https://developer.github.com/v3/orgs/hooks/#list-hooks +

    + + + + + + +

    func (*OrganizationsService) ListMembers

    +
    func (s *OrganizationsService) ListMembers(org string, opt *ListMembersOptions) ([]*User, *Response, error)
    +

    +ListMembers lists the members for an organization. If the authenticated +user is an owner of the organization, this will return both concealed and +public members, otherwise it will only return public members. +

    +

    +GitHub API docs: http://developer.github.com/v3/orgs/members/#members-list +

    + + + + + + +

    func (*OrganizationsService) ListOrgMemberships

    +
    func (s *OrganizationsService) ListOrgMemberships(opt *ListOrgMembershipsOptions) ([]*Membership, *Response, error)
    +

    +ListOrgMemberships lists the organization memberships for the authenticated user. +

    +

    +GitHub API docs: https://developer.github.com/v3/orgs/members/#list-your-organization-memberships +

    + + + + + + +

    func (*OrganizationsService) ListTeamMembers

    +
    func (s *OrganizationsService) ListTeamMembers(team int, opt *OrganizationListTeamMembersOptions) ([]*User, *Response, error)
    +

    +ListTeamMembers lists all of the users who are members of the specified +team. +

    +

    +GitHub API docs: http://developer.github.com/v3/orgs/teams/#list-team-members +

    + + + + + + +

    func (*OrganizationsService) ListTeamRepos

    +
    func (s *OrganizationsService) ListTeamRepos(team int, opt *ListOptions) ([]*Repository, *Response, error)
    +

    +ListTeamRepos lists the repositories that the specified team has access to. +

    +

    +GitHub API docs: http://developer.github.com/v3/orgs/teams/#list-team-repos +

    + + + + + + +

    func (*OrganizationsService) ListTeams

    +
    func (s *OrganizationsService) ListTeams(org string, opt *ListOptions) ([]*Team, *Response, error)
    +

    +ListTeams lists all of the teams for an organization. +

    +

    +GitHub API docs: http://developer.github.com/v3/orgs/teams/#list-teams +

    + + + + + + +

    func (*OrganizationsService) ListUserTeams

    +
    func (s *OrganizationsService) ListUserTeams(opt *ListOptions) ([]*Team, *Response, error)
    +

    +ListUserTeams lists a user's teams +GitHub API docs: https://developer.github.com/v3/orgs/teams/#list-user-teams +

    + + + + + + +

    func (*OrganizationsService) PingHook

    +
    func (s *OrganizationsService) PingHook(org string, id int) (*Response, error)
    +

    +PingHook triggers a 'ping' event to be sent to the Hook. +

    +

    +GitHub API docs: https://developer.github.com/v3/orgs/hooks/#ping-a-hook +

    + + + + + + +

    func (*OrganizationsService) PublicizeMembership

    +
    func (s *OrganizationsService) PublicizeMembership(org, user string) (*Response, error)
    +

    +PublicizeMembership publicizes a user's membership in an organization. (A +user cannot publicize the membership for another user.) +

    +

    +GitHub API docs: http://developer.github.com/v3/orgs/members/#publicize-a-users-membership +

    + + + + + + +

    func (*OrganizationsService) RemoveMember

    +
    func (s *OrganizationsService) RemoveMember(org, user string) (*Response, error)
    +

    +RemoveMember removes a user from all teams of an organization. +

    +

    +GitHub API docs: http://developer.github.com/v3/orgs/members/#remove-a-member +

    + + + + + + +

    func (*OrganizationsService) RemoveOrgMembership

    +
    func (s *OrganizationsService) RemoveOrgMembership(user, org string) (*Response, error)
    +

    +RemoveOrgMembership removes user from the specified organization. If the +user has been invited to the organization, this will cancel their invitation. +

    +

    +GitHub API docs: https://developer.github.com/v3/orgs/members/#remove-organization-membership +

    + + + + + + +

    func (*OrganizationsService) RemoveTeamMembership

    +
    func (s *OrganizationsService) RemoveTeamMembership(team int, user string) (*Response, error)
    +

    +RemoveTeamMembership removes a user from a team. +

    +

    +GitHub API docs: https://developer.github.com/v3/orgs/teams/#remove-team-membership +

    + + + + + + +

    func (*OrganizationsService) RemoveTeamRepo

    +
    func (s *OrganizationsService) RemoveTeamRepo(team int, owner string, repo string) (*Response, error)
    +

    +RemoveTeamRepo removes a repository from being managed by the specified +team. Note that this does not delete the repository, it just removes it +from the team. +

    +

    +GitHub API docs: http://developer.github.com/v3/orgs/teams/#remove-team-repo +

    + + + + + + + + +

    type Page

    +
    type Page struct {
    +    PageName *string `json:"page_name,omitempty"`
    +    Title    *string `json:"title,omitempty"`
    +    Summary  *string `json:"summary,omitempty"`
    +    Action   *string `json:"action,omitempty"`
    +    SHA      *string `json:"sha,omitempty"`
    +    HTMLURL  *string `json:"html_url,omitempty"`
    +}
    +

    +Page represents a single Wiki page. +

    + + + + + + + + + + + + + + + + +

    type PageBuildEvent

    +
    type PageBuildEvent struct {
    +    Build *PagesBuild `json:"build,omitempty"`
    +
    +    // The following fields are only populated by Webhook events.
    +    ID     *int        `json:"id,omitempty"`
    +    Repo   *Repository `json:"repository,omitempty"`
    +    Sender *User       `json:"sender,omitempty"`
    +}
    +

    +PageBuildEvent represents an attempted build of a GitHub Pages site, whether +successful or not. +The Webhook event name is "page_build". +

    +

    +This event is triggered on push to a GitHub Pages enabled branch (gh-pages +for project pages, master for user and organization pages). +

    +

    +Events of this type are not visible in timelines, they are only used to trigger hooks. +

    +

    +GitHub docs: https://developer.github.com/v3/activity/events/types/#pagebuildevent +

    + + + + + + + + + + + + + + + + +

    type Pages

    +
    type Pages struct {
    +    URL       *string `json:"url,omitempty"`
    +    Status    *string `json:"status,omitempty"`
    +    CNAME     *string `json:"cname,omitempty"`
    +    Custom404 *bool   `json:"custom_404,omitempty"`
    +    HTMLURL   *string `json:"html_url,omitempty"`
    +}
    +

    +Pages represents a GitHub Pages site configuration. +

    + + + + + + + + + + + + + + + + +

    type PagesBuild

    +
    type PagesBuild struct {
    +    URL       *string     `json:"url,omitempty"`
    +    Status    *string     `json:"status,omitempty"`
    +    Error     *PagesError `json:"error,omitempty"`
    +    Pusher    *User       `json:"pusher,omitempty"`
    +    Commit    *string     `json:"commit,omitempty"`
    +    Duration  *int        `json:"duration,omitempty"`
    +    CreatedAt *Timestamp  `json:"created_at,omitempty"`
    +    UpdatedAt *Timestamp  `json:"created_at,omitempty"`
    +}
    +

    +PagesBuild represents the build information for a GitHub Pages site. +

    + + + + + + + + + + + + + + + + +

    type PagesError

    +
    type PagesError struct {
    +    Message *string `json:"message,omitempty"`
    +}
    +

    +PagesError represents a build error for a GitHub Pages site. +

    + + + + + + + + + + + + + + + + +

    type Plan

    +
    type Plan struct {
    +    Name          *string `json:"name,omitempty"`
    +    Space         *int    `json:"space,omitempty"`
    +    Collaborators *int    `json:"collaborators,omitempty"`
    +    PrivateRepos  *int    `json:"private_repos,omitempty"`
    +}
    +

    +Plan represents the payment plan for an account. See plans at https://github.com/plans. +

    + + + + + + + + + + + + + + +

    func (Plan) String

    +
    func (p Plan) String() string
    + + + + + + + + +

    type Protection

    +
    type Protection struct {
    +    Enabled              *bool                 `json:"enabled,omitempty"`
    +    RequiredStatusChecks *RequiredStatusChecks `json:"required_status_checks,omitempty"`
    +}
    +

    +Protection represents a repository branch's protection +

    + + + + + + + + + + + + + + + + +

    type PublicEvent

    +
    type PublicEvent struct {
    +    // The following fields are only populated by Webhook events.
    +    Repo   *Repository `json:"repository,omitempty"`
    +    Sender *User       `json:"sender,omitempty"`
    +}
    +

    +PublicEvent is triggered when a private repository is open sourced. +According to GitHub: "Without a doubt: the best GitHub event." +The Webhook event name is "public". +

    +

    +GitHub docs: https://developer.github.com/v3/activity/events/types/#publicevent +

    + + + + + + + + + + + + + + + + +

    type PullRequest

    +
    type PullRequest struct {
    +    ID           *int       `json:"id,omitempty"`
    +    Number       *int       `json:"number,omitempty"`
    +    State        *string    `json:"state,omitempty"`
    +    Title        *string    `json:"title,omitempty"`
    +    Body         *string    `json:"body,omitempty"`
    +    CreatedAt    *time.Time `json:"created_at,omitempty"`
    +    UpdatedAt    *time.Time `json:"updated_at,omitempty"`
    +    ClosedAt     *time.Time `json:"closed_at,omitempty"`
    +    MergedAt     *time.Time `json:"merged_at,omitempty"`
    +    User         *User      `json:"user,omitempty"`
    +    Merged       *bool      `json:"merged,omitempty"`
    +    Mergeable    *bool      `json:"mergeable,omitempty"`
    +    MergedBy     *User      `json:"merged_by,omitempty"`
    +    Comments     *int       `json:"comments,omitempty"`
    +    Commits      *int       `json:"commits,omitempty"`
    +    Additions    *int       `json:"additions,omitempty"`
    +    Deletions    *int       `json:"deletions,omitempty"`
    +    ChangedFiles *int       `json:"changed_files,omitempty"`
    +    URL          *string    `json:"url,omitempty"`
    +    HTMLURL      *string    `json:"html_url,omitempty"`
    +    IssueURL     *string    `json:"issue_url,omitempty"`
    +    StatusesURL  *string    `json:"statuses_url,omitempty"`
    +    DiffURL      *string    `json:"diff_url,omitempty"`
    +    PatchURL     *string    `json:"patch_url,omitempty"`
    +    Assignee     *User      `json:"assignee,omitempty"` // probably only in webhooks
    +
    +    Head *PullRequestBranch `json:"head,omitempty"`
    +    Base *PullRequestBranch `json:"base,omitempty"`
    +}
    +

    +PullRequest represents a GitHub pull request on a repository. +

    + + + + + + + + + + + + + + +

    func (PullRequest) String

    +
    func (p PullRequest) String() string
    + + + + + + + + +

    type PullRequestBranch

    +
    type PullRequestBranch struct {
    +    Label *string     `json:"label,omitempty"`
    +    Ref   *string     `json:"ref,omitempty"`
    +    SHA   *string     `json:"sha,omitempty"`
    +    Repo  *Repository `json:"repo,omitempty"`
    +    User  *User       `json:"user,omitempty"`
    +}
    +

    +PullRequestBranch represents a base or head branch in a GitHub pull request. +

    + + + + + + + + + + + + + + + + +

    type PullRequestComment

    +
    type PullRequestComment struct {
    +    ID               *int       `json:"id,omitempty"`
    +    InReplyTo        *int       `json:"in_reply_to,omitempty"`
    +    Body             *string    `json:"body,omitempty"`
    +    Path             *string    `json:"path,omitempty"`
    +    DiffHunk         *string    `json:"diff_hunk,omitempty"`
    +    Position         *int       `json:"position,omitempty"`
    +    OriginalPosition *int       `json:"original_position,omitempty"`
    +    CommitID         *string    `json:"commit_id,omitempty"`
    +    OriginalCommitID *string    `json:"original_commit_id,omitempty"`
    +    User             *User      `json:"user,omitempty"`
    +    Reactions        *Reactions `json:"reactions,omitempty"`
    +    CreatedAt        *time.Time `json:"created_at,omitempty"`
    +    UpdatedAt        *time.Time `json:"updated_at,omitempty"`
    +    URL              *string    `json:"url,omitempty"`
    +    HTMLURL          *string    `json:"html_url,omitempty"`
    +    PullRequestURL   *string    `json:"pull_request_url,omitempty"`
    +}
    +

    +PullRequestComment represents a comment left on a pull request. +

    + + + + + + + + + + + + + + +

    func (PullRequestComment) String

    +
    func (p PullRequestComment) String() string
    + + + + + + + + +

    type PullRequestEvent

    +
    type PullRequestEvent struct {
    +    // Action is the action that was performed. Possible values are: "assigned",
    +    // "unassigned", "labeled", "unlabeled", "opened", "closed", or "reopened",
    +    // "synchronize", "edited". If the action is "closed" and the merged key is false,
    +    // the pull request was closed with unmerged commits. If the action is "closed"
    +    // and the merged key is true, the pull request was merged.
    +    Action      *string      `json:"action,omitempty"`
    +    Number      *int         `json:"number,omitempty"`
    +    PullRequest *PullRequest `json:"pull_request,omitempty"`
    +
    +    // The following fields are only populated by Webhook events.
    +    Changes *EditChange `json:"changes,omitempty"`
    +    Repo    *Repository `json:"repository,omitempty"`
    +    Sender  *User       `json:"sender,omitempty"`
    +}
    +

    +PullRequestEvent is triggered when a pull request is assigned, unassigned, +labeled, unlabeled, opened, closed, reopened, or synchronized. +The Webhook event name is "pull_request". +

    +

    +GitHub docs: https://developer.github.com/v3/activity/events/types/#pullrequestevent +

    + + + + + + + + + + + + + + + + + +
    type PullRequestLinks struct {
    +    URL      *string `json:"url,omitempty"`
    +    HTMLURL  *string `json:"html_url,omitempty"`
    +    DiffURL  *string `json:"diff_url,omitempty"`
    +    PatchURL *string `json:"patch_url,omitempty"`
    +}
    +

    +PullRequestLinks object is added to the Issue object when it's an issue included +in the IssueCommentEvent webhook payload, if the webhooks is fired by a comment on a PR +

    + + + + + + + + + + + + + + + + +

    type PullRequestListCommentsOptions

    +
    type PullRequestListCommentsOptions struct {
    +    // Sort specifies how to sort comments.  Possible values are: created, updated.
    +    Sort string `url:"sort,omitempty"`
    +
    +    // Direction in which to sort comments.  Possible values are: asc, desc.
    +    Direction string `url:"direction,omitempty"`
    +
    +    // Since filters comments by time.
    +    Since time.Time `url:"since,omitempty"`
    +
    +    ListOptions
    +}
    +

    +PullRequestListCommentsOptions specifies the optional parameters to the +PullRequestsService.ListComments method. +

    + + + + + + + + + + + + + + + + +

    type PullRequestListOptions

    +
    type PullRequestListOptions struct {
    +    // State filters pull requests based on their state.  Possible values are:
    +    // open, closed.  Default is "open".
    +    State string `url:"state,omitempty"`
    +
    +    // Head filters pull requests by head user and branch name in the format of:
    +    // "user:ref-name".
    +    Head string `url:"head,omitempty"`
    +
    +    // Base filters pull requests by base branch name.
    +    Base string `url:"base,omitempty"`
    +
    +    // Sort specifies how to sort pull requests. Possible values are: created,
    +    // updated, popularity, long-running. Default is "created".
    +    Sort string `url:"sort,omitempty"`
    +
    +    // Direction in which to sort pull requests. Possible values are: asc, desc.
    +    // If Sort is "created" or not specified, Default is "desc", otherwise Default
    +    // is "asc"
    +    Direction string `url:"direction,omitempty"`
    +
    +    ListOptions
    +}
    +

    +PullRequestListOptions specifies the optional parameters to the +PullRequestsService.List method. +

    + + + + + + + + + + + + + + + + +

    type PullRequestMergeResult

    +
    type PullRequestMergeResult struct {
    +    SHA     *string `json:"sha,omitempty"`
    +    Merged  *bool   `json:"merged,omitempty"`
    +    Message *string `json:"message,omitempty"`
    +}
    +

    +PullRequestMergeResult represents the result of merging a pull request. +

    + + + + + + + + + + + + + + + + +

    type PullRequestOptions

    +
    type PullRequestOptions struct {
    +    Squash bool
    +}
    +

    +PullRequestOptions lets you define how a pull request will be merged. +

    + + + + + + + + + + + + + + + + +

    type PullRequestReviewCommentEvent

    +
    type PullRequestReviewCommentEvent struct {
    +    // Action is the action that was performed on the comment.
    +    // Possible values are: "created", "edited", "deleted".
    +    Action      *string             `json:"action,omitempty"`
    +    PullRequest *PullRequest        `json:"pull_request,omitempty"`
    +    Comment     *PullRequestComment `json:"comment,omitempty"`
    +
    +    // The following fields are only populated by Webhook events.
    +    Changes *EditChange `json:"changes,omitempty"`
    +    Repo    *Repository `json:"repository,omitempty"`
    +    Sender  *User       `json:"sender,omitempty"`
    +}
    +

    +PullRequestReviewCommentEvent is triggered when a comment is created on a +portion of the unified diff of a pull request. +The Webhook event name is "pull_request_review_comment". +

    +

    +GitHub docs: https://developer.github.com/v3/activity/events/types/#pullrequestreviewcommentevent +

    + + + + + + + + + + + + + + + + +

    type PullRequestsService

    +
    type PullRequestsService service
    +

    +PullRequestsService handles communication with the pull request related +methods of the GitHub API. +

    +

    +GitHub API docs: http://developer.github.com/v3/pulls/ +

    + + + + + + + + + + + + + + +

    func (*PullRequestsService) Create

    +
    func (s *PullRequestsService) Create(owner string, repo string, pull *NewPullRequest) (*PullRequest, *Response, error)
    +

    +Create a new pull request on the specified repository. +

    +

    +GitHub API docs: https://developer.github.com/v3/pulls/#create-a-pull-request +

    + + + + + + +

    func (*PullRequestsService) CreateComment

    +
    func (s *PullRequestsService) CreateComment(owner string, repo string, number int, comment *PullRequestComment) (*PullRequestComment, *Response, error)
    +

    +CreateComment creates a new comment on the specified pull request. +

    +

    +GitHub API docs: https://developer.github.com/v3/pulls/comments/#create-a-comment +

    + + + + + + +

    func (*PullRequestsService) DeleteComment

    +
    func (s *PullRequestsService) DeleteComment(owner string, repo string, number int) (*Response, error)
    +

    +DeleteComment deletes a pull request comment. +

    +

    +GitHub API docs: https://developer.github.com/v3/pulls/comments/#delete-a-comment +

    + + + + + + +

    func (*PullRequestsService) Edit

    +
    func (s *PullRequestsService) Edit(owner string, repo string, number int, pull *PullRequest) (*PullRequest, *Response, error)
    +

    +Edit a pull request. +

    +

    +GitHub API docs: https://developer.github.com/v3/pulls/#update-a-pull-request +

    + + + + + + +

    func (*PullRequestsService) EditComment

    +
    func (s *PullRequestsService) EditComment(owner string, repo string, number int, comment *PullRequestComment) (*PullRequestComment, *Response, error)
    +

    +EditComment updates a pull request comment. +

    +

    +GitHub API docs: https://developer.github.com/v3/pulls/comments/#edit-a-comment +

    + + + + + + +

    func (*PullRequestsService) Get

    +
    func (s *PullRequestsService) Get(owner string, repo string, number int) (*PullRequest, *Response, error)
    +

    +Get a single pull request. +

    +

    +GitHub API docs: https://developer.github.com/v3/pulls/#get-a-single-pull-request +

    + + + + + + +

    func (*PullRequestsService) GetComment

    +
    func (s *PullRequestsService) GetComment(owner string, repo string, number int) (*PullRequestComment, *Response, error)
    +

    +GetComment fetches the specified pull request comment. +

    +

    +GitHub API docs: https://developer.github.com/v3/pulls/comments/#get-a-single-comment +

    + + + + + + +

    func (*PullRequestsService) IsMerged

    +
    func (s *PullRequestsService) IsMerged(owner string, repo string, number int) (bool, *Response, error)
    +

    +IsMerged checks if a pull request has been merged. +

    +

    +GitHub API docs: https://developer.github.com/v3/pulls/#get-if-a-pull-request-has-been-merged +

    + + + + + + +

    func (*PullRequestsService) List

    +
    func (s *PullRequestsService) List(owner string, repo string, opt *PullRequestListOptions) ([]*PullRequest, *Response, error)
    +

    +List the pull requests for the specified repository. +

    +

    +GitHub API docs: http://developer.github.com/v3/pulls/#list-pull-requests +

    + + + + + + +

    func (*PullRequestsService) ListComments

    +
    func (s *PullRequestsService) ListComments(owner string, repo string, number int, opt *PullRequestListCommentsOptions) ([]*PullRequestComment, *Response, error)
    +

    +ListComments lists all comments on the specified pull request. Specifying a +pull request number of 0 will return all comments on all pull requests for +the repository. +

    +

    +GitHub API docs: https://developer.github.com/v3/pulls/comments/#list-comments-on-a-pull-request +

    + + + + + + +

    func (*PullRequestsService) ListCommits

    +
    func (s *PullRequestsService) ListCommits(owner string, repo string, number int, opt *ListOptions) ([]*RepositoryCommit, *Response, error)
    +

    +ListCommits lists the commits in a pull request. +

    +

    +GitHub API docs: https://developer.github.com/v3/pulls/#list-commits-on-a-pull-request +

    + + + + + + +

    func (*PullRequestsService) ListFiles

    +
    func (s *PullRequestsService) ListFiles(owner string, repo string, number int, opt *ListOptions) ([]*CommitFile, *Response, error)
    +

    +ListFiles lists the files in a pull request. +

    +

    +GitHub API docs: https://developer.github.com/v3/pulls/#list-pull-requests-files +

    + + + + + + +

    func (*PullRequestsService) Merge

    +
    func (s *PullRequestsService) Merge(owner string, repo string, number int, commitMessage string, options *PullRequestOptions) (*PullRequestMergeResult, *Response, error)
    +

    +Merge a pull request (Merge Button™). +

    +

    +GitHub API docs: https://developer.github.com/v3/pulls/#merge-a-pull-request-merge-buttontrade +

    + + + + + + + + +

    type PunchCard

    +
    type PunchCard struct {
    +    Day     *int // Day of the week (0-6: =Sunday - Saturday).
    +    Hour    *int // Hour of day (0-23).
    +    Commits *int // Number of commits.
    +}
    +

    +PunchCard represents the number of commits made during a given hour of a +day of thew eek. +

    + + + + + + + + + + + + + + + + +

    type PushEvent

    +
    type PushEvent struct {
    +    PushID       *int                 `json:"push_id,omitempty"`
    +    Head         *string              `json:"head,omitempty"`
    +    Ref          *string              `json:"ref,omitempty"`
    +    Size         *int                 `json:"size,omitempty"`
    +    Commits      []PushEventCommit    `json:"commits,omitempty"`
    +    Repo         *PushEventRepository `json:"repository,omitempty"`
    +    Before       *string              `json:"before,omitempty"`
    +    DistinctSize *int                 `json:"distinct_size,omitempty"`
    +
    +    // The following fields are only populated by Webhook events.
    +    After      *string          `json:"after,omitempty"`
    +    Created    *bool            `json:"created,omitempty"`
    +    Deleted    *bool            `json:"deleted,omitempty"`
    +    Forced     *bool            `json:"forced,omitempty"`
    +    BaseRef    *string          `json:"base_ref,omitempty"`
    +    Compare    *string          `json:"compare,omitempty"`
    +    HeadCommit *PushEventCommit `json:"head_commit,omitempty"`
    +    Pusher     *User            `json:"pusher,omitempty"`
    +    Sender     *User            `json:"sender,omitempty"`
    +}
    +

    +PushEvent represents a git push to a GitHub repository. +

    +

    +GitHub API docs: http://developer.github.com/v3/activity/events/types/#pushevent +

    + + + + + + + + + + + + + + +

    func (PushEvent) String

    +
    func (p PushEvent) String() string
    + + + + + + + + +

    type PushEventCommit

    +
    type PushEventCommit struct {
    +    Message  *string       `json:"message,omitempty"`
    +    Author   *CommitAuthor `json:"author,omitempty"`
    +    URL      *string       `json:"url,omitempty"`
    +    Distinct *bool         `json:"distinct,omitempty"`
    +
    +    // The following fields are only populated by Events API.
    +    SHA *string `json:"sha,omitempty"`
    +
    +    // The following fields are only populated by Webhook events.
    +    ID        *string       `json:"id,omitempty"`
    +    TreeID    *string       `json:"tree_id,omitempty"`
    +    Timestamp *Timestamp    `json:"timestamp,omitempty"`
    +    Committer *CommitAuthor `json:"committer,omitempty"`
    +    Added     []string      `json:"added,omitempty"`
    +    Removed   []string      `json:"removed,omitempty"`
    +    Modified  []string      `json:"modified,omitempty"`
    +}
    +

    +PushEventCommit represents a git commit in a GitHub PushEvent. +

    + + + + + + + + + + + + + + +

    func (PushEventCommit) String

    +
    func (p PushEventCommit) String() string
    + + + + + + + + +

    type PushEventRepoOwner

    +
    type PushEventRepoOwner struct {
    +    Name  *string `json:"name,omitempty"`
    +    Email *string `json:"email,omitempty"`
    +}
    +

    +PushEventRepoOwner is a basic reporesntation of user/org in a PushEvent payload +

    + + + + + + + + + + + + + + + + +

    type PushEventRepository

    +
    type PushEventRepository struct {
    +    ID              *int                `json:"id,omitempty"`
    +    Name            *string             `json:"name,omitempty"`
    +    FullName        *string             `json:"full_name,omitempty"`
    +    Owner           *PushEventRepoOwner `json:"owner,omitempty"`
    +    Private         *bool               `json:"private,omitempty"`
    +    Description     *string             `json:"description,omitempty"`
    +    Fork            *bool               `json:"fork,omitempty"`
    +    CreatedAt       *Timestamp          `json:"created_at,omitempty"`
    +    PushedAt        *Timestamp          `json:"pushed_at,omitempty"`
    +    UpdatedAt       *Timestamp          `json:"updated_at,omitempty"`
    +    Homepage        *string             `json:"homepage,omitempty"`
    +    Size            *int                `json:"size,omitempty"`
    +    StargazersCount *int                `json:"stargazers_count,omitempty"`
    +    WatchersCount   *int                `json:"watchers_count,omitempty"`
    +    Language        *string             `json:"language,omitempty"`
    +    HasIssues       *bool               `json:"has_issues,omitempty"`
    +    HasDownloads    *bool               `json:"has_downloads,omitempty"`
    +    HasWiki         *bool               `json:"has_wiki,omitempty"`
    +    HasPages        *bool               `json:"has_pages,omitempty"`
    +    ForksCount      *int                `json:"forks_count,omitempty"`
    +    OpenIssuesCount *int                `json:"open_issues_count,omitempty"`
    +    DefaultBranch   *string             `json:"default_branch,omitempty"`
    +    MasterBranch    *string             `json:"master_branch,omitempty"`
    +    Organization    *string             `json:"organization,omitempty"`
    +
    +    // The following fields are only populated by Webhook events.
    +    URL     *string `json:"url,omitempty"`
    +    HTMLURL *string `json:"html_url,omitempty"`
    +}
    +

    +PushEventRepository represents the repo object in a PushEvent payload +

    + + + + + + + + + + + + + + + + +

    type Rate

    +
    type Rate struct {
    +    // The number of requests per hour the client is currently limited to.
    +    Limit int `json:"limit"`
    +
    +    // The number of remaining requests the client can make this hour.
    +    Remaining int `json:"remaining"`
    +
    +    // The time at which the current rate limit will reset.
    +    Reset Timestamp `json:"reset"`
    +}
    +

    +Rate represents the rate limit for the current client. +

    + + + + + + + + + + + + + + +

    func (Rate) String

    +
    func (r Rate) String() string
    + + + + + + + + +

    type RateLimitError

    +
    type RateLimitError struct {
    +    Rate     Rate           // Rate specifies last known rate limit for the client
    +    Response *http.Response // HTTP response that caused this error
    +    Message  string         `json:"message"` // error message
    +}
    +

    +RateLimitError occurs when GitHub returns 403 Forbidden response with a rate limit +remaining value of 0, and error message starts with "API rate limit exceeded for ". +

    + + + + + + + + + + + + + + +

    func (*RateLimitError) Error

    +
    func (r *RateLimitError) Error() string
    + + + + + + + + +

    type RateLimits

    +
    type RateLimits struct {
    +    // The rate limit for non-search API requests.  Unauthenticated
    +    // requests are limited to 60 per hour.  Authenticated requests are
    +    // limited to 5,000 per hour.
    +    //
    +    // GitHub API docs: https://developer.github.com/v3/#rate-limiting
    +    Core *Rate `json:"core"`
    +
    +    // The rate limit for search API requests.  Unauthenticated requests
    +    // are limited to 5 requests per minutes.  Authenticated requests are
    +    // limited to 20 per minute.
    +    //
    +    // GitHub API docs: https://developer.github.com/v3/search/#rate-limit
    +    Search *Rate `json:"search"`
    +}
    +

    +RateLimits represents the rate limits for the current client. +

    + + + + + + + + + + + + + + +

    func (RateLimits) String

    +
    func (r RateLimits) String() string
    + + + + + + + + +

    type Reaction

    +
    type Reaction struct {
    +    // ID is the Reaction ID.
    +    ID   *int  `json:"id,omitempty"`
    +    User *User `json:"user,omitempty"`
    +    // Content is the type of reaction.
    +    // Possible values are:
    +    //     "+1", "-1", "laugh", "confused", "heart", "hooray".
    +    Content *string `json:"content,omitempty"`
    +}
    +

    +Reaction represents a GitHub reaction. +

    + + + + + + + + + + + + + + +

    func (Reaction) String

    +
    func (r Reaction) String() string
    + + + + + + + + +

    type Reactions

    +
    type Reactions struct {
    +    TotalCount *int    `json:"total_count,omitempty"`
    +    PlusOne    *int    `json:"+1,omitempty"`
    +    MinusOne   *int    `json:"-1,omitempty"`
    +    Laugh      *int    `json:"laugh,omitempty"`
    +    Confused   *int    `json:"confused,omitempty"`
    +    Heart      *int    `json:"heart,omitempty"`
    +    Hooray     *int    `json:"hooray,omitempty"`
    +    URL        *string `json:"url,omitempty"`
    +}
    +

    +Reactions represents a summary of GitHub reactions. +

    + + + + + + + + + + + + + + + + +

    type ReactionsService

    +
    type ReactionsService service
    +

    +ReactionsService provides access to the reactions-related functions in the +GitHub API. +

    +

    +GitHub API docs: https://developer.github.com/v3/reactions/ +

    + + + + + + + + + + + + + + +

    func (ReactionsService) CreateCommentReaction

    +
    func (s ReactionsService) CreateCommentReaction(owner, repo string, id int, content string) (*Reaction, *Response, error)
    +

    +CreateCommentReaction creates a reaction for a commit comment. +Note that if you have already created a reaction of type content, the +previously created reaction will be returned with Status: 200 OK. +

    +

    +GitHub API docs: https://developer.github.com/v3/reactions/#create-reaction-for-a-commit-comment +

    + + + + + + +

    func (ReactionsService) CreateIssueCommentReaction

    +
    func (s ReactionsService) CreateIssueCommentReaction(owner, repo string, id int, content string) (*Reaction, *Response, error)
    +

    +CreateIssueCommentReaction creates a reaction for an issue comment. +Note that if you have already created a reaction of type content, the +previously created reaction will be returned with Status: 200 OK. +

    +

    +GitHub API docs: https://developer.github.com/v3/reactions/#create-reaction-for-an-issue-comment +

    + + + + + + +

    func (ReactionsService) CreateIssueReaction

    +
    func (s ReactionsService) CreateIssueReaction(owner, repo string, number int, content string) (*Reaction, *Response, error)
    +

    +CreateIssueReaction creates a reaction for an issue. +Note that if you have already created a reaction of type content, the +previously created reaction will be returned with Status: 200 OK. +

    +

    +GitHub API docs: https://developer.github.com/v3/reactions/#create-reaction-for-an-issue +

    + + + + + + +

    func (ReactionsService) CreatePullRequestCommentReaction

    +
    func (s ReactionsService) CreatePullRequestCommentReaction(owner, repo string, id int, content string) (*Reaction, *Response, error)
    +

    +CreatePullRequestCommentReaction creates a reaction for a pull request review comment. +Note that if you have already created a reaction of type content, the +previously created reaction will be returned with Status: 200 OK. +

    +

    +GitHub API docs: https://developer.github.com/v3/reactions/#create-reaction-for-an-issue-comment +

    + + + + + + +

    func (*ReactionsService) DeleteReaction

    +
    func (s *ReactionsService) DeleteReaction(id int) (*Response, error)
    +

    +DeleteReaction deletes a reaction. +

    +

    +GitHub API docs: https://developer.github.com/v3/reaction/reactions/#delete-a-reaction-archive +

    + + + + + + +

    func (*ReactionsService) ListCommentReactions

    +
    func (s *ReactionsService) ListCommentReactions(owner, repo string, id int, opt *ListOptions) ([]*Reaction, *Response, error)
    +

    +ListCommentReactions lists the reactions for a commit comment. +

    +

    +GitHub API docs: https://developer.github.com/v3/reactions/#list-reactions-for-a-commit-comment +

    + + + + + + +

    func (*ReactionsService) ListIssueCommentReactions

    +
    func (s *ReactionsService) ListIssueCommentReactions(owner, repo string, id int, opt *ListOptions) ([]*Reaction, *Response, error)
    +

    +ListIssueCommentReactions lists the reactions for an issue comment. +

    +

    +GitHub API docs: https://developer.github.com/v3/reactions/#list-reactions-for-an-issue-comment +

    + + + + + + +

    func (*ReactionsService) ListIssueReactions

    +
    func (s *ReactionsService) ListIssueReactions(owner, repo string, number int, opt *ListOptions) ([]*Reaction, *Response, error)
    +

    +ListIssueReactions lists the reactions for an issue. +

    +

    +GitHub API docs: https://developer.github.com/v3/reactions/#list-reactions-for-an-issue +

    + + + + + + +

    func (*ReactionsService) ListPullRequestCommentReactions

    +
    func (s *ReactionsService) ListPullRequestCommentReactions(owner, repo string, id int, opt *ListOptions) ([]*Reaction, *Response, error)
    +

    +ListPullRequestCommentReactions lists the reactions for a pull request review comment. +

    +

    +GitHub API docs: https://developer.github.com/v3/reactions/#list-reactions-for-an-issue-comment +

    + + + + + + + + +

    type Reference

    +
    type Reference struct {
    +    Ref    *string    `json:"ref"`
    +    URL    *string    `json:"url"`
    +    Object *GitObject `json:"object"`
    +}
    +

    +Reference represents a GitHub reference. +

    + + + + + + + + + + + + + + +

    func (Reference) String

    +
    func (r Reference) String() string
    + + + + + + + + +

    type ReferenceListOptions

    +
    type ReferenceListOptions struct {
    +    Type string `url:"-"`
    +
    +    ListOptions
    +}
    +

    +ReferenceListOptions specifies optional parameters to the +GitService.ListRefs method. +

    + + + + + + + + + + + + + + + + +

    type ReleaseAsset

    +
    type ReleaseAsset struct {
    +    ID                 *int       `json:"id,omitempty"`
    +    URL                *string    `json:"url,omitempty"`
    +    Name               *string    `json:"name,omitempty"`
    +    Label              *string    `json:"label,omitempty"`
    +    State              *string    `json:"state,omitempty"`
    +    ContentType        *string    `json:"content_type,omitempty"`
    +    Size               *int       `json:"size,omitempty"`
    +    DownloadCount      *int       `json:"download_count,omitempty"`
    +    CreatedAt          *Timestamp `json:"created_at,omitempty"`
    +    UpdatedAt          *Timestamp `json:"updated_at,omitempty"`
    +    BrowserDownloadURL *string    `json:"browser_download_url,omitempty"`
    +    Uploader           *User      `json:"uploader,omitempty"`
    +}
    +

    +ReleaseAsset represents a Github release asset in a repository. +

    + + + + + + + + + + + + + + +

    func (ReleaseAsset) String

    +
    func (r ReleaseAsset) String() string
    + + + + + + + + +

    type ReleaseEvent

    +
    type ReleaseEvent struct {
    +    // Action is the action that was performed. Possible value is: "published".
    +    Action  *string            `json:"action,omitempty"`
    +    Release *RepositoryRelease `json:"release,omitempty"`
    +
    +    // The following fields are only populated by Webhook events.
    +    Repo   *Repository `json:"repository,omitempty"`
    +    Sender *User       `json:"sender,omitempty"`
    +}
    +

    +ReleaseEvent is triggered when a release is published. +The Webhook event name is "release". +

    +

    +GitHub docs: https://developer.github.com/v3/activity/events/types/#releaseevent +

    + + + + + + + + + + + + + + + + +

    type Rename

    +
    type Rename struct {
    +    From *string `json:"from,omitempty"`
    +    To   *string `json:"to,omitempty"`
    +}
    +

    +Rename contains details for 'renamed' events. +

    + + + + + + + + + + + + + + +

    func (Rename) String

    +
    func (r Rename) String() string
    + + + + + + + + +

    type RepoStatus

    +
    type RepoStatus struct {
    +    ID  *int    `json:"id,omitempty"`
    +    URL *string `json:"url,omitempty"`
    +
    +    // State is the current state of the repository.  Possible values are:
    +    // pending, success, error, or failure.
    +    State *string `json:"state,omitempty"`
    +
    +    // TargetURL is the URL of the page representing this status.  It will be
    +    // linked from the GitHub UI to allow users to see the source of the status.
    +    TargetURL *string `json:"target_url,omitempty"`
    +
    +    // Description is a short high level summary of the status.
    +    Description *string `json:"description,omitempty"`
    +
    +    // A string label to differentiate this status from the statuses of other systems.
    +    Context *string `json:"context,omitempty"`
    +
    +    Creator   *User      `json:"creator,omitempty"`
    +    CreatedAt *time.Time `json:"created_at,omitempty"`
    +    UpdatedAt *time.Time `json:"updated_at,omitempty"`
    +}
    +

    +RepoStatus represents the status of a repository at a particular reference. +

    + + + + + + + + + + + + + + +

    func (RepoStatus) String

    +
    func (r RepoStatus) String() string
    + + + + + + + + +

    type RepositoriesSearchResult

    +
    type RepositoriesSearchResult struct {
    +    Total        *int         `json:"total_count,omitempty"`
    +    Repositories []Repository `json:"items,omitempty"`
    +}
    +

    +RepositoriesSearchResult represents the result of a repositories search. +

    + + + + + + + + + + + + + + + + +

    type RepositoriesService

    +
    type RepositoriesService service
    +

    +RepositoriesService handles communication with the repository related +methods of the GitHub API. +

    +

    +GitHub API docs: http://developer.github.com/v3/repos/ +

    + + + + + + + + + + + + + + +

    func (*RepositoriesService) AddCollaborator

    +
    func (s *RepositoriesService) AddCollaborator(owner, repo, user string, opt *RepositoryAddCollaboratorOptions) (*Response, error)
    +

    +AddCollaborator adds the specified Github user as collaborator to the given repo. +

    +

    +GitHub API docs: https://developer.github.com/v3/repos/collaborators/#add-user-as-a-collaborator +

    + + + + + + +

    func (*RepositoriesService) CompareCommits

    +
    func (s *RepositoriesService) CompareCommits(owner, repo string, base, head string) (*CommitsComparison, *Response, error)
    +

    +CompareCommits compares a range of commits with each other. +todo: support media formats - https://github.com/google/go-github/issues/6 +

    +

    +GitHub API docs: http://developer.github.com/v3/repos/commits/index.html#compare-two-commits +

    + + + + + + +

    func (*RepositoriesService) Create

    +
    func (s *RepositoriesService) Create(org string, repo *Repository) (*Repository, *Response, error)
    +

    +Create a new repository. If an organization is specified, the new +repository will be created under that org. If the empty string is +specified, it will be created for the authenticated user. +

    +

    +GitHub API docs: http://developer.github.com/v3/repos/#create +

    + + + + + + +

    func (*RepositoriesService) CreateComment

    +
    func (s *RepositoriesService) CreateComment(owner, repo, sha string, comment *RepositoryComment) (*RepositoryComment, *Response, error)
    +

    +CreateComment creates a comment for the given commit. +Note: GitHub allows for comments to be created for non-existing files and positions. +

    +

    +GitHub API docs: http://developer.github.com/v3/repos/comments/#create-a-commit-comment +

    + + + + + + +

    func (*RepositoriesService) CreateDeployment

    +
    func (s *RepositoriesService) CreateDeployment(owner, repo string, request *DeploymentRequest) (*Deployment, *Response, error)
    +

    +CreateDeployment creates a new deployment for a repository. +

    +

    +GitHub API docs: https://developer.github.com/v3/repos/deployments/#create-a-deployment +

    + + + + + + +

    func (*RepositoriesService) CreateDeploymentStatus

    +
    func (s *RepositoriesService) CreateDeploymentStatus(owner, repo string, deployment int, request *DeploymentStatusRequest) (*DeploymentStatus, *Response, error)
    +

    +CreateDeploymentStatus creates a new status for a deployment. +

    +

    +GitHub API docs: https://developer.github.com/v3/repos/deployments/#create-a-deployment-status +

    + + + + + + +

    func (*RepositoriesService) CreateFile

    +
    func (s *RepositoriesService) CreateFile(owner, repo, path string, opt *RepositoryContentFileOptions) (*RepositoryContentResponse, *Response, error)
    +

    +CreateFile creates a new file in a repository at the given path and returns +the commit and file metadata. +

    +

    +GitHub API docs: http://developer.github.com/v3/repos/contents/#create-a-file +

    + + + + + + +

    func (*RepositoriesService) CreateFork

    +
    func (s *RepositoriesService) CreateFork(owner, repo string, opt *RepositoryCreateForkOptions) (*Repository, *Response, error)
    +

    +CreateFork creates a fork of the specified repository. +

    +

    +GitHub API docs: http://developer.github.com/v3/repos/forks/#list-forks +

    + + + + + + +

    func (*RepositoriesService) CreateHook

    +
    func (s *RepositoriesService) CreateHook(owner, repo string, hook *Hook) (*Hook, *Response, error)
    +

    +CreateHook creates a Hook for the specified repository. +Name and Config are required fields. +

    +

    +GitHub API docs: http://developer.github.com/v3/repos/hooks/#create-a-hook +

    + + + + + + +

    func (*RepositoriesService) CreateKey

    +
    func (s *RepositoriesService) CreateKey(owner string, repo string, key *Key) (*Key, *Response, error)
    +

    +CreateKey adds a deploy key for a repository. +

    +

    +GitHub API docs: http://developer.github.com/v3/repos/keys/#create +

    + + + + + + +

    func (*RepositoriesService) CreateRelease

    +
    func (s *RepositoriesService) CreateRelease(owner, repo string, release *RepositoryRelease) (*RepositoryRelease, *Response, error)
    +

    +CreateRelease adds a new release for a repository. +

    +

    +GitHub API docs : http://developer.github.com/v3/repos/releases/#create-a-release +

    + + + + + + +

    func (*RepositoriesService) CreateStatus

    +
    func (s *RepositoriesService) CreateStatus(owner, repo, ref string, status *RepoStatus) (*RepoStatus, *Response, error)
    +

    +CreateStatus creates a new status for a repository at the specified +reference. Ref can be a SHA, a branch name, or a tag name. +

    +

    +GitHub API docs: http://developer.github.com/v3/repos/statuses/#create-a-status +

    + + + + + + +

    func (*RepositoriesService) Delete

    +
    func (s *RepositoriesService) Delete(owner, repo string) (*Response, error)
    +

    +Delete a repository. +

    +

    +GitHub API docs: https://developer.github.com/v3/repos/#delete-a-repository +

    + + + + + + +

    func (*RepositoriesService) DeleteComment

    +
    func (s *RepositoriesService) DeleteComment(owner, repo string, id int) (*Response, error)
    +

    +DeleteComment deletes a single comment from a repository. +

    +

    +GitHub API docs: http://developer.github.com/v3/repos/comments/#delete-a-commit-comment +

    + + + + + + +

    func (*RepositoriesService) DeleteFile

    +
    func (s *RepositoriesService) DeleteFile(owner, repo, path string, opt *RepositoryContentFileOptions) (*RepositoryContentResponse, *Response, error)
    +

    +DeleteFile deletes a file from a repository and returns the commit. +Requires the blob SHA of the file to be deleted. +

    +

    +GitHub API docs: http://developer.github.com/v3/repos/contents/#delete-a-file +

    + + + + + + +

    func (*RepositoriesService) DeleteHook

    +
    func (s *RepositoriesService) DeleteHook(owner, repo string, id int) (*Response, error)
    +

    +DeleteHook deletes a specified Hook. +

    +

    +GitHub API docs: http://developer.github.com/v3/repos/hooks/#delete-a-hook +

    + + + + + + +

    func (*RepositoriesService) DeleteInvitation

    +
    func (s *RepositoriesService) DeleteInvitation(repoID, invitationID int) (*Response, error)
    +

    +DeleteInvitation deletes a repository invitation. +

    +

    +GitHub API docs: https://developer.github.com/v3/repos/invitations/#delete-a-repository-invitation +

    + + + + + + +

    func (*RepositoriesService) DeleteKey

    +
    func (s *RepositoriesService) DeleteKey(owner string, repo string, id int) (*Response, error)
    +

    +DeleteKey deletes a deploy key. +

    +

    +GitHub API docs: http://developer.github.com/v3/repos/keys/#delete +

    + + + + + + +

    func (*RepositoriesService) DeleteRelease

    +
    func (s *RepositoriesService) DeleteRelease(owner, repo string, id int) (*Response, error)
    +

    +DeleteRelease delete a single release from a repository. +

    +

    +GitHub API docs : http://developer.github.com/v3/repos/releases/#delete-a-release +

    + + + + + + +

    func (*RepositoriesService) DeleteReleaseAsset

    +
    func (s *RepositoriesService) DeleteReleaseAsset(owner, repo string, id int) (*Response, error)
    +

    +DeleteReleaseAsset delete a single release asset from a repository. +

    +

    +GitHub API docs : http://developer.github.com/v3/repos/releases/#delete-a-release-asset +

    + + + + + + +

    func (*RepositoriesService) DownloadContents

    +
    func (s *RepositoriesService) DownloadContents(owner, repo, filepath string, opt *RepositoryContentGetOptions) (io.ReadCloser, error)
    +

    +DownloadContents returns an io.ReadCloser that reads the contents of the +specified file. This function will work with files of any size, as opposed +to GetContents which is limited to 1 Mb files. It is the caller's +responsibility to close the ReadCloser. +

    + + + + + + +

    func (*RepositoriesService) DownloadReleaseAsset

    +
    func (s *RepositoriesService) DownloadReleaseAsset(owner, repo string, id int) (rc io.ReadCloser, redirectURL string, err error)
    +

    +DownloadReleaseAsset downloads a release asset or returns a redirect URL. +

    +

    +DownloadReleaseAsset returns an io.ReadCloser that reads the contents of the +specified release asset. It is the caller's responsibility to close the ReadCloser. +If a redirect is returned, the redirect URL will be returned as a string instead +of the io.ReadCloser. Exactly one of rc and redirectURL will be zero. +

    +

    +GitHub API docs : http://developer.github.com/v3/repos/releases/#get-a-single-release-asset +

    + + + + + + +

    func (*RepositoriesService) Edit

    +
    func (s *RepositoriesService) Edit(owner, repo string, repository *Repository) (*Repository, *Response, error)
    +

    +Edit updates a repository. +

    +

    +GitHub API docs: http://developer.github.com/v3/repos/#edit +

    + + + + + + +

    func (*RepositoriesService) EditBranch

    +
    func (s *RepositoriesService) EditBranch(owner, repo, branchName string, branch *Branch) (*Branch, *Response, error)
    +

    +EditBranch edits the branch (currently only Branch Protection) +

    +

    +GitHub API docs: https://developer.github.com/v3/repos/#enabling-and-disabling-branch-protection +

    + + + + + + +

    func (*RepositoriesService) EditHook

    +
    func (s *RepositoriesService) EditHook(owner, repo string, id int, hook *Hook) (*Hook, *Response, error)
    +

    +EditHook updates a specified Hook. +

    +

    +GitHub API docs: http://developer.github.com/v3/repos/hooks/#edit-a-hook +

    + + + + + + +

    func (*RepositoriesService) EditKey

    +
    func (s *RepositoriesService) EditKey(owner string, repo string, id int, key *Key) (*Key, *Response, error)
    +

    +EditKey edits a deploy key. +

    +

    +GitHub API docs: http://developer.github.com/v3/repos/keys/#edit +

    + + + + + + +

    func (*RepositoriesService) EditRelease

    +
    func (s *RepositoriesService) EditRelease(owner, repo string, id int, release *RepositoryRelease) (*RepositoryRelease, *Response, error)
    +

    +EditRelease edits a repository release. +

    +

    +GitHub API docs : http://developer.github.com/v3/repos/releases/#edit-a-release +

    + + + + + + +

    func (*RepositoriesService) EditReleaseAsset

    +
    func (s *RepositoriesService) EditReleaseAsset(owner, repo string, id int, release *ReleaseAsset) (*ReleaseAsset, *Response, error)
    +

    +EditReleaseAsset edits a repository release asset. +

    +

    +GitHub API docs : http://developer.github.com/v3/repos/releases/#edit-a-release-asset +

    + + + + + + +

    func (*RepositoriesService) Get

    +
    func (s *RepositoriesService) Get(owner, repo string) (*Repository, *Response, error)
    +

    +Get fetches a repository. +

    +

    +GitHub API docs: http://developer.github.com/v3/repos/#get +

    + + + + + + + +
    func (s *RepositoriesService) GetArchiveLink(owner, repo string, archiveformat archiveFormat, opt *RepositoryContentGetOptions) (*url.URL, *Response, error)
    +

    +GetArchiveLink returns an URL to download a tarball or zipball archive for a +repository. The archiveFormat can be specified by either the github.Tarball +or github.Zipball constant. +

    +

    +GitHub API docs: http://developer.github.com/v3/repos/contents/#get-archive-link +

    + + + + + + +

    func (*RepositoriesService) GetBranch

    +
    func (s *RepositoriesService) GetBranch(owner, repo, branch string) (*Branch, *Response, error)
    +

    +GetBranch gets the specified branch for a repository. +

    +

    +GitHub API docs: https://developer.github.com/v3/repos/#get-branch +

    + + + + + + +

    func (*RepositoriesService) GetByID

    +
    func (s *RepositoriesService) GetByID(id int) (*Repository, *Response, error)
    +

    +GetByID fetches a repository. +

    +

    +Note: GetByID uses the undocumented GitHub API endpoint /repositories/:id. +

    + + + + + + +

    func (*RepositoriesService) GetCombinedStatus

    +
    func (s *RepositoriesService) GetCombinedStatus(owner, repo, ref string, opt *ListOptions) (*CombinedStatus, *Response, error)
    +

    +GetCombinedStatus returns the combined status of a repository at the specified +reference. ref can be a SHA, a branch name, or a tag name. +

    +

    +GitHub API docs: https://developer.github.com/v3/repos/statuses/#get-the-combined-status-for-a-specific-ref +

    + + + + + + +

    func (*RepositoriesService) GetComment

    +
    func (s *RepositoriesService) GetComment(owner, repo string, id int) (*RepositoryComment, *Response, error)
    +

    +GetComment gets a single comment from a repository. +

    +

    +GitHub API docs: http://developer.github.com/v3/repos/comments/#get-a-single-commit-comment +

    + + + + + + +

    func (*RepositoriesService) GetCommit

    +
    func (s *RepositoriesService) GetCommit(owner, repo, sha string) (*RepositoryCommit, *Response, error)
    +

    +GetCommit fetches the specified commit, including all details about it. +todo: support media formats - https://github.com/google/go-github/issues/6 +

    +

    +GitHub API docs: http://developer.github.com/v3/repos/commits/#get-a-single-commit +See also: http://developer.github.com//v3/git/commits/#get-a-single-commit provides the same functionality +

    + + + + + + +

    func (*RepositoriesService) GetCommitSHA1

    +
    func (s *RepositoriesService) GetCommitSHA1(owner, repo, ref, lastSHA string) (string, *Response, error)
    +

    +GetCommitSHA1 gets the SHA-1 of a commit reference. If a last-known SHA1 is +supplied and no new commits have occurred, a 304 Unmodified response is returned. +

    +

    +GitHub API docs: https://developer.github.com/v3/repos/commits/#get-the-sha-1-of-a-commit-reference +

    + + + + + + +

    func (*RepositoriesService) GetContents

    +
    func (s *RepositoriesService) GetContents(owner, repo, path string, opt *RepositoryContentGetOptions) (fileContent *RepositoryContent, directoryContent []*RepositoryContent, resp *Response, err error)
    +

    +GetContents can return either the metadata and content of a single file +(when path references a file) or the metadata of all the files and/or +subdirectories of a directory (when path references a directory). To make it +easy to distinguish between both result types and to mimic the API as much +as possible, both result types will be returned but only one will contain a +value and the other will be nil. +

    +

    +GitHub API docs: http://developer.github.com/v3/repos/contents/#get-contents +

    + + + + + + +

    func (*RepositoriesService) GetHook

    +
    func (s *RepositoriesService) GetHook(owner, repo string, id int) (*Hook, *Response, error)
    +

    +GetHook returns a single specified Hook. +

    +

    +GitHub API docs: http://developer.github.com/v3/repos/hooks/#get-single-hook +

    + + + + + + +

    func (*RepositoriesService) GetKey

    +
    func (s *RepositoriesService) GetKey(owner string, repo string, id int) (*Key, *Response, error)
    +

    +GetKey fetches a single deploy key. +

    +

    +GitHub API docs: http://developer.github.com/v3/repos/keys/#get +

    + + + + + + +

    func (*RepositoriesService) GetLatestPagesBuild

    +
    func (s *RepositoriesService) GetLatestPagesBuild(owner string, repo string) (*PagesBuild, *Response, error)
    +

    +GetLatestPagesBuild fetches the latest build information for a GitHub pages site. +

    +

    +GitHub API docs: https://developer.github.com/v3/repos/pages/#list-latest-pages-build +

    + + + + + + +

    func (*RepositoriesService) GetLatestRelease

    +
    func (s *RepositoriesService) GetLatestRelease(owner, repo string) (*RepositoryRelease, *Response, error)
    +

    +GetLatestRelease fetches the latest published release for the repository. +

    +

    +GitHub API docs: https://developer.github.com/v3/repos/releases/#get-the-latest-release +

    + + + + + + +

    func (*RepositoriesService) GetPagesInfo

    +
    func (s *RepositoriesService) GetPagesInfo(owner string, repo string) (*Pages, *Response, error)
    +

    +GetPagesInfo fetches information about a GitHub Pages site. +

    +

    +GitHub API docs: https://developer.github.com/v3/repos/pages/#get-information-about-a-pages-site +

    + + + + + + +

    func (*RepositoriesService) GetReadme

    +
    func (s *RepositoriesService) GetReadme(owner, repo string, opt *RepositoryContentGetOptions) (*RepositoryContent, *Response, error)
    +

    +GetReadme gets the Readme file for the repository. +

    +

    +GitHub API docs: http://developer.github.com/v3/repos/contents/#get-the-readme +

    + + +
    + +
    +

    Example

    + + + +

    Code:

    +
    +client := github.NewClient(nil)
    +
    +readme, _, err := client.Repositories.GetReadme("google", "go-github", nil)
    +if err != nil {
    +    fmt.Println(err)
    +    return
    +}
    +
    +content, err := readme.GetContent()
    +if err != nil {
    +    fmt.Println(err)
    +    return
    +}
    +
    +fmt.Printf("google/go-github README:\n%v\n", content)
    +
    + + +
    +
    + + + + +

    func (*RepositoriesService) GetRelease

    +
    func (s *RepositoriesService) GetRelease(owner, repo string, id int) (*RepositoryRelease, *Response, error)
    +

    +GetRelease fetches a single release. +

    +

    +GitHub API docs: http://developer.github.com/v3/repos/releases/#get-a-single-release +

    + + + + + + +

    func (*RepositoriesService) GetReleaseAsset

    +
    func (s *RepositoriesService) GetReleaseAsset(owner, repo string, id int) (*ReleaseAsset, *Response, error)
    +

    +GetReleaseAsset fetches a single release asset. +

    +

    +GitHub API docs : http://developer.github.com/v3/repos/releases/#get-a-single-release-asset +

    + + + + + + +

    func (*RepositoriesService) GetReleaseByTag

    +
    func (s *RepositoriesService) GetReleaseByTag(owner, repo, tag string) (*RepositoryRelease, *Response, error)
    +

    +GetReleaseByTag fetches a release with the specified tag. +

    +

    +GitHub API docs: https://developer.github.com/v3/repos/releases/#get-a-release-by-tag-name +

    + + + + + + +

    func (*RepositoriesService) IsCollaborator

    +
    func (s *RepositoriesService) IsCollaborator(owner, repo, user string) (bool, *Response, error)
    +

    +IsCollaborator checks whether the specified Github user has collaborator +access to the given repo. +Note: This will return false if the user is not a collaborator OR the user +is not a GitHub user. +

    +

    +GitHub API docs: http://developer.github.com/v3/repos/collaborators/#get +

    + + + + + + +

    func (*RepositoriesService) License

    +
    func (s *RepositoriesService) License(owner, repo string) (*License, *Response, error)
    +

    +License gets the contents of a repository's license if one is detected. +

    +

    +GitHub API docs: https://developer.github.com/v3/licenses/#get-the-contents-of-a-repositorys-license +

    + + + + + + +

    func (*RepositoriesService) List

    +
    func (s *RepositoriesService) List(user string, opt *RepositoryListOptions) ([]*Repository, *Response, error)
    +

    +List the repositories for a user. Passing the empty string will list +repositories for the authenticated user. +

    +

    +GitHub API docs: http://developer.github.com/v3/repos/#list-user-repositories +

    + + +
    + +
    +

    Example

    + + + +

    Code:

    +
    +client := github.NewClient(nil)
    +
    +user := "willnorris"
    +opt := &github.RepositoryListOptions{Type: "owner", Sort: "updated", Direction: "desc"}
    +
    +repos, _, err := client.Repositories.List(user, opt)
    +if err != nil {
    +    fmt.Println(err)
    +}
    +
    +fmt.Printf("Recently updated repositories by %q: %v", user, github.Stringify(repos))
    +
    + + +
    +
    + + + + +

    func (*RepositoriesService) ListAll

    +
    func (s *RepositoriesService) ListAll(opt *RepositoryListAllOptions) ([]*Repository, *Response, error)
    +

    +ListAll lists all GitHub repositories in the order that they were created. +

    +

    +GitHub API docs: http://developer.github.com/v3/repos/#list-all-public-repositories +

    + + + + + + +

    func (*RepositoriesService) ListBranches

    +
    func (s *RepositoriesService) ListBranches(owner string, repo string, opt *ListOptions) ([]*Branch, *Response, error)
    +

    +ListBranches lists branches for the specified repository. +

    +

    +GitHub API docs: http://developer.github.com/v3/repos/#list-branches +

    + + + + + + +

    func (*RepositoriesService) ListByOrg

    +
    func (s *RepositoriesService) ListByOrg(org string, opt *RepositoryListByOrgOptions) ([]*Repository, *Response, error)
    +

    +ListByOrg lists the repositories for an organization. +

    +

    +GitHub API docs: http://developer.github.com/v3/repos/#list-organization-repositories +

    + + + + + + +

    func (*RepositoriesService) ListCodeFrequency

    +
    func (s *RepositoriesService) ListCodeFrequency(owner, repo string) ([]*WeeklyStats, *Response, error)
    +

    +ListCodeFrequency returns a weekly aggregate of the number of additions and +deletions pushed to a repository. Returned WeeklyStats will contain +additions and deletions, but not total commits. +

    +

    +GitHub API Docs: https://developer.github.com/v3/repos/statistics/#code-frequency +

    + + + + + + +

    func (*RepositoriesService) ListCollaborators

    +
    func (s *RepositoriesService) ListCollaborators(owner, repo string, opt *ListOptions) ([]*User, *Response, error)
    +

    +ListCollaborators lists the Github users that have access to the repository. +

    +

    +GitHub API docs: http://developer.github.com/v3/repos/collaborators/#list +

    + + + + + + +

    func (*RepositoriesService) ListComments

    +
    func (s *RepositoriesService) ListComments(owner, repo string, opt *ListOptions) ([]*RepositoryComment, *Response, error)
    +

    +ListComments lists all the comments for the repository. +

    +

    +GitHub API docs: http://developer.github.com/v3/repos/comments/#list-commit-comments-for-a-repository +

    + + + + + + +

    func (*RepositoriesService) ListCommitActivity

    +
    func (s *RepositoriesService) ListCommitActivity(owner, repo string) ([]*WeeklyCommitActivity, *Response, error)
    +

    +ListCommitActivity returns the last year of commit activity +grouped by week. The days array is a group of commits per day, +starting on Sunday. +

    +

    +If this is the first time these statistics are requested for the given +repository, this method will return a non-nil error and a status code of +202. This is because this is the status that github returns to signify that +it is now computing the requested statistics. A follow up request, after a +delay of a second or so, should result in a successful request. +

    +

    +GitHub API Docs: https://developer.github.com/v3/repos/statistics/#commit-activity +

    + + + + + + +

    func (*RepositoriesService) ListCommitComments

    +
    func (s *RepositoriesService) ListCommitComments(owner, repo, sha string, opt *ListOptions) ([]*RepositoryComment, *Response, error)
    +

    +ListCommitComments lists all the comments for a given commit SHA. +

    +

    +GitHub API docs: http://developer.github.com/v3/repos/comments/#list-comments-for-a-single-commit +

    + + + + + + +

    func (*RepositoriesService) ListCommits

    +
    func (s *RepositoriesService) ListCommits(owner, repo string, opt *CommitsListOptions) ([]*RepositoryCommit, *Response, error)
    +

    +ListCommits lists the commits of a repository. +

    +

    +GitHub API docs: http://developer.github.com/v3/repos/commits/#list +

    + + + + + + +

    func (*RepositoriesService) ListContributors

    +
    func (s *RepositoriesService) ListContributors(owner string, repository string, opt *ListContributorsOptions) ([]*Contributor, *Response, error)
    +

    +ListContributors lists contributors for a repository. +

    +

    +GitHub API docs: http://developer.github.com/v3/repos/#list-contributors +

    + + + + + + +

    func (*RepositoriesService) ListContributorsStats

    +
    func (s *RepositoriesService) ListContributorsStats(owner, repo string) ([]*ContributorStats, *Response, error)
    +

    +ListContributorsStats gets a repo's contributor list with additions, +deletions and commit counts. +

    +

    +If this is the first time these statistics are requested for the given +repository, this method will return a non-nil error and a status code of +202. This is because this is the status that github returns to signify that +it is now computing the requested statistics. A follow up request, after a +delay of a second or so, should result in a successful request. +

    +

    +GitHub API Docs: https://developer.github.com/v3/repos/statistics/#contributors +

    + + + + + + +

    func (*RepositoriesService) ListDeploymentStatuses

    +
    func (s *RepositoriesService) ListDeploymentStatuses(owner, repo string, deployment int, opt *ListOptions) ([]*DeploymentStatus, *Response, error)
    +

    +ListDeploymentStatuses lists the statuses of a given deployment of a repository. +

    +

    +GitHub API docs: https://developer.github.com/v3/repos/deployments/#list-deployment-statuses +

    + + + + + + +

    func (*RepositoriesService) ListDeployments

    +
    func (s *RepositoriesService) ListDeployments(owner, repo string, opt *DeploymentsListOptions) ([]*Deployment, *Response, error)
    +

    +ListDeployments lists the deployments of a repository. +

    +

    +GitHub API docs: https://developer.github.com/v3/repos/deployments/#list-deployments +

    + + + + + + +

    func (*RepositoriesService) ListForks

    +
    func (s *RepositoriesService) ListForks(owner, repo string, opt *RepositoryListForksOptions) ([]*Repository, *Response, error)
    +

    +ListForks lists the forks of the specified repository. +

    +

    +GitHub API docs: http://developer.github.com/v3/repos/forks/#list-forks +

    + + + + + + +

    func (*RepositoriesService) ListHooks

    +
    func (s *RepositoriesService) ListHooks(owner, repo string, opt *ListOptions) ([]*Hook, *Response, error)
    +

    +ListHooks lists all Hooks for the specified repository. +

    +

    +GitHub API docs: http://developer.github.com/v3/repos/hooks/#list +

    + + + + + + +

    func (*RepositoriesService) ListInvitations

    +
    func (s *RepositoriesService) ListInvitations(repoID int, opt *ListOptions) ([]*RepositoryInvitation, *Response, error)
    +

    +ListInvitations lists all currently-open repository invitations. +

    +

    +GitHub API docs: https://developer.github.com/v3/repos/invitations/#list-invitations-for-a-repository +

    + + + + + + +

    func (*RepositoriesService) ListKeys

    +
    func (s *RepositoriesService) ListKeys(owner string, repo string, opt *ListOptions) ([]*Key, *Response, error)
    +

    +ListKeys lists the deploy keys for a repository. +

    +

    +GitHub API docs: http://developer.github.com/v3/repos/keys/#list +

    + + + + + + +

    func (*RepositoriesService) ListLanguages

    +
    func (s *RepositoriesService) ListLanguages(owner string, repo string) (map[string]int, *Response, error)
    +

    +ListLanguages lists languages for the specified repository. The returned map +specifies the languages and the number of bytes of code written in that +language. For example: +

    +
    {
    +  "C": 78769,
    +  "Python": 7769
    +}
    +
    +

    +GitHub API Docs: http://developer.github.com/v3/repos/#list-languages +

    + + + + + + +

    func (*RepositoriesService) ListPagesBuilds

    +
    func (s *RepositoriesService) ListPagesBuilds(owner string, repo string) ([]*PagesBuild, *Response, error)
    +

    +ListPagesBuilds lists the builds for a GitHub Pages site. +

    +

    +GitHub API docs: https://developer.github.com/v3/repos/pages/#list-pages-builds +

    + + + + + + +

    func (*RepositoriesService) ListParticipation

    +
    func (s *RepositoriesService) ListParticipation(owner, repo string) (*RepositoryParticipation, *Response, error)
    +

    +ListParticipation returns the total commit counts for the 'owner' +and total commit counts in 'all'. 'all' is everyone combined, +including the 'owner' in the last 52 weeks. If you’d like to get +the commit counts for non-owners, you can subtract 'all' from 'owner'. +

    +

    +The array order is oldest week (index 0) to most recent week. +

    +

    +If this is the first time these statistics are requested for the given +repository, this method will return a non-nil error and a status code +of 202. This is because this is the status that github returns to +signify that it is now computing the requested statistics. A follow +up request, after a delay of a second or so, should result in a +successful request. +

    +

    +GitHub API Docs: https://developer.github.com/v3/repos/statistics/#participation +

    + + + + + + +

    func (*RepositoriesService) ListPunchCard

    +
    func (s *RepositoriesService) ListPunchCard(owner, repo string) ([]*PunchCard, *Response, error)
    +

    +ListPunchCard returns the number of commits per hour in each day. +

    +

    +GitHub API Docs: https://developer.github.com/v3/repos/statistics/#punch-card +

    + + + + + + +

    func (*RepositoriesService) ListReleaseAssets

    +
    func (s *RepositoriesService) ListReleaseAssets(owner, repo string, id int, opt *ListOptions) ([]*ReleaseAsset, *Response, error)
    +

    +ListReleaseAssets lists the release's assets. +

    +

    +GitHub API docs : http://developer.github.com/v3/repos/releases/#list-assets-for-a-release +

    + + + + + + +

    func (*RepositoriesService) ListReleases

    +
    func (s *RepositoriesService) ListReleases(owner, repo string, opt *ListOptions) ([]*RepositoryRelease, *Response, error)
    +

    +ListReleases lists the releases for a repository. +

    +

    +GitHub API docs: http://developer.github.com/v3/repos/releases/#list-releases-for-a-repository +

    + + + + + + +

    func (*RepositoriesService) ListServiceHooks

    +
    func (s *RepositoriesService) ListServiceHooks() ([]*ServiceHook, *Response, error)
    +

    +ListServiceHooks is deprecated. Use Client.ListServiceHooks instead. +

    + + + + + + +

    func (*RepositoriesService) ListStatuses

    +
    func (s *RepositoriesService) ListStatuses(owner, repo, ref string, opt *ListOptions) ([]*RepoStatus, *Response, error)
    +

    +ListStatuses lists the statuses of a repository at the specified +reference. ref can be a SHA, a branch name, or a tag name. +

    +

    +GitHub API docs: http://developer.github.com/v3/repos/statuses/#list-statuses-for-a-specific-ref +

    + + + + + + +

    func (*RepositoriesService) ListTags

    +
    func (s *RepositoriesService) ListTags(owner string, repo string, opt *ListOptions) ([]*RepositoryTag, *Response, error)
    +

    +ListTags lists tags for the specified repository. +

    +

    +GitHub API docs: https://developer.github.com/v3/repos/#list-tags +

    + + + + + + +

    func (*RepositoriesService) ListTeams

    +
    func (s *RepositoriesService) ListTeams(owner string, repo string, opt *ListOptions) ([]*Team, *Response, error)
    +

    +ListTeams lists the teams for the specified repository. +

    +

    +GitHub API docs: https://developer.github.com/v3/repos/#list-teams +

    + + + + + + +

    func (*RepositoriesService) Merge

    +
    func (s *RepositoriesService) Merge(owner, repo string, request *RepositoryMergeRequest) (*RepositoryCommit, *Response, error)
    +

    +Merge a branch in the specified repository. +

    +

    +GitHub API docs: https://developer.github.com/v3/repos/merging/#perform-a-merge +

    + + + + + + +

    func (*RepositoriesService) PingHook

    +
    func (s *RepositoriesService) PingHook(owner, repo string, id int) (*Response, error)
    +

    +PingHook triggers a 'ping' event to be sent to the Hook. +

    +

    +GitHub API docs: https://developer.github.com/v3/repos/hooks/#ping-a-hook +

    + + + + + + +

    func (*RepositoriesService) RemoveCollaborator

    +
    func (s *RepositoriesService) RemoveCollaborator(owner, repo, user string) (*Response, error)
    +

    +RemoveCollaborator removes the specified Github user as collaborator from the given repo. +Note: Does not return error if a valid user that is not a collaborator is removed. +

    +

    +GitHub API docs: http://developer.github.com/v3/repos/collaborators/#remove-collaborator +

    + + + + + + +

    func (*RepositoriesService) RequestPageBuild

    +
    func (s *RepositoriesService) RequestPageBuild(owner string, repo string) (*PagesBuild, *Response, error)
    +

    +RequestPageBuild requests a build of a GitHub Pages site without needing to push new commit. +

    +

    +GitHub API docs: https://developer.github.com/v3/repos/pages/#request-a-page-build +

    + + + + + + +

    func (*RepositoriesService) TestHook

    +
    func (s *RepositoriesService) TestHook(owner, repo string, id int) (*Response, error)
    +

    +TestHook triggers a test Hook by github. +

    +

    +GitHub API docs: http://developer.github.com/v3/repos/hooks/#test-a-push-hook +

    + + + + + + +

    func (*RepositoriesService) UpdateComment

    +
    func (s *RepositoriesService) UpdateComment(owner, repo string, id int, comment *RepositoryComment) (*RepositoryComment, *Response, error)
    +

    +UpdateComment updates the body of a single comment. +

    +

    +GitHub API docs: http://developer.github.com/v3/repos/comments/#update-a-commit-comment +

    + + + + + + +

    func (*RepositoriesService) UpdateFile

    +
    func (s *RepositoriesService) UpdateFile(owner, repo, path string, opt *RepositoryContentFileOptions) (*RepositoryContentResponse, *Response, error)
    +

    +UpdateFile updates a file in a repository at the given path and returns the +commit and file metadata. Requires the blob SHA of the file being updated. +

    +

    +GitHub API docs: http://developer.github.com/v3/repos/contents/#update-a-file +

    + + + + + + +

    func (*RepositoriesService) UpdateInvitation

    +
    func (s *RepositoriesService) UpdateInvitation(repoID, invitationID int, permissions string) (*RepositoryInvitation, *Response, error)
    +

    +UpdateInvitation updates the permissions associated with a repository +invitation. +

    +

    +permissions represents the permissions that the associated user will have +on the repository. Possible values are: "read", "write", "admin". +

    +

    +GitHub API docs: https://developer.github.com/v3/repos/invitations/#update-a-repository-invitation +

    + + + + + + +

    func (*RepositoriesService) UploadReleaseAsset

    +
    func (s *RepositoriesService) UploadReleaseAsset(owner, repo string, id int, opt *UploadOptions, file *os.File) (*ReleaseAsset, *Response, error)
    +

    +UploadReleaseAsset creates an asset by uploading a file into a release repository. +To upload assets that cannot be represented by an os.File, call NewUploadRequest directly. +

    +

    +GitHub API docs : http://developer.github.com/v3/repos/releases/#upload-a-release-asset +

    + + + + + + + + +

    type Repository

    +
    type Repository struct {
    +    ID               *int             `json:"id,omitempty"`
    +    Owner            *User            `json:"owner,omitempty"`
    +    Name             *string          `json:"name,omitempty"`
    +    FullName         *string          `json:"full_name,omitempty"`
    +    Description      *string          `json:"description,omitempty"`
    +    Homepage         *string          `json:"homepage,omitempty"`
    +    DefaultBranch    *string          `json:"default_branch,omitempty"`
    +    MasterBranch     *string          `json:"master_branch,omitempty"`
    +    CreatedAt        *Timestamp       `json:"created_at,omitempty"`
    +    PushedAt         *Timestamp       `json:"pushed_at,omitempty"`
    +    UpdatedAt        *Timestamp       `json:"updated_at,omitempty"`
    +    HTMLURL          *string          `json:"html_url,omitempty"`
    +    CloneURL         *string          `json:"clone_url,omitempty"`
    +    GitURL           *string          `json:"git_url,omitempty"`
    +    MirrorURL        *string          `json:"mirror_url,omitempty"`
    +    SSHURL           *string          `json:"ssh_url,omitempty"`
    +    SVNURL           *string          `json:"svn_url,omitempty"`
    +    Language         *string          `json:"language,omitempty"`
    +    Fork             *bool            `json:"fork"`
    +    ForksCount       *int             `json:"forks_count,omitempty"`
    +    NetworkCount     *int             `json:"network_count,omitempty"`
    +    OpenIssuesCount  *int             `json:"open_issues_count,omitempty"`
    +    StargazersCount  *int             `json:"stargazers_count,omitempty"`
    +    SubscribersCount *int             `json:"subscribers_count,omitempty"`
    +    WatchersCount    *int             `json:"watchers_count,omitempty"`
    +    Size             *int             `json:"size,omitempty"`
    +    AutoInit         *bool            `json:"auto_init,omitempty"`
    +    Parent           *Repository      `json:"parent,omitempty"`
    +    Source           *Repository      `json:"source,omitempty"`
    +    Organization     *Organization    `json:"organization,omitempty"`
    +    Permissions      *map[string]bool `json:"permissions,omitempty"`
    +
    +    // Only provided when using RepositoriesService.Get while in preview
    +    License *License `json:"license,omitempty"`
    +
    +    // Additional mutable fields when creating and editing a repository
    +    Private      *bool `json:"private"`
    +    HasIssues    *bool `json:"has_issues"`
    +    HasWiki      *bool `json:"has_wiki"`
    +    HasDownloads *bool `json:"has_downloads"`
    +    // Creating an organization repository. Required for non-owners.
    +    TeamID *int `json:"team_id"`
    +
    +    // API URLs
    +    URL              *string `json:"url,omitempty"`
    +    ArchiveURL       *string `json:"archive_url,omitempty"`
    +    AssigneesURL     *string `json:"assignees_url,omitempty"`
    +    BlobsURL         *string `json:"blobs_url,omitempty"`
    +    BranchesURL      *string `json:"branches_url,omitempty"`
    +    CollaboratorsURL *string `json:"collaborators_url,omitempty"`
    +    CommentsURL      *string `json:"comments_url,omitempty"`
    +    CommitsURL       *string `json:"commits_url,omitempty"`
    +    CompareURL       *string `json:"compare_url,omitempty"`
    +    ContentsURL      *string `json:"contents_url,omitempty"`
    +    ContributorsURL  *string `json:"contributors_url,omitempty"`
    +    DownloadsURL     *string `json:"downloads_url,omitempty"`
    +    EventsURL        *string `json:"events_url,omitempty"`
    +    ForksURL         *string `json:"forks_url,omitempty"`
    +    GitCommitsURL    *string `json:"git_commits_url,omitempty"`
    +    GitRefsURL       *string `json:"git_refs_url,omitempty"`
    +    GitTagsURL       *string `json:"git_tags_url,omitempty"`
    +    HooksURL         *string `json:"hooks_url,omitempty"`
    +    IssueCommentURL  *string `json:"issue_comment_url,omitempty"`
    +    IssueEventsURL   *string `json:"issue_events_url,omitempty"`
    +    IssuesURL        *string `json:"issues_url,omitempty"`
    +    KeysURL          *string `json:"keys_url,omitempty"`
    +    LabelsURL        *string `json:"labels_url,omitempty"`
    +    LanguagesURL     *string `json:"languages_url,omitempty"`
    +    MergesURL        *string `json:"merges_url,omitempty"`
    +    MilestonesURL    *string `json:"milestones_url,omitempty"`
    +    NotificationsURL *string `json:"notifications_url,omitempty"`
    +    PullsURL         *string `json:"pulls_url,omitempty"`
    +    ReleasesURL      *string `json:"releases_url,omitempty"`
    +    StargazersURL    *string `json:"stargazers_url,omitempty"`
    +    StatusesURL      *string `json:"statuses_url,omitempty"`
    +    SubscribersURL   *string `json:"subscribers_url,omitempty"`
    +    SubscriptionURL  *string `json:"subscription_url,omitempty"`
    +    TagsURL          *string `json:"tags_url,omitempty"`
    +    TreesURL         *string `json:"trees_url,omitempty"`
    +    TeamsURL         *string `json:"teams_url,omitempty"`
    +
    +    // TextMatches is only populated from search results that request text matches
    +    // See: search.go and https://developer.github.com/v3/search/#text-match-metadata
    +    TextMatches []TextMatch `json:"text_matches,omitempty"`
    +}
    +

    +Repository represents a GitHub repository. +

    + + + + + + + + + + + + + + +

    func (Repository) String

    +
    func (r Repository) String() string
    + + + + + + + + +

    type RepositoryAddCollaboratorOptions

    +
    type RepositoryAddCollaboratorOptions struct {
    +    // Permission specifies the permission to grant the user on this repository.
    +    // Possible values are:
    +    //     pull - team members can pull, but not push to or administer this repository
    +    //     push - team members can pull and push, but not administer this repository
    +    //     admin - team members can pull, push and administer this repository
    +    //
    +    // Default value is "push".  This option is only valid for organization-owned repositories.
    +    Permission string `json:"permission,omitempty"`
    +}
    +

    +RepositoryAddCollaboratorOptions specifies the optional parameters to the +RepositoriesService.AddCollaborator method. +

    + + + + + + + + + + + + + + + + +

    type RepositoryComment

    +
    type RepositoryComment struct {
    +    HTMLURL   *string    `json:"html_url,omitempty"`
    +    URL       *string    `json:"url,omitempty"`
    +    ID        *int       `json:"id,omitempty"`
    +    CommitID  *string    `json:"commit_id,omitempty"`
    +    User      *User      `json:"user,omitempty"`
    +    Reactions *Reactions `json:"reactions,omitempty"`
    +    CreatedAt *time.Time `json:"created_at,omitempty"`
    +    UpdatedAt *time.Time `json:"updated_at,omitempty"`
    +
    +    // User-mutable fields
    +    Body *string `json:"body"`
    +    // User-initialized fields
    +    Path     *string `json:"path,omitempty"`
    +    Position *int    `json:"position,omitempty"`
    +}
    +

    +RepositoryComment represents a comment for a commit, file, or line in a repository. +

    + + + + + + + + + + + + + + +

    func (RepositoryComment) String

    +
    func (r RepositoryComment) String() string
    + + + + + + + + +

    type RepositoryCommit

    +
    type RepositoryCommit struct {
    +    SHA       *string  `json:"sha,omitempty"`
    +    Commit    *Commit  `json:"commit,omitempty"`
    +    Author    *User    `json:"author,omitempty"`
    +    Committer *User    `json:"committer,omitempty"`
    +    Parents   []Commit `json:"parents,omitempty"`
    +    Message   *string  `json:"message,omitempty"`
    +    HTMLURL   *string  `json:"html_url,omitempty"`
    +
    +    // Details about how many changes were made in this commit. Only filled in during GetCommit!
    +    Stats *CommitStats `json:"stats,omitempty"`
    +    // Details about which files, and how this commit touched. Only filled in during GetCommit!
    +    Files []CommitFile `json:"files,omitempty"`
    +}
    +

    +RepositoryCommit represents a commit in a repo. +Note that it's wrapping a Commit, so author/committer information is in two places, +but contain different details about them: in RepositoryCommit "github details", in Commit - "git details". +

    + + + + + + + + + + + + + + +

    func (RepositoryCommit) String

    +
    func (r RepositoryCommit) String() string
    + + + + + + + + +

    type RepositoryContent

    +
    type RepositoryContent struct {
    +    Type     *string `json:"type,omitempty"`
    +    Encoding *string `json:"encoding,omitempty"`
    +    Size     *int    `json:"size,omitempty"`
    +    Name     *string `json:"name,omitempty"`
    +    Path     *string `json:"path,omitempty"`
    +    // Content contains the actual file content, which may be encoded.
    +    // Callers should call GetContent which will decode the content if
    +    // necessary.
    +    Content     *string `json:"content,omitempty"`
    +    SHA         *string `json:"sha,omitempty"`
    +    URL         *string `json:"url,omitempty"`
    +    GitURL      *string `json:"git_url,omitempty"`
    +    HTMLURL     *string `json:"html_url,omitempty"`
    +    DownloadURL *string `json:"download_url,omitempty"`
    +}
    +

    +RepositoryContent represents a file or directory in a github repository. +

    + + + + + + + + + + + + + + +

    func (*RepositoryContent) Decode

    +
    func (r *RepositoryContent) Decode() ([]byte, error)
    +

    +Decode decodes the file content if it is base64 encoded. +

    +

    +Deprecated: Use GetContent instead. +

    + + + + + + +

    func (*RepositoryContent) GetContent

    +
    func (r *RepositoryContent) GetContent() (string, error)
    +

    +GetContent returns the content of r, decoding it if necessary. +

    + + + + + + +

    func (RepositoryContent) String

    +
    func (r RepositoryContent) String() string
    +

    +String converts RepositoryContent to a string. It's primarily for testing. +

    + + + + + + + + +

    type RepositoryContentFileOptions

    +
    type RepositoryContentFileOptions struct {
    +    Message   *string       `json:"message,omitempty"`
    +    Content   []byte        `json:"content,omitempty"` // unencoded
    +    SHA       *string       `json:"sha,omitempty"`
    +    Branch    *string       `json:"branch,omitempty"`
    +    Author    *CommitAuthor `json:"author,omitempty"`
    +    Committer *CommitAuthor `json:"committer,omitempty"`
    +}
    +

    +RepositoryContentFileOptions specifies optional parameters for CreateFile, UpdateFile, and DeleteFile. +

    + + + + + + + + + + + + + + + + +

    type RepositoryContentGetOptions

    +
    type RepositoryContentGetOptions struct {
    +    Ref string `url:"ref,omitempty"`
    +}
    +

    +RepositoryContentGetOptions represents an optional ref parameter, which can be a SHA, +branch, or tag +

    + + + + + + + + + + + + + + + + +

    type RepositoryContentResponse

    +
    type RepositoryContentResponse struct {
    +    Content *RepositoryContent `json:"content,omitempty"`
    +    Commit  `json:"commit,omitempty"`
    +}
    +

    +RepositoryContentResponse holds the parsed response from CreateFile, UpdateFile, and DeleteFile. +

    + + + + + + + + + + + + + + + + +

    type RepositoryCreateForkOptions

    +
    type RepositoryCreateForkOptions struct {
    +    // The organization to fork the repository into.
    +    Organization string `url:"organization,omitempty"`
    +}
    +

    +RepositoryCreateForkOptions specifies the optional parameters to the +RepositoriesService.CreateFork method. +

    + + + + + + + + + + + + + + + + +

    type RepositoryEvent

    +
    type RepositoryEvent struct {
    +    // Action is the action that was performed. Possible values are: "created", "deleted",
    +    // "publicized", "privatized".
    +    Action *string     `json:"action,omitempty"`
    +    Repo   *Repository `json:"repository,omitempty"`
    +
    +    // The following fields are only populated by Webhook events.
    +    Org    *Organization `json:"organization,omitempty"`
    +    Sender *User         `json:"sender,omitempty"`
    +}
    +

    +RepositoryEvent is triggered when a repository is created. +The Webhook event name is "repository". +

    +

    +Events of this type are not visible in timelines, they are only used to +trigger organization webhooks. +

    +

    +GitHub docs: https://developer.github.com/v3/activity/events/types/#repositoryevent +

    + + + + + + + + + + + + + + + + +

    type RepositoryInvitation

    +
    type RepositoryInvitation struct {
    +    ID      *int        `json:"id,omitempty"`
    +    Repo    *Repository `json:"repository,omitempty"`
    +    Invitee *User       `json:"invitee,omitempty"`
    +    Inviter *User       `json:"inviter,omitempty"`
    +
    +    // Permissions represents the permissions that the associated user will have
    +    // on the repository. Possible values are: "read", "write", "admin".
    +    Permissions *string    `json:"permissions,omitempty"`
    +    CreatedAt   *Timestamp `json:"created_at,omitempty"`
    +    URL         *string    `json:"url,omitempty"`
    +    HTMLURL     *string    `json:"html_url,omitempty"`
    +}
    +

    +RepositoryInvitation represents an invitation to collaborate on a repo. +

    + + + + + + + + + + + + + + + + +

    type RepositoryListAllOptions

    +
    type RepositoryListAllOptions struct {
    +    // ID of the last repository seen
    +    Since int `url:"since,omitempty"`
    +
    +    ListOptions
    +}
    +

    +RepositoryListAllOptions specifies the optional parameters to the +RepositoriesService.ListAll method. +

    + + + + + + + + + + + + + + + + +

    type RepositoryListByOrgOptions

    +
    type RepositoryListByOrgOptions struct {
    +    // Type of repositories to list.  Possible values are: all, public, private,
    +    // forks, sources, member.  Default is "all".
    +    Type string `url:"type,omitempty"`
    +
    +    ListOptions
    +}
    +

    +RepositoryListByOrgOptions specifies the optional parameters to the +RepositoriesService.ListByOrg method. +

    + + + + + + + + + + + + + + + + +

    type RepositoryListForksOptions

    +
    type RepositoryListForksOptions struct {
    +    // How to sort the forks list.  Possible values are: newest, oldest,
    +    // watchers.  Default is "newest".
    +    Sort string `url:"sort,omitempty"`
    +
    +    ListOptions
    +}
    +

    +RepositoryListForksOptions specifies the optional parameters to the +RepositoriesService.ListForks method. +

    + + + + + + + + + + + + + + + + +

    type RepositoryListOptions

    +
    type RepositoryListOptions struct {
    +    // Visibility of repositories to list. Can be one of all, public, or private.
    +    // Default: all
    +    Visibility string `url:"visibility,omitempty"`
    +
    +    // List repos of given affiliation[s].
    +    // Comma-separated list of values. Can include:
    +    // * owner: Repositories that are owned by the authenticated user.
    +    // * collaborator: Repositories that the user has been added to as a
    +    //   collaborator.
    +    // * organization_member: Repositories that the user has access to through
    +    //   being a member of an organization. This includes every repository on
    +    //   every team that the user is on.
    +    // Default: owner,collaborator,organization_member
    +    Affiliation string `url:"affiliation,omitempty"`
    +
    +    // Type of repositories to list.
    +    // Can be one of all, owner, public, private, member. Default: all
    +    // Will cause a 422 error if used in the same request as visibility or
    +    // affiliation.
    +    Type string `url:"type,omitempty"`
    +
    +    // How to sort the repository list. Can be one of created, updated, pushed,
    +    // full_name. Default: full_name
    +    Sort string `url:"sort,omitempty"`
    +
    +    // Direction in which to sort repositories. Can be one of asc or desc.
    +    // Default: when using full_name: asc; otherwise desc
    +    Direction string `url:"direction,omitempty"`
    +
    +    ListOptions
    +}
    +

    +RepositoryListOptions specifies the optional parameters to the +RepositoriesService.List method. +

    + + + + + + + + + + + + + + + + +

    type RepositoryMergeRequest

    +
    type RepositoryMergeRequest struct {
    +    Base          *string `json:"base,omitempty"`
    +    Head          *string `json:"head,omitempty"`
    +    CommitMessage *string `json:"commit_message,omitempty"`
    +}
    +

    +RepositoryMergeRequest represents a request to merge a branch in a +repository. +

    + + + + + + + + + + + + + + + + +

    type RepositoryParticipation

    +
    type RepositoryParticipation struct {
    +    All   []int `json:"all,omitempty"`
    +    Owner []int `json:"owner,omitempty"`
    +}
    +

    +RepositoryParticipation is the number of commits by everyone +who has contributed to the repository (including the owner) +as well as the number of commits by the owner themself. +

    + + + + + + + + + + + + + + +

    func (RepositoryParticipation) String

    +
    func (r RepositoryParticipation) String() string
    + + + + + + + + +

    type RepositoryRelease

    +
    type RepositoryRelease struct {
    +    ID              *int           `json:"id,omitempty"`
    +    TagName         *string        `json:"tag_name,omitempty"`
    +    TargetCommitish *string        `json:"target_commitish,omitempty"`
    +    Name            *string        `json:"name,omitempty"`
    +    Body            *string        `json:"body,omitempty"`
    +    Draft           *bool          `json:"draft,omitempty"`
    +    Prerelease      *bool          `json:"prerelease,omitempty"`
    +    CreatedAt       *Timestamp     `json:"created_at,omitempty"`
    +    PublishedAt     *Timestamp     `json:"published_at,omitempty"`
    +    URL             *string        `json:"url,omitempty"`
    +    HTMLURL         *string        `json:"html_url,omitempty"`
    +    AssetsURL       *string        `json:"assets_url,omitempty"`
    +    Assets          []ReleaseAsset `json:"assets,omitempty"`
    +    UploadURL       *string        `json:"upload_url,omitempty"`
    +    ZipballURL      *string        `json:"zipball_url,omitempty"`
    +    TarballURL      *string        `json:"tarball_url,omitempty"`
    +    Author          *CommitAuthor  `json:"author,omitempty"`
    +}
    +

    +RepositoryRelease represents a GitHub release in a repository. +

    + + + + + + + + + + + + + + +

    func (RepositoryRelease) String

    +
    func (r RepositoryRelease) String() string
    + + + + + + + + +

    type RepositoryTag

    +
    type RepositoryTag struct {
    +    Name       *string `json:"name,omitempty"`
    +    Commit     *Commit `json:"commit,omitempty"`
    +    ZipballURL *string `json:"zipball_url,omitempty"`
    +    TarballURL *string `json:"tarball_url,omitempty"`
    +}
    +

    +RepositoryTag represents a repository tag. +

    + + + + + + + + + + + + + + + + +

    type RequiredStatusChecks

    +
    type RequiredStatusChecks struct {
    +    // Who required status checks apply to.
    +    // Possible values are:
    +    //     off
    +    //     non_admins
    +    //     everyone
    +    EnforcementLevel *string `json:"enforcement_level,omitempty"`
    +    // The list of status checks which are required
    +    Contexts *[]string `json:"contexts,omitempty"`
    +}
    +

    +RequiredStatusChecks represents the protection status of a individual branch +

    + + + + + + + + + + + + + + + + +

    type Response

    +
    type Response struct {
    +    *http.Response
    +
    +    NextPage  int
    +    PrevPage  int
    +    FirstPage int
    +    LastPage  int
    +
    +    Rate
    +}
    +

    +Response is a GitHub API response. This wraps the standard http.Response +returned from GitHub and provides convenient access to things like +pagination links. +

    + + + + + + + + + + + + + + + + +

    type Scope

    +
    type Scope string
    +

    +Scope models a GitHub authorization scope. +

    +

    +GitHub API docs:https://developer.github.com/v3/oauth/#scopes +

    + + + +
    const (
    +    ScopeNone           Scope = "(no scope)" // REVISIT: is this actually returned, or just a documentation artifact?
    +    ScopeUser           Scope = "user"
    +    ScopeUserEmail      Scope = "user:email"
    +    ScopeUserFollow     Scope = "user:follow"
    +    ScopePublicRepo     Scope = "public_repo"
    +    ScopeRepo           Scope = "repo"
    +    ScopeRepoDeployment Scope = "repo_deployment"
    +    ScopeRepoStatus     Scope = "repo:status"
    +    ScopeDeleteRepo     Scope = "delete_repo"
    +    ScopeNotifications  Scope = "notifications"
    +    ScopeGist           Scope = "gist"
    +    ScopeReadRepoHook   Scope = "read:repo_hook"
    +    ScopeWriteRepoHook  Scope = "write:repo_hook"
    +    ScopeAdminRepoHook  Scope = "admin:repo_hook"
    +    ScopeAdminOrgHook   Scope = "admin:org_hook"
    +    ScopeReadOrg        Scope = "read:org"
    +    ScopeWriteOrg       Scope = "write:org"
    +    ScopeAdminOrg       Scope = "admin:org"
    +    ScopeReadPublicKey  Scope = "read:public_key"
    +    ScopeWritePublicKey Scope = "write:public_key"
    +    ScopeAdminPublicKey Scope = "admin:public_key"
    +    ScopeReadGPGKey     Scope = "read:gpg_key"
    +    ScopeWriteGPGKey    Scope = "write:gpg_key"
    +    ScopeAdminGPGKey    Scope = "admin:gpg_key"
    +)
    +

    +This is the set of scopes for GitHub API V3 +

    + + + + + + + + + + + + + + + +

    type SearchOptions

    +
    type SearchOptions struct {
    +    // How to sort the search results.  Possible values are:
    +    //   - for repositories: stars, fork, updated
    +    //   - for code: indexed
    +    //   - for issues: comments, created, updated
    +    //   - for users: followers, repositories, joined
    +    //
    +    // Default is to sort by best match.
    +    Sort string `url:"sort,omitempty"`
    +
    +    // Sort order if sort parameter is provided. Possible values are: asc,
    +    // desc. Default is desc.
    +    Order string `url:"order,omitempty"`
    +
    +    // Whether to retrieve text match metadata with a query
    +    TextMatch bool `url:"-"`
    +
    +    ListOptions
    +}
    +

    +SearchOptions specifies optional parameters to the SearchService methods. +

    + + + + + + + + + + + + + + + + +

    type SearchService

    +
    type SearchService service
    +

    +SearchService provides access to the search related functions +in the GitHub API. +

    +

    +GitHub API docs: http://developer.github.com/v3/search/ +

    + + + + + + + + + + + + + + +

    func (*SearchService) Code

    +
    func (s *SearchService) Code(query string, opt *SearchOptions) (*CodeSearchResult, *Response, error)
    +

    +Code searches code via various criteria. +

    +

    +GitHub API docs: http://developer.github.com/v3/search/#search-code +

    + + + + + + +

    func (*SearchService) Issues

    +
    func (s *SearchService) Issues(query string, opt *SearchOptions) (*IssuesSearchResult, *Response, error)
    +

    +Issues searches issues via various criteria. +

    +

    +GitHub API docs: http://developer.github.com/v3/search/#search-issues +

    + + + + + + +

    func (*SearchService) Repositories

    +
    func (s *SearchService) Repositories(query string, opt *SearchOptions) (*RepositoriesSearchResult, *Response, error)
    +

    +Repositories searches repositories via various criteria. +

    +

    +GitHub API docs: http://developer.github.com/v3/search/#search-repositories +

    + + + + + + +

    func (*SearchService) Users

    +
    func (s *SearchService) Users(query string, opt *SearchOptions) (*UsersSearchResult, *Response, error)
    +

    +Users searches users via various criteria. +

    +

    +GitHub API docs: http://developer.github.com/v3/search/#search-users +

    + + + + + + + + +

    type ServiceHook

    +
    type ServiceHook struct {
    +    Name            *string    `json:"name,omitempty"`
    +    Events          []string   `json:"events,omitempty"`
    +    SupportedEvents []string   `json:"supported_events,omitempty"`
    +    Schema          [][]string `json:"schema,omitempty"`
    +}
    +

    +ServiceHook represents a hook that has configuration settings, a list of +available events, and default events. +

    + + + + + + + + + + + + + + +

    func (*ServiceHook) String

    +
    func (s *ServiceHook) String() string
    + + + + + + + + +

    type SignatureVerification

    +
    type SignatureVerification struct {
    +    Verified  *bool   `json:"verified,omitempty"`
    +    Reason    *string `json:"reason,omitempty"`
    +    Signature *string `json:"signature,omitempty"`
    +    Payload   *string `json:"payload,omitempty"`
    +}
    +

    +SignatureVerification represents GPG signature verification. +

    + + + + + + + + + + + + + + + + +

    type Source

    +
    type Source struct {
    +    ID    *int    `json:"id,omitempty"`
    +    URL   *string `json:"url,omitempty"`
    +    Actor *User   `json:"actor,omitempty"`
    +}
    +

    +Source represents a reference's source. +

    + + + + + + + + + + + + + + + + +

    type SourceImportAuthor

    +
    type SourceImportAuthor struct {
    +    ID         *int    `json:"id,omitempty"`
    +    RemoteID   *string `json:"remote_id,omitempty"`
    +    RemoteName *string `json:"remote_name,omitempty"`
    +    Email      *string `json:"email,omitempty"`
    +    Name       *string `json:"name,omitempty"`
    +    URL        *string `json:"url,omitempty"`
    +    ImportURL  *string `json:"import_url,omitempty"`
    +}
    +

    +SourceImportAuthor identifies an author imported from a source repository. +

    +

    +GitHub API docs: https://developer.github.com/v3/migration/source_imports/#get-commit-authors +

    + + + + + + + + + + + + + + +

    func (SourceImportAuthor) String

    +
    func (a SourceImportAuthor) String() string
    + + + + + + + + +

    type Stargazer

    +
    type Stargazer struct {
    +    StarredAt *Timestamp `json:"starred_at,omitempty"`
    +    User      *User      `json:"user,omitempty"`
    +}
    +

    +Stargazer represents a user that has starred a repository. +

    + + + + + + + + + + + + + + + + +

    type StarredRepository

    +
    type StarredRepository struct {
    +    StarredAt  *Timestamp  `json:"starred_at,omitempty"`
    +    Repository *Repository `json:"repo,omitempty"`
    +}
    +

    +StarredRepository is returned by ListStarred. +

    + + + + + + + + + + + + + + + + +

    type StatusEvent

    +
    type StatusEvent struct {
    +    SHA *string `json:"sha,omitempty"`
    +    // State is the new state. Possible values are: "pending", "success", "failure", "error".
    +    State       *string   `json:"state,omitempty"`
    +    Description *string   `json:"description,omitempty"`
    +    TargetURL   *string   `json:"target_url,omitempty"`
    +    Branches    []*Branch `json:"branches,omitempty"`
    +
    +    // The following fields are only populated by Webhook events.
    +    ID        *int             `json:"id,omitempty"`
    +    Name      *string          `json:"name,omitempty"`
    +    Context   *string          `json:"context,omitempty"`
    +    Commit    *PushEventCommit `json:"commit,omitempty"`
    +    CreatedAt *Timestamp       `json:"created_at,omitempty"`
    +    UpdatedAt *Timestamp       `json:"updated_at,omitempty"`
    +    Repo      *Repository      `json:"repository,omitempty"`
    +    Sender    *User            `json:"sender,omitempty"`
    +}
    +

    +StatusEvent is triggered when the status of a Git commit changes. +The Webhook event name is "status". +

    +

    +Events of this type are not visible in timelines, they are only used to +trigger hooks. +

    +

    +GitHub docs: https://developer.github.com/v3/activity/events/types/#statusevent +

    + + + + + + + + + + + + + + + + +

    type Subscription

    +
    type Subscription struct {
    +    Subscribed *bool      `json:"subscribed,omitempty"`
    +    Ignored    *bool      `json:"ignored,omitempty"`
    +    Reason     *string    `json:"reason,omitempty"`
    +    CreatedAt  *Timestamp `json:"created_at,omitempty"`
    +    URL        *string    `json:"url,omitempty"`
    +
    +    // only populated for repository subscriptions
    +    RepositoryURL *string `json:"repository_url,omitempty"`
    +
    +    // only populated for thread subscriptions
    +    ThreadURL *string `json:"thread_url,omitempty"`
    +}
    +

    +Subscription identifies a repository or thread subscription. +

    + + + + + + + + + + + + + + + + +

    type Tag

    +
    type Tag struct {
    +    Tag          *string                `json:"tag,omitempty"`
    +    SHA          *string                `json:"sha,omitempty"`
    +    URL          *string                `json:"url,omitempty"`
    +    Message      *string                `json:"message,omitempty"`
    +    Tagger       *CommitAuthor          `json:"tagger,omitempty"`
    +    Object       *GitObject             `json:"object,omitempty"`
    +    Verification *SignatureVerification `json:"verification,omitempty"`
    +}
    +

    +Tag represents a tag object. +

    + + + + + + + + + + + + + + + + +

    type Team

    +
    type Team struct {
    +    ID          *int    `json:"id,omitempty"`
    +    Name        *string `json:"name,omitempty"`
    +    Description *string `json:"description,omitempty"`
    +    URL         *string `json:"url,omitempty"`
    +    Slug        *string `json:"slug,omitempty"`
    +
    +    // Permission is deprecated when creating or editing a team in an org
    +    // using the new GitHub permission model.  It no longer identifies the
    +    // permission a team has on its repos, but only specifies the default
    +    // permission a repo is initially added with.  Avoid confusion by
    +    // specifying a permission value when calling AddTeamRepo.
    +    Permission *string `json:"permission,omitempty"`
    +
    +    // Privacy identifies the level of privacy this team should have.
    +    // Possible values are:
    +    //     secret - only visible to organization owners and members of this team
    +    //     closed - visible to all members of this organization
    +    // Default is "secret".
    +    Privacy *string `json:"privacy,omitempty"`
    +
    +    MembersCount    *int          `json:"members_count,omitempty"`
    +    ReposCount      *int          `json:"repos_count,omitempty"`
    +    Organization    *Organization `json:"organization,omitempty"`
    +    MembersURL      *string       `json:"members_url,omitempty"`
    +    RepositoriesURL *string       `json:"repositories_url,omitempty"`
    +}
    +

    +Team represents a team within a GitHub organization. Teams are used to +manage access to an organization's repositories. +

    + + + + + + + + + + + + + + +

    func (Team) String

    +
    func (t Team) String() string
    + + + + + + + + +

    type TeamAddEvent

    +
    type TeamAddEvent struct {
    +    Team *Team       `json:"team,omitempty"`
    +    Repo *Repository `json:"repository,omitempty"`
    +
    +    // The following fields are only populated by Webhook events.
    +    Org    *Organization `json:"organization,omitempty"`
    +    Sender *User         `json:"sender,omitempty"`
    +}
    +

    +TeamAddEvent is triggered when a repository is added to a team. +The Webhook event name is "team_add". +

    +

    +Events of this type are not visible in timelines. These events are only used +to trigger hooks. +

    +

    +GitHub docs: https://developer.github.com/v3/activity/events/types/#teamaddevent +

    + + + + + + + + + + + + + + + + +

    type TextMatch

    +
    type TextMatch struct {
    +    ObjectURL  *string `json:"object_url,omitempty"`
    +    ObjectType *string `json:"object_type,omitempty"`
    +    Property   *string `json:"property,omitempty"`
    +    Fragment   *string `json:"fragment,omitempty"`
    +    Matches    []Match `json:"matches,omitempty"`
    +}
    +

    +TextMatch represents a text match for a SearchResult +

    + + + + + + + + + + + + + + +

    func (TextMatch) String

    +
    func (tm TextMatch) String() string
    + + + + + + + + +

    type Timeline

    +
    type Timeline struct {
    +    ID        *int    `json:"id,omitempty"`
    +    URL       *string `json:"url,omitempty"`
    +    CommitURL *string `json:"commit_url,omitempty"`
    +
    +    // The User object that generated the event.
    +    Actor *User `json:"actor,omitempty"`
    +
    +    // Event identifies the actual type of Event that occurred. Possible values
    +    // are:
    +    //
    +    //     assigned
    +    //       The issue was assigned to the assignee.
    +    //
    +    //     closed
    +    //       The issue was closed by the actor. When the commit_id is present, it
    +    //       identifies the commit that closed the issue using "closes / fixes #NN"
    +    //       syntax.
    +    //
    +    //     commented
    +    //       A comment was added to the issue.
    +    //
    +    //     committed
    +    //       A commit was added to the pull request's 'HEAD' branch. Only provided
    +    //       for pull requests.
    +    //
    +    //     cross-referenced
    +    //       The issue was referenced from another issue. The 'source' attribute
    +    //       contains the 'id', 'actor', and 'url' of the reference's source.
    +    //
    +    //     demilestoned
    +    //       The issue was removed from a milestone.
    +    //
    +    //     head_ref_deleted
    +    //       The pull request's branch was deleted.
    +    //
    +    //     head_ref_restored
    +    //       The pull request's branch was restored.
    +    //
    +    //     labeled
    +    //       A label was added to the issue.
    +    //
    +    //     locked
    +    //       The issue was locked by the actor.
    +    //
    +    //     mentioned
    +    //       The actor was @mentioned in an issue body.
    +    //
    +    //     merged
    +    //       The issue was merged by the actor. The 'commit_id' attribute is the
    +    //       SHA1 of the HEAD commit that was merged.
    +    //
    +    //     milestoned
    +    //       The issue was added to a milestone.
    +    //
    +    //     referenced
    +    //       The issue was referenced from a commit message. The 'commit_id'
    +    //       attribute is the commit SHA1 of where that happened.
    +    //
    +    //     renamed
    +    //       The issue title was changed.
    +    //
    +    //     reopened
    +    //       The issue was reopened by the actor.
    +    //
    +    //     subscribed
    +    //       The actor subscribed to receive notifications for an issue.
    +    //
    +    //     unassigned
    +    //       The assignee was unassigned from the issue.
    +    //
    +    //     unlabeled
    +    //       A label was removed from the issue.
    +    //
    +    //     unlocked
    +    //       The issue was unlocked by the actor.
    +    //
    +    //     unsubscribed
    +    //       The actor unsubscribed to stop receiving notifications for an issue.
    +    //
    +    Event *string `json:"event,omitempty"`
    +
    +    // The string SHA of a commit that referenced this Issue or Pull Request.
    +    CommitID *string `json:"commit_id,omitempty"`
    +    // The timestamp indicating when the event occurred.
    +    CreatedAt *time.Time `json:"created_at,omitempty"`
    +    // The Label object including `name` and `color` attributes. Only provided for
    +    // 'labeled' and 'unlabeled' events.
    +    Label *Label `json:"label,omitempty"`
    +    // The User object which was assigned to (or unassigned from) this Issue or
    +    // Pull Request. Only provided for 'assigned' and 'unassigned' events.
    +    Assignee *User `json:"assignee,omitempty"`
    +    // The Milestone object including a 'title' attribute.
    +    // Only provided for 'milestoned' and 'demilestoned' events.
    +    Milestone *Milestone `json:"milestone,omitempty"`
    +    // The 'id', 'actor', and 'url' for the source of a reference from another issue.
    +    // Only provided for 'cross-referenced' events.
    +    Source *Source `json:"source,omitempty"`
    +    // An object containing rename details including 'from' and 'to' attributes.
    +    // Only provided for 'renamed' events.
    +    Rename *Rename `json:"rename,omitempty"`
    +}
    +

    +Timeline represents an event that occurred around an Issue or Pull Request. +

    +

    +It is similar to an IssueEvent but may contain more information. +GitHub API docs: https://developer.github.com/v3/issues/timeline/ +

    + + + + + + + + + + + + + + + + +

    type Timestamp

    +
    type Timestamp struct {
    +    time.Time
    +}
    +

    +Timestamp represents a time that can be unmarshalled from a JSON string +formatted as either an RFC3339 or Unix timestamp. This is necessary for some +fields since the GitHub API is inconsistent in how it represents times. All +exported methods of time.Time can be called on Timestamp. +

    + + + + + + + + + + + + + + +

    func (Timestamp) Equal

    +
    func (t Timestamp) Equal(u Timestamp) bool
    +

    +Equal reports whether t and u are equal based on time.Equal +

    + + + + + + +

    func (Timestamp) String

    +
    func (t Timestamp) String() string
    + + + + + + +

    func (*Timestamp) UnmarshalJSON

    +
    func (t *Timestamp) UnmarshalJSON(data []byte) (err error)
    +

    +UnmarshalJSON implements the json.Unmarshaler interface. +Time is expected in RFC3339 or Unix format. +

    + + + + + + + + +

    type Tree

    +
    type Tree struct {
    +    SHA     *string     `json:"sha,omitempty"`
    +    Entries []TreeEntry `json:"tree,omitempty"`
    +}
    +

    +Tree represents a GitHub tree. +

    + + + + + + + + + + + + + + +

    func (Tree) String

    +
    func (t Tree) String() string
    + + + + + + + + +

    type TreeEntry

    +
    type TreeEntry struct {
    +    SHA     *string `json:"sha,omitempty"`
    +    Path    *string `json:"path,omitempty"`
    +    Mode    *string `json:"mode,omitempty"`
    +    Type    *string `json:"type,omitempty"`
    +    Size    *int    `json:"size,omitempty"`
    +    Content *string `json:"content,omitempty"`
    +}
    +

    +TreeEntry represents the contents of a tree structure. TreeEntry can +represent either a blob, a commit (in the case of a submodule), or another +tree. +

    + + + + + + + + + + + + + + +

    func (TreeEntry) String

    +
    func (t TreeEntry) String() string
    + + + + + + + + +

    type TwoFactorAuthError

    +
    type TwoFactorAuthError ErrorResponse
    +

    +TwoFactorAuthError occurs when using HTTP Basic Authentication for a user +that has two-factor authentication enabled. The request can be reattempted +by providing a one-time password in the request. +

    + + + + + + + + + + + + + + +

    func (*TwoFactorAuthError) Error

    +
    func (r *TwoFactorAuthError) Error() string
    + + + + + + + + +

    type UnauthenticatedRateLimitedTransport

    +
    type UnauthenticatedRateLimitedTransport struct {
    +    // ClientID is the GitHub OAuth client ID of the current application, which
    +    // can be found by selecting its entry in the list at
    +    // https://github.com/settings/applications.
    +    ClientID string
    +
    +    // ClientSecret is the GitHub OAuth client secret of the current
    +    // application.
    +    ClientSecret string
    +
    +    // Transport is the underlying HTTP transport to use when making requests.
    +    // It will default to http.DefaultTransport if nil.
    +    Transport http.RoundTripper
    +}
    +

    +UnauthenticatedRateLimitedTransport allows you to make unauthenticated calls +that need to use a higher rate limit associated with your OAuth application. +

    +
    t := &github.UnauthenticatedRateLimitedTransport{
    +	ClientID:     "your app's client ID",
    +	ClientSecret: "your app's client secret",
    +}
    +client := github.NewClient(t.Client())
    +
    +

    +This will append the querystring params client_id=xxx&client_secret=yyy to all +requests. +

    +

    +See http://developer.github.com/v3/#unauthenticated-rate-limited-requests for +more information. +

    + + + + + + + + + + + + + + +

    func (*UnauthenticatedRateLimitedTransport) Client

    +
    func (t *UnauthenticatedRateLimitedTransport) Client() *http.Client
    +

    +Client returns an *http.Client that makes requests which are subject to the +rate limit of your OAuth application. +

    + + + + + + +

    func (*UnauthenticatedRateLimitedTransport) RoundTrip

    +
    func (t *UnauthenticatedRateLimitedTransport) RoundTrip(req *http.Request) (*http.Response, error)
    +

    +RoundTrip implements the RoundTripper interface. +

    + + + + + + + + +

    type UploadOptions

    +
    type UploadOptions struct {
    +    Name string `url:"name,omitempty"`
    +}
    +

    +UploadOptions specifies the parameters to methods that support uploads. +

    + + + + + + + + + + + + + + + + +

    type User

    +
    type User struct {
    +    Login             *string    `json:"login,omitempty"`
    +    ID                *int       `json:"id,omitempty"`
    +    AvatarURL         *string    `json:"avatar_url,omitempty"`
    +    HTMLURL           *string    `json:"html_url,omitempty"`
    +    GravatarID        *string    `json:"gravatar_id,omitempty"`
    +    Name              *string    `json:"name,omitempty"`
    +    Company           *string    `json:"company,omitempty"`
    +    Blog              *string    `json:"blog,omitempty"`
    +    Location          *string    `json:"location,omitempty"`
    +    Email             *string    `json:"email,omitempty"`
    +    Hireable          *bool      `json:"hireable,omitempty"`
    +    Bio               *string    `json:"bio,omitempty"`
    +    PublicRepos       *int       `json:"public_repos,omitempty"`
    +    PublicGists       *int       `json:"public_gists,omitempty"`
    +    Followers         *int       `json:"followers,omitempty"`
    +    Following         *int       `json:"following,omitempty"`
    +    CreatedAt         *Timestamp `json:"created_at,omitempty"`
    +    UpdatedAt         *Timestamp `json:"updated_at,omitempty"`
    +    SuspendedAt       *Timestamp `json:"suspended_at,omitempty"`
    +    Type              *string    `json:"type,omitempty"`
    +    SiteAdmin         *bool      `json:"site_admin,omitempty"`
    +    TotalPrivateRepos *int       `json:"total_private_repos,omitempty"`
    +    OwnedPrivateRepos *int       `json:"owned_private_repos,omitempty"`
    +    PrivateGists      *int       `json:"private_gists,omitempty"`
    +    DiskUsage         *int       `json:"disk_usage,omitempty"`
    +    Collaborators     *int       `json:"collaborators,omitempty"`
    +    Plan              *Plan      `json:"plan,omitempty"`
    +
    +    // API URLs
    +    URL               *string `json:"url,omitempty"`
    +    EventsURL         *string `json:"events_url,omitempty"`
    +    FollowingURL      *string `json:"following_url,omitempty"`
    +    FollowersURL      *string `json:"followers_url,omitempty"`
    +    GistsURL          *string `json:"gists_url,omitempty"`
    +    OrganizationsURL  *string `json:"organizations_url,omitempty"`
    +    ReceivedEventsURL *string `json:"received_events_url,omitempty"`
    +    ReposURL          *string `json:"repos_url,omitempty"`
    +    StarredURL        *string `json:"starred_url,omitempty"`
    +    SubscriptionsURL  *string `json:"subscriptions_url,omitempty"`
    +
    +    // TextMatches is only populated from search results that request text matches
    +    // See: search.go and https://developer.github.com/v3/search/#text-match-metadata
    +    TextMatches []TextMatch `json:"text_matches,omitempty"`
    +
    +    // Permissions identifies the permissions that a user has on a given
    +    // repository. This is only populated when calling Repositories.ListCollaborators.
    +    Permissions *map[string]bool `json:"permissions,omitempty"`
    +}
    +

    +User represents a GitHub user. +

    + + + + + + + + + + + + + + +

    func (User) String

    +
    func (u User) String() string
    + + + + + + + + +

    type UserEmail

    +
    type UserEmail struct {
    +    Email    *string `json:"email,omitempty"`
    +    Primary  *bool   `json:"primary,omitempty"`
    +    Verified *bool   `json:"verified,omitempty"`
    +}
    +

    +UserEmail represents user's email address +

    + + + + + + + + + + + + + + + + +

    type UserListOptions

    +
    type UserListOptions struct {
    +    // ID of the last user seen
    +    Since int `url:"since,omitempty"`
    +
    +    ListOptions
    +}
    +

    +UserListOptions specifies optional parameters to the UsersService.ListAll +method. +

    + + + + + + + + + + + + + + + + +

    type UsersSearchResult

    +
    type UsersSearchResult struct {
    +    Total *int   `json:"total_count,omitempty"`
    +    Users []User `json:"items,omitempty"`
    +}
    +

    +UsersSearchResult represents the result of an issues search. +

    + + + + + + + + + + + + + + + + +

    type UsersService

    +
    type UsersService service
    +

    +UsersService handles communication with the user related +methods of the GitHub API. +

    +

    +GitHub API docs: http://developer.github.com/v3/users/ +

    + + + + + + + + + + + + + + +

    func (*UsersService) AcceptInvitation

    +
    func (s *UsersService) AcceptInvitation(invitationID int) (*Response, error)
    +

    +AcceptInvitation accepts the currently-open repository invitation for the +authenticated user. +

    +

    +GitHub API docs: https://developer.github.com/v3/repos/invitations/#accept-a-repository-invitation +

    + + + + + + +

    func (*UsersService) AddEmails

    +
    func (s *UsersService) AddEmails(emails []string) ([]*UserEmail, *Response, error)
    +

    +AddEmails adds email addresses of the authenticated user. +

    +

    +GitHub API docs: http://developer.github.com/v3/users/emails/#add-email-addresses +

    + + + + + + +

    func (*UsersService) CreateGPGKey

    +
    func (s *UsersService) CreateGPGKey(armoredPublicKey string) (*GPGKey, *Response, error)
    +

    +CreateGPGKey creates a GPG key. It requires authenticatation via Basic Auth +or OAuth with at least write:gpg_key scope. +

    +

    +GitHub API docs: https://developer.github.com/v3/users/gpg_keys/#create-a-gpg-key +

    + + + + + + +

    func (*UsersService) CreateKey

    +
    func (s *UsersService) CreateKey(key *Key) (*Key, *Response, error)
    +

    +CreateKey adds a public key for the authenticated user. +

    +

    +GitHub API docs: http://developer.github.com/v3/users/keys/#create-a-public-key +

    + + + + + + +

    func (*UsersService) DeclineInvitation

    +
    func (s *UsersService) DeclineInvitation(invitationID int) (*Response, error)
    +

    +DeclineInvitation declines the currently-open repository invitation for the +authenticated user. +

    +

    +GitHub API docs: https://developer.github.com/v3/repos/invitations/#decline-a-repository-invitation +

    + + + + + + +

    func (*UsersService) DeleteEmails

    +
    func (s *UsersService) DeleteEmails(emails []string) (*Response, error)
    +

    +DeleteEmails deletes email addresses from authenticated user. +

    +

    +GitHub API docs: http://developer.github.com/v3/users/emails/#delete-email-addresses +

    + + + + + + +

    func (*UsersService) DeleteGPGKey

    +
    func (s *UsersService) DeleteGPGKey(id int) (*Response, error)
    +

    +DeleteGPGKey deletes a GPG key. It requires authentication via Basic Auth or +via OAuth with at least admin:gpg_key scope. +

    +

    +GitHub API docs: https://developer.github.com/v3/users/gpg_keys/#delete-a-gpg-key +

    + + + + + + +

    func (*UsersService) DeleteKey

    +
    func (s *UsersService) DeleteKey(id int) (*Response, error)
    +

    +DeleteKey deletes a public key. +

    +

    +GitHub API docs: http://developer.github.com/v3/users/keys/#delete-a-public-key +

    + + + + + + +

    func (*UsersService) DemoteSiteAdmin

    +
    func (s *UsersService) DemoteSiteAdmin(user string) (*Response, error)
    +

    +DemoteSiteAdmin demotes a user from site administrator of a GitHub Enterprise instance. +

    +

    +GitHub API docs: https://developer.github.com/v3/users/administration/#demote-a-site-administrator-to-an-ordinary-user +

    + + + + + + +

    func (*UsersService) Edit

    +
    func (s *UsersService) Edit(user *User) (*User, *Response, error)
    +

    +Edit the authenticated user. +

    +

    +GitHub API docs: http://developer.github.com/v3/users/#update-the-authenticated-user +

    + + + + + + +

    func (*UsersService) Follow

    +
    func (s *UsersService) Follow(user string) (*Response, error)
    +

    +Follow will cause the authenticated user to follow the specified user. +

    +

    +GitHub API docs: http://developer.github.com/v3/users/followers/#follow-a-user +

    + + + + + + +

    func (*UsersService) Get

    +
    func (s *UsersService) Get(user string) (*User, *Response, error)
    +

    +Get fetches a user. Passing the empty string will fetch the authenticated +user. +

    +

    +GitHub API docs: http://developer.github.com/v3/users/#get-a-single-user +

    + + + + + + +

    func (*UsersService) GetByID

    +
    func (s *UsersService) GetByID(id int) (*User, *Response, error)
    +

    +GetByID fetches a user. +

    +

    +Note: GetByID uses the undocumented GitHub API endpoint /user/:id. +

    + + + + + + +

    func (*UsersService) GetGPGKey

    +
    func (s *UsersService) GetGPGKey(id int) (*GPGKey, *Response, error)
    +

    +GetGPGKey gets extended details for a single GPG key. It requires authentication +via Basic Auth or via OAuth with at least read:gpg_key scope. +

    +

    +GitHub API docs: https://developer.github.com/v3/users/gpg_keys/#get-a-single-gpg-key +

    + + + + + + +

    func (*UsersService) GetKey

    +
    func (s *UsersService) GetKey(id int) (*Key, *Response, error)
    +

    +GetKey fetches a single public key. +

    +

    +GitHub API docs: http://developer.github.com/v3/users/keys/#get-a-single-public-key +

    + + + + + + +

    func (*UsersService) IsFollowing

    +
    func (s *UsersService) IsFollowing(user, target string) (bool, *Response, error)
    +

    +IsFollowing checks if "user" is following "target". Passing the empty +string for "user" will check if the authenticated user is following "target". +

    +

    +GitHub API docs: http://developer.github.com/v3/users/followers/#check-if-you-are-following-a-user +

    + + + + + + +

    func (*UsersService) ListAll

    +
    func (s *UsersService) ListAll(opt *UserListOptions) ([]*User, *Response, error)
    +

    +ListAll lists all GitHub users. +

    +

    +To paginate through all users, populate 'Since' with the ID of the last user. +

    +

    +GitHub API docs: http://developer.github.com/v3/users/#get-all-users +

    + + +
    + +
    +

    Example

    + + + +

    Code:

    +
    +client := github.NewClient(nil)
    +opts := &github.UserListOptions{}
    +for {
    +    users, _, err := client.Users.ListAll(opts)
    +    if err != nil {
    +        log.Fatalf("error listing users: %v", err)
    +    }
    +    if len(users) == 0 {
    +        break
    +    }
    +    opts.Since = *users[len(users)-1].ID
    +    // Process users...
    +}
    +
    + + +
    +
    + + + + +

    func (*UsersService) ListEmails

    +
    func (s *UsersService) ListEmails(opt *ListOptions) ([]*UserEmail, *Response, error)
    +

    +ListEmails lists all email addresses for the authenticated user. +

    +

    +GitHub API docs: http://developer.github.com/v3/users/emails/#list-email-addresses-for-a-user +

    + + + + + + +

    func (*UsersService) ListFollowers

    +
    func (s *UsersService) ListFollowers(user string, opt *ListOptions) ([]*User, *Response, error)
    +

    +ListFollowers lists the followers for a user. Passing the empty string will +fetch followers for the authenticated user. +

    +

    +GitHub API docs: http://developer.github.com/v3/users/followers/#list-followers-of-a-user +

    + + + + + + +

    func (*UsersService) ListFollowing

    +
    func (s *UsersService) ListFollowing(user string, opt *ListOptions) ([]*User, *Response, error)
    +

    +ListFollowing lists the people that a user is following. Passing the empty +string will list people the authenticated user is following. +

    +

    +GitHub API docs: http://developer.github.com/v3/users/followers/#list-users-followed-by-another-user +

    + + + + + + +

    func (*UsersService) ListGPGKeys

    +
    func (s *UsersService) ListGPGKeys() ([]*GPGKey, *Response, error)
    +

    +ListGPGKeys lists the current user's GPG keys. It requires authentication +via Basic Auth or via OAuth with at least read:gpg_key scope. +

    +

    +GitHub API docs: https://developer.github.com/v3/users/gpg_keys/#list-your-gpg-keys +

    + + + + + + +

    func (*UsersService) ListInvitations

    +
    func (s *UsersService) ListInvitations() ([]*RepositoryInvitation, *Response, error)
    +

    +ListInvitations lists all currently-open repository invitations for the +authenticated user. +

    +

    +GitHub API docs: https://developer.github.com/v3/repos/invitations/#list-a-users-repository-invitations +

    + + + + + + +

    func (*UsersService) ListKeys

    +
    func (s *UsersService) ListKeys(user string, opt *ListOptions) ([]*Key, *Response, error)
    +

    +ListKeys lists the verified public keys for a user. Passing the empty +string will fetch keys for the authenticated user. +

    +

    +GitHub API docs: http://developer.github.com/v3/users/keys/#list-public-keys-for-a-user +

    + + + + + + +

    func (*UsersService) PromoteSiteAdmin

    +
    func (s *UsersService) PromoteSiteAdmin(user string) (*Response, error)
    +

    +PromoteSiteAdmin promotes a user to a site administrator of a GitHub Enterprise instance. +

    +

    +GitHub API docs: https://developer.github.com/v3/users/administration/#promote-an-ordinary-user-to-a-site-administrator +

    + + + + + + +

    func (*UsersService) Suspend

    +
    func (s *UsersService) Suspend(user string) (*Response, error)
    +

    +Suspend a user on a GitHub Enterprise instance. +

    +

    +GitHub API docs: https://developer.github.com/v3/users/administration/#suspend-a-user +

    + + + + + + +

    func (*UsersService) Unfollow

    +
    func (s *UsersService) Unfollow(user string) (*Response, error)
    +

    +Unfollow will cause the authenticated user to unfollow the specified user. +

    +

    +GitHub API docs: http://developer.github.com/v3/users/followers/#unfollow-a-user +

    + + + + + + +

    func (*UsersService) Unsuspend

    +
    func (s *UsersService) Unsuspend(user string) (*Response, error)
    +

    +Unsuspend a user on a GitHub Enterprise instance. +

    +

    +GitHub API docs: https://developer.github.com/v3/users/administration/#unsuspend-a-user +

    + + + + + + + + +

    type WatchEvent

    +
    type WatchEvent struct {
    +    // Action is the action that was performed. Possible value is: "started".
    +    Action *string `json:"action,omitempty"`
    +
    +    // The following fields are only populated by Webhook events.
    +    Repo   *Repository `json:"repository,omitempty"`
    +    Sender *User       `json:"sender,omitempty"`
    +}
    +

    +WatchEvent is related to starring a repository, not watching. See this API +blog post for an explanation: https://developer.github.com/changes/2012-09-05-watcher-api/ +

    +

    +The event’s actor is the user who starred a repository, and the event’s +repository is the repository that was starred. +

    +

    +GitHub docs: https://developer.github.com/v3/activity/events/types/#watchevent +

    + + + + + + + + + + + + + + + + +

    type WebHookAuthor

    +
    type WebHookAuthor struct {
    +    Email    *string `json:"email,omitempty"`
    +    Name     *string `json:"name,omitempty"`
    +    Username *string `json:"username,omitempty"`
    +}
    +

    +WebHookAuthor represents the author or committer of a commit, as specified +in a WebHookCommit. The commit author may not correspond to a GitHub User. +

    + + + + + + + + + + + + + + +

    func (WebHookAuthor) String

    +
    func (w WebHookAuthor) String() string
    + + + + + + + + +

    type WebHookCommit

    +
    type WebHookCommit struct {
    +    Added     []string       `json:"added,omitempty"`
    +    Author    *WebHookAuthor `json:"author,omitempty"`
    +    Committer *WebHookAuthor `json:"committer,omitempty"`
    +    Distinct  *bool          `json:"distinct,omitempty"`
    +    ID        *string        `json:"id,omitempty"`
    +    Message   *string        `json:"message,omitempty"`
    +    Modified  []string       `json:"modified,omitempty"`
    +    Removed   []string       `json:"removed,omitempty"`
    +    Timestamp *time.Time     `json:"timestamp,omitempty"`
    +}
    +

    +WebHookCommit represents the commit variant we receive from GitHub in a +WebHookPayload. +

    + + + + + + + + + + + + + + +

    func (WebHookCommit) String

    +
    func (w WebHookCommit) String() string
    + + + + + + + + +

    type WebHookPayload

    +
    type WebHookPayload struct {
    +    After      *string         `json:"after,omitempty"`
    +    Before     *string         `json:"before,omitempty"`
    +    Commits    []WebHookCommit `json:"commits,omitempty"`
    +    Compare    *string         `json:"compare,omitempty"`
    +    Created    *bool           `json:"created,omitempty"`
    +    Deleted    *bool           `json:"deleted,omitempty"`
    +    Forced     *bool           `json:"forced,omitempty"`
    +    HeadCommit *WebHookCommit  `json:"head_commit,omitempty"`
    +    Pusher     *User           `json:"pusher,omitempty"`
    +    Ref        *string         `json:"ref,omitempty"`
    +    Repo       *Repository     `json:"repository,omitempty"`
    +    Sender     *User           `json:"sender,omitempty"`
    +}
    +

    +WebHookPayload represents the data that is received from GitHub when a push +event hook is triggered. The format of these payloads pre-date most of the +GitHub v3 API, so there are lots of minor incompatibilities with the types +defined in the rest of the API. Therefore, several types are duplicated +here to account for these differences. +

    +

    +GitHub API docs: https://help.github.com/articles/post-receive-hooks +

    + + + + + + + + + + + + + + +

    func (WebHookPayload) String

    +
    func (w WebHookPayload) String() string
    + + + + + + + + +

    type WeeklyCommitActivity

    +
    type WeeklyCommitActivity struct {
    +    Days  []int      `json:"days,omitempty"`
    +    Total *int       `json:"total,omitempty"`
    +    Week  *Timestamp `json:"week,omitempty"`
    +}
    +

    +WeeklyCommitActivity represents the weekly commit activity for a repository. +The days array is a group of commits per day, starting on Sunday. +

    + + + + + + + + + + + + + + +

    func (WeeklyCommitActivity) String

    +
    func (w WeeklyCommitActivity) String() string
    + + + + + + + + +

    type WeeklyStats

    +
    type WeeklyStats struct {
    +    Week      *Timestamp `json:"w,omitempty"`
    +    Additions *int       `json:"a,omitempty"`
    +    Deletions *int       `json:"d,omitempty"`
    +    Commits   *int       `json:"c,omitempty"`
    +}
    +

    +WeeklyStats represents the number of additions, deletions and commits +a Contributor made in a given week. +

    + + + + + + + + + + + + + + +

    func (WeeklyStats) String

    +
    func (w WeeklyStats) String() string
    + + + + + + + + + + + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/github.com/google/go-github/index.html b/pkg/github.com/google/go-github/index.html new file mode 100644 index 0000000..41515e5 --- /dev/null +++ b/pkg/github.com/google/go-github/index.html @@ -0,0 +1,130 @@ + + + + + + + + /src/github.com/google/go-github - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Directory /src/github.com/google/go-github

    + + + + + + + + + + + + + + + + + + + +
    + + + + + + + + + + + + + + + + + + + + +
    NameSynopsis
    ..
    + github + + Package github provides a client for using the GitHub API. +
    +
    + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/github.com/google/go-querystring/index.html b/pkg/github.com/google/go-querystring/index.html new file mode 100644 index 0000000..4607072 --- /dev/null +++ b/pkg/github.com/google/go-querystring/index.html @@ -0,0 +1,130 @@ + + + + + + + + /src/github.com/google/go-querystring - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Directory /src/github.com/google/go-querystring

    + + + + + + + + + + + + + + + + + + + +
    + + + + + + + + + + + + + + + + + + + + +
    NameSynopsis
    ..
    + query + + Package query implements encoding of structs into URL query parameters. +
    +
    + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/github.com/google/go-querystring/query/index.html b/pkg/github.com/google/go-querystring/query/index.html new file mode 100644 index 0000000..617123b --- /dev/null +++ b/pkg/github.com/google/go-querystring/query/index.html @@ -0,0 +1,348 @@ + + + + + + + + query - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Package query

    + + + + + + + + + + + + + + +
    +
    +
    import "github.com/google/go-querystring/query"
    +
    +
    +
    Overview
    +
    Index
    + + +
    +
    + +
    + +
    +

    Overview ▾

    +

    +Package query implements encoding of structs into URL query parameters. +

    +

    +As a simple example: +

    +
    type Options struct {
    +	Query   string `url:"q"`
    +	ShowAll bool   `url:"all"`
    +	Page    int    `url:"page"`
    +}
    +
    +opt := Options{ "foo", true, 2 }
    +v, _ := query.Values(opt)
    +fmt.Print(v.Encode()) // will output: "q=foo&all=true&page=2"
    +
    +

    +The exact mapping between Go values and url.Values is described in the +documentation for the Values() function. +

    + +
    +
    + + +
    + +
    +

    Index ▾

    + + + + + + + +

    Package files

    +

    + + + encode.go + + +

    + +
    +
    + + + + + + + + +

    func Values

    +
    func Values(v interface{}) (url.Values, error)
    +

    +Values returns the url.Values encoding of v. +

    +

    +Values expects to be passed a struct, and traverses it recursively using the +following encoding rules. +

    +

    +Each exported struct field is encoded as a URL parameter unless +

    +
    - the field's tag is "-", or
    +- the field is empty and its tag specifies the "omitempty" option
    +
    +

    +The empty values are false, 0, any nil pointer or interface value, any array +slice, map, or string of length zero, and any time.Time that returns true +for IsZero(). +

    +

    +The URL parameter name defaults to the struct field name but can be +specified in the struct field's tag value. The "url" key in the struct +field's tag value is the key name, followed by an optional comma and +options. For example: +

    +
    // Field is ignored by this package.
    +Field int `url:"-"`
    +
    +// Field appears as URL parameter "myName".
    +Field int `url:"myName"`
    +
    +// Field appears as URL parameter "myName" and the field is omitted if
    +// its value is empty
    +Field int `url:"myName,omitempty"`
    +
    +// Field appears as URL parameter "Field" (the default), but the field
    +// is skipped if empty.  Note the leading comma.
    +Field int `url:",omitempty"`
    +
    +

    +For encoding individual field values, the following type-dependent rules +apply: +

    +

    +Boolean values default to encoding as the strings "true" or "false". +Including the "int" option signals that the field should be encoded as the +strings "1" or "0". +

    +

    +time.Time values default to encoding as RFC3339 timestamps. Including the +"unix" option signals that the field should be encoded as a Unix time (see +time.Unix()) +

    +

    +Slice and Array values default to encoding as multiple URL values of the +same name. Including the "comma" option signals that the field should be +encoded as a single comma-delimited value. Including the "space" option +similarly encodes the value as a single space-delimited string. Including +the "semicolon" option will encode the value as a semicolon-delimited string. +Including the "brackets" option signals that the multiple URL values should +have "[]" appended to the value name. "numbered" will append a number to +the end of each incidence of the value name, example: +name0=value0&name1=value1, etc. +

    +

    +Anonymous struct fields are usually encoded as if their inner exported +fields were fields in the outer struct, subject to the standard Go +visibility rules. An anonymous struct field with a name given in its URL +tag is treated as having that name, rather than being anonymous. +

    +

    +Non-nil pointer values are encoded as the value pointed to. +

    +

    +Nested structs are encoded including parent fields in value names for +scoping. e.g: +

    +
    "user[name]=acme&user[addr][postcode]=1234&user[addr][city]=SFO"
    +
    +

    +All other values are encoded using their default string representation. +

    +

    +Multiple fields that encode to the same URL parameter name will be included +as multiple URL values of the same name. +

    + + + + + + + + +

    type Encoder

    +
    type Encoder interface {
    +    EncodeValues(key string, v *url.Values) error
    +}
    +

    +Encoder is an interface implemented by any type that wishes to encode +itself into URL values in a non-standard way. +

    + + + + + + + + + + + + + + + + + + + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/github.com/google/index.html b/pkg/github.com/google/index.html new file mode 100644 index 0000000..7710ffe --- /dev/null +++ b/pkg/github.com/google/index.html @@ -0,0 +1,174 @@ + + + + + + + + /src/github.com/google - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Directory /src/github.com/google

    + + + + + + + + + + + + + + + + + + + +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    NameSynopsis
    ..
    + btree + + Package btree implements in-memory B-Trees of arbitrary degree. +
    + go-github + + +
    + github + + Package github provides a client for using the GitHub API. +
    + go-querystring + + +
    + query + + Package query implements encoding of structs into URL query parameters. +
    +
    + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/github.com/gregjones/httpcache/diskcache/index.html b/pkg/github.com/gregjones/httpcache/diskcache/index.html new file mode 100644 index 0000000..d194423 --- /dev/null +++ b/pkg/github.com/gregjones/httpcache/diskcache/index.html @@ -0,0 +1,303 @@ + + + + + + + + diskcache - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Package diskcache

    + + + + + + + + + + + + + + +
    +
    +
    import "github.com/gregjones/httpcache/diskcache"
    +
    +
    +
    Overview
    +
    Index
    + + +
    +
    + +
    + +
    +

    Overview ▾

    +

    +Package diskcache provides an implementation of httpcache.Cache that uses the diskv package +to supplement an in-memory map with persistent storage +

    + +
    +
    + + +
    + +
    +

    Index ▾

    + + + + + + + +

    Package files

    +

    + + + diskcache.go + + +

    + +
    +
    + + + + + + + + + +

    type Cache

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

    +Cache is an implementation of httpcache.Cache that supplements the in-memory map with persistent storage +

    + + + + + + + + + + + + +

    func New

    +
    func New(basePath string) *Cache
    +

    +New returns a new Cache that will store files in basePath +

    + + + + + +

    func NewWithDiskv

    +
    func NewWithDiskv(d *diskv.Diskv) *Cache
    +

    +NewWithDiskv returns a new Cache using the provided Diskv as underlying +storage. +

    + + + + + + + +

    func (*Cache) Delete

    +
    func (c *Cache) Delete(key string)
    +

    +Delete removes the response with key from the cache +

    + + + + + + +

    func (*Cache) Get

    +
    func (c *Cache) Get(key string) (resp []byte, ok bool)
    +

    +Get returns the response corresponding to key if present +

    + + + + + + +

    func (*Cache) Set

    +
    func (c *Cache) Set(key string, resp []byte)
    +

    +Set saves a response to the cache as key +

    + + + + + + + + + + + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/github.com/gregjones/httpcache/index.html b/pkg/github.com/gregjones/httpcache/index.html new file mode 100644 index 0000000..b8999d8 --- /dev/null +++ b/pkg/github.com/gregjones/httpcache/index.html @@ -0,0 +1,569 @@ + + + + + + + + httpcache - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Package httpcache

    + + + + + + + + + + + + + + +
    +
    +
    import "github.com/gregjones/httpcache"
    +
    +
    +
    Overview
    +
    Index
    + + +
    Subdirectories
    + +
    +
    + +
    + +
    +

    Overview ▾

    +

    +Package httpcache provides a http.RoundTripper implementation that works as a +mostly RFC-compliant cache for http responses. +

    +

    +It is only suitable for use as a 'private' cache (i.e. for a web-browser or an API-client +and not for a shared proxy). +

    + +
    +
    + + + + + + + +

    Constants

    + +
    const (
    +
    +    // XFromCache is the header added to responses that are returned from the cache
    +    XFromCache = "X-From-Cache"
    +)
    + + + + +

    Variables

    + +
    var ErrNoDateHeader = errors.New("no Date header")
    +

    +ErrNoDateHeader indicates that the HTTP headers contained no Date header. +

    + + + + + + +

    func CachedResponse

    +
    func CachedResponse(c Cache, req *http.Request) (resp *http.Response, err error)
    +

    +CachedResponse returns the cached http.Response for req if present, and nil +otherwise. +

    + + + + + + + +

    func Date

    +
    func Date(respHeaders http.Header) (date time.Time, err error)
    +

    +Date parses and returns the value of the Date header. +

    + + + + + + + + +

    type Cache

    +
    type Cache interface {
    +    // Get returns the []byte representation of a cached response and a bool
    +    // set to true if the value isn't empty
    +    Get(key string) (responseBytes []byte, ok bool)
    +    // Set stores the []byte representation of a response against a key
    +    Set(key string, responseBytes []byte)
    +    // Delete removes the value associated with the key
    +    Delete(key string)
    +}
    +

    +A Cache interface is used by the Transport to store and retrieve responses. +

    + + + + + + + + + + + + + + + + +

    type MemoryCache

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

    +MemoryCache is an implemtation of Cache that stores responses in an in-memory map. +

    + + + + + + + + + + + + +

    func NewMemoryCache

    +
    func NewMemoryCache() *MemoryCache
    +

    +NewMemoryCache returns a new Cache that will store items in an in-memory map +

    + + + + + + + +

    func (*MemoryCache) Delete

    +
    func (c *MemoryCache) Delete(key string)
    +

    +Delete removes key from the cache +

    + + + + + + +

    func (*MemoryCache) Get

    +
    func (c *MemoryCache) Get(key string) (resp []byte, ok bool)
    +

    +Get returns the []byte representation of the response and true if present, false if not +

    + + + + + + +

    func (*MemoryCache) Set

    +
    func (c *MemoryCache) Set(key string, resp []byte)
    +

    +Set saves response resp to the cache with key +

    + + + + + + + + +

    type Transport

    +
    type Transport struct {
    +    // The RoundTripper interface actually used to make requests
    +    // If nil, http.DefaultTransport is used
    +    Transport http.RoundTripper
    +    Cache     Cache
    +    // If true, responses returned from the cache will be given an extra header, X-From-Cache
    +    MarkCachedResponses bool
    +    // contains filtered or unexported fields
    +}
    +

    +Transport is an implementation of http.RoundTripper that will return values from a cache +where possible (avoiding a network request) and will additionally add validators (etag/if-modified-since) +to repeated requests allowing servers to return 304 / Not Modified +

    + + + + + + + + + + + + +

    func NewMemoryCacheTransport

    +
    func NewMemoryCacheTransport() *Transport
    +

    +NewMemoryCacheTransport returns a new Transport using the in-memory cache implementation +

    + + + + + +

    func NewTransport

    +
    func NewTransport(c Cache) *Transport
    +

    +NewTransport returns a new Transport with the +provided Cache implementation and MarkCachedResponses set to true +

    + + + + + + + +

    func (*Transport) CancelRequest

    +
    func (t *Transport) CancelRequest(req *http.Request)
    +

    +CancelRequest calls CancelRequest on the underlaying transport if implemented or +throw a warning otherwise. +

    + + + + + + +

    func (*Transport) Client

    +
    func (t *Transport) Client() *http.Client
    +

    +Client returns an *http.Client that caches responses. +

    + + + + + + +

    func (*Transport) RoundTrip

    +
    func (t *Transport) RoundTrip(req *http.Request) (resp *http.Response, err error)
    +

    +RoundTrip takes a Request and returns a Response +

    +

    +If there is a fresh Response already in cache, then it will be returned without connecting to +the server. +

    +

    +If there is a stale Response, then any validators it contains will be set on the new request +to give the server a chance to respond with NotModified. If this happens, then the cached Response +will be returned. +

    + + + + + + + + + + + + + + + + +

    Subdirectories

    + + + + +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    NameSynopsis
    ..
    + diskcache + + Package diskcache provides an implementation of httpcache.Cache that uses the diskv package to supplement an in-memory map with persistent storage +
    + leveldbcache + + Package leveldbcache provides an implementation of httpcache.Cache that uses github.com/syndtr/goleveldb/leveldb +
    + memcache + + Package memcache provides an implementation of httpcache.Cache that uses App Engine's memcache package to store cached responses. +
    + redis + + Package redis provides a redis interface for http caching. +
    +
    + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/github.com/gregjones/httpcache/leveldbcache/index.html b/pkg/github.com/gregjones/httpcache/leveldbcache/index.html new file mode 100644 index 0000000..d4698ef --- /dev/null +++ b/pkg/github.com/gregjones/httpcache/leveldbcache/index.html @@ -0,0 +1,303 @@ + + + + + + + + leveldbcache - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Package leveldbcache

    + + + + + + + + + + + + + + +
    +
    +
    import "github.com/gregjones/httpcache/leveldbcache"
    +
    +
    +
    Overview
    +
    Index
    + + +
    +
    + +
    + +
    +

    Overview ▾

    +

    +Package leveldbcache provides an implementation of httpcache.Cache that +uses github.com/syndtr/goleveldb/leveldb +

    + +
    +
    + + +
    + +
    +

    Index ▾

    + + + + + + + +

    Package files

    +

    + + + leveldbcache.go + + +

    + +
    +
    + + + + + + + + + +

    type Cache

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

    +Cache is an implementation of httpcache.Cache with leveldb storage +

    + + + + + + + + + + + + +

    func New

    +
    func New(path string) (*Cache, error)
    +

    +New returns a new Cache that will store leveldb in path +

    + + + + + +

    func NewWithDB

    +
    func NewWithDB(db *leveldb.DB) *Cache
    +

    +NewWithDB returns a new Cache using the provided leveldb as underlying +storage. +

    + + + + + + + +

    func (*Cache) Delete

    +
    func (c *Cache) Delete(key string)
    +

    +Delete removes the response with key from the cache +

    + + + + + + +

    func (*Cache) Get

    +
    func (c *Cache) Get(key string) (resp []byte, ok bool)
    +

    +Get returns the response corresponding to key if present +

    + + + + + + +

    func (*Cache) Set

    +
    func (c *Cache) Set(key string, resp []byte)
    +

    +Set saves a response to the cache as key +

    + + + + + + + + + + + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/github.com/gregjones/httpcache/memcache/index.html b/pkg/github.com/gregjones/httpcache/memcache/index.html new file mode 100644 index 0000000..e6d9372 --- /dev/null +++ b/pkg/github.com/gregjones/httpcache/memcache/index.html @@ -0,0 +1,310 @@ + + + + + + + + memcache - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Package memcache

    + + + + + + + + + + + + + + +
    +
    +
    import "github.com/gregjones/httpcache/memcache"
    +
    +
    +
    Overview
    +
    Index
    + + +
    +
    + +
    + +
    +

    Overview ▾

    +

    +Package memcache provides an implementation of httpcache.Cache that uses +gomemcache to store cached responses. +

    +

    +When built for Google App Engine, this package will provide an +implementation that uses App Engine's memcache service. See the +appengine.go file in this package for details. +

    + +
    +
    + + +
    + + +
    + + + + + + + + + +

    type Cache

    +
    type Cache struct {
    +    *memcache.Client
    +}
    +

    +Cache is an implementation of httpcache.Cache that caches responses in a +memcache server. +

    + + + + + + + + + + + + +

    func New

    +
    func New(server ...string) *Cache
    +

    +New returns a new Cache using the provided memcache server(s) with equal +weight. If a server is listed multiple times, it gets a proportional amount +of weight. +

    + + + + + +

    func NewWithClient

    +
    func NewWithClient(client *memcache.Client) *Cache
    +

    +NewWithClient returns a new Cache with the given memcache client. +

    + + + + + + + +

    func (*Cache) Delete

    +
    func (c *Cache) Delete(key string)
    +

    +Delete removes the response with key from the cache. +

    + + + + + + +

    func (*Cache) Get

    +
    func (c *Cache) Get(key string) (resp []byte, ok bool)
    +

    +Get returns the response corresponding to key if present. +

    + + + + + + +

    func (*Cache) Set

    +
    func (c *Cache) Set(key string, resp []byte)
    +

    +Set saves a response to the cache as key. +

    + + + + + + + + + + + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/github.com/gregjones/httpcache/redis/index.html b/pkg/github.com/gregjones/httpcache/redis/index.html new file mode 100644 index 0000000..b40817d --- /dev/null +++ b/pkg/github.com/gregjones/httpcache/redis/index.html @@ -0,0 +1,220 @@ + + + + + + + + redis - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Package redis

    + + + + + + + + + + + + + + +
    +
    +
    import "github.com/gregjones/httpcache/redis"
    +
    +
    +
    Overview
    +
    Index
    + + +
    +
    + +
    + +
    +

    Overview ▾

    +

    +Package redis provides a redis interface for http caching. +

    + +
    +
    + + +
    + +
    +

    Index ▾

    + + + + + + + +

    Package files

    +

    + + + redis.go + + +

    + +
    +
    + + + + + + + + +

    func NewWithClient

    +
    func NewWithClient(client redis.Conn) httpcache.Cache
    +

    +NewWithClient returns a new Cache with the given redis connection. +

    + + + + + + + + + + + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/github.com/gregjones/index.html b/pkg/github.com/gregjones/index.html new file mode 100644 index 0000000..21b4404 --- /dev/null +++ b/pkg/github.com/gregjones/index.html @@ -0,0 +1,174 @@ + + + + + + + + /src/github.com/gregjones - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Directory /src/github.com/gregjones

    + + + + + + + + + + + + + + + + + + + +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    NameSynopsis
    ..
    + httpcache + + Package httpcache provides a http.RoundTripper implementation that works as a mostly RFC-compliant cache for http responses. +
    + diskcache + + Package diskcache provides an implementation of httpcache.Cache that uses the diskv package to supplement an in-memory map with persistent storage +
    + leveldbcache + + Package leveldbcache provides an implementation of httpcache.Cache that uses github.com/syndtr/goleveldb/leveldb +
    + memcache + + Package memcache provides an implementation of httpcache.Cache that uses App Engine's memcache package to store cached responses. +
    + redis + + Package redis provides a redis interface for http caching. +
    +
    + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/github.com/index.html b/pkg/github.com/index.html new file mode 100644 index 0000000..5f90a89 --- /dev/null +++ b/pkg/github.com/index.html @@ -0,0 +1,1659 @@ + + + + + + + + /src/github.com - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Directory /src/github.com

    + + + + + + + + + + + + + + + + + + + +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    NameSynopsis
    ..
    + PuerkitoBio + + +
    + goquery + + Package goquery implements features similar to jQuery, including the chainable syntax, to manipulate and query an HTML document. +
    + Sirupsen + + +
    + logrus + + Package logrus is a structured logger for Go, completely API compatible with the standard library logger. +
    + examples + + +
    + basic + + +
    + hook + + +
    + hooks + + +
    + syslog + + +
    + test + + +
    + andybalholm + + +
    + cascadia + + The cascadia package is an implementation of CSS selectors. +
    + fuzz + + +
    + andygrunwald + + +
    + go-jira + + +
    + beorn7 + + +
    + perks + + +
    + quantile + + Package quantile computes approximate quantiles over an unbounded data stream within low memory and CPU bounds. +
    + bradfitz + + +
    + gomemcache + + +
    + memcache + + Package memcache provides a client for the memcached cache server. +
    + cenkalti + + +
    + backoff + + Package backoff implements backoff algorithms for retrying operations. +
    + codegangsta + + +
    + cli + + Package cli provides a minimal framework for creating and organizing command line Go applications. +
    + altsrc + + +
    + dghubble + + +
    + go-twitter + + +
    + twitter + + Package twitter provides a Client for the Twitter API. +
    + oauth1 + + Package oauth1 is a Go implementation of the OAuth1 spec RFC 5849. +
    + dropbox + + Package dropbox provides constants for using OAuth1 to access Dropbox. +
    + examples + + +
    + tumblr + + Package tumblr provides constants for using OAuth 1 to access Tumblr. +
    + twitter + + Package twitter provides constants for using OAuth1 to access Twitter. +
    + sling + + Package sling is a Go HTTP client library for creating and sending API requests. +
    + examples + + +
    + die-net + + +
    + lrucache + + Package lrucache provides a byte-size-limited implementation of httpcache.Cache that stores data in memory. +
    + twotier + + Package twotier provides a wrapper for two httpcache.Cache instances, allowing you to use both a small and fast cache for popular objects and fall back to a larger and slower cache for less popular ones. +
    + garyburd + + +
    + redigo + + +
    + redis + + Package redis is a client for the Redis database. +
    + golang + + +
    + protobuf + + +
    + proto + + Package proto converts data structures to and from the wire format of protocol buffers. +
    + proto3_proto + + Package proto3_proto is a generated protocol buffer package. +
    + snappy + + Package snappy implements the snappy block-based compression format. +
    + google + + +
    + btree + + Package btree implements in-memory B-Trees of arbitrary degree. +
    + go-github + + +
    + github + + Package github provides a client for using the GitHub API. +
    + go-querystring + + +
    + query + + Package query implements encoding of structs into URL query parameters. +
    + gregjones + + +
    + httpcache + + Package httpcache provides a http.RoundTripper implementation that works as a mostly RFC-compliant cache for http responses. +
    + diskcache + + Package diskcache provides an implementation of httpcache.Cache that uses the diskv package to supplement an in-memory map with persistent storage +
    + leveldbcache + + Package leveldbcache provides an implementation of httpcache.Cache that uses github.com/syndtr/goleveldb/leveldb +
    + memcache + + Package memcache provides an implementation of httpcache.Cache that uses App Engine's memcache package to store cached responses. +
    + redis + + Package redis provides a redis interface for http caching. +
    + matrix-org + + +
    + dugong + + +
    + go-neb + + +
    + api + + Package api contains the fundamental data types used by Go-NEB. +
    + handlers + + Package handlers contains the HTTP handlers for Go-NEB. +
    + clients + + +
    + database + + +
    + errors + + +
    + matrix + + Package matrix provides an HTTP client that can interact with a Homeserver via r0 APIs (/sync). +
    + metrics + + +
    + plugin + + +
    + polling + + +
    + realms + + +
    + github + + +
    + jira + + +
    + urls + + Package urls handles converting between various JIRA URL representations in a consistent way. +
    + server + + Package server contains building blocks for REST APIs. +
    + services + + +
    + echo + + +
    + giphy + + +
    + github + + +
    + client + + +
    + webhook + + +
    + guggy + + +
    + jira + + +
    + webhook + + +
    + rssbot + + +
    + types + + +
    + util + + +
    + mattn + + +
    + go-shellwords + + +
    + go-sqlite3 + + Package sqlite3 provides interface to SQLite3 databases. +
    + sqlite3_test + + +
    + tool + + +
    + matttproud + + +
    + golang_protobuf_extensions + + +
    + pbutil + + Package pbutil provides record length-delimited Protocol Buffer streaming. +
    + mmcdole + + +
    + gofeed + + +
    + atom + + +
    + cmd + + +
    + ftest + + +
    + extensions + + +
    + rss + + +
    + goxpp + + +
    + peterbourgon + + +
    + diskv + + +
    + examples + + +
    + content-addressable-store + + +
    + super-simple-store + + +
    + prometheus + + +
    + client_golang + + +
    + api + + +
    + prometheus + + Package prometheus provides bindings to the Prometheus HTTP API: http://prometheus.io/docs/querying/api/ +
    + examples + + +
    + random + + A simple example exposing fictional RPC latencies with different types of random distributions (uniform, normal, and exponential) as Prometheus metrics. +
    + simple + + A minimal example of how to include Prometheus instrumentation. +
    + prometheus + + Package prometheus provides metrics primitives to instrument code for monitoring. +
    + promhttp + + Package promhttp contains functions to create http.Handler instances to expose Prometheus metrics via HTTP. +
    + push + + Package push provides functions to push metrics to a Pushgateway. +
    + client_model + + +
    + go + + Package io_prometheus_client is a generated protocol buffer package. +
    + common + + +
    + expfmt + + A package for reading and writing Prometheus metrics. +
    + model + + Package model contains common data structures that are shared across Prometheus components and libraries. +
    + procfs + + Package procfs provides functions to retrieve system, kernel and process metrics from the pseudo-filesystem proc. +
    + syndtr + + +
    + goleveldb + + +
    + leveldb + + Package leveldb provides implementation of LevelDB key/value database. +
    + cache + + Package cache provides interface and implementation of a cache algorithms. +
    + comparer + + Package comparer provides interface and implementation for ordering sets of data. +
    + errors + + Package errors provides common error types used throughout leveldb. +
    + filter + + Package filter provides interface and implementation of probabilistic data structure. +
    + iterator + + Package iterator provides interface and implementation to traverse over contents of a database. +
    + journal + + Package journal reads and writes sequences of journals. +
    + memdb + + Package memdb provides in-memory key/value database implementation. +
    + opt + + Package opt provides sets of options used by LevelDB. +
    + storage + + Package storage provides storage abstraction for LevelDB. +
    + table + + Package table allows read and write sorted key/value. +
    + testutil + + +
    + util + + Package util provides utilities used throughout leveldb. +
    +
    + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/github.com/matrix-org/dugong/index.html b/pkg/github.com/matrix-org/dugong/index.html new file mode 100644 index 0000000..5f4dc79 --- /dev/null +++ b/pkg/github.com/matrix-org/dugong/index.html @@ -0,0 +1,307 @@ + + + + + + + + dugong - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Package dugong

    + + + + + + + + + + + + + + +
    +
    +
    import "github.com/matrix-org/dugong"
    +
    +
    +
    Overview
    +
    Index
    + + +
    +
    + +
    + +
    +

    Overview ▾

    + +
    +
    + + + + + + + + + + + +

    func NewFSHook

    +
    func NewFSHook(infoPath, warnPath, errorPath string, formatter log.Formatter, rotSched RotationScheduler) log.Hook
    +

    +NewFSHook makes a logging hook that writes formatted +log entries to info, warn and error log files. Each log file +contains the messages with that severity or higher. If a formatter is +not specified, they will be logged using a JSON formatter. If a +RotationScheduler is set, the files will be cycled according to its rules. +

    + + + + + + + + +

    type DailyRotationSchedule

    +
    type DailyRotationSchedule struct {
    +    GZip bool
    +    // contains filtered or unexported fields
    +}
    +

    +DailyRotationSchedule rotates log files daily. Logs are only rotated +when midnight passes *whilst the process is running*. E.g: if you run +the process on Day 4 then stop it and start it on Day 7, no rotation will +occur when the process starts. +

    + + + + + + + + + + + + + + +

    func (*DailyRotationSchedule) ShouldGZip

    +
    func (rs *DailyRotationSchedule) ShouldGZip() bool
    + + + + + + +

    func (*DailyRotationSchedule) ShouldRotate

    +
    func (rs *DailyRotationSchedule) ShouldRotate() (bool, string)
    + + + + + + + + +

    type RotationScheduler

    +
    type RotationScheduler interface {
    +    // ShouldRotate returns true if the file should be rotated. The suffix to apply
    +    // to the filename is returned as the 2nd arg.
    +    ShouldRotate() (bool, string)
    +    // ShouldGZip returns true if the file should be gzipped when it is rotated.
    +    ShouldGZip() bool
    +}
    +

    +RotationScheduler determines when files should be rotated. +

    + + + + + + + + + + + + + + + + + + + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/github.com/matrix-org/go-neb/api/handlers/index.html b/pkg/github.com/matrix-org/go-neb/api/handlers/index.html new file mode 100644 index 0000000..c6a3087 --- /dev/null +++ b/pkg/github.com/matrix-org/go-neb/api/handlers/index.html @@ -0,0 +1,875 @@ + + + + + + + + handlers - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Package handlers

    + + + + + + + + + + + + + + +
    +
    +
    import "github.com/matrix-org/go-neb/api/handlers"
    +
    +
    +
    Overview
    +
    Index
    + + +
    +
    + +
    + +
    +

    Overview ▾

    +

    +Package handlers contains the HTTP handlers for Go-NEB. +

    +

    +This includes detail on the API paths and top-level JSON keys. For specific service JSON, +see the service you're interested in. +

    +

    See also

    +

    +Package "api" for the format of the JSON request bodies. +

    + +
    +
    + + +
    + +
    +

    Index ▾

    + + +
    +
    + + + + + +
    type ConfigureAuthRealm
    + + + +
        func (h *ConfigureAuthRealm) OnIncomingRequest(req *http.Request) (interface{}, *errors.HTTPError)
    + + + +
    type ConfigureClient
    + + + +
        func (s *ConfigureClient) OnIncomingRequest(req *http.Request) (interface{}, *errors.HTTPError)
    + + + +
    type ConfigureService
    + + +
        func NewConfigureService(db *database.ServiceDB, clients *clients.Clients) *ConfigureService
    + + + +
        func (s *ConfigureService) OnIncomingRequest(req *http.Request) (interface{}, *errors.HTTPError)
    + + + +
    type GetService
    + + + +
        func (h *GetService) OnIncomingRequest(req *http.Request) (interface{}, *errors.HTTPError)
    + + + +
    type GetSession
    + + + +
        func (h *GetSession) OnIncomingRequest(req *http.Request) (interface{}, *errors.HTTPError)
    + + + +
    type Heartbeat
    + + + +
        func (*Heartbeat) OnIncomingRequest(req *http.Request) (interface{}, *errors.HTTPError)
    + + + +
    type RealmRedirect
    + + + +
        func (rh *RealmRedirect) Handle(w http.ResponseWriter, req *http.Request)
    + + + +
    type RemoveAuthSession
    + + + +
        func (h *RemoveAuthSession) OnIncomingRequest(req *http.Request) (interface{}, *errors.HTTPError)
    + + + +
    type RequestAuthSession
    + + + +
        func (h *RequestAuthSession) OnIncomingRequest(req *http.Request) (interface{}, *errors.HTTPError)
    + + + +
    type Webhook
    + + +
        func NewWebhook(db *database.ServiceDB, cli *clients.Clients) *Webhook
    + + + +
        func (wh *Webhook) Handle(w http.ResponseWriter, req *http.Request)
    + + + +
    +
    + + + + +

    Package files

    +

    + + + auth.go + + client.go + + heartbeat.go + + service.go + + webhook.go + + +

    + +
    +
    + + + + + + + + + +

    type ConfigureAuthRealm

    +
    type ConfigureAuthRealm struct {
    +    Db *database.ServiceDB
    +}
    +

    +ConfigureAuthRealm represents an HTTP handler capable of processing /admin/configureAuthRealm requests. +

    + + + + + + + + + + + + + + +

    func (*ConfigureAuthRealm) OnIncomingRequest

    +
    func (h *ConfigureAuthRealm) OnIncomingRequest(req *http.Request) (interface{}, *errors.HTTPError)
    +

    +OnIncomingRequest handles POST requests to /admin/configureAuthRealm. The JSON object +provided is of type "api.ConfigureAuthRealmRequest". +

    +

    +Request: +

    +
    POST /admin/configureAuthRealm
    +{
    +    "ID": "my-realm-id",
    +    "Type": "github",
    +    "Config": {
    +        // Realm-specific configuration information
    +    }
    +}
    +
    +

    +Response: +

    +
    HTTP/1.1 200 OK
    +{
    +    "ID": "my-realm-id",
    +    "Type": "github",
    +    "OldConfig": {
    +        // Old auth realm config information
    +    },
    +    "NewConfig": {
    +        // New auth realm config information
    +    },
    +}
    +
    + + + + + + + + +

    type ConfigureClient

    +
    type ConfigureClient struct {
    +    Clients *clients.Clients
    +}
    +

    +ConfigureClient represents an HTTP handler capable of processing /admin/configureClient requests. +

    + + + + + + + + + + + + + + +

    func (*ConfigureClient) OnIncomingRequest

    +
    func (s *ConfigureClient) OnIncomingRequest(req *http.Request) (interface{}, *errors.HTTPError)
    +

    +OnIncomingRequest handles POST requests to /admin/configureClient. The JSON object provided +is of type "api.ClientConfig". +

    +

    +If a DisplayName is supplied, this request will set this client's display name +if the old ClientConfig DisplayName differs from the new ClientConfig DisplayName. +

    +

    +Request: +

    +
    POST /admin/configureClient
    +{
    +    "UserID": "@my_bot:localhost",
    +    "HomeserverURL": "http://localhost:8008",
    +    "Sync": true,
    +    "DisplayName": "My Bot"
    +}
    +
    +

    +Response: +

    +
    HTTP/1.1 200 OK
    +{
    +     "OldClient": {
    +       // The old api.ClientConfig
    +     },
    +     "NewClient": {
    +       // The new api.ClientConfig
    +     }
    +}
    +
    + + + + + + + + +

    type ConfigureService

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

    +ConfigureService represents an HTTP handler which can process /admin/configureService requests. +

    + + + + + + + + + + + + +

    func NewConfigureService

    +
    func NewConfigureService(db *database.ServiceDB, clients *clients.Clients) *ConfigureService
    +

    +NewConfigureService creates a new ConfigureService handler +

    + + + + + + + +

    func (*ConfigureService) OnIncomingRequest

    +
    func (s *ConfigureService) OnIncomingRequest(req *http.Request) (interface{}, *errors.HTTPError)
    +

    +OnIncomingRequest handles POST requests to /admin/configureService. +

    +

    +The request body MUST be of type "api.ConfigureServiceRequest". +

    +

    +Request: +

    +
    POST /admin/configureService
    +{
    +    "ID": "my_service_id",
    +    "Type": "service-type",
    +    "UserID": "@my_bot:localhost",
    +    "Config": {
    +        // service-specific config information
    +    }
    +}
    +
    +

    +Response: +

    +
    HTTP/1.1 200 OK
    +{
    +    "ID": "my_service_id",
    +    "Type": "service-type",
    +    "OldConfig": {
    +        // old service-specific config information
    +    },
    +    "NewConfig": {
    +        // new service-specific config information
    +    },
    +}
    +
    + + + + + + + + +

    type GetService

    +
    type GetService struct {
    +    Db *database.ServiceDB
    +}
    +

    +GetService represents an HTTP handler which can process /admin/getService requests. +

    + + + + + + + + + + + + + + +

    func (*GetService) OnIncomingRequest

    +
    func (h *GetService) OnIncomingRequest(req *http.Request) (interface{}, *errors.HTTPError)
    +

    +OnIncomingRequest handles POST requests to /admin/getService. +

    +

    +The request body MUST be a JSON body which has an "ID" key which represents +the service ID to get. +

    +

    +Request: +

    +
    POST /admin/getService
    +{
    +    "ID": "my_service_id"
    +}
    +
    +

    +Response: +

    +
    HTTP/1.1 200 OK
    +{
    +    "ID": "my_service_id",
    +    "Type": "github",
    +    "Config": {
    +        // service-specific config information
    +    }
    +}
    +
    + + + + + + + + +

    type GetSession

    +
    type GetSession struct {
    +    Db *database.ServiceDB
    +}
    +

    +GetSession represents an HTTP handler capable of processing /admin/getSession requests. +

    + + + + + + + + + + + + + + +

    func (*GetSession) OnIncomingRequest

    +
    func (h *GetSession) OnIncomingRequest(req *http.Request) (interface{}, *errors.HTTPError)
    +

    +OnIncomingRequest handles POST requests to /admin/getSession. +

    +

    +The JSON object provided MUST have a "RealmID" and "UserID" in order to fetch the +correct AuthSession. If there is no session for this tuple of realm and user ID, +a 200 OK is still returned with "Authenticated" set to false. +

    +

    +Request: +

    +
    POST /admin/getSession
    +{
    +    "RealmID": "my-realm",
    +    "UserID": "@my_user:localhost"
    +}
    +
    +

    +Response: +

    +
    HTTP/1.1 200 OK
    +{
    +    "ID": "session_id",
    +    "Authenticated": true,
    +    "Info": {
    +        // Session-specific config info
    +    }
    +}
    +
    +

    +Response if session not found: +

    +
    HTTP/1.1 200 OK
    +{
    +    "Authenticated": false
    +}
    +
    + + + + + + + + +

    type Heartbeat

    +
    type Heartbeat struct{}
    +

    +Heartbeat implements the heartbeat API +

    + + + + + + + + + + + + + + +

    func (*Heartbeat) OnIncomingRequest

    +
    func (*Heartbeat) OnIncomingRequest(req *http.Request) (interface{}, *errors.HTTPError)
    +

    +OnIncomingRequest returns an empty JSON object which can be used to detect liveness of Go-NEB. +

    +

    +Request: +

    +
    GET /test
    +
    +

    +Response: +

    +
    HTTP/1.1 200 OK
    +{}
    +
    + + + + + + + + +

    type RealmRedirect

    +
    type RealmRedirect struct {
    +    Db *database.ServiceDB
    +}
    +

    +RealmRedirect represents an HTTP handler which can process incoming redirects for auth realms. +

    + + + + + + + + + + + + + + +

    func (*RealmRedirect) Handle

    +
    func (rh *RealmRedirect) Handle(w http.ResponseWriter, req *http.Request)
    +

    +Handle requests for an auth realm. +

    +

    +The last path segment of the URL MUST be the base64 form of the Realm ID. What response +this returns depends on the specific AuthRealm implementation. +

    + + + + + + + + +

    type RemoveAuthSession

    +
    type RemoveAuthSession struct {
    +    Db *database.ServiceDB
    +}
    +

    +RemoveAuthSession represents an HTTP handler capable of processing /admin/removeAuthSession requests. +

    + + + + + + + + + + + + + + +

    func (*RemoveAuthSession) OnIncomingRequest

    +
    func (h *RemoveAuthSession) OnIncomingRequest(req *http.Request) (interface{}, *errors.HTTPError)
    +

    +OnIncomingRequest handles POST requests to /admin/removeAuthSession. +

    +

    +The JSON object MUST contain the keys "RealmID" and "UserID" to identify the session to remove. +

    +

    +Request +

    +
    POST /admin/removeAuthSession
    +{
    +    "RealmID": "github-realm",
    +    "UserID": "@my_user:localhost"
    +}
    +
    +

    +Response: +

    +
    HTTP/1.1 200 OK
    +{}
    +
    + + + + + + + + +

    type RequestAuthSession

    +
    type RequestAuthSession struct {
    +    Db *database.ServiceDB
    +}
    +

    +RequestAuthSession represents an HTTP handler capable of processing /admin/requestAuthSession requests. +

    + + + + + + + + + + + + + + +

    func (*RequestAuthSession) OnIncomingRequest

    +
    func (h *RequestAuthSession) OnIncomingRequest(req *http.Request) (interface{}, *errors.HTTPError)
    +

    +OnIncomingRequest handles POST requests to /admin/requestAuthSession. The HTTP body MUST be +a JSON object representing type "api.RequestAuthSessionRequest". +

    +

    +This will return HTTP 400 if there are missing fields or the Realm ID is unknown. +For the format of the response, see the specific AuthRealm that the Realm ID corresponds to. +

    +

    +Request: +

    +
    POST /admin/requestAuthSession
    +{
    +    "RealmID": "github_realm_id",
    +    "UserID": "@my_user:localhost",
    +    "Config": {
    +        // AuthRealm specific config info
    +    }
    +}
    +
    +

    +Response: +

    +
    HTTP/1.1 200 OK
    +{
    +    // AuthRealm-specific information
    +}
    +
    + + + + + + + + +

    type Webhook

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

    +Webhook represents an HTTP handler capable of accepting webhook requests on behalf of services. +

    + + + + + + + + + + + + +

    func NewWebhook

    +
    func NewWebhook(db *database.ServiceDB, cli *clients.Clients) *Webhook
    +

    +NewWebhook returns a new webhook HTTP handler +

    + + + + + + + +

    func (*Webhook) Handle

    +
    func (wh *Webhook) Handle(w http.ResponseWriter, req *http.Request)
    +

    +Handle an incoming webhook HTTP request. +

    +

    +The webhook MUST have a known base64 encoded service ID as the last path segment +in order for this request to be passed to the correct service, or else this will return +HTTP 400. If the base64 encoded service ID is unknown, this will return HTTP 404. +Beyond this, the exact response is determined by the specific Service implementation. +

    + + + + + + + + + + + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/github.com/matrix-org/go-neb/api/index.html b/pkg/github.com/matrix-org/go-neb/api/index.html new file mode 100644 index 0000000..1de214f --- /dev/null +++ b/pkg/github.com/matrix-org/go-neb/api/index.html @@ -0,0 +1,540 @@ + + + + + + + + api - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Package api

    + + + + + + + + + + + + + + +
    +
    +
    import "github.com/matrix-org/go-neb/api"
    +
    +
    +
    Overview
    +
    Index
    + + +
    Subdirectories
    + +
    +
    + +
    + +
    +

    Overview ▾

    +

    +Package api contains the fundamental data types used by Go-NEB. +

    +

    +Most HTTP API calls and/or config file sections are just ways of representing these +data types. +

    +

    See also

    +

    +Package "api.handlers" for information on the HTTP API calls. +

    + +
    +
    + + + + + + + + + + + + +

    type ClientConfig

    +
    type ClientConfig struct {
    +    // The matrix User ID to connect with. E.g. @alice:matrix.org
    +    UserID string
    +    // A URL with the host and port of the matrix server. E.g. https://matrix.org:8448
    +    HomeserverURL string
    +    // The matrix access token to authenticate the requests with.
    +    AccessToken string
    +    // True to start a sync stream for this user. If false, no /sync goroutine will be
    +    // created and this client won't listen for new events from Matrix. For services
    +    // which only SEND events into Matrix, it may be desirable to set Sync to false to reduce the
    +    // number of goroutines Go-NEB has to maintain. For services which respond to !commands,
    +    // Sync MUST be set to true in order to receive those commands.
    +    Sync bool
    +    // True to automatically join every room this client is invited to.
    +    // This is desirable for services which have !commands as that means anyone can pull the bot
    +    // into the room. It is up to the service to decide which, if any, users to respond to however.
    +    AutoJoinRooms bool
    +    // The desired display name for this client.
    +    // This does not automatically set the display name for this client. See /configureClient.
    +    DisplayName string
    +}
    +

    +A ClientConfig contains the configuration information for a matrix client so that +Go-NEB can drive it. It forms the HTTP body to /configureClient requests. +

    + + + + + + + + + + + + + + +

    func (*ClientConfig) Check

    +
    func (c *ClientConfig) Check() error
    +

    +Check that the client has supplied the correct fields. +

    + + + + + + + + +

    type ConfigFile

    +
    type ConfigFile struct {
    +    Clients  []ClientConfig
    +    Realms   []ConfigureAuthRealmRequest
    +    Services []ConfigureServiceRequest
    +    Sessions []Session
    +}
    +

    +ConfigFile represents config.sample.yaml +

    + + + + + + + + + + + + + + + + +

    type ConfigureAuthRealmRequest

    +
    type ConfigureAuthRealmRequest struct {
    +    // An arbitrary unique identifier for this auth realm. This can be anything.
    +    // Using an existing ID will REPLACE the entire existing AuthRealm with the new information.
    +    ID string
    +    // The type of auth realm. This determines which code is loaded to execute the
    +    // auth realm. It must be a known type. E.g. "github".
    +    Type string
    +    // AuthRealm specific config information. See the docs for the auth realm you're interested in.
    +    Config json.RawMessage
    +}
    +

    +ConfigureAuthRealmRequest is a request to /configureAuthRealm +

    + + + + + + + + + + + + + + +

    func (*ConfigureAuthRealmRequest) Check

    +
    func (c *ConfigureAuthRealmRequest) Check() error
    +

    +Check validates the /configureAuthRealm request +

    + + + + + + + + +

    type ConfigureServiceRequest

    +
    type ConfigureServiceRequest struct {
    +    // An arbitrary unique identifier for this service. This can be anything.
    +    // Using an existing ID will REPLACE the entire Service with the new information.
    +    ID string
    +    // The type of service. This determines which code is loaded to execute the
    +    // service. It must be a known type, e.g. "github".
    +    Type string
    +    // The user ID of the configured client that this service will use to communicate with Matrix.
    +    // The user MUST already be configured.
    +    UserID string
    +    // Service-specific config information. See the docs for the service you're interested in.
    +    Config json.RawMessage
    +}
    +

    +ConfigureServiceRequest is a request to /configureService +

    + + + + + + + + + + + + + + +

    func (*ConfigureServiceRequest) Check

    +
    func (c *ConfigureServiceRequest) Check() error
    +

    +Check validates the /configureService request +

    + + + + + + + + +

    type RequestAuthSessionRequest

    +
    type RequestAuthSessionRequest struct {
    +    // The realm ID to request a new auth session on. The realm MUST already exist.
    +    RealmID string
    +    // The Matrix user ID requesting the auth session. If the auth is successful,
    +    // this user ID will be associated with the third-party credentials obtained.
    +    UserID string
    +    // AuthRealm specific config information. See the docs for the auth realm you're interested in.
    +    Config json.RawMessage
    +}
    +

    +RequestAuthSessionRequest is a request to /requestAuthSession +

    + + + + + + + + + + + + + + +

    func (*RequestAuthSessionRequest) Check

    +
    func (r *RequestAuthSessionRequest) Check() error
    +

    +Check that the request is valid. +

    + + + + + + + + +

    type Session

    +
    type Session struct {
    +    SessionID string
    +    RealmID   string
    +    UserID    string
    +    Config    json.RawMessage
    +}
    +

    +Session contains the complete auth session information for a given user on a given realm. +They are created for use with ConfigFile. +

    + + + + + + + + + + + + + + +

    func (*Session) Check

    +
    func (c *Session) Check() error
    +

    +Check validates the session config request +

    + + + + + + + + + + + + + + + + +

    Subdirectories

    + + + + +
    + + + + + + + + + + + + + + + + + + + + +
    NameSynopsis
    ..
    + handlers + + Package handlers contains the HTTP handlers for Go-NEB. +
    +
    + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/github.com/matrix-org/go-neb/clients/index.html b/pkg/github.com/matrix-org/go-neb/clients/index.html new file mode 100644 index 0000000..311233a --- /dev/null +++ b/pkg/github.com/matrix-org/go-neb/clients/index.html @@ -0,0 +1,285 @@ + + + + + + + + clients - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Package clients

    + + + + + + + + + + + + + + +
    +
    +
    import "github.com/matrix-org/go-neb/clients"
    +
    +
    +
    Overview
    +
    Index
    + + +
    +
    + +
    + +
    +

    Overview ▾

    + +
    +
    + + + + + + + + + + + + +

    type Clients

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

    +A Clients is a collection of clients used for bot services. +

    + + + + + + + + + + + + +

    func New

    +
    func New(db *database.ServiceDB, cli *http.Client) *Clients
    +

    +New makes a new collection of matrix clients +

    + + + + + + + +

    func (*Clients) Client

    +
    func (c *Clients) Client(userID string) (*matrix.Client, error)
    +

    +Client gets a client for the userID +

    + + + + + + +

    func (*Clients) Start

    +
    func (c *Clients) Start() error
    +

    +Start listening on client /sync streams +

    + + + + + + +

    func (*Clients) Update

    +
    func (c *Clients) Update(config api.ClientConfig) (api.ClientConfig, error)
    +

    +Update updates the config for a matrix client +

    + + + + + + + + + + + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/github.com/matrix-org/go-neb/database/index.html b/pkg/github.com/matrix-org/go-neb/database/index.html new file mode 100644 index 0000000..1379281 --- /dev/null +++ b/pkg/github.com/matrix-org/go-neb/database/index.html @@ -0,0 +1,940 @@ + + + + + + + + database - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Package database

    + + + + + + + + + + + + + + +
    +
    +
    import "github.com/matrix-org/go-neb/database"
    +
    +
    +
    Overview
    +
    Index
    + + +
    +
    + +
    + +
    +

    Overview ▾

    + +
    +
    + + +
    + +
    +

    Index ▾

    + + +
    +
    + + + + +
    func SetServiceDB(db Storer)
    + + + +
    type NopStorage
    + + + +
        func (s *NopStorage) DeleteService(serviceID string) (err error)
    + + +
        func (s *NopStorage) InsertFromConfig(cfg *api.ConfigFile) error
    + + +
        func (s *NopStorage) LoadAuthRealm(realmID string) (realm types.AuthRealm, err error)
    + + +
        func (s *NopStorage) LoadAuthRealmsByType(realmType string) (realms []types.AuthRealm, err error)
    + + +
        func (s *NopStorage) LoadAuthSessionByID(realmID, sessionID string) (session types.AuthSession, err error)
    + + +
        func (s *NopStorage) LoadAuthSessionByUser(realmID, userID string) (session types.AuthSession, err error)
    + + +
        func (s *NopStorage) LoadBotOptions(userID, roomID string) (opts types.BotOptions, err error)
    + + +
        func (s *NopStorage) LoadMatrixClientConfig(userID string) (config api.ClientConfig, err error)
    + + +
        func (s *NopStorage) LoadMatrixClientConfigs() (configs []api.ClientConfig, err error)
    + + +
        func (s *NopStorage) LoadNextBatch(userID string) (nextBatch string, err error)
    + + +
        func (s *NopStorage) LoadService(serviceID string) (service types.Service, err error)
    + + +
        func (s *NopStorage) LoadServicesByType(serviceType string) (services []types.Service, err error)
    + + +
        func (s *NopStorage) LoadServicesForUser(serviceUserID string) (services []types.Service, err error)
    + + +
        func (s *NopStorage) RemoveAuthSession(realmID, userID string) error
    + + +
        func (s *NopStorage) StoreAuthRealm(realm types.AuthRealm) (old types.AuthRealm, err error)
    + + +
        func (s *NopStorage) StoreAuthSession(session types.AuthSession) (old types.AuthSession, err error)
    + + +
        func (s *NopStorage) StoreBotOptions(opts types.BotOptions) (oldOpts types.BotOptions, err error)
    + + +
        func (s *NopStorage) StoreMatrixClientConfig(config api.ClientConfig) (oldConfig api.ClientConfig, err error)
    + + +
        func (s *NopStorage) StoreService(service types.Service) (oldService types.Service, err error)
    + + +
        func (s *NopStorage) UpdateNextBatch(userID, nextBatch string) (err error)
    + + + +
    type ServiceDB
    + + +
        func Open(databaseType, databaseURL string) (serviceDB *ServiceDB, err error)
    + + + +
        func (d *ServiceDB) DeleteService(serviceID string) (err error)
    + + +
        func (d *ServiceDB) InsertFromConfig(cfg *api.ConfigFile) error
    + + +
        func (d *ServiceDB) LoadAuthRealm(realmID string) (realm types.AuthRealm, err error)
    + + +
        func (d *ServiceDB) LoadAuthRealmsByType(realmType string) (realms []types.AuthRealm, err error)
    + + +
        func (d *ServiceDB) LoadAuthSessionByID(realmID, sessionID string) (session types.AuthSession, err error)
    + + +
        func (d *ServiceDB) LoadAuthSessionByUser(realmID, userID string) (session types.AuthSession, err error)
    + + +
        func (d *ServiceDB) LoadBotOptions(userID, roomID string) (opts types.BotOptions, err error)
    + + +
        func (d *ServiceDB) LoadMatrixClientConfig(userID string) (config api.ClientConfig, err error)
    + + +
        func (d *ServiceDB) LoadMatrixClientConfigs() (configs []api.ClientConfig, err error)
    + + +
        func (d *ServiceDB) LoadNextBatch(userID string) (nextBatch string, err error)
    + + +
        func (d *ServiceDB) LoadService(serviceID string) (service types.Service, err error)
    + + +
        func (d *ServiceDB) LoadServicesByType(serviceType string) (services []types.Service, err error)
    + + +
        func (d *ServiceDB) LoadServicesForUser(serviceUserID string) (services []types.Service, err error)
    + + +
        func (d *ServiceDB) RemoveAuthSession(realmID, userID string) error
    + + +
        func (d *ServiceDB) StoreAuthRealm(realm types.AuthRealm) (old types.AuthRealm, err error)
    + + +
        func (d *ServiceDB) StoreAuthSession(session types.AuthSession) (old types.AuthSession, err error)
    + + +
        func (d *ServiceDB) StoreBotOptions(opts types.BotOptions) (oldOpts types.BotOptions, err error)
    + + +
        func (d *ServiceDB) StoreMatrixClientConfig(config api.ClientConfig) (oldConfig api.ClientConfig, err error)
    + + +
        func (d *ServiceDB) StoreService(service types.Service) (oldService types.Service, err error)
    + + +
        func (d *ServiceDB) UpdateNextBatch(userID, nextBatch string) (err error)
    + + + +
    type Storer
    + + +
        func GetServiceDB() Storer
    + + + + +
    +
    + + + + +

    Package files

    +

    + + + db.go + + interface.go + + schema.go + + +

    + +
    +
    + + + + + + + + +

    func SetServiceDB

    +
    func SetServiceDB(db Storer)
    +

    +SetServiceDB sets the global service DB instance. +

    + + + + + + + + +

    type NopStorage

    +
    type NopStorage struct{}
    +

    +NopStorage nops every store API call. This is intended to be embedded into derived structs +in tests +

    + + + + + + + + + + + + + + +

    func (*NopStorage) DeleteService

    +
    func (s *NopStorage) DeleteService(serviceID string) (err error)
    +

    +DeleteService NOP +

    + + + + + + +

    func (*NopStorage) InsertFromConfig

    +
    func (s *NopStorage) InsertFromConfig(cfg *api.ConfigFile) error
    +

    +InsertFromConfig NOP +

    + + + + + + +

    func (*NopStorage) LoadAuthRealm

    +
    func (s *NopStorage) LoadAuthRealm(realmID string) (realm types.AuthRealm, err error)
    +

    +LoadAuthRealm NOP +

    + + + + + + +

    func (*NopStorage) LoadAuthRealmsByType

    +
    func (s *NopStorage) LoadAuthRealmsByType(realmType string) (realms []types.AuthRealm, err error)
    +

    +LoadAuthRealmsByType NOP +

    + + + + + + +

    func (*NopStorage) LoadAuthSessionByID

    +
    func (s *NopStorage) LoadAuthSessionByID(realmID, sessionID string) (session types.AuthSession, err error)
    +

    +LoadAuthSessionByID NOP +

    + + + + + + +

    func (*NopStorage) LoadAuthSessionByUser

    +
    func (s *NopStorage) LoadAuthSessionByUser(realmID, userID string) (session types.AuthSession, err error)
    +

    +LoadAuthSessionByUser NOP +

    + + + + + + +

    func (*NopStorage) LoadBotOptions

    +
    func (s *NopStorage) LoadBotOptions(userID, roomID string) (opts types.BotOptions, err error)
    +

    +LoadBotOptions NOP +

    + + + + + + +

    func (*NopStorage) LoadMatrixClientConfig

    +
    func (s *NopStorage) LoadMatrixClientConfig(userID string) (config api.ClientConfig, err error)
    +

    +LoadMatrixClientConfig NOP +

    + + + + + + +

    func (*NopStorage) LoadMatrixClientConfigs

    +
    func (s *NopStorage) LoadMatrixClientConfigs() (configs []api.ClientConfig, err error)
    +

    +LoadMatrixClientConfigs NOP +

    + + + + + + +

    func (*NopStorage) LoadNextBatch

    +
    func (s *NopStorage) LoadNextBatch(userID string) (nextBatch string, err error)
    +

    +LoadNextBatch NOP +

    + + + + + + +

    func (*NopStorage) LoadService

    +
    func (s *NopStorage) LoadService(serviceID string) (service types.Service, err error)
    +

    +LoadService NOP +

    + + + + + + +

    func (*NopStorage) LoadServicesByType

    +
    func (s *NopStorage) LoadServicesByType(serviceType string) (services []types.Service, err error)
    +

    +LoadServicesByType NOP +

    + + + + + + +

    func (*NopStorage) LoadServicesForUser

    +
    func (s *NopStorage) LoadServicesForUser(serviceUserID string) (services []types.Service, err error)
    +

    +LoadServicesForUser NOP +

    + + + + + + +

    func (*NopStorage) RemoveAuthSession

    +
    func (s *NopStorage) RemoveAuthSession(realmID, userID string) error
    +

    +RemoveAuthSession NOP +

    + + + + + + +

    func (*NopStorage) StoreAuthRealm

    +
    func (s *NopStorage) StoreAuthRealm(realm types.AuthRealm) (old types.AuthRealm, err error)
    +

    +StoreAuthRealm NOP +

    + + + + + + +

    func (*NopStorage) StoreAuthSession

    +
    func (s *NopStorage) StoreAuthSession(session types.AuthSession) (old types.AuthSession, err error)
    +

    +StoreAuthSession NOP +

    + + + + + + +

    func (*NopStorage) StoreBotOptions

    +
    func (s *NopStorage) StoreBotOptions(opts types.BotOptions) (oldOpts types.BotOptions, err error)
    +

    +StoreBotOptions NOP +

    + + + + + + +

    func (*NopStorage) StoreMatrixClientConfig

    +
    func (s *NopStorage) StoreMatrixClientConfig(config api.ClientConfig) (oldConfig api.ClientConfig, err error)
    +

    +StoreMatrixClientConfig NOP +

    + + + + + + +

    func (*NopStorage) StoreService

    +
    func (s *NopStorage) StoreService(service types.Service) (oldService types.Service, err error)
    +

    +StoreService NOP +

    + + + + + + +

    func (*NopStorage) UpdateNextBatch

    +
    func (s *NopStorage) UpdateNextBatch(userID, nextBatch string) (err error)
    +

    +UpdateNextBatch NOP +

    + + + + + + + + +

    type ServiceDB

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

    +A ServiceDB stores the configuration for the services +

    + + + + + + + + + + + + +

    func Open

    +
    func Open(databaseType, databaseURL string) (serviceDB *ServiceDB, err error)
    +

    +Open a SQL database to use as a ServiceDB. This will automatically create +the necessary database tables if they aren't already present. +

    + + + + + + + +

    func (*ServiceDB) DeleteService

    +
    func (d *ServiceDB) DeleteService(serviceID string) (err error)
    +

    +DeleteService deletes the given service from the database. +

    + + + + + + +

    func (*ServiceDB) InsertFromConfig

    +
    func (d *ServiceDB) InsertFromConfig(cfg *api.ConfigFile) error
    +

    +InsertFromConfig inserts entries from the config file into the database. This only really +makes sense for in-memory databases. +

    + + + + + + +

    func (*ServiceDB) LoadAuthRealm

    +
    func (d *ServiceDB) LoadAuthRealm(realmID string) (realm types.AuthRealm, err error)
    +

    +LoadAuthRealm loads an AuthRealm from the database. +Returns sql.ErrNoRows if the realm isn't in the database. +

    + + + + + + +

    func (*ServiceDB) LoadAuthRealmsByType

    +
    func (d *ServiceDB) LoadAuthRealmsByType(realmType string) (realms []types.AuthRealm, err error)
    +

    +LoadAuthRealmsByType loads all auth realms with the given type from the database. +The realms are ordered based on their realm ID. +Returns an empty list if there are no realms with that type. +

    + + + + + + +

    func (*ServiceDB) LoadAuthSessionByID

    +
    func (d *ServiceDB) LoadAuthSessionByID(realmID, sessionID string) (session types.AuthSession, err error)
    +

    +LoadAuthSessionByID loads an AuthSession from the database based on the given +realm and session ID. +Returns sql.ErrNoRows if the session isn't in the database. +

    + + + + + + +

    func (*ServiceDB) LoadAuthSessionByUser

    +
    func (d *ServiceDB) LoadAuthSessionByUser(realmID, userID string) (session types.AuthSession, err error)
    +

    +LoadAuthSessionByUser loads an AuthSession from the database based on the given +realm and user ID. +Returns sql.ErrNoRows if the session isn't in the database. +

    + + + + + + +

    func (*ServiceDB) LoadBotOptions

    +
    func (d *ServiceDB) LoadBotOptions(userID, roomID string) (opts types.BotOptions, err error)
    +

    +LoadBotOptions loads bot options from the database. +Returns sql.ErrNoRows if the bot options isn't in the database. +

    + + + + + + +

    func (*ServiceDB) LoadMatrixClientConfig

    +
    func (d *ServiceDB) LoadMatrixClientConfig(userID string) (config api.ClientConfig, err error)
    +

    +LoadMatrixClientConfig loads a Matrix client config from the database. +Returns sql.ErrNoRows if the client isn't in the database. +

    + + + + + + +

    func (*ServiceDB) LoadMatrixClientConfigs

    +
    func (d *ServiceDB) LoadMatrixClientConfigs() (configs []api.ClientConfig, err error)
    +

    +LoadMatrixClientConfigs loads all Matrix client configs from the database. +

    + + + + + + +

    func (*ServiceDB) LoadNextBatch

    +
    func (d *ServiceDB) LoadNextBatch(userID string) (nextBatch string, err error)
    +

    +LoadNextBatch loads the next_batch token for the given user. +

    + + + + + + +

    func (*ServiceDB) LoadService

    +
    func (d *ServiceDB) LoadService(serviceID string) (service types.Service, err error)
    +

    +LoadService loads a service from the database. +Returns sql.ErrNoRows if the service isn't in the database. +

    + + + + + + +

    func (*ServiceDB) LoadServicesByType

    +
    func (d *ServiceDB) LoadServicesByType(serviceType string) (services []types.Service, err error)
    +

    +LoadServicesByType loads all the bot services configured for a given type. +Returns an empty list if there aren't any services configured. +

    + + + + + + +

    func (*ServiceDB) LoadServicesForUser

    +
    func (d *ServiceDB) LoadServicesForUser(serviceUserID string) (services []types.Service, err error)
    +

    +LoadServicesForUser loads all the bot services configured for a given user. +Returns an empty list if there aren't any services configured. +

    + + + + + + +

    func (*ServiceDB) RemoveAuthSession

    +
    func (d *ServiceDB) RemoveAuthSession(realmID, userID string) error
    +

    +RemoveAuthSession removes the auth session for the given user on the given realm. +No error is returned if the session did not exist in the first place. +

    + + + + + + +

    func (*ServiceDB) StoreAuthRealm

    +
    func (d *ServiceDB) StoreAuthRealm(realm types.AuthRealm) (old types.AuthRealm, err error)
    +

    +StoreAuthRealm stores the given AuthRealm, clobbering based on the realm ID. +This function updates the time added/updated values. The previous realm, if any, is +returned. +

    + + + + + + +

    func (*ServiceDB) StoreAuthSession

    +
    func (d *ServiceDB) StoreAuthSession(session types.AuthSession) (old types.AuthSession, err error)
    +

    +StoreAuthSession stores the given AuthSession, clobbering based on the tuple of +user ID and realm ID. This function updates the time added/updated values. +The previous session, if any, is returned. +

    + + + + + + +

    func (*ServiceDB) StoreBotOptions

    +
    func (d *ServiceDB) StoreBotOptions(opts types.BotOptions) (oldOpts types.BotOptions, err error)
    +

    +StoreBotOptions stores a BotOptions into the database either by inserting a new +bot options or updating an existing bot options. Returns the old bot options if there +was one. +

    + + + + + + +

    func (*ServiceDB) StoreMatrixClientConfig

    +
    func (d *ServiceDB) StoreMatrixClientConfig(config api.ClientConfig) (oldConfig api.ClientConfig, err error)
    +

    +StoreMatrixClientConfig stores the Matrix client config for a bot service. +If a config already exists then it will be updated, otherwise a new config +will be inserted. The previous config is returned. +

    + + + + + + +

    func (*ServiceDB) StoreService

    +
    func (d *ServiceDB) StoreService(service types.Service) (oldService types.Service, err error)
    +

    +StoreService stores a service into the database either by inserting a new +service or updating an existing service. Returns the old service if there +was one. +

    + + + + + + +

    func (*ServiceDB) UpdateNextBatch

    +
    func (d *ServiceDB) UpdateNextBatch(userID, nextBatch string) (err error)
    +

    +UpdateNextBatch updates the next_batch token for the given user. +

    + + + + + + + + +

    type Storer

    +
    type Storer interface {
    +    StoreMatrixClientConfig(config api.ClientConfig) (oldConfig api.ClientConfig, err error)
    +    LoadMatrixClientConfigs() (configs []api.ClientConfig, err error)
    +    LoadMatrixClientConfig(userID string) (config api.ClientConfig, err error)
    +
    +    UpdateNextBatch(userID, nextBatch string) (err error)
    +    LoadNextBatch(userID string) (nextBatch string, err error)
    +
    +    LoadService(serviceID string) (service types.Service, err error)
    +    DeleteService(serviceID string) (err error)
    +    LoadServicesForUser(serviceUserID string) (services []types.Service, err error)
    +    LoadServicesByType(serviceType string) (services []types.Service, err error)
    +    StoreService(service types.Service) (oldService types.Service, err error)
    +
    +    LoadAuthRealm(realmID string) (realm types.AuthRealm, err error)
    +    LoadAuthRealmsByType(realmType string) (realms []types.AuthRealm, err error)
    +    StoreAuthRealm(realm types.AuthRealm) (old types.AuthRealm, err error)
    +
    +    StoreAuthSession(session types.AuthSession) (old types.AuthSession, err error)
    +    LoadAuthSessionByUser(realmID, userID string) (session types.AuthSession, err error)
    +    LoadAuthSessionByID(realmID, sessionID string) (session types.AuthSession, err error)
    +    RemoveAuthSession(realmID, userID string) error
    +
    +    LoadBotOptions(userID, roomID string) (opts types.BotOptions, err error)
    +    StoreBotOptions(opts types.BotOptions) (oldOpts types.BotOptions, err error)
    +
    +    InsertFromConfig(cfg *api.ConfigFile) error
    +}
    +

    +Storer is the interface which needs to be conformed to in order to persist Go-NEB data +

    + + + + + + + + + + + + +

    func GetServiceDB

    +
    func GetServiceDB() Storer
    +

    +GetServiceDB gets the global service DB instance. +

    + + + + + + + + + + + + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/github.com/matrix-org/go-neb/errors/index.html b/pkg/github.com/matrix-org/go-neb/errors/index.html new file mode 100644 index 0000000..e8a9b4a --- /dev/null +++ b/pkg/github.com/matrix-org/go-neb/errors/index.html @@ -0,0 +1,243 @@ + + + + + + + + errors - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Package errors

    + + + + + + + + + + + + + + +
    +
    +
    import "github.com/matrix-org/go-neb/errors"
    +
    +
    +
    Overview
    +
    Index
    + + +
    +
    + +
    + +
    +

    Overview ▾

    + +
    +
    + + +
    + +
    +

    Index ▾

    + + +
    +
    + + + + + +
    type HTTPError
    + + + +
        func (e HTTPError) Error() string
    + + + +
    +
    + + + + +

    Package files

    +

    + + + errors.go + + +

    + +
    +
    + + + + + + + + + +

    type HTTPError

    +
    type HTTPError struct {
    +    WrappedError error
    +    Message      string
    +    Code         int
    +}
    +

    +HTTPError An HTTP Error response, which may wrap an underlying native Go Error. +

    + + + + + + + + + + + + + + +

    func (HTTPError) Error

    +
    func (e HTTPError) Error() string
    + + + + + + + + + + + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/github.com/matrix-org/go-neb/index.html b/pkg/github.com/matrix-org/go-neb/index.html new file mode 100644 index 0000000..654afaf --- /dev/null +++ b/pkg/github.com/matrix-org/go-neb/index.html @@ -0,0 +1,419 @@ + + + + + + + + go-neb - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Command go-neb

    + + + + + + + + + + + + + + + + + + + + + + + + + +

    Subdirectories

    + + + + +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    NameSynopsis
    ..
    + api + + Package api contains the fundamental data types used by Go-NEB. +
    + handlers + + Package handlers contains the HTTP handlers for Go-NEB. +
    + clients + + +
    + database + + +
    + errors + + +
    + matrix + + Package matrix provides an HTTP client that can interact with a Homeserver via r0 APIs (/sync). +
    + metrics + + +
    + plugin + + +
    + polling + + +
    + realms + + +
    + github + + +
    + jira + + +
    + urls + + Package urls handles converting between various JIRA URL representations in a consistent way. +
    + server + + Package server contains building blocks for REST APIs. +
    + services + + +
    + echo + + +
    + giphy + + +
    + github + + +
    + client + + +
    + webhook + + +
    + guggy + + +
    + jira + + +
    + webhook + + +
    + rssbot + + +
    + types + + +
    + util + + +
    +
    + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/github.com/matrix-org/go-neb/matrix/index.html b/pkg/github.com/matrix-org/go-neb/matrix/index.html new file mode 100644 index 0000000..9f574f9 --- /dev/null +++ b/pkg/github.com/matrix-org/go-neb/matrix/index.html @@ -0,0 +1,819 @@ + + + + + + + + matrix - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Package matrix

    + + + + + + + + + + + + + + +
    +
    +
    import "github.com/matrix-org/go-neb/matrix"
    +
    +
    +
    Overview
    +
    Index
    + + +
    +
    + +
    + +
    +

    Overview ▾

    +

    +Package matrix provides an HTTP client that can interact with a Homeserver via r0 APIs (/sync). +

    +

    +It is NOT safe to access the field (or any sub-fields of) 'Rooms' concurrently. In essence, this +structure MUST be treated as read-only. The matrix client will update this structure as new events +arrive from the homeserver. +

    +

    +Internally, the client has 1 goroutine for polling the server, and 1 goroutine for processing data +returned. The polling goroutine communicates to the processing goroutine by a buffered channel +which feedback loops if processing takes a while as it will delay more data from being pulled down +if the buffer gets full. Modification of the 'Rooms' field of the client is done EXCLUSIVELY on the +processing goroutine. +

    + +
    +
    + + +
    + +
    +

    Index ▾

    + + +
    +
    + + + + + +
    type Client
    + + +
        func NewClient(httpClient *http.Client, homeserverURL *url.URL, accessToken, userID string) *Client
    + + + +
        func (cli *Client) JoinRoom(roomIDorAlias, serverName, invitingUserID string) (string, error)
    + + +
        func (cli *Client) SendMessageEvent(roomID string, eventType string, contentJSON interface{}) (string, error)
    + + +
        func (cli *Client) SendText(roomID, text string) (string, error)
    + + +
        func (cli *Client) SetDisplayName(displayName string) error
    + + +
        func (cli *Client) StopSync()
    + + +
        func (cli *Client) Sync()
    + + +
        func (cli *Client) UploadLink(link string) (string, error)
    + + +
        func (cli *Client) UploadToContentRepo(content io.Reader, contentType string, contentLength int64) (string, error)
    + + + +
    type Event
    + + + +
        func (event *Event) Body() (body string, ok bool)
    + + +
        func (event *Event) MessageType() (msgtype string, ok bool)
    + + + +
    type HTMLMessage
    + + +
        func GetHTMLMessage(msgtype, htmlText string) HTMLMessage
    + + + + +
    type ImageInfo
    + + + + +
    type ImageMessage
    + + + + +
    type NextBatchStorer
    + + + + +
    type OnEventListener
    + + + + +
    type Room
    + + +
        func NewRoom(roomID string) *Room
    + + + +
        func (room Room) GetMembershipState(userID string) string
    + + +
        func (room Room) GetStateEvent(eventType string, stateKey string) *Event
    + + +
        func (room Room) UpdateState(event *Event)
    + + + +
    type StarterLinkMessage
    + + + +
        func (m StarterLinkMessage) MarshalJSON() ([]byte, error)
    + + + +
    type TextMessage
    + + + + +
    type Worker
    + + + +
        func (worker *Worker) OnEventType(eventType string, callback OnEventListener)
    + + + +
    +
    + + + + +

    Package files

    +

    + + + matrix.go + + responses.go + + types.go + + worker.go + + +

    + +
    +
    + + + + + + + + + +

    type Client

    +
    type Client struct {
    +    HomeserverURL *url.URL
    +    Prefix        string
    +    UserID        string
    +    AccessToken   string
    +    Rooms         map[string]*Room
    +    Worker        *Worker
    +
    +    NextBatchStorer NextBatchStorer
    +    // contains filtered or unexported fields
    +}
    +

    +Client represents a Matrix client. +

    + + + + + + + + + + + + +

    func NewClient

    +
    func NewClient(httpClient *http.Client, homeserverURL *url.URL, accessToken, userID string) *Client
    +

    +NewClient creates a new Matrix Client ready for syncing +

    + + + + + + + +

    func (*Client) JoinRoom

    +
    func (cli *Client) JoinRoom(roomIDorAlias, serverName, invitingUserID string) (string, error)
    +

    +JoinRoom joins the client to a room ID or alias. If serverName is specified, this will be added as a query param +to instruct the homeserver to join via that server. If invitingUserID is specified, the inviting user ID will be +inserted into the content of the join request. Returns a room ID. +

    + + + + + + +

    func (*Client) SendMessageEvent

    +
    func (cli *Client) SendMessageEvent(roomID string, eventType string, contentJSON interface{}) (string, error)
    +

    +SendMessageEvent sends a message event into a room, returning the event_id on success. +contentJSON should be a pointer to something that can be encoded as JSON using json.Marshal. +

    + + + + + + +

    func (*Client) SendText

    +
    func (cli *Client) SendText(roomID, text string) (string, error)
    +

    +SendText sends an m.room.message event into the given room with a msgtype of m.text +

    + + + + + + +

    func (*Client) SetDisplayName

    +
    func (cli *Client) SetDisplayName(displayName string) error
    +

    +SetDisplayName sets the user's profile display name +

    + + + + + + +

    func (*Client) StopSync

    +
    func (cli *Client) StopSync()
    +

    +StopSync stops the ongoing sync started by Sync. +

    + + + + + + +

    func (*Client) Sync

    +
    func (cli *Client) Sync()
    +

    +Sync starts syncing with the provided Homeserver. This function will be invoked continually. +If Sync is called twice then the first sync will be stopped. +

    + + + + + + + +
    func (cli *Client) UploadLink(link string) (string, error)
    +

    +UploadLink uploads an HTTP URL and then returns an MXC URI. +

    + + + + + + +

    func (*Client) UploadToContentRepo

    +
    func (cli *Client) UploadToContentRepo(content io.Reader, contentType string, contentLength int64) (string, error)
    +

    +UploadToContentRepo uploads the given bytes to the content repository and returns an MXC URI. +

    + + + + + + + + +

    type Event

    +
    type Event struct {
    +    StateKey  string                 `json:"state_key"`        // The state key for the event. Only present on State Events.
    +    Sender    string                 `json:"sender"`           // The user ID of the sender of the event
    +    Type      string                 `json:"type"`             // The event type
    +    Timestamp int                    `json:"origin_server_ts"` // The unix timestamp when this message was sent by the origin server
    +    ID        string                 `json:"event_id"`         // The unique ID of this event
    +    RoomID    string                 `json:"room_id"`          // The room the event was sent to. May be nil (e.g. for presence)
    +    Content   map[string]interface{} `json:"content"`          // The JSON content of the event.
    +}
    +

    +Event represents a single Matrix event. +

    + + + + + + + + + + + + + + +

    func (*Event) Body

    +
    func (event *Event) Body() (body string, ok bool)
    +

    +Body returns the value of the "body" key in the event content if it is +present and is a string. +

    + + + + + + +

    func (*Event) MessageType

    +
    func (event *Event) MessageType() (msgtype string, ok bool)
    +

    +MessageType returns the value of the "msgtype" key in the event content if +it is present and is a string. +

    + + + + + + + + +

    type HTMLMessage

    +
    type HTMLMessage struct {
    +    Body          string `json:"body"`
    +    MsgType       string `json:"msgtype"`
    +    Format        string `json:"format"`
    +    FormattedBody string `json:"formatted_body"`
    +}
    +

    +An HTMLMessage is the contents of a Matrix HTML formated message event. +

    + + + + + + + + + + + + +

    func GetHTMLMessage

    +
    func GetHTMLMessage(msgtype, htmlText string) HTMLMessage
    +

    +GetHTMLMessage returns an HTMLMessage with the body set to a stripped version of the provided HTML, in addition +to the provided HTML. +

    + + + + + + + + + +

    type ImageInfo

    +
    type ImageInfo struct {
    +    Height   uint   `json:"h"`
    +    Width    uint   `json:"w"`
    +    Mimetype string `json:"mimetype"`
    +    Size     uint   `json:"size"`
    +}
    +

    +ImageInfo contains info about an image +

    + + + + + + + + + + + + + + + + +

    type ImageMessage

    +
    type ImageMessage struct {
    +    MsgType string    `json:"msgtype"`
    +    Body    string    `json:"body"`
    +    URL     string    `json:"url"`
    +    Info    ImageInfo `json:"info"`
    +}
    +

    +ImageMessage is an m.image event +

    + + + + + + + + + + + + + + + + +

    type NextBatchStorer

    +
    type NextBatchStorer interface {
    +    // Save a next_batch token for a given user. Best effort.
    +    Save(userID, nextBatch string)
    +    // Load a next_batch token for a given user. Return an empty string if no token exists.
    +    Load(userID string) string
    +}
    +

    +NextBatchStorer controls loading/saving of next_batch tokens for users +

    + + + + + + + + + + + + + + + + +

    type OnEventListener

    +
    type OnEventListener func(*Event)
    +

    +OnEventListener can be used with Worker.OnEventType to be informed of incoming events. +

    + + + + + + + + + + + + + + + + +

    type Room

    +
    type Room struct {
    +    ID       string
    +    State    map[string]map[string]*Event
    +    Timeline []Event
    +}
    +

    +Room represents a single Matrix room. +

    + + + + + + + + + + + + +

    func NewRoom

    +
    func NewRoom(roomID string) *Room
    +

    +NewRoom creates a new Room with the given ID +

    + + + + + + + +

    func (Room) GetMembershipState

    +
    func (room Room) GetMembershipState(userID string) string
    +

    +GetMembershipState returns the membership state of the given user ID in this room. If there is +no entry for this member, 'leave' is returned for consistency with left users. +

    + + + + + + +

    func (Room) GetStateEvent

    +
    func (room Room) GetStateEvent(eventType string, stateKey string) *Event
    +

    +GetStateEvent returns the state event for the given type/state_key combo, or nil. +

    + + + + + + +

    func (Room) UpdateState

    +
    func (room Room) UpdateState(event *Event)
    +

    +UpdateState updates the room's current state with the given Event. This will clobber events based +on the type/state_key combination. +

    + + + + + + + + +

    type StarterLinkMessage

    +
    type StarterLinkMessage struct {
    +    Body string
    +    Link string
    +}
    +

    +StarterLinkMessage represents a message with a starter_link custom data. +

    + + + + + + + + + + + + + + +

    func (StarterLinkMessage) MarshalJSON

    +
    func (m StarterLinkMessage) MarshalJSON() ([]byte, error)
    +

    +MarshalJSON converts this message into actual event content JSON. +

    + + + + + + + + +

    type TextMessage

    +
    type TextMessage struct {
    +    MsgType string `json:"msgtype"`
    +    Body    string `json:"body"`
    +}
    +

    +TextMessage is the contents of a Matrix formated message event. +

    + + + + + + + + + + + + + + + + +

    type Worker

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

    +Worker processes incoming events and updates the Matrix client's data structures. It also informs +any attached listeners of the new events. +

    + + + + + + + + + + + + + + +

    func (*Worker) OnEventType

    +
    func (worker *Worker) OnEventType(eventType string, callback OnEventListener)
    +

    +OnEventType allows callers to be notified when there are new events for the given event type. +There are no duplicate checks. +

    + + + + + + + + + + + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/github.com/matrix-org/go-neb/metrics/index.html b/pkg/github.com/matrix-org/go-neb/metrics/index.html new file mode 100644 index 0000000..2424768 --- /dev/null +++ b/pkg/github.com/matrix-org/go-neb/metrics/index.html @@ -0,0 +1,302 @@ + + + + + + + + metrics - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Package metrics

    + + + + + + + + + + + + + + +
    +
    +
    import "github.com/matrix-org/go-neb/metrics"
    +
    +
    +
    Overview
    +
    Index
    + + +
    +
    + +
    + +
    +

    Overview ▾

    + +
    +
    + + +
    + + +
    + + + + +

    Constants

    + +
    const (
    +    StatusSuccess = "success"
    +    StatusFailure = "failure"
    +)
    +

    +Common status values +

    + + + + + + + +

    func IncrementAuthSession

    +
    func IncrementAuthSession(realmType string)
    +

    +IncrementAuthSession increments the /requestAuthSession request counter +

    + + + + + + + +

    func IncrementCommand

    +
    func IncrementCommand(cmdName string, st Status)
    +

    +IncrementCommand increments the pling command counter +

    + + + + + + + +

    func IncrementConfigureService

    +
    func IncrementConfigureService(serviceType string)
    +

    +IncrementConfigureService increments the /configureService counter +

    + + + + + + + +

    func IncrementWebhook

    +
    func IncrementWebhook(serviceType string)
    +

    +IncrementWebhook increments the incoming webhook request counter +

    + + + + + + + + +

    type Status

    +
    type Status string
    +

    +Status is the status of a measurable metric (incoming commands, outgoing polls, etc) +

    + + + + + + + + + + + + + + + + + + + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/github.com/matrix-org/go-neb/plugin/index.html b/pkg/github.com/matrix-org/go-neb/plugin/index.html new file mode 100644 index 0000000..cb66123 --- /dev/null +++ b/pkg/github.com/matrix-org/go-neb/plugin/index.html @@ -0,0 +1,314 @@ + + + + + + + + plugin - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Package plugin

    + + + + + + + + + + + + + + +
    +
    +
    import "github.com/matrix-org/go-neb/plugin"
    +
    +
    +
    Overview
    +
    Index
    + + +
    +
    + +
    + +
    +

    Overview ▾

    + +
    +
    + + +
    + +
    +

    Index ▾

    + + + + + + + +

    Package files

    +

    + + + plugin.go + + +

    + +
    +
    + + + + + + + + +

    func OnMessage

    +
    func OnMessage(plugins []Plugin, client *matrix.Client, event *matrix.Event)
    +

    +OnMessage checks the message event to see whether it contains any commands +or expansions from the listed plugins and processes those commands or +expansions. +

    + + + + + + + + +

    type Command

    +
    type Command struct {
    +    Path      []string
    +    Arguments []string
    +    Help      string
    +    Command   func(roomID, userID string, arguments []string) (content interface{}, err error)
    +}
    +

    +A Command is something that a user invokes by sending a message starting with '!' +followed by a list of strings that name the command, followed by a list of argument +strings. The argument strings may be quoted using '\"' and '\” in the same way +that they are quoted in the unix shell. +

    + + + + + + + + + + + + + + + + +

    type Expansion

    +
    type Expansion struct {
    +    Regexp *regexp.Regexp
    +    Expand func(roomID, userID string, matchingGroups []string) interface{}
    +}
    +

    +An Expansion is something that actives when the user sends any message +containing a string matching a given pattern. For example an RFC expansion +might expand "RFC 6214" into "Adaptation of RFC 1149 for IPv6" and link to +the appropriate RFC. +

    + + + + + + + + + + + + + + + + +

    type Plugin

    +
    type Plugin struct {
    +    Commands   []Command
    +    Expansions []Expansion
    +}
    +

    +A Plugin is a list of commands and expansions to apply to incoming messages. +

    + + + + + + + + + + + + + + + + + + + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/github.com/matrix-org/go-neb/polling/index.html b/pkg/github.com/matrix-org/go-neb/polling/index.html new file mode 100644 index 0000000..0752b01 --- /dev/null +++ b/pkg/github.com/matrix-org/go-neb/polling/index.html @@ -0,0 +1,265 @@ + + + + + + + + polling - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Package polling

    + + + + + + + + + + + + + + +
    +
    +
    import "github.com/matrix-org/go-neb/polling"
    +
    +
    +
    Overview
    +
    Index
    + + +
    +
    + +
    + +
    +

    Overview ▾

    + +
    +
    + + +
    + +
    +

    Index ▾

    + + + + + + + +

    Package files

    +

    + + + polling.go + + +

    + +
    +
    + + + + + + + + +

    func SetClients

    +
    func SetClients(clis *clients.Clients)
    +

    +SetClients sets a pool of clients for passing into OnPoll +

    + + + + + + + +

    func Start

    +
    func Start() error
    +

    +Start polling already existing services +

    + + + + + + + +

    func StartPolling

    +
    func StartPolling(service types.Service) error
    +

    +StartPolling begins a polling loop for this service. +If one already exists for this service, it will be instructed to die. The new poll will not wait for this to happen, +so there may be a brief period of overlap. It is safe to immediately call `StopPolling(service)` to immediately terminate +this poll. +

    + + + + + + + +

    func StopPolling

    +
    func StopPolling(service types.Service)
    +

    +StopPolling stops all pollers for this service. +

    + + + + + + + + + + + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/github.com/matrix-org/go-neb/realms/github/index.html b/pkg/github.com/matrix-org/go-neb/realms/github/index.html new file mode 100644 index 0000000..32b0434 --- /dev/null +++ b/pkg/github.com/matrix-org/go-neb/realms/github/index.html @@ -0,0 +1,435 @@ + + + + + + + + realms - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Package realms

    + + + + + + + + + + + + + + +
    +
    +
    import "github.com/matrix-org/go-neb/realms/github"
    +
    +
    +
    Overview
    +
    Index
    + + +
    +
    + +
    + +
    +

    Overview ▾

    + +
    +
    + + + + + + + + + + + + +

    type GithubRealm

    +
    type GithubRealm struct {
    +    ClientSecret string
    +    ClientID     string
    +    StarterLink  string
    +    // contains filtered or unexported fields
    +}
    +

    +GithubRealm can handle OAuth processes with github.com +

    + + + + + + + + + + + + + + +

    func (*GithubRealm) AuthSession

    +
    func (r *GithubRealm) AuthSession(id, userID, realmID string) types.AuthSession
    +

    +AuthSession returns a GithubSession for this user +

    + + + + + + +

    func (*GithubRealm) ID

    +
    func (r *GithubRealm) ID() string
    +

    +ID returns the realm ID +

    + + + + + + +

    func (*GithubRealm) Init

    +
    func (r *GithubRealm) Init() error
    +

    +Init does nothing. +

    + + + + + + +

    func (*GithubRealm) OnReceiveRedirect

    +
    func (r *GithubRealm) OnReceiveRedirect(w http.ResponseWriter, req *http.Request)
    +

    +OnReceiveRedirect processes OAuth redirect requests from Github +

    + + + + + + +

    func (*GithubRealm) Register

    +
    func (r *GithubRealm) Register() error
    +

    +Register does nothing. +

    + + + + + + +

    func (*GithubRealm) RequestAuthSession

    +
    func (r *GithubRealm) RequestAuthSession(userID string, req json.RawMessage) interface{}
    +

    +RequestAuthSession generates an OAuth2 URL for this user to auth with github via. +

    + + + + + + +

    func (*GithubRealm) Type

    +
    func (r *GithubRealm) Type() string
    +

    +Type is github +

    + + + + + + + + +

    type GithubSession

    +
    type GithubSession struct {
    +    // The client-supplied URL to redirect them to after the auth process is complete.
    +    ClientsRedirectURL string
    +    // AccessToken is the github access token for the user
    +    AccessToken string
    +    // Scopes are the set of *ALLOWED* scopes (which may not be the same as the requested scopes)
    +    Scopes string
    +    // contains filtered or unexported fields
    +}
    +

    +GithubSession represents an authenticated github session +

    + + + + + + + + + + + + + + +

    func (*GithubSession) Authenticated

    +
    func (s *GithubSession) Authenticated() bool
    +

    +Authenticated returns true if the user has completed the auth process +

    + + + + + + +

    func (*GithubSession) ID

    +
    func (s *GithubSession) ID() string
    +

    +ID returns the session ID +

    + + + + + + +

    func (*GithubSession) Info

    +
    func (s *GithubSession) Info() interface{}
    +

    +Info returns a list of possible repositories that this session can integrate with. +

    + + + + + + +

    func (*GithubSession) RealmID

    +
    func (s *GithubSession) RealmID() string
    +

    +RealmID returns the realm ID of the realm which performed the authentication +

    + + + + + + +

    func (*GithubSession) UserID

    +
    func (s *GithubSession) UserID() string
    +

    +UserID returns the user_id who authorised with Github +

    + + + + + + + + + + + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/github.com/matrix-org/go-neb/realms/index.html b/pkg/github.com/matrix-org/go-neb/realms/index.html new file mode 100644 index 0000000..e59e25e --- /dev/null +++ b/pkg/github.com/matrix-org/go-neb/realms/index.html @@ -0,0 +1,152 @@ + + + + + + + + /src/github.com/matrix-org/go-neb/realms - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Directory /src/github.com/matrix-org/go-neb/realms

    + + + + + + + + + + + + + + + + + + + +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    NameSynopsis
    ..
    + github + + +
    + jira + + +
    + urls + + Package urls handles converting between various JIRA URL representations in a consistent way. +
    +
    + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/github.com/matrix-org/go-neb/realms/jira/index.html b/pkg/github.com/matrix-org/go-neb/realms/jira/index.html new file mode 100644 index 0000000..d620ede --- /dev/null +++ b/pkg/github.com/matrix-org/go-neb/realms/jira/index.html @@ -0,0 +1,514 @@ + + + + + + + + realms - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Package realms

    + + + + + + + + + + + + + + +
    +
    +
    import "github.com/matrix-org/go-neb/realms/jira"
    +
    +
    +
    Overview
    +
    Index
    + + +
    Subdirectories
    + +
    +
    + +
    + +
    +

    Overview ▾

    + +
    +
    + + + + + + + + + + + + +

    type JIRARealm

    +
    type JIRARealm struct {
    +    JIRAEndpoint   string
    +    Server         string // clobbered based on /serverInfo request
    +    Version        string // clobbered based on /serverInfo request
    +    ConsumerName   string
    +    ConsumerKey    string
    +    ConsumerSecret string
    +    PublicKeyPEM   string // clobbered based on PrivateKeyPEM
    +    PrivateKeyPEM  string
    +    HasWebhook     bool // clobbered based on NEB
    +    StarterLink    string
    +    // contains filtered or unexported fields
    +}
    +

    +JIRARealm is an AuthRealm which can process JIRA installations +

    + + + + + + + + + + + + + + +

    func (*JIRARealm) AuthSession

    +
    func (r *JIRARealm) AuthSession(id, userID, realmID string) types.AuthSession
    +

    +AuthSession returns a JIRASession with the given parameters +

    + + + + + + +

    func (*JIRARealm) ID

    +
    func (r *JIRARealm) ID() string
    +

    +ID returns the ID of this JIRA realm. +

    + + + + + + +

    func (*JIRARealm) Init

    +
    func (r *JIRARealm) Init() error
    +

    +Init initialises the private key for this JIRA realm. +

    + + + + + + +

    func (*JIRARealm) JIRAClient

    +
    func (r *JIRARealm) JIRAClient(userID string, allowUnauth bool) (*jira.Client, error)
    +

    +JIRAClient returns an authenticated jira.Client for the given userID. Returns an unauthenticated +client if allowUnauth is true and no authenticated session is found, else returns an error. +

    + + + + + + +

    func (*JIRARealm) OnReceiveRedirect

    +
    func (r *JIRARealm) OnReceiveRedirect(w http.ResponseWriter, req *http.Request)
    +

    +OnReceiveRedirect is called when JIRA installations redirect back to NEB +

    + + + + + + +

    func (*JIRARealm) ProjectKeyExists

    +
    func (r *JIRARealm) ProjectKeyExists(userID, projectKey string) (bool, error)
    +

    +ProjectKeyExists returns true if the given project key exists on this JIRA realm. +An authenticated client for userID will be used if one exists, else an +unauthenticated client will be used, which may not be able to see the complete list +of projects. +

    + + + + + + +

    func (*JIRARealm) Register

    +
    func (r *JIRARealm) Register() error
    +

    +Register is called when this realm is being created from an external entity +

    + + + + + + +

    func (*JIRARealm) RequestAuthSession

    +
    func (r *JIRARealm) RequestAuthSession(userID string, req json.RawMessage) interface{}
    +

    +RequestAuthSession is called by a user wishing to auth with this JIRA realm +

    + + + + + + +

    func (*JIRARealm) Type

    +
    func (r *JIRARealm) Type() string
    +

    +Type returns the type of realm this is. +

    + + + + + + + + +

    type JIRASession

    +
    type JIRASession struct {
    +    RequestSecret      string
    +    AccessToken        string
    +    AccessSecret       string
    +    ClientsRedirectURL string // where to redirect the client to after auth
    +    // contains filtered or unexported fields
    +}
    +

    +JIRASession represents a single authentication session between a user and a JIRA endpoint. +The endpoint is dictated by the realm ID. +

    + + + + + + + + + + + + + + +

    func (*JIRASession) Authenticated

    +
    func (s *JIRASession) Authenticated() bool
    +

    +Authenticated returns true if the user has completed the auth process +

    + + + + + + +

    func (*JIRASession) ID

    +
    func (s *JIRASession) ID() string
    +

    +ID returns the OAuth1 request_token which is used when looking up sessions in the redirect +handler. +

    + + + + + + +

    func (*JIRASession) Info

    +
    func (s *JIRASession) Info() interface{}
    +

    +Info returns nothing +

    + + + + + + +

    func (*JIRASession) RealmID

    +
    func (s *JIRASession) RealmID() string
    +

    +RealmID returns the JIRA realm ID which created this session. +

    + + + + + + +

    func (*JIRASession) UserID

    +
    func (s *JIRASession) UserID() string
    +

    +UserID returns the ID of the user performing the authentication. +

    + + + + + + + + + + + + + + + + +

    Subdirectories

    + + + + +
    + + + + + + + + + + + + + + + + + + + + +
    NameSynopsis
    ..
    + urls + + Package urls handles converting between various JIRA URL representations in a consistent way. +
    +
    + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/github.com/matrix-org/go-neb/realms/jira/urls/index.html b/pkg/github.com/matrix-org/go-neb/realms/jira/urls/index.html new file mode 100644 index 0000000..3701f59 --- /dev/null +++ b/pkg/github.com/matrix-org/go-neb/realms/jira/urls/index.html @@ -0,0 +1,277 @@ + + + + + + + + urls - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Package urls

    + + + + + + + + + + + + + + +
    +
    +
    import "github.com/matrix-org/go-neb/realms/jira/urls"
    +
    +
    +
    Overview
    +
    Index
    + + +
    +
    + +
    + +
    +

    Overview ▾

    +

    +Package urls handles converting between various JIRA URL representations in a consistent way. There exists three main +types of JIRA URL which Go-NEB cares about: +

    +
    - URL Keys => matrix.org/jira
    +- Base URLs => https://matrix.org/jira/
    +- REST URLs => https://matrix.org/jira/rest/api/2/issue/12680
    +
    +

    +When making outbound requests to JIRA, Go-NEB needs to use the Base URL representation. Likewise, when Go-NEB +sends Matrix messages with JIRA URLs in them, the Base URL needs to be used to form the URL. The URL Key is +used to determine equivalence of various JIRA installations and is mainly required when searching the database. +The REST URLs are present on incoming webhook events and are the only way to map the event to a JIRA installation. +

    + +
    +
    + + +
    + +
    +

    Index ▾

    + + + + + + + +

    Package files

    +

    + + + urls.go + + +

    + +
    +
    + + + + + + + + +

    func SameJIRAURL

    +
    func SameJIRAURL(a, b string) bool
    +

    +SameJIRAURL returns true if the two given JIRA URLs are pointing to the same JIRA installation. +Equivalence is determined solely by the provided URLs, by sanitising them then comparing. +

    + + + + + + + + +

    type JIRAURL

    +
    type JIRAURL struct {
    +    Base string // The base URL of the JIRA installation. Always has a trailing / and a protocol.
    +    Key  string // The URL key of the JIRA installation. Never has a trailing / or a protocol.
    +    Raw  string // The raw input URL, if given. Freeform.
    +}
    +

    +JIRAURL contains the parsed representation of a JIRA URL +

    + + + + + + + + + + + + +

    func ParseJIRAURL

    +
    func ParseJIRAURL(u string) (j JIRAURL, err error)
    +

    +ParseJIRAURL parses a raw input URL and returns a struct which has various JIRA URL representations. The input +URL can be a JIRA REST URL, a speculative base JIRA URL from a client, or a URL key. The input string will be +stored as under JIRAURL.Raw. If a URL key is given, this struct will default to https as the protocol. +

    + + + + + + + + + + + + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/github.com/matrix-org/go-neb/server/index.html b/pkg/github.com/matrix-org/go-neb/server/index.html new file mode 100644 index 0000000..6ba4047 --- /dev/null +++ b/pkg/github.com/matrix-org/go-neb/server/index.html @@ -0,0 +1,328 @@ + + + + + + + + server - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Package server

    + + + + + + + + + + + + + + +
    +
    +
    import "github.com/matrix-org/go-neb/server"
    +
    +
    +
    Overview
    +
    Index
    + + +
    +
    + +
    + +
    +

    Overview ▾

    +

    +Package server contains building blocks for REST APIs. +

    + +
    +
    + + + + + + + + + + + +

    func MakeJSONAPI

    +
    func MakeJSONAPI(handler JSONRequestHandler) http.HandlerFunc
    +

    +MakeJSONAPI creates an HTTP handler which always responds to incoming requests with JSON responses. +

    + + + + + + + +

    func Protect

    +
    func Protect(handler http.HandlerFunc) http.HandlerFunc
    +

    +Protect panicking HTTP requests from taking down the entire process, and log them using +the correct logger, returning a 500 with a JSON response rather than abruptly closing the +connection. +

    + + + + + + + +

    func SetCORSHeaders

    +
    func SetCORSHeaders(w http.ResponseWriter)
    +

    +SetCORSHeaders sets unrestricted origin Access-Control headers on the response writer +

    + + + + + + + +

    func WithCORSOptions

    +
    func WithCORSOptions(handler http.HandlerFunc) http.HandlerFunc
    +

    +WithCORSOptions intercepts all OPTIONS requests and responds with CORS headers. The request handler +is not invoked when this happens. +

    + + + + + + + + +

    type JSONError

    +
    type JSONError struct {
    +    Message string `json:"message"`
    +}
    +

    +JSONError represents a JSON API error response +

    + + + + + + + + + + + + + + + + +

    type JSONRequestHandler

    +
    type JSONRequestHandler interface {
    +    OnIncomingRequest(req *http.Request) (interface{}, *errors.HTTPError)
    +}
    +

    +JSONRequestHandler represents an interface that must be satisfied in order to respond to incoming +HTTP requests with JSON. The interface returned will be marshalled into JSON to be sent to the client, +unless the interface is []byte in which case the bytes are sent to the client unchanged. +If an error is returned, a JSON error response will also be returned, unless the error code +is a 302 REDIRECT in which case a redirect is sent based on the Message field. +

    + + + + + + + + + + + + + + + + + + + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/github.com/matrix-org/go-neb/services/echo/index.html b/pkg/github.com/matrix-org/go-neb/services/echo/index.html new file mode 100644 index 0000000..47a8e44 --- /dev/null +++ b/pkg/github.com/matrix-org/go-neb/services/echo/index.html @@ -0,0 +1,202 @@ + + + + + + + + services - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Package services

    + + + + + + + + + + + + + + +
    +
    +
    import "github.com/matrix-org/go-neb/services/echo"
    +
    +
    +
    Overview
    +
    Index
    + + +
    +
    + +
    + +
    +

    Overview ▾

    + +
    +
    + + +
    + +
    +

    Index ▾

    + + +
    +
    + + + + + +
    +
    + + + + +

    Package files

    +

    + + + echo.go + + +

    + +
    +
    + + + + + + + + + + + + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/github.com/matrix-org/go-neb/services/giphy/index.html b/pkg/github.com/matrix-org/go-neb/services/giphy/index.html new file mode 100644 index 0000000..ec7b9bf --- /dev/null +++ b/pkg/github.com/matrix-org/go-neb/services/giphy/index.html @@ -0,0 +1,202 @@ + + + + + + + + services - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Package services

    + + + + + + + + + + + + + + +
    +
    +
    import "github.com/matrix-org/go-neb/services/giphy"
    +
    +
    +
    Overview
    +
    Index
    + + +
    +
    + +
    + +
    +

    Overview ▾

    + +
    +
    + + +
    + +
    +

    Index ▾

    + + +
    +
    + + + + + +
    +
    + + + + +

    Package files

    +

    + + + giphy.go + + +

    + +
    +
    + + + + + + + + + + + + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/github.com/matrix-org/go-neb/services/github/client/index.html b/pkg/github.com/matrix-org/go-neb/services/github/client/index.html new file mode 100644 index 0000000..840a8df --- /dev/null +++ b/pkg/github.com/matrix-org/go-neb/services/github/client/index.html @@ -0,0 +1,270 @@ + + + + + + + + client - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Package client

    + + + + + + + + + + + + + + +
    +
    +
    import "github.com/matrix-org/go-neb/services/github/client"
    +
    +
    +
    Overview
    +
    Index
    + + +
    +
    + +
    + +
    +

    Overview ▾

    + +
    +
    + + +
    + +
    +

    Index ▾

    + + + + + + + +

    Package files

    +

    + + + client.go + + +

    + +
    +
    + + + + + + + + +

    func New

    +
    func New(token string) *github.Client
    +

    +New returns a github Client which can perform Github API operations. +If `token` is empty, a non-authenticated client will be created. This should be +used sparingly where possible as you only get 60 requests/hour like that (IP locked). +

    + + + + + + + + +

    type TrimmedRepository

    +
    type TrimmedRepository struct {
    +    Name        *string           `json:"name"`
    +    Description *string           `json:"description"`
    +    Private     *bool             `json:"private"`
    +    HTMLURL     *string           `json:"html_url"`
    +    CreatedAt   *github.Timestamp `json:"created_at"`
    +    UpdatedAt   *github.Timestamp `json:"updated_at"`
    +    PushedAt    *github.Timestamp `json:"pushed_at"`
    +    Fork        *bool             `json:"fork"`
    +    FullName    *string           `json:"full_name"`
    +    Permissions *map[string]bool  `json:"permissions"`
    +}
    +

    +TrimmedRepository represents a cut-down version of github.Repository with only the keys the end-user is +likely to want. +

    + + + + + + + + + + + + +

    func TrimRepository

    +
    func TrimRepository(repo *github.Repository) TrimmedRepository
    +

    +TrimRepository trims a github repo into important fields only. +

    + + + + + + + + + + + + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/github.com/matrix-org/go-neb/services/github/index.html b/pkg/github.com/matrix-org/go-neb/services/github/index.html new file mode 100644 index 0000000..c1f1e0b --- /dev/null +++ b/pkg/github.com/matrix-org/go-neb/services/github/index.html @@ -0,0 +1,255 @@ + + + + + + + + services - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Package services

    + + + + + + + + + + + + + + +
    +
    +
    import "github.com/matrix-org/go-neb/services/github"
    +
    +
    +
    Overview
    +
    Index
    + + +
    Subdirectories
    + +
    +
    + +
    + +
    +

    Overview ▾

    + +
    +
    + + +
    + +
    +

    Index ▾

    + + +
    +
    + + + + + +
    +
    + + + + +

    Package files

    +

    + + + github.go + + github_webhook.go + + +

    + +
    +
    + + + + + + + + + + + + + + + + + +

    Subdirectories

    + + + + +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    NameSynopsis
    ..
    + client + + +
    + webhook + + +
    +
    + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/github.com/matrix-org/go-neb/services/github/webhook/index.html b/pkg/github.com/matrix-org/go-neb/services/github/webhook/index.html new file mode 100644 index 0000000..4ab67e1 --- /dev/null +++ b/pkg/github.com/matrix-org/go-neb/services/github/webhook/index.html @@ -0,0 +1,220 @@ + + + + + + + + webhook - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Package webhook

    + + + + + + + + + + + + + + +
    +
    +
    import "github.com/matrix-org/go-neb/services/github/webhook"
    +
    +
    +
    Overview
    +
    Index
    + + +
    +
    + +
    + +
    +

    Overview ▾

    + +
    +
    + + +
    + + +
    + + + + + + + + +

    func OnReceiveRequest

    +
    func OnReceiveRequest(r *http.Request, secretToken string) (string, *github.Repository, *matrix.HTMLMessage, *errors.HTTPError)
    +

    +OnReceiveRequest processes incoming github webhook requests and returns a +matrix message to send, along with parsed repo information. +The secretToken, if supplied, will be used to verify the request is from +Github. If it isn't, an error is returned. +

    + + + + + + + + + + + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/github.com/matrix-org/go-neb/services/guggy/index.html b/pkg/github.com/matrix-org/go-neb/services/guggy/index.html new file mode 100644 index 0000000..8adf7ba --- /dev/null +++ b/pkg/github.com/matrix-org/go-neb/services/guggy/index.html @@ -0,0 +1,202 @@ + + + + + + + + services - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Package services

    + + + + + + + + + + + + + + +
    +
    +
    import "github.com/matrix-org/go-neb/services/guggy"
    +
    +
    +
    Overview
    +
    Index
    + + +
    +
    + +
    + +
    +

    Overview ▾

    + +
    +
    + + +
    + +
    +

    Index ▾

    + + +
    +
    + + + + + +
    +
    + + + + +

    Package files

    +

    + + + guggy.go + + +

    + +
    +
    + + + + + + + + + + + + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/github.com/matrix-org/go-neb/services/index.html b/pkg/github.com/matrix-org/go-neb/services/index.html new file mode 100644 index 0000000..c80a387 --- /dev/null +++ b/pkg/github.com/matrix-org/go-neb/services/index.html @@ -0,0 +1,218 @@ + + + + + + + + /src/github.com/matrix-org/go-neb/services - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Directory /src/github.com/matrix-org/go-neb/services

    + + + + + + + + + + + + + + + + + + + +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    NameSynopsis
    ..
    + echo + + +
    + giphy + + +
    + github + + +
    + client + + +
    + webhook + + +
    + guggy + + +
    + jira + + +
    + webhook + + +
    + rssbot + + +
    +
    + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/github.com/matrix-org/go-neb/services/jira/index.html b/pkg/github.com/matrix-org/go-neb/services/jira/index.html new file mode 100644 index 0000000..261d1de --- /dev/null +++ b/pkg/github.com/matrix-org/go-neb/services/jira/index.html @@ -0,0 +1,242 @@ + + + + + + + + services - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Package services

    + + + + + + + + + + + + + + +
    +
    +
    import "github.com/matrix-org/go-neb/services/jira"
    +
    +
    +
    Overview
    +
    Index
    + + +
    Subdirectories
    + +
    +
    + +
    + +
    +

    Overview ▾

    + +
    +
    + + +
    + +
    +

    Index ▾

    + + +
    +
    + + + + + +
    +
    + + + + +

    Package files

    +

    + + + jira.go + + +

    + +
    +
    + + + + + + + + + + + + + + + + + +

    Subdirectories

    + + + + +
    + + + + + + + + + + + + + + + + + + + + +
    NameSynopsis
    ..
    + webhook + + +
    +
    + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/github.com/matrix-org/go-neb/services/jira/webhook/index.html b/pkg/github.com/matrix-org/go-neb/services/jira/webhook/index.html new file mode 100644 index 0000000..a3ac1eb --- /dev/null +++ b/pkg/github.com/matrix-org/go-neb/services/jira/webhook/index.html @@ -0,0 +1,264 @@ + + + + + + + + webhook - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Package webhook

    + + + + + + + + + + + + + + +
    +
    +
    import "github.com/matrix-org/go-neb/services/jira/webhook"
    +
    +
    +
    Overview
    +
    Index
    + + +
    +
    + +
    + +
    +

    Overview ▾

    + +
    +
    + + + + + + + + + + + +

    func OnReceiveRequest

    +
    func OnReceiveRequest(req *http.Request) (string, *Event, *errors.HTTPError)
    +

    +OnReceiveRequest is called when JIRA hits NEB with an update. +Returns the project key and webhook event, or an error. +

    + + + + + + + +

    func RegisterHook

    +
    func RegisterHook(jrealm *realms.JIRARealm, projects []string, userID, webhookEndpointURL string) error
    +

    +RegisterHook checks to see if this user is allowed to track the given projects and then tracks them. +

    + + + + + + + + +

    type Event

    +
    type Event struct {
    +    WebhookEvent string     `json:"webhookEvent"`
    +    Timestamp    int64      `json:"timestamp"`
    +    User         jira.User  `json:"user"`
    +    Issue        jira.Issue `json:"issue"`
    +}
    +

    +Event represents an incoming JIRA webhook event +

    + + + + + + + + + + + + + + + + + + + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/github.com/matrix-org/go-neb/services/rssbot/index.html b/pkg/github.com/matrix-org/go-neb/services/rssbot/index.html new file mode 100644 index 0000000..2e74be2 --- /dev/null +++ b/pkg/github.com/matrix-org/go-neb/services/rssbot/index.html @@ -0,0 +1,202 @@ + + + + + + + + services - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Package services

    + + + + + + + + + + + + + + +
    +
    +
    import "github.com/matrix-org/go-neb/services/rssbot"
    +
    +
    +
    Overview
    +
    Index
    + + +
    +
    + +
    + +
    +

    Overview ▾

    + +
    +
    + + +
    + +
    +

    Index ▾

    + + +
    +
    + + + + + +
    +
    + + + + +

    Package files

    +

    + + + rssbot.go + + +

    + +
    +
    + + + + + + + + + + + + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/github.com/matrix-org/go-neb/types/index.html b/pkg/github.com/matrix-org/go-neb/types/index.html new file mode 100644 index 0000000..33d50f6 --- /dev/null +++ b/pkg/github.com/matrix-org/go-neb/types/index.html @@ -0,0 +1,547 @@ + + + + + + + + types - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Package types

    + + + + + + + + + + + + + + +
    +
    +
    import "github.com/matrix-org/go-neb/types"
    +
    +
    +
    Overview
    +
    Index
    + + +
    +
    + +
    + +
    +

    Overview ▾

    + +
    +
    + + + + + + + + + + + +

    func BaseURL

    +
    func BaseURL(u string) error
    +

    +BaseURL sets the base URL of NEB to the url given. This URL must be accessible from the +public internet. +

    + + + + + + + +

    func PollingServiceTypes

    +
    func PollingServiceTypes() (types []string)
    +

    +PollingServiceTypes returns a list of service types which meet the Poller interface +

    + + + + + + + +

    func RegisterAuthRealm

    +
    func RegisterAuthRealm(factory func(string, string) AuthRealm)
    +

    +RegisterAuthRealm registers a factory for creating AuthRealm instances. +

    + + + + + + + +

    func RegisterService

    +
    func RegisterService(factory func(string, string, string) Service)
    +

    +RegisterService registers a factory for creating Service instances. +

    + + + + + + + + +

    type AuthRealm

    +
    type AuthRealm interface {
    +    ID() string
    +    Type() string
    +    Init() error
    +    Register() error
    +    OnReceiveRedirect(w http.ResponseWriter, req *http.Request)
    +    AuthSession(id, userID, realmID string) AuthSession
    +    RequestAuthSession(userID string, config json.RawMessage) interface{}
    +}
    +

    +AuthRealm represents a place where a user can authenticate themselves. +This may static (like github.com) or a specific domain (like matrix.org/jira) +

    + + + + + + + + + + + + +

    func CreateAuthRealm

    +
    func CreateAuthRealm(realmID, realmType string, realmJSON []byte) (AuthRealm, error)
    +

    +CreateAuthRealm creates an AuthRealm of the given type and realm ID. +Returns an error if the realm couldn't be created or the JSON cannot be unmarshalled. +

    + + + + + + + + + +

    type AuthSession

    +
    type AuthSession interface {
    +    ID() string
    +    UserID() string
    +    RealmID() string
    +    Authenticated() bool
    +    Info() interface{}
    +}
    +

    +AuthSession represents a single authentication session between a user and +an auth realm. +

    + + + + + + + + + + + + + + + + +

    type BotOptions

    +
    type BotOptions struct {
    +    RoomID      string
    +    UserID      string
    +    SetByUserID string
    +    Options     map[string]interface{}
    +}
    +

    +BotOptions for a given bot user in a given room +

    + + + + + + + + + + + + + + + + +

    type DefaultService

    +
    type DefaultService struct{}
    +

    +DefaultService NO-OPs the implementation of optional Service interface methods. Feel free to override them. +

    + + + + + + + + + + + + + + +

    func (*DefaultService) OnReceiveWebhook

    +
    func (s *DefaultService) OnReceiveWebhook(w http.ResponseWriter, req *http.Request, cli *matrix.Client)
    +

    +OnReceiveWebhook does nothing but 200 OK the request. +

    + + + + + + +

    func (*DefaultService) Plugin

    +
    func (s *DefaultService) Plugin(cli *matrix.Client, roomID string) plugin.Plugin
    +

    +Plugin returns no plugins. +

    + + + + + + +

    func (*DefaultService) PostRegister

    +
    func (s *DefaultService) PostRegister(oldService Service)
    +

    +PostRegister does nothing. +

    + + + + + + +

    func (*DefaultService) Register

    +
    func (s *DefaultService) Register(oldService Service, client *matrix.Client) error
    +

    +Register does nothing and returns no error. +

    + + + + + + + + +

    type Poller

    +
    type Poller interface {
    +    // OnPoll is called when the poller should poll. Return the timestamp when you want to be polled again.
    +    // Return 0 to never be polled again.
    +    OnPoll(client *matrix.Client) time.Time
    +}
    +

    +Poller represents a thing which can poll. Services should implement this method signature to support polling. +

    + + + + + + + + + + + + + + + + +

    type Service

    +
    type Service interface {
    +    // Return the user ID of this service.
    +    ServiceUserID() string
    +    // Return an opaque ID used to identify this service.
    +    ServiceID() string
    +    // Return the type of service. This string MUST NOT change.
    +    ServiceType() string
    +    Plugin(cli *matrix.Client, roomID string) plugin.Plugin
    +    OnReceiveWebhook(w http.ResponseWriter, req *http.Request, cli *matrix.Client)
    +    // A lifecycle function which is invoked when the service is being registered. The old service, if one exists, is provided,
    +    // along with a Client instance for ServiceUserID(). If this function returns an error, the service will not be registered
    +    // or persisted to the database, and the user's request will fail. This can be useful if you depend on external factors
    +    // such as registering webhooks.
    +    Register(oldService Service, client *matrix.Client) error
    +    // A lifecycle function which is invoked after the service has been successfully registered and persisted to the database.
    +    // This function is invoked within the critical section for configuring services, guaranteeing that there will not be
    +    // concurrent modifications to this service whilst this function executes. This lifecycle hook should be used to clean
    +    // up resources which are no longer needed (e.g. removing old webhooks).
    +    PostRegister(oldService Service)
    +}
    +

    +A Service is the configuration for a bot service. +

    + + + + + + + + + + + + +

    func CreateService

    +
    func CreateService(serviceID, serviceType, serviceUserID string, serviceJSON []byte) (Service, error)
    +

    +CreateService creates a Service of the given type and serviceID. +Returns an error if the Service couldn't be created. +

    + + + + + + + + + + + + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/github.com/matrix-org/go-neb/util/index.html b/pkg/github.com/matrix-org/go-neb/util/index.html new file mode 100644 index 0000000..0b37e4b --- /dev/null +++ b/pkg/github.com/matrix-org/go-neb/util/index.html @@ -0,0 +1,219 @@ + + + + + + + + util - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Package util

    + + + + + + + + + + + + + + +
    +
    +
    import "github.com/matrix-org/go-neb/util"
    +
    +
    +
    Overview
    +
    Index
    + + +
    +
    + +
    + +
    +

    Overview ▾

    + +
    +
    + + +
    + +
    +

    Index ▾

    + + + + + + + +

    Package files

    +

    + + + util.go + + +

    + +
    +
    + + + + + + + + +

    func Difference

    +
    func Difference(a, b []string) (onlyA, onlyB []string)
    +

    +Difference returns the elements that are only in the first list and +the elements that are only in the second. As a side-effect this sorts +the input lists in-place. +

    + + + + + + + + + + + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/github.com/matrix-org/index.html b/pkg/github.com/matrix-org/index.html new file mode 100644 index 0000000..560090c --- /dev/null +++ b/pkg/github.com/matrix-org/index.html @@ -0,0 +1,427 @@ + + + + + + + + /src/github.com/matrix-org - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Directory /src/github.com/matrix-org

    + + + + + + + + + + + + + + + + + + + +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    NameSynopsis
    ..
    + dugong + + +
    + go-neb + + +
    + api + + Package api contains the fundamental data types used by Go-NEB. +
    + handlers + + Package handlers contains the HTTP handlers for Go-NEB. +
    + clients + + +
    + database + + +
    + errors + + +
    + matrix + + Package matrix provides an HTTP client that can interact with a Homeserver via r0 APIs (/sync). +
    + metrics + + +
    + plugin + + +
    + polling + + +
    + realms + + +
    + github + + +
    + jira + + +
    + urls + + Package urls handles converting between various JIRA URL representations in a consistent way. +
    + server + + Package server contains building blocks for REST APIs. +
    + services + + +
    + echo + + +
    + giphy + + +
    + github + + +
    + client + + +
    + webhook + + +
    + guggy + + +
    + jira + + +
    + webhook + + +
    + rssbot + + +
    + types + + +
    + util + + +
    +
    + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/github.com/mattn/go-shellwords/index.html b/pkg/github.com/mattn/go-shellwords/index.html new file mode 100644 index 0000000..658601f --- /dev/null +++ b/pkg/github.com/mattn/go-shellwords/index.html @@ -0,0 +1,274 @@ + + + + + + + + shellwords - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Package shellwords

    + + + + + + + + + + + + + + +
    +
    +
    import "github.com/mattn/go-shellwords"
    +
    +
    +
    Overview
    +
    Index
    + + +
    +
    + +
    + +
    +

    Overview ▾

    + +
    +
    + + +
    + +
    +

    Index ▾

    + + + + + + + +

    Package files

    +

    + + + shellwords.go + + util_posix.go + + +

    + +
    +
    + + + + + +

    Variables

    + +
    var (
    +    ParseEnv      bool = false
    +    ParseBacktick bool = false
    +)
    + + + + + + +

    func Parse

    +
    func Parse(line string) ([]string, error)
    + + + + + + + + +

    type Parser

    +
    type Parser struct {
    +    ParseEnv      bool
    +    ParseBacktick bool
    +}
    + + + + + + + + + + + + +

    func NewParser

    +
    func NewParser() *Parser
    + + + + + + + +

    func (*Parser) Parse

    +
    func (p *Parser) Parse(line string) ([]string, error)
    + + + + + + + + + + + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/github.com/mattn/go-sqlite3/index.html b/pkg/github.com/mattn/go-sqlite3/index.html new file mode 100644 index 0000000..2b6f37a --- /dev/null +++ b/pkg/github.com/mattn/go-sqlite3/index.html @@ -0,0 +1,1245 @@ + + + + + + + + sqlite3 - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Package sqlite3

    + + + + + + + + + + + + + + +
    +
    +
    import "github.com/mattn/go-sqlite3"
    +
    +
    +
    Overview
    +
    Index
    + + +
    Subdirectories
    + +
    +
    + +
    + +
    +

    Overview ▾

    +

    +Package sqlite3 provides interface to SQLite3 databases. +

    +

    +This works as a driver for database/sql. +

    +

    +Installation +

    +
    go get github.com/mattn/go-sqlite3
    +
    +

    Supported Types

    +

    +Currently, go-sqlite3 supports the following data types. +

    +
    +------------------------------+
    +|go        | sqlite3           |
    +|----------|-------------------|
    +|nil       | null              |
    +|int       | integer           |
    +|int64     | integer           |
    +|float64   | float             |
    +|bool      | integer           |
    +|[]byte    | blob              |
    +|string    | text              |
    +|time.Time | timestamp/datetime|
    ++------------------------------+
    +
    +

    SQLite3 Extension

    +

    +You can write your own extension module for sqlite3. For example, below is an +extension for a Regexp matcher operation. +

    +
    #include <pcre.h>
    +#include <string.h>
    +#include <stdio.h>
    +#include <sqlite3ext.h>
    +
    +SQLITE_EXTENSION_INIT1
    +static void regexp_func(sqlite3_context *context, int argc, sqlite3_value **argv) {
    +  if (argc >= 2) {
    +    const char *target  = (const char *)sqlite3_value_text(argv[1]);
    +    const char *pattern = (const char *)sqlite3_value_text(argv[0]);
    +    const char* errstr = NULL;
    +    int erroff = 0;
    +    int vec[500];
    +    int n, rc;
    +    pcre* re = pcre_compile(pattern, 0, &errstr, &erroff, NULL);
    +    rc = pcre_exec(re, NULL, target, strlen(target), 0, 0, vec, 500);
    +    if (rc <= 0) {
    +      sqlite3_result_error(context, errstr, 0);
    +      return;
    +    }
    +    sqlite3_result_int(context, 1);
    +  }
    +}
    +
    +#ifdef _WIN32
    +__declspec(dllexport)
    +#endif
    +int sqlite3_extension_init(sqlite3 *db, char **errmsg,
    +      const sqlite3_api_routines *api) {
    +  SQLITE_EXTENSION_INIT2(api);
    +  return sqlite3_create_function(db, "regexp", 2, SQLITE_UTF8,
    +      (void*)db, regexp_func, NULL, NULL);
    +}
    +
    +

    +It needs to be built as a so/dll shared library. And you need to register +the extension module like below. +

    +
    sql.Register("sqlite3_with_extensions",
    +	&sqlite3.SQLiteDriver{
    +		Extensions: []string{
    +			"sqlite3_mod_regexp",
    +		},
    +	})
    +
    +

    +Then, you can use this extension. +

    +
    rows, err := db.Query("select text from mytable where name regexp '^golang'")
    +
    +

    Connection Hook

    +

    +You can hook and inject your code when the connection is established. database/sql +doesn't provide a way to get native go-sqlite3 interfaces. So if you want, +you need to set ConnectHook and get the SQLiteConn. +

    +
    sql.Register("sqlite3_with_hook_example",
    +		&sqlite3.SQLiteDriver{
    +				ConnectHook: func(conn *sqlite3.SQLiteConn) error {
    +					sqlite3conn = append(sqlite3conn, conn)
    +					return nil
    +				},
    +		})
    +
    +

    Go SQlite3 Extensions

    +

    +If you want to register Go functions as SQLite extension functions, +call RegisterFunction from ConnectHook. +

    +
    regex = func(re, s string) (bool, error) {
    +	return regexp.MatchString(re, s)
    +}
    +sql.Register("sqlite3_with_go_func",
    +		&sqlite3.SQLiteDriver{
    +				ConnectHook: func(conn *sqlite3.SQLiteConn) error {
    +					return conn.RegisterFunc("regexp", regex, true)
    +				},
    +		})
    +
    +

    +See the documentation of RegisterFunc for more details. +

    + +
    +
    + + +
    + +
    +

    Index ▾

    + + +
    +
    + +
    Constants
    + + +
    Variables
    + + + +
    func Version() (libVersion string, libVersionNumber int, sourceId string)
    + + + +
    type ErrNo
    + + + +
        func (err ErrNo) Error() string
    + + +
        func (err ErrNo) Extend(by int) ErrNoExtended
    + + + +
    type ErrNoExtended
    + + + +
        func (err ErrNoExtended) Error() string
    + + + +
    type Error
    + + + +
        func (err Error) Error() string
    + + + +
    type SQLiteBackup
    + + + +
        func (b *SQLiteBackup) Close() error
    + + +
        func (b *SQLiteBackup) Finish() error
    + + +
        func (b *SQLiteBackup) PageCount() int
    + + +
        func (b *SQLiteBackup) Remaining() int
    + + +
        func (b *SQLiteBackup) Step(p int) (bool, error)
    + + + +
    type SQLiteConn
    + + + +
        func (c *SQLiteConn) AutoCommit() bool
    + + +
        func (c *SQLiteConn) Backup(dest string, conn *SQLiteConn, src string) (*SQLiteBackup, error)
    + + +
        func (c *SQLiteConn) Begin() (driver.Tx, error)
    + + +
        func (c *SQLiteConn) Close() error
    + + +
        func (c *SQLiteConn) Exec(query string, args []driver.Value) (driver.Result, error)
    + + +
        func (c *SQLiteConn) LoadExtension(lib string, entry string) error
    + + +
        func (c *SQLiteConn) Prepare(query string) (driver.Stmt, error)
    + + +
        func (c *SQLiteConn) Query(query string, args []driver.Value) (driver.Rows, error)
    + + +
        func (c *SQLiteConn) RegisterAggregator(name string, impl interface{}, pure bool) error
    + + +
        func (c *SQLiteConn) RegisterFunc(name string, impl interface{}, pure bool) error
    + + + +
    type SQLiteDriver
    + + + +
        func (d *SQLiteDriver) Open(dsn string) (driver.Conn, error)
    + + + +
    type SQLiteResult
    + + + +
        func (r *SQLiteResult) LastInsertId() (int64, error)
    + + +
        func (r *SQLiteResult) RowsAffected() (int64, error)
    + + + +
    type SQLiteRows
    + + + +
        func (rc *SQLiteRows) Close() error
    + + +
        func (rc *SQLiteRows) Columns() []string
    + + +
        func (rc *SQLiteRows) DeclTypes() []string
    + + +
        func (rc *SQLiteRows) Next(dest []driver.Value) error
    + + + +
    type SQLiteStmt
    + + + +
        func (s *SQLiteStmt) Close() error
    + + +
        func (s *SQLiteStmt) Exec(args []driver.Value) (driver.Result, error)
    + + +
        func (s *SQLiteStmt) NumInput() int
    + + +
        func (s *SQLiteStmt) Query(args []driver.Value) (driver.Rows, error)
    + + + +
    type SQLiteTx
    + + + +
        func (tx *SQLiteTx) Commit() error
    + + +
        func (tx *SQLiteTx) Rollback() error
    + + + +
    +
    + + + + +

    Package files

    +

    + + + backup.go + + callback.go + + doc.go + + error.go + + sqlite3.go + + sqlite3_load_extension.go + + sqlite3_other.go + + tracecallback_noimpl.go + + +

    + +
    +
    + + + + +

    Constants

    + +
    const ErrNoMask C.int = 0xff
    + + + + +

    Variables

    + +
    var (
    +    ErrError      = ErrNo(1)  /* SQL error or missing database */
    +    ErrInternal   = ErrNo(2)  /* Internal logic error in SQLite */
    +    ErrPerm       = ErrNo(3)  /* Access permission denied */
    +    ErrAbort      = ErrNo(4)  /* Callback routine requested an abort */
    +    ErrBusy       = ErrNo(5)  /* The database file is locked */
    +    ErrLocked     = ErrNo(6)  /* A table in the database is locked */
    +    ErrNomem      = ErrNo(7)  /* A malloc() failed */
    +    ErrReadonly   = ErrNo(8)  /* Attempt to write a readonly database */
    +    ErrInterrupt  = ErrNo(9)  /* Operation terminated by sqlite3_interrupt() */
    +    ErrIoErr      = ErrNo(10) /* Some kind of disk I/O error occurred */
    +    ErrCorrupt    = ErrNo(11) /* The database disk image is malformed */
    +    ErrNotFound   = ErrNo(12) /* Unknown opcode in sqlite3_file_control() */
    +    ErrFull       = ErrNo(13) /* Insertion failed because database is full */
    +    ErrCantOpen   = ErrNo(14) /* Unable to open the database file */
    +    ErrProtocol   = ErrNo(15) /* Database lock protocol error */
    +    ErrEmpty      = ErrNo(16) /* Database is empty */
    +    ErrSchema     = ErrNo(17) /* The database schema changed */
    +    ErrTooBig     = ErrNo(18) /* String or BLOB exceeds size limit */
    +    ErrConstraint = ErrNo(19) /* Abort due to constraint violation */
    +    ErrMismatch   = ErrNo(20) /* Data type mismatch */
    +    ErrMisuse     = ErrNo(21) /* Library used incorrectly */
    +    ErrNoLFS      = ErrNo(22) /* Uses OS features not supported on host */
    +    ErrAuth       = ErrNo(23) /* Authorization denied */
    +    ErrFormat     = ErrNo(24) /* Auxiliary database format error */
    +    ErrRange      = ErrNo(25) /* 2nd parameter to sqlite3_bind out of range */
    +    ErrNotADB     = ErrNo(26) /* File opened that is not a database file */
    +    ErrNotice     = ErrNo(27) /* Notifications from sqlite3_log() */
    +    ErrWarning    = ErrNo(28) /* Warnings from sqlite3_log() */
    +)
    +

    +result codes from http://www.sqlite.org/c3ref/c_abort.html +

    + + +
    var (
    +    ErrIoErrRead              = ErrIoErr.Extend(1)
    +    ErrIoErrShortRead         = ErrIoErr.Extend(2)
    +    ErrIoErrWrite             = ErrIoErr.Extend(3)
    +    ErrIoErrFsync             = ErrIoErr.Extend(4)
    +    ErrIoErrDirFsync          = ErrIoErr.Extend(5)
    +    ErrIoErrTruncate          = ErrIoErr.Extend(6)
    +    ErrIoErrFstat             = ErrIoErr.Extend(7)
    +    ErrIoErrUnlock            = ErrIoErr.Extend(8)
    +    ErrIoErrRDlock            = ErrIoErr.Extend(9)
    +    ErrIoErrDelete            = ErrIoErr.Extend(10)
    +    ErrIoErrBlocked           = ErrIoErr.Extend(11)
    +    ErrIoErrNoMem             = ErrIoErr.Extend(12)
    +    ErrIoErrAccess            = ErrIoErr.Extend(13)
    +    ErrIoErrCheckReservedLock = ErrIoErr.Extend(14)
    +    ErrIoErrLock              = ErrIoErr.Extend(15)
    +    ErrIoErrClose             = ErrIoErr.Extend(16)
    +    ErrIoErrDirClose          = ErrIoErr.Extend(17)
    +    ErrIoErrSHMOpen           = ErrIoErr.Extend(18)
    +    ErrIoErrSHMSize           = ErrIoErr.Extend(19)
    +    ErrIoErrSHMLock           = ErrIoErr.Extend(20)
    +    ErrIoErrSHMMap            = ErrIoErr.Extend(21)
    +    ErrIoErrSeek              = ErrIoErr.Extend(22)
    +    ErrIoErrDeleteNoent       = ErrIoErr.Extend(23)
    +    ErrIoErrMMap              = ErrIoErr.Extend(24)
    +    ErrIoErrGetTempPath       = ErrIoErr.Extend(25)
    +    ErrIoErrConvPath          = ErrIoErr.Extend(26)
    +    ErrLockedSharedCache      = ErrLocked.Extend(1)
    +    ErrBusyRecovery           = ErrBusy.Extend(1)
    +    ErrBusySnapshot           = ErrBusy.Extend(2)
    +    ErrCantOpenNoTempDir      = ErrCantOpen.Extend(1)
    +    ErrCantOpenIsDir          = ErrCantOpen.Extend(2)
    +    ErrCantOpenFullPath       = ErrCantOpen.Extend(3)
    +    ErrCantOpenConvPath       = ErrCantOpen.Extend(4)
    +    ErrCorruptVTab            = ErrCorrupt.Extend(1)
    +    ErrReadonlyRecovery       = ErrReadonly.Extend(1)
    +    ErrReadonlyCantLock       = ErrReadonly.Extend(2)
    +    ErrReadonlyRollback       = ErrReadonly.Extend(3)
    +    ErrReadonlyDbMoved        = ErrReadonly.Extend(4)
    +    ErrAbortRollback          = ErrAbort.Extend(2)
    +    ErrConstraintCheck        = ErrConstraint.Extend(1)
    +    ErrConstraintCommitHook   = ErrConstraint.Extend(2)
    +    ErrConstraintForeignKey   = ErrConstraint.Extend(3)
    +    ErrConstraintFunction     = ErrConstraint.Extend(4)
    +    ErrConstraintNotNull      = ErrConstraint.Extend(5)
    +    ErrConstraintPrimaryKey   = ErrConstraint.Extend(6)
    +    ErrConstraintTrigger      = ErrConstraint.Extend(7)
    +    ErrConstraintUnique       = ErrConstraint.Extend(8)
    +    ErrConstraintVTab         = ErrConstraint.Extend(9)
    +    ErrConstraintRowId        = ErrConstraint.Extend(10)
    +    ErrNoticeRecoverWAL       = ErrNotice.Extend(1)
    +    ErrNoticeRecoverRollback  = ErrNotice.Extend(2)
    +    ErrWarningAutoIndex       = ErrWarning.Extend(1)
    +)
    +

    +result codes from http://www.sqlite.org/c3ref/c_abort_rollback.html +

    + + +
    var SQLiteTimestampFormats = []string{
    +
    +    "2006-01-02 15:04:05.999999999-07:00",
    +    "2006-01-02T15:04:05.999999999-07:00",
    +    "2006-01-02 15:04:05.999999999",
    +    "2006-01-02T15:04:05.999999999",
    +    "2006-01-02 15:04:05",
    +    "2006-01-02T15:04:05",
    +    "2006-01-02 15:04",
    +    "2006-01-02T15:04",
    +    "2006-01-02",
    +}
    +

    +Timestamp formats understood by both this module and SQLite. +The first format in the slice will be used when saving time values +into the database. When parsing a string from a timestamp or +datetime column, the formats are tried in order. +

    + + + + + + +

    func Version

    +
    func Version() (libVersion string, libVersionNumber int, sourceId string)
    +

    +Version returns SQLite library version information. +

    + + + + + + + + +

    type ErrNo

    +
    type ErrNo int
    + + + + + + + + + + + + + + +

    func (ErrNo) Error

    +
    func (err ErrNo) Error() string
    + + + + + + +

    func (ErrNo) Extend

    +
    func (err ErrNo) Extend(by int) ErrNoExtended
    + + + + + + + + +

    type ErrNoExtended

    +
    type ErrNoExtended int
    + + + + + + + + + + + + + + +

    func (ErrNoExtended) Error

    +
    func (err ErrNoExtended) Error() string
    + + + + + + + + +

    type Error

    +
    type Error struct {
    +    Code         ErrNo         /* The error code returned by SQLite */
    +    ExtendedCode ErrNoExtended /* The extended error code returned by SQLite */
    +    // contains filtered or unexported fields
    +}
    + + + + + + + + + + + + + + +

    func (Error) Error

    +
    func (err Error) Error() string
    + + + + + + + + +

    type SQLiteBackup

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

    func (*SQLiteBackup) Close

    +
    func (b *SQLiteBackup) Close() error
    + + + + + + +

    func (*SQLiteBackup) Finish

    +
    func (b *SQLiteBackup) Finish() error
    + + + + + + +

    func (*SQLiteBackup) PageCount

    +
    func (b *SQLiteBackup) PageCount() int
    + + + + + + +

    func (*SQLiteBackup) Remaining

    +
    func (b *SQLiteBackup) Remaining() int
    + + + + + + +

    func (*SQLiteBackup) Step

    +
    func (b *SQLiteBackup) Step(p int) (bool, error)
    +

    +Backs up for one step. Calls the underlying `sqlite3_backup_step` function. +This function returns a boolean indicating if the backup is done and +an error signalling any other error. Done is returned if the underlying C +function returns SQLITE_DONE (Code 101) +

    + + + + + + + + +

    type SQLiteConn

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

    +Conn struct. +

    + + + + + + + + + + + + + + +

    func (*SQLiteConn) AutoCommit

    +
    func (c *SQLiteConn) AutoCommit() bool
    +

    +AutoCommit return which currently auto commit or not. +

    + + + + + + +

    func (*SQLiteConn) Backup

    +
    func (c *SQLiteConn) Backup(dest string, conn *SQLiteConn, src string) (*SQLiteBackup, error)
    + + + + + + +

    func (*SQLiteConn) Begin

    +
    func (c *SQLiteConn) Begin() (driver.Tx, error)
    +

    +Begin transaction. +

    + + + + + + +

    func (*SQLiteConn) Close

    +
    func (c *SQLiteConn) Close() error
    +

    +Close the connection. +

    + + + + + + +

    func (*SQLiteConn) Exec

    +
    func (c *SQLiteConn) Exec(query string, args []driver.Value) (driver.Result, error)
    +

    +Implements Execer +

    + + + + + + +

    func (*SQLiteConn) LoadExtension

    +
    func (c *SQLiteConn) LoadExtension(lib string, entry string) error
    + + + + + + +

    func (*SQLiteConn) Prepare

    +
    func (c *SQLiteConn) Prepare(query string) (driver.Stmt, error)
    +

    +Prepare the query string. Return a new statement. +

    + + + + + + +

    func (*SQLiteConn) Query

    +
    func (c *SQLiteConn) Query(query string, args []driver.Value) (driver.Rows, error)
    +

    +Implements Queryer +

    + + + + + + +

    func (*SQLiteConn) RegisterAggregator

    +
    func (c *SQLiteConn) RegisterAggregator(name string, impl interface{}, pure bool) error
    + + + + + + +

    func (*SQLiteConn) RegisterFunc

    +
    func (c *SQLiteConn) RegisterFunc(name string, impl interface{}, pure bool) error
    +

    +RegisterFunc makes a Go function available as a SQLite function. +

    +

    +The Go function can have arguments of the following types: any +numeric type except complex, bool, []byte, string and +interface{}. interface{} arguments are given the direct translation +of the SQLite data type: int64 for INTEGER, float64 for FLOAT, +[]byte for BLOB, string for TEXT. +

    +

    +The function can additionally be variadic, as long as the type of +the variadic argument is one of the above. +

    +

    +If pure is true. SQLite will assume that the function's return +value depends only on its inputs, and make more aggressive +optimizations in its queries. +

    +

    +See _example/go_custom_funcs for a detailed example. +

    + + + + + + + + +

    type SQLiteDriver

    +
    type SQLiteDriver struct {
    +    Extensions  []string
    +    ConnectHook func(*SQLiteConn) error
    +}
    +

    +Driver struct. +

    + + + + + + + + + + + + + + +

    func (*SQLiteDriver) Open

    +
    func (d *SQLiteDriver) Open(dsn string) (driver.Conn, error)
    +

    +Open database and return a new connection. +You can specify a DSN string using a URI as the filename. +

    +
    test.db
    +file:test.db?cache=shared&mode=memory
    +:memory:
    +file::memory:
    +
    +

    +go-sqlite3 adds the following query parameters to those used by SQLite: +

    +
    _loc=XXX
    +  Specify location of time format. It's possible to specify "auto".
    +_busy_timeout=XXX
    +  Specify value for sqlite3_busy_timeout.
    +_txlock=XXX
    +  Specify locking behavior for transactions.  XXX can be "immediate",
    +  "deferred", "exclusive".
    +
    + + + + + + + + +

    type SQLiteResult

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

    +Result struct. +

    + + + + + + + + + + + + + + +

    func (*SQLiteResult) LastInsertId

    +
    func (r *SQLiteResult) LastInsertId() (int64, error)
    +

    +Return last inserted ID. +

    + + + + + + +

    func (*SQLiteResult) RowsAffected

    +
    func (r *SQLiteResult) RowsAffected() (int64, error)
    +

    +Return how many rows affected. +

    + + + + + + + + +

    type SQLiteRows

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

    +Rows struct. +

    + + + + + + + + + + + + + + +

    func (*SQLiteRows) Close

    +
    func (rc *SQLiteRows) Close() error
    +

    +Close the rows. +

    + + + + + + +

    func (*SQLiteRows) Columns

    +
    func (rc *SQLiteRows) Columns() []string
    +

    +Return column names. +

    + + + + + + +

    func (*SQLiteRows) DeclTypes

    +
    func (rc *SQLiteRows) DeclTypes() []string
    +

    +Return column types. +

    + + + + + + +

    func (*SQLiteRows) Next

    +
    func (rc *SQLiteRows) Next(dest []driver.Value) error
    +

    +Move cursor to next. +

    + + + + + + + + +

    type SQLiteStmt

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

    +Stmt struct. +

    + + + + + + + + + + + + + + +

    func (*SQLiteStmt) Close

    +
    func (s *SQLiteStmt) Close() error
    +

    +Close the statement. +

    + + + + + + +

    func (*SQLiteStmt) Exec

    +
    func (s *SQLiteStmt) Exec(args []driver.Value) (driver.Result, error)
    +

    +Execute the statement with arguments. Return result object. +

    + + + + + + +

    func (*SQLiteStmt) NumInput

    +
    func (s *SQLiteStmt) NumInput() int
    +

    +Return a number of parameters. +

    + + + + + + +

    func (*SQLiteStmt) Query

    +
    func (s *SQLiteStmt) Query(args []driver.Value) (driver.Rows, error)
    +

    +Query the statement with arguments. Return records. +

    + + + + + + + + +

    type SQLiteTx

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

    +Tx struct. +

    + + + + + + + + + + + + + + +

    func (*SQLiteTx) Commit

    +
    func (tx *SQLiteTx) Commit() error
    +

    +Commit transaction. +

    + + + + + + +

    func (*SQLiteTx) Rollback

    +
    func (tx *SQLiteTx) Rollback() error
    +

    +Rollback transaction. +

    + + + + + + + + + + + + + + + + +

    Subdirectories

    + + + + +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    NameSynopsis
    ..
    + sqlite3_test + + +
    + tool + + +
    +
    + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/github.com/mattn/go-sqlite3/sqlite3_test/index.html b/pkg/github.com/mattn/go-sqlite3/sqlite3_test/index.html new file mode 100644 index 0000000..9f8fcae --- /dev/null +++ b/pkg/github.com/mattn/go-sqlite3/sqlite3_test/index.html @@ -0,0 +1,406 @@ + + + + + + + + sqlite3_test - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Package sqlite3_test

    + + + + + + + + + + + + + + +
    +
    +
    import "github.com/mattn/go-sqlite3/sqlite3_test"
    +
    +
    +
    Overview
    +
    Index
    + + +
    +
    + +
    + +
    +

    Overview ▾

    + +
    +
    + + + + + + + + + + + +

    func BenchmarkExec

    +
    func BenchmarkExec(b *testing.B)
    + + + + + + + +

    func BenchmarkParams

    +
    func BenchmarkParams(b *testing.B)
    + + + + + + + +

    func BenchmarkQuery

    +
    func BenchmarkQuery(b *testing.B)
    + + + + + + + +

    func BenchmarkRows

    +
    func BenchmarkRows(b *testing.B)
    + + + + + + + +

    func BenchmarkStmt

    +
    func BenchmarkStmt(b *testing.B)
    + + + + + + + +

    func BenchmarkStmtRows

    +
    func BenchmarkStmtRows(b *testing.B)
    + + + + + + + +

    func RunTests

    +
    func RunTests(t *testing.T, d *sql.DB, dialect Dialect)
    +

    +RunTests runs the SQL test suite +

    + + + + + + + +

    func TestBlobs

    +
    func TestBlobs(t *testing.T)
    + + + + + + + +

    func TestManyQueryRow

    +
    func TestManyQueryRow(t *testing.T)
    + + + + + + + +

    func TestPreparedStmt

    +
    func TestPreparedStmt(t *testing.T)
    + + + + + + + +

    func TestResult

    +
    func TestResult(t *testing.T)
    + + + + + + + +

    func TestTxQuery

    +
    func TestTxQuery(t *testing.T)
    + + + + + + + + +

    type DB

    +
    type DB struct {
    +    *testing.T
    +    *sql.DB
    +    // contains filtered or unexported fields
    +}
    + + + + + + + + + + + + + + + + +

    type Dialect

    +
    type Dialect int
    + + + +
    const (
    +    SQLITE Dialect = iota
    +    POSTGRESQL
    +    MYSQL
    +)
    + + + + + + + + + + + + + + + + + + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/github.com/mattn/go-sqlite3/tool/index.html b/pkg/github.com/mattn/go-sqlite3/tool/index.html new file mode 100644 index 0000000..6b6c5b7 --- /dev/null +++ b/pkg/github.com/mattn/go-sqlite3/tool/index.html @@ -0,0 +1,106 @@ + + + + + + + + tool - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Command tool

    + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/github.com/mattn/index.html b/pkg/github.com/mattn/index.html new file mode 100644 index 0000000..03f364a --- /dev/null +++ b/pkg/github.com/mattn/index.html @@ -0,0 +1,163 @@ + + + + + + + + /src/github.com/mattn - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Directory /src/github.com/mattn

    + + + + + + + + + + + + + + + + + + + +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    NameSynopsis
    ..
    + go-shellwords + + +
    + go-sqlite3 + + Package sqlite3 provides interface to SQLite3 databases. +
    + sqlite3_test + + +
    + tool + + +
    +
    + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/github.com/matttproud/golang_protobuf_extensions/index.html b/pkg/github.com/matttproud/golang_protobuf_extensions/index.html new file mode 100644 index 0000000..04d47b2 --- /dev/null +++ b/pkg/github.com/matttproud/golang_protobuf_extensions/index.html @@ -0,0 +1,130 @@ + + + + + + + + /src/github.com/matttproud/golang_protobuf_extensions - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Directory /src/github.com/matttproud/golang_protobuf_extensions

    + + + + + + + + + + + + + + + + + + + +
    + + + + + + + + + + + + + + + + + + + + +
    NameSynopsis
    ..
    + pbutil + + Package pbutil provides record length-delimited Protocol Buffer streaming. +
    +
    + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/github.com/matttproud/golang_protobuf_extensions/pbutil/index.html b/pkg/github.com/matttproud/golang_protobuf_extensions/pbutil/index.html new file mode 100644 index 0000000..9a570d9 --- /dev/null +++ b/pkg/github.com/matttproud/golang_protobuf_extensions/pbutil/index.html @@ -0,0 +1,254 @@ + + + + + + + + pbutil - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Package pbutil

    + + + + + + + + + + + + + + +
    +
    +
    import "github.com/matttproud/golang_protobuf_extensions/pbutil"
    +
    +
    +
    Overview
    +
    Index
    + + +
    +
    + +
    + +
    +

    Overview ▾

    +

    +Package pbutil provides record length-delimited Protocol Buffer streaming. +

    + +
    +
    + + +
    + + +
    + + + + + + + + +

    func ReadDelimited

    +
    func ReadDelimited(r io.Reader, m proto.Message) (n int, err error)
    +

    +ReadDelimited decodes a message from the provided length-delimited stream, +where the length is encoded as 32-bit varint prefix to the message body. +It returns the total number of bytes read and any applicable error. This is +roughly equivalent to the companion Java API's +MessageLite#parseDelimitedFrom. As per the reader contract, this function +calls r.Read repeatedly as required until exactly one message including its +prefix is read and decoded (or an error has occurred). The function never +reads more bytes from the stream than required. The function never returns +an error if a message has been read and decoded correctly, even if the end +of the stream has been reached in doing so. In that case, any subsequent +calls return (0, io.EOF). +

    + + + + + + + +

    func WriteDelimited

    +
    func WriteDelimited(w io.Writer, m proto.Message) (n int, err error)
    +

    +WriteDelimited encodes and dumps a message to the provided writer prefixed +with a 32-bit varint indicating the length of the encoded message, producing +a length-delimited record stream, which can be used to chain together +encoded messages of the same type together in a file. It returns the total +number of bytes written and any applicable error. This is roughly +equivalent to the companion Java API's MessageLite#writeDelimitedTo. +

    + + + + + + + + + + + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/github.com/matttproud/index.html b/pkg/github.com/matttproud/index.html new file mode 100644 index 0000000..c33ba2f --- /dev/null +++ b/pkg/github.com/matttproud/index.html @@ -0,0 +1,141 @@ + + + + + + + + /src/github.com/matttproud - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Directory /src/github.com/matttproud

    + + + + + + + + + + + + + + + + + + + +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    NameSynopsis
    ..
    + golang_protobuf_extensions + + +
    + pbutil + + Package pbutil provides record length-delimited Protocol Buffer streaming. +
    +
    + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/github.com/mmcdole/gofeed/atom/index.html b/pkg/github.com/mmcdole/gofeed/atom/index.html new file mode 100644 index 0000000..2894316 --- /dev/null +++ b/pkg/github.com/mmcdole/gofeed/atom/index.html @@ -0,0 +1,540 @@ + + + + + + + + atom - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Package atom

    + + + + + + + + + + + + + + +
    +
    +
    import "github.com/mmcdole/gofeed/atom"
    +
    +
    +
    Overview
    +
    Index
    + + +
    +
    + +
    + +
    +

    Overview ▾

    + +
    +
    + + +
    + +
    +

    Index ▾

    + + +
    +
    + + + + + +
    type Category
    + + + + +
    type Content
    + + + + +
    type Entry
    + + + + +
    type Feed
    + + + +
        func (f Feed) String() string
    + + + +
    type Generator
    + + + + +
    type Link
    + + + + +
    type Parser
    + + + +
        func (ap *Parser) Parse(feed io.Reader) (*Feed, error)
    + + + +
    type Person
    + + + + +
    type Source
    + + + + +
    +
    + + + + +

    Package files

    +

    + + + feed.go + + parser.go + + +

    + +
    +
    + + + + + + + + + +

    type Category

    +
    type Category struct {
    +    Term   string `json:"term,omitempty"`
    +    Scheme string `json:"scheme,omitempty"`
    +    Label  string `json:"label,omitempty"`
    +}
    +

    +Category is category metadata for Feeds and Entries +

    + + + + + + + + + + + + + + + + +

    type Content

    +
    type Content struct {
    +    Src   string `json:"src,omitempty"`
    +    Type  string `json:"type,omitempty"`
    +    Value string `json:"value,omitempty"`
    +}
    +

    +Content either contains or links to the content of +the entry +

    + + + + + + + + + + + + + + + + +

    type Entry

    +
    type Entry struct {
    +    Title           string         `json:"title,omitempty"`
    +    ID              string         `json:"id,omitempty"`
    +    Updated         string         `json:"updated,omitempty"`
    +    UpdatedParsed   *time.Time     `json:"updatedParsed,omitempty"`
    +    Summary         string         `json:"summary,omitempty"`
    +    Authors         []*Person      `json:"authors,omitempty"`
    +    Contributors    []*Person      `json:"contributors,omitempty"`
    +    Categories      []*Category    `json:"categories,omitempty"`
    +    Links           []*Link        `json:"links,omitempty"`
    +    Rights          string         `json:"rights,omitempty"`
    +    Published       string         `json:"published,omitempty"`
    +    PublishedParsed *time.Time     `json:"publishedParsed,omitempty"`
    +    Source          *Source        `json:"source,omitempty"`
    +    Content         *Content       `json:"content,omitempty"`
    +    Extensions      ext.Extensions `json:"extensions,omitempty"`
    +}
    +

    +Entry is an Atom Entry +

    + + + + + + + + + + + + + + + + +

    type Feed

    +
    type Feed struct {
    +    Title         string         `json:"title,omitempty"`
    +    ID            string         `json:"id,omitempty"`
    +    Updated       string         `json:"updated,omitempty"`
    +    UpdatedParsed *time.Time     `json:"updatedParsed,omitempty"`
    +    Subtitle      string         `json:"subtitle,omitempty"`
    +    Links         []*Link        `json:"links,omitempty"`
    +    Language      string         `json:"language,omitempty"`
    +    Generator     *Generator     `json:"generator,omitempty"`
    +    Icon          string         `json:"icon,omitempty"`
    +    Logo          string         `json:"logo,omitempty"`
    +    Rights        string         `json:"rights,omitempty"`
    +    Contributors  []*Person      `json:"contributors,omitempty"`
    +    Authors       []*Person      `json:"authors,omitempty"`
    +    Categories    []*Category    `json:"categories,omitempty"`
    +    Entries       []*Entry       `json:"entries"`
    +    Extensions    ext.Extensions `json:"extensions,omitempty"`
    +    Version       string         `json:"version"`
    +}
    +

    +Feed is an Atom Feed +

    + + + + + + + + + + + + + + +

    func (Feed) String

    +
    func (f Feed) String() string
    + + + + + + + + +

    type Generator

    +
    type Generator struct {
    +    Value   string `json:"value,omitempty"`
    +    URI     string `json:"uri,omitempty"`
    +    Version string `json:"version,omitempty"`
    +}
    +

    +Generator identifies the agent used to generate a +feed, for debugging and other purposes. +

    + + + + + + + + + + + + + + + + + +
    type Link struct {
    +    Href     string `json:"href,omitempty"`
    +    Hreflang string `json:"hreflang,omitempty"`
    +    Rel      string `json:"rel,omitempty"`
    +    Type     string `json:"type,omitempty"`
    +    Title    string `json:"title,omitempty"`
    +    Length   string `json:"length,omitempty"`
    +}
    +

    +Link is an Atom link that defines a reference +from an entry or feed to a Web resource +

    + + + + + + + + + + + + + + + + +

    type Parser

    +
    type Parser struct{}
    +

    +Parser is an Atom Parser +

    + + + + + + + + + + + + + + +

    func (*Parser) Parse

    +
    func (ap *Parser) Parse(feed io.Reader) (*Feed, error)
    +

    +Parse parses an xml feed into an atom.Feed +

    + + + + + + + + +

    type Person

    +
    type Person struct {
    +    Name  string `json:"name,omitempty"`
    +    Email string `json:"email,omitempty"`
    +    URI   string `json:"uri,omitempty"`
    +}
    +

    +Person represents a person in an Atom feed +for things like Authors, Contributors, etc +

    + + + + + + + + + + + + + + + + +

    type Source

    +
    type Source struct {
    +    Title         string         `json:"title,omitempty"`
    +    ID            string         `json:"id,omitempty"`
    +    Updated       string         `json:"updated,omitempty"`
    +    UpdatedParsed *time.Time     `json:"updatedParsed,omitempty"`
    +    Subtitle      string         `json:"subtitle,omitempty"`
    +    Links         []*Link        `json:"links,omitempty"`
    +    Generator     *Generator     `json:"generator,omitempty"`
    +    Icon          string         `json:"icon,omitempty"`
    +    Logo          string         `json:"logo,omitempty"`
    +    Rights        string         `json:"rights,omitempty"`
    +    Contributors  []*Person      `json:"contributors,omitempty"`
    +    Authors       []*Person      `json:"authors,omitempty"`
    +    Categories    []*Category    `json:"categories,omitempty"`
    +    Extensions    ext.Extensions `json:"extensions,omitempty"`
    +}
    +

    +Source contains the feed information for another +feed if a given entry came from that feed. +

    + + + + + + + + + + + + + + + + + + + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/github.com/mmcdole/gofeed/cmd/ftest/index.html b/pkg/github.com/mmcdole/gofeed/cmd/ftest/index.html new file mode 100644 index 0000000..036f050 --- /dev/null +++ b/pkg/github.com/mmcdole/gofeed/cmd/ftest/index.html @@ -0,0 +1,106 @@ + + + + + + + + ftest - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Command ftest

    + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/github.com/mmcdole/gofeed/cmd/index.html b/pkg/github.com/mmcdole/gofeed/cmd/index.html new file mode 100644 index 0000000..6a711a9 --- /dev/null +++ b/pkg/github.com/mmcdole/gofeed/cmd/index.html @@ -0,0 +1,130 @@ + + + + + + + + /src/github.com/mmcdole/gofeed/cmd - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Directory /src/github.com/mmcdole/gofeed/cmd

    + + + + + + + + + + + + + + + + + + + +
    + + + + + + + + + + + + + + + + + + + + +
    NameSynopsis
    ..
    + ftest + + +
    +
    + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/github.com/mmcdole/gofeed/extensions/index.html b/pkg/github.com/mmcdole/gofeed/extensions/index.html new file mode 100644 index 0000000..365aed4 --- /dev/null +++ b/pkg/github.com/mmcdole/gofeed/extensions/index.html @@ -0,0 +1,487 @@ + + + + + + + + ext - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Package ext

    + + + + + + + + + + + + + + +
    +
    +
    import "github.com/mmcdole/gofeed/extensions"
    +
    +
    +
    Overview
    +
    Index
    + + +
    +
    + +
    + +
    +

    Overview ▾

    + +
    +
    + + + + + + + + + + + + +

    type DublinCoreExtension

    +
    type DublinCoreExtension struct {
    +    Title       []string `json:"title,omitempty"`
    +    Creator     []string `json:"creator,omitempty"`
    +    Author      []string `json:"author,omitempty"`
    +    Subject     []string `json:"subject,omitempty"`
    +    Description []string `json:"description,omitempty"`
    +    Publisher   []string `json:"publisher,omitempty"`
    +    Contributor []string `json:"contributor,omitempty"`
    +    Date        []string `json:"date,omitempty"`
    +    Type        []string `json:"type,omitempty"`
    +    Format      []string `json:"format,omitempty"`
    +    Identifier  []string `json:"identifier,omitempty"`
    +    Source      []string `json:"source,omitempty"`
    +    Language    []string `json:"language,omitempty"`
    +    Relation    []string `json:"relation,omitempty"`
    +    Coverage    []string `json:"coverage,omitempty"`
    +    Rights      []string `json:"rights,omitempty"`
    +}
    +

    +DublinCoreExtension represents a feed extension +for the Dublin Core specification. +

    + + + + + + + + + + + + +

    func NewDublinCoreExtension

    +
    func NewDublinCoreExtension(extensions map[string][]Extension) *DublinCoreExtension
    +

    +NewDublinCoreExtension creates a new DublinCoreExtension +given the generic extension map for the "dc" prefix. +

    + + + + + + + + + +

    type Extension

    +
    type Extension struct {
    +    Name     string                 `json:"name"`
    +    Value    string                 `json:"value"`
    +    Attrs    map[string]string      `json:"attrs"`
    +    Children map[string][]Extension `json:"children"`
    +}
    +

    +Extension represents a single XML element that was in a non +default namespace in a Feed or Item/Entry. +

    + + + + + + + + + + + + + + + + +

    type Extensions

    +
    type Extensions map[string]map[string][]Extension
    +

    +Extensions is the generic extension map for Feeds and Items. +The first map is for the element namespace prefix (e.g., itunes). +The second map is for the element name (e.g., author). +

    + + + + + + + + + + + + + + + + +

    type ITunesCategory

    +
    type ITunesCategory struct {
    +    Text        string          `json:"text,omitempty"`
    +    Subcategory *ITunesCategory `json:"subcategory,omitempty"`
    +}
    +

    +ITunesCategory is a category element for itunes feeds. +

    + + + + + + + + + + + + + + + + +

    type ITunesFeedExtension

    +
    type ITunesFeedExtension struct {
    +    Author     string            `json:"author,omitempty"`
    +    Block      string            `json:"block,omitempty"`
    +    Categories []*ITunesCategory `json:"categories,omitempty"`
    +    Explicit   string            `json:"explicit,omitempty"`
    +    Keywords   string            `json:"keywords,omitempty"`
    +    Owner      *ITunesOwner      `json:"owner,omitempty"`
    +    Subtitle   string            `json:"subtitle,omitempty"`
    +    Summary    string            `json:"summary,omitempty"`
    +    Image      string            `json:"image,omitempty"`
    +    Complete   string            `json:"complete,omitempty"`
    +    NewFeedURL string            `json:"newFeedUrl,omitempty"`
    +}
    +

    +ITunesFeedExtension is a set of extension +fields for RSS feeds. +

    + + + + + + + + + + + + +

    func NewITunesFeedExtension

    +
    func NewITunesFeedExtension(extensions map[string][]Extension) *ITunesFeedExtension
    +

    +NewITunesFeedExtension creates an ITunesFeedExtension given an +extension map for the "itunes" key. +

    + + + + + + + + + +

    type ITunesItemExtension

    +
    type ITunesItemExtension struct {
    +    Author            string `json:"author,omitempty"`
    +    Block             string `json:"block,omitempty"`
    +    Duration          string `json:"duration,omitempty"`
    +    Explicit          string `json:"explicit,omitempty"`
    +    Keywords          string `json:"keywords,omitempty"`
    +    Subtitle          string `json:"subtitle,omitempty"`
    +    Summary           string `json:"summary,omitempty"`
    +    Image             string `json:"image,omitempty"`
    +    IsClosedCaptioned string `json:"isClosedCaptioned,omitempty"`
    +    Order             string `json:"order,omitempty"`
    +}
    +

    +ITunesItemExtension is a set of extension +fields for RSS items. +

    + + + + + + + + + + + + +

    func NewITunesItemExtension

    +
    func NewITunesItemExtension(extensions map[string][]Extension) *ITunesItemExtension
    +

    +NewITunesItemExtension creates an ITunesItemExtension given an +extension map for the "itunes" key. +

    + + + + + + + + + +

    type ITunesOwner

    +
    type ITunesOwner struct {
    +    Email string `json:"email,omitempty"`
    +    Name  string `json:"name,omitempty"`
    +}
    +

    +ITunesOwner is the owner of a particular itunes feed. +

    + + + + + + + + + + + + + + + + + + + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/github.com/mmcdole/gofeed/index.html b/pkg/github.com/mmcdole/gofeed/index.html new file mode 100644 index 0000000..9bc1330 --- /dev/null +++ b/pkg/github.com/mmcdole/gofeed/index.html @@ -0,0 +1,911 @@ + + + + + + + + gofeed - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Package gofeed

    + + + + + + + + + + + + + + +
    +
    +
    import "github.com/mmcdole/gofeed"
    +
    +
    +
    Overview
    +
    Index
    + +
    Examples
    + + +
    Subdirectories
    + +
    +
    + +
    + +
    +

    Overview ▾

    + +
    +
    + + + + + + + + + + + + +

    type DefaultAtomTranslator

    +
    type DefaultAtomTranslator struct{}
    +

    +DefaultAtomTranslator converts an atom.Feed struct +into the generic Feed struct. +

    +

    +This default implementation defines a set of +mapping rules between atom.Feed -> Feed +for each of the fields in Feed. +

    + + + + + + + + + + + + + + +

    func (*DefaultAtomTranslator) Translate

    +
    func (t *DefaultAtomTranslator) Translate(feed interface{}) (*Feed, error)
    +

    +Translate converts an Atom feed into the universal +feed type. +

    + + + + + + + + +

    type DefaultRSSTranslator

    +
    type DefaultRSSTranslator struct{}
    +

    +DefaultRSSTranslator converts an rss.Feed struct +into the generic Feed struct. +

    +

    +This default implementation defines a set of +mapping rules between rss.Feed -> Feed +for each of the fields in Feed. +

    + + + + + + + + + + + + + + +

    func (*DefaultRSSTranslator) Translate

    +
    func (t *DefaultRSSTranslator) Translate(feed interface{}) (*Feed, error)
    +

    +Translate converts an RSS feed into the universal +feed type. +

    + + + + + + + + +

    type Enclosure

    +
    type Enclosure struct {
    +    URL    string `json:"url,omitempty"`
    +    Length string `json:"length,omitempty"`
    +    Type   string `json:"type,omitempty"`
    +}
    +

    +Enclosure is a file associated with a given Item. +

    + + + + + + + + + + + + + + + + +

    type Feed

    +
    type Feed struct {
    +    Title           string            `json:"title,omitempty"`
    +    Description     string            `json:"description,omitempty"`
    +    Link            string            `json:"link,omitempty"`
    +    FeedLink        string            `json:"feedLink,omitempty"`
    +    Updated         string            `json:"updated,omitempty"`
    +    UpdatedParsed   *time.Time        `json:"updatedParsed,omitempty"`
    +    Published       string            `json:"published,omitempty"`
    +    PublishedParsed *time.Time        `json:"publishedParsed,omitempty"`
    +    Author          *Person           `json:"author,omitempty"`
    +    Language        string            `json:"language,omitempty"`
    +    Image           *Image            `json:"image,omitempty"`
    +    Copyright       string            `json:"copyright,omitempty"`
    +    Generator       string            `json:"generator,omitempty"`
    +    Categories      []string          `json:"categories,omitempty"`
    +    Extensions      ext.Extensions    `json:"extensions,omitempty"`
    +    Custom          map[string]string `json:"custom,omitempty"`
    +    Items           []*Item           `json:"items"`
    +    FeedType        string            `json:"feedType"`
    +    FeedVersion     string            `json:"feedVersion"`
    +}
    +

    +Feed is the universal Feed type that atom.Feed +and rss.Feed gets translated to. It represents +a web feed. +

    + + + + + + + + + + + + + + +

    func (Feed) String

    +
    func (f Feed) String() string
    + + + + + + + + +

    type FeedType

    +
    type FeedType int
    +

    +FeedType represents one of the possible feed +types that we can detect. +

    + + + +
    const (
    +    // FeedTypeUnknown represents a feed that could not have its
    +    // type determiend.
    +    FeedTypeUnknown FeedType = iota
    +    // FeedTypeAtom repesents an Atom feed
    +    FeedTypeAtom
    +    // FeedTypeRSS represents an RSS feed
    +    FeedTypeRSS
    +)
    + + + + + + + + + + + +

    func DetectFeedType

    +
    func DetectFeedType(feed io.Reader) FeedType
    +

    +DetectFeedType attempts to determine the type of feed +by looking for specific xml elements unique to the +various feed types. +

    + +
    + +
    +

    Example

    + + + +

    Code:

    +
    +feedData := `<rss version="2.0">
    +<channel>
    +<title>Sample Feed</title>
    +</channel>
    +</rss>`
    +feedType := gofeed.DetectFeedType(strings.NewReader(feedData))
    +if feedType == gofeed.FeedTypeRSS {
    +    fmt.Println("Wow! This is an RSS feed!")
    +}
    +
    + + +
    +
    + + + + + + + + +

    type HTTPError

    +
    type HTTPError struct {
    +    StatusCode int
    +    Status     string
    +}
    +

    +HTTPError represents an HTTP error returned by a server. +

    + + + + + + + + + + + + + + +

    func (HTTPError) Error

    +
    func (err HTTPError) Error() string
    + + + + + + + + +

    type Image

    +
    type Image struct {
    +    URL   string `json:"url,omitempty"`
    +    Title string `json:"title,omitempty"`
    +}
    +

    +Image is an image that is the artwork for a given +feed or item. +

    + + + + + + + + + + + + + + + + +

    type Item

    +
    type Item struct {
    +    Title           string            `json:"title,omitempty"`
    +    Description     string            `json:"description,omitempty"`
    +    Content         string            `json:"content,omitempty"`
    +    Link            string            `json:"link,omitempty"`
    +    Updated         string            `json:"updated,omitempty"`
    +    UpdatedParsed   *time.Time        `json:"updatedParsed,omitempty"`
    +    Published       string            `json:"published,omitempty"`
    +    PublishedParsed *time.Time        `json:"publishedParsed,omitempty"`
    +    Author          *Person           `json:"author,omitempty"`
    +    GUID            string            `json:"guid,omitempty"`
    +    Image           *Image            `json:"image,omitempty"`
    +    Categories      []string          `json:"categories,omitempty"`
    +    Enclosures      []*Enclosure      `json:"enclosures,omitempty"`
    +    Extensions      ext.Extensions    `json:"extensions,omitempty"`
    +    Custom          map[string]string `json:"custom,omitempty"`
    +}
    +

    +Item is the universal Item type that atom.Entry +and rss.Item gets translated to. It represents +a single entry in a given feed. +

    + + + + + + + + + + + + + + + + +

    type Parser

    +
    type Parser struct {
    +    AtomTranslator Translator
    +    RSSTranslator  Translator
    +    Client         *http.Client
    +    // contains filtered or unexported fields
    +}
    +

    +Parser is a universal feed parser that detects +a given feed type, parsers it, and translates it +to the universal feed type. +

    + + + + + + + + + + + + +

    func NewParser

    +
    func NewParser() *Parser
    +

    +NewParser creates a universal feed parser. +

    + + + + + + + +

    func (*Parser) Parse

    +
    func (f *Parser) Parse(feed io.Reader) (*Feed, error)
    +

    +Parse parses a RSS or Atom feed into +the universal gofeed.Feed. It takes an +io.Reader which should return the xml content. +

    + + +
    + +
    +

    Example

    + + + +

    Code:

    +
    +feedData := `<rss version="2.0">
    +<channel>
    +<title>Sample Feed</title>
    +</channel>
    +</rss>`
    +fp := gofeed.NewParser()
    +feed, err := fp.Parse(strings.NewReader(feedData))
    +if err != nil {
    +    panic(err)
    +}
    +fmt.Println(feed.Title)
    +
    + + +
    +
    + + + + +

    func (*Parser) ParseString

    +
    func (f *Parser) ParseString(feed string) (*Feed, error)
    +

    +ParseString parses a feed XML string and into the +universal feed type. +

    + + +
    + +
    +

    Example

    + + + +

    Code:

    +
    +feedData := `<rss version="2.0">
    +<channel>
    +<title>Sample Feed</title>
    +</channel>
    +</rss>`
    +fp := gofeed.NewParser()
    +feed, err := fp.ParseString(feedData)
    +if err != nil {
    +    panic(err)
    +}
    +fmt.Println(feed.Title)
    +
    + + +
    +
    + + + + +

    func (*Parser) ParseURL

    +
    func (f *Parser) ParseURL(feedURL string) (feed *Feed, err error)
    +

    +ParseURL fetches the contents of a given url and +attempts to parse the response into the universal feed type. +

    + + +
    + +
    +

    Example

    + + + +

    Code:

    +
    +fp := gofeed.NewParser()
    +feed, err := fp.ParseURL("http://feeds.twit.tv/twit.xml")
    +if err != nil {
    +    panic(err)
    +}
    +fmt.Println(feed.Title)
    +
    + + +
    +
    + + + + + + +

    type Person

    +
    type Person struct {
    +    Name  string `json:"name,omitempty"`
    +    Email string `json:"email,omitempty"`
    +}
    +

    +Person is an individual specified in a feed +(e.g. an author) +

    + + + + + + + + + + + + + + + + +

    type Translator

    +
    type Translator interface {
    +    Translate(feed interface{}) (*Feed, error)
    +}
    +

    +Translator converts a particular feed (atom.Feed or rss.Feed) +into the generic Feed struct +

    + + + + + + + + + + + + + + + + + + + + + + + + +

    Subdirectories

    + + + + +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    NameSynopsis
    ..
    + atom + + +
    + cmd + + +
    + ftest + + +
    + extensions + + +
    + rss + + +
    +
    + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/github.com/mmcdole/gofeed/rss/index.html b/pkg/github.com/mmcdole/gofeed/rss/index.html new file mode 100644 index 0000000..6e858d5 --- /dev/null +++ b/pkg/github.com/mmcdole/gofeed/rss/index.html @@ -0,0 +1,568 @@ + + + + + + + + rss - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Package rss

    + + + + + + + + + + + + + + +
    +
    +
    import "github.com/mmcdole/gofeed/rss"
    +
    +
    +
    Overview
    +
    Index
    + + +
    +
    + +
    + +
    +

    Overview ▾

    + +
    +
    + + +
    + +
    +

    Index ▾

    + + +
    +
    + + + + + +
    type Category
    + + + + +
    type Cloud
    + + + + +
    type Enclosure
    + + + + +
    type Feed
    + + + +
        func (f Feed) String() string
    + + + +
    type GUID
    + + + + +
    type Image
    + + + + +
    type Item
    + + + + +
    type Parser
    + + + +
        func (rp *Parser) Parse(feed io.Reader) (*Feed, error)
    + + + +
    type Source
    + + + + +
    type TextInput
    + + + + +
    +
    + + + + +

    Package files

    +

    + + + feed.go + + parser.go + + +

    + +
    +
    + + + + + + + + + +

    type Category

    +
    type Category struct {
    +    Domain string `json:"domain,omitempty"`
    +    Value  string `json:"value,omitempty"`
    +}
    +

    +Category is category metadata for Feeds and Entries +

    + + + + + + + + + + + + + + + + +

    type Cloud

    +
    type Cloud struct {
    +    Domain            string `json:"domain,omitempty"`
    +    Port              string `json:"port,omitempty"`
    +    Path              string `json:"path,omitempty"`
    +    RegisterProcedure string `json:"registerProcedure,omitempty"`
    +    Protocol          string `json:"protocol,omitempty"`
    +}
    +

    +Cloud allows processes to register with a +cloud to be notified of updates to the channel, +implementing a lightweight publish-subscribe protocol +for RSS feeds +

    + + + + + + + + + + + + + + + + +

    type Enclosure

    +
    type Enclosure struct {
    +    URL    string `json:"url,omitempty"`
    +    Length string `json:"length,omitempty"`
    +    Type   string `json:"type,omitempty"`
    +}
    +

    +Enclosure is a media object that is attached to +the item +

    + + + + + + + + + + + + + + + + +

    type Feed

    +
    type Feed struct {
    +    Title               string                   `json:"title,omitempty"`
    +    Link                string                   `json:"link,omitempty"`
    +    Description         string                   `json:"description,omitempty"`
    +    Language            string                   `json:"language,omitempty"`
    +    Copyright           string                   `json:"copyright,omitempty"`
    +    ManagingEditor      string                   `json:"managingEditor,omitempty"`
    +    WebMaster           string                   `json:"webMaster,omitempty"`
    +    PubDate             string                   `json:"pubDate,omitempty"`
    +    PubDateParsed       *time.Time               `json:"pubDateParsed,omitempty"`
    +    LastBuildDate       string                   `json:"lastBuildDate,omitempty"`
    +    LastBuildDateParsed *time.Time               `json:"lastBuildDateParsed,omitempty"`
    +    Categories          []*Category              `json:"categories,omitempty"`
    +    Generator           string                   `json:"generator,omitempty"`
    +    Docs                string                   `json:"docs,omitempty"`
    +    TTL                 string                   `json:"ttl,omitempty"`
    +    Image               *Image                   `json:"image,omitempty"`
    +    Rating              string                   `json:"rating,omitempty"`
    +    SkipHours           []string                 `json:"skipHours,omitempty"`
    +    SkipDays            []string                 `json:"skipDays,omitempty"`
    +    Cloud               *Cloud                   `json:"cloud,omitempty"`
    +    TextInput           *TextInput               `json:"textInput,omitempty"`
    +    DublinCoreExt       *ext.DublinCoreExtension `json:"dcExt,omitempty"`
    +    ITunesExt           *ext.ITunesFeedExtension `json:"itunesExt,omitempty"`
    +    Extensions          ext.Extensions           `json:"extensions,omitempty"`
    +    Items               []*Item                  `json:"items"`
    +    Version             string                   `json:"version"`
    +}
    +

    +Feed is an RSS Feed +

    + + + + + + + + + + + + + + +

    func (Feed) String

    +
    func (f Feed) String() string
    + + + + + + + + +

    type GUID

    +
    type GUID struct {
    +    Value       string `json:"value,omitempty"`
    +    IsPermalink string `json:"isPermalink,omitempty"`
    +}
    +

    +GUID is a unique identifier for an item +

    + + + + + + + + + + + + + + + + +

    type Image

    +
    type Image struct {
    +    URL         string `json:"url,omitempty"`
    +    Link        string `json:"link,omitempty"`
    +    Title       string `json:"title,omitempty"`
    +    Width       string `json:"width,omitempty"`
    +    Height      string `json:"height,omitempty"`
    +    Description string `json:"description,omitempty"`
    +}
    +

    +Image is an image that represents the feed +

    + + + + + + + + + + + + + + + + +

    type Item

    +
    type Item struct {
    +    Title         string                   `json:"title,omitempty"`
    +    Link          string                   `json:"link,omitempty"`
    +    Description   string                   `json:"description,omitempty"`
    +    Author        string                   `json:"author,omitempty"`
    +    Categories    []*Category              `json:"categories,omitempty"`
    +    Comments      string                   `json:"comments,omitempty"`
    +    Enclosure     *Enclosure               `json:"enclosure,omitempty"`
    +    GUID          *GUID                    `json:"guid,omitempty"`
    +    PubDate       string                   `json:"pubDate,omitempty"`
    +    PubDateParsed *time.Time               `json:"pubDateParsed,omitempty"`
    +    Source        *Source                  `json:"source,omitempty"`
    +    DublinCoreExt *ext.DublinCoreExtension `json:"dcExt,omitempty"`
    +    ITunesExt     *ext.ITunesItemExtension `json:"itunesExt,omitempty"`
    +    Extensions    ext.Extensions           `json:"extensions,omitempty"`
    +}
    +

    +Item is an RSS Item +

    + + + + + + + + + + + + + + + + +

    type Parser

    +
    type Parser struct{}
    +

    +Parser is a RSS Parser +

    + + + + + + + + + + + + + + +

    func (*Parser) Parse

    +
    func (rp *Parser) Parse(feed io.Reader) (*Feed, error)
    +

    +Parse parses an xml feed into an rss.Feed +

    + + + + + + + + +

    type Source

    +
    type Source struct {
    +    Title string `json:"title,omitempty"`
    +    URL   string `json:"url,omitempty"`
    +}
    +

    +Source contains feed information for another +feed if a given item came from that feed +

    + + + + + + + + + + + + + + + + +

    type TextInput

    +
    type TextInput struct {
    +    Title       string `json:"title,omitempty"`
    +    Description string `json:"description,omitempty"`
    +    Name        string `json:"name,omitempty"`
    +    Link        string `json:"link,omitempty"`
    +}
    +

    +TextInput specifies a text input box that +can be displayed with the channel +

    + + + + + + + + + + + + + + + + + + + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/github.com/mmcdole/goxpp/index.html b/pkg/github.com/mmcdole/goxpp/index.html new file mode 100644 index 0000000..602cb8a --- /dev/null +++ b/pkg/github.com/mmcdole/goxpp/index.html @@ -0,0 +1,439 @@ + + + + + + + + xpp - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Package xpp

    + + + + + + + + + + + + + + +
    +
    +
    import "github.com/mmcdole/goxpp"
    +
    +
    +
    Overview
    +
    Index
    + + +
    +
    + +
    + +
    +

    Overview ▾

    + +
    +
    + + + + + + + + + + + + +

    type CharsetReader

    +
    type CharsetReader func(charset string, input io.Reader) (io.Reader, error)
    + + + + + + + + + + + + + + + + +

    type XMLEventType

    +
    type XMLEventType int
    + + + +
    const (
    +    StartDocument XMLEventType = iota
    +    EndDocument
    +    StartTag
    +    EndTag
    +    Text
    +    Comment
    +    ProcessingInstruction
    +    Directive
    +    IgnorableWhitespace // TODO: ?
    +
    +)
    + + + + + + + + + + + + + + + +

    type XMLPullParser

    +
    type XMLPullParser struct {
    +    // Document State
    +    Spaces map[string]string
    +
    +    // Token State
    +    Depth int
    +    Event XMLEventType
    +    Attrs []xml.Attr
    +    Name  string
    +    Space string
    +    Text  string
    +    // contains filtered or unexported fields
    +}
    + + + + + + + + + + + + +

    func NewXMLPullParser

    +
    func NewXMLPullParser(r io.Reader, strict bool, cr CharsetReader) *XMLPullParser
    + + + + + + + +

    func (*XMLPullParser) Attribute

    +
    func (p *XMLPullParser) Attribute(name string) string
    + + + + + + +

    func (*XMLPullParser) DecodeElement

    +
    func (p *XMLPullParser) DecodeElement(v interface{}) error
    + + + + + + +

    func (*XMLPullParser) EventName

    +
    func (p *XMLPullParser) EventName(e XMLEventType) (name string)
    + + + + + + +

    func (*XMLPullParser) EventType

    +
    func (p *XMLPullParser) EventType(t xml.Token) (event XMLEventType)
    + + + + + + +

    func (*XMLPullParser) Expect

    +
    func (p *XMLPullParser) Expect(event XMLEventType, name string) (err error)
    + + + + + + +

    func (*XMLPullParser) ExpectAll

    +
    func (p *XMLPullParser) ExpectAll(event XMLEventType, space string, name string) (err error)
    + + + + + + +

    func (*XMLPullParser) IsWhitespace

    +
    func (p *XMLPullParser) IsWhitespace() bool
    + + + + + + +

    func (*XMLPullParser) Next

    +
    func (p *XMLPullParser) Next() (event XMLEventType, err error)
    + + + + + + +

    func (*XMLPullParser) NextTag

    +
    func (p *XMLPullParser) NextTag() (event XMLEventType, err error)
    + + + + + + +

    func (*XMLPullParser) NextText

    +
    func (p *XMLPullParser) NextText() (string, error)
    + + + + + + +

    func (*XMLPullParser) NextToken

    +
    func (p *XMLPullParser) NextToken() (event XMLEventType, err error)
    + + + + + + +

    func (*XMLPullParser) Skip

    +
    func (p *XMLPullParser) Skip() error
    + + + + + + + + + + + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/github.com/mmcdole/index.html b/pkg/github.com/mmcdole/index.html new file mode 100644 index 0000000..b492899 --- /dev/null +++ b/pkg/github.com/mmcdole/index.html @@ -0,0 +1,196 @@ + + + + + + + + /src/github.com/mmcdole - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Directory /src/github.com/mmcdole

    + + + + + + + + + + + + + + + + + + + +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    NameSynopsis
    ..
    + gofeed + + +
    + atom + + +
    + cmd + + +
    + ftest + + +
    + extensions + + +
    + rss + + +
    + goxpp + + +
    +
    + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/github.com/peterbourgon/diskv/examples/content-addressable-store/index.html b/pkg/github.com/peterbourgon/diskv/examples/content-addressable-store/index.html new file mode 100644 index 0000000..838e081 --- /dev/null +++ b/pkg/github.com/peterbourgon/diskv/examples/content-addressable-store/index.html @@ -0,0 +1,106 @@ + + + + + + + + content-addressable-store - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Command content-addressable-store

    + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/github.com/peterbourgon/diskv/examples/index.html b/pkg/github.com/peterbourgon/diskv/examples/index.html new file mode 100644 index 0000000..5b83b72 --- /dev/null +++ b/pkg/github.com/peterbourgon/diskv/examples/index.html @@ -0,0 +1,141 @@ + + + + + + + + /src/github.com/peterbourgon/diskv/examples - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Directory /src/github.com/peterbourgon/diskv/examples

    + + + + + + + + + + + + + + + + + + + +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    NameSynopsis
    ..
    + content-addressable-store + + +
    + super-simple-store + + +
    +
    + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/github.com/peterbourgon/diskv/examples/super-simple-store/index.html b/pkg/github.com/peterbourgon/diskv/examples/super-simple-store/index.html new file mode 100644 index 0000000..c531ece --- /dev/null +++ b/pkg/github.com/peterbourgon/diskv/examples/super-simple-store/index.html @@ -0,0 +1,106 @@ + + + + + + + + super-simple-store - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Command super-simple-store

    + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/github.com/peterbourgon/diskv/index.html b/pkg/github.com/peterbourgon/diskv/index.html new file mode 100644 index 0000000..83cbb41 --- /dev/null +++ b/pkg/github.com/peterbourgon/diskv/index.html @@ -0,0 +1,802 @@ + + + + + + + + diskv - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Package diskv

    + + + + + + + + + + + + + + +
    +
    +
    import "github.com/peterbourgon/diskv"
    +
    +
    +
    Overview
    +
    Index
    + + +
    Subdirectories
    + +
    +
    + +
    + +
    +

    Overview ▾

    + +
    +
    + + +
    + +
    +

    Index ▾

    + + + + + + + +

    Package files

    +

    + + + compression.go + + diskv.go + + index.go + + +

    + +
    +
    + + + + + + + + + +

    type BTreeIndex

    +
    type BTreeIndex struct {
    +    sync.RWMutex
    +    LessFunction
    +    *btree.BTree
    +}
    +

    +BTreeIndex is an implementation of the Index interface using google/btree. +

    + + + + + + + + + + + + + + +

    func (*BTreeIndex) Delete

    +
    func (i *BTreeIndex) Delete(key string)
    +

    +Delete removes the given key (only) from the BTree tree. +

    + + + + + + +

    func (*BTreeIndex) Initialize

    +
    func (i *BTreeIndex) Initialize(less LessFunction, keys <-chan string)
    +

    +Initialize populates the BTree tree with data from the keys channel, +according to the passed less function. It's destructive to the BTreeIndex. +

    + + + + + + +

    func (*BTreeIndex) Insert

    +
    func (i *BTreeIndex) Insert(key string)
    +

    +Insert inserts the given key (only) into the BTree tree. +

    + + + + + + +

    func (*BTreeIndex) Keys

    +
    func (i *BTreeIndex) Keys(from string, n int) []string
    +

    +Keys yields a maximum of n keys in order. If the passed 'from' key is empty, +Keys will return the first n keys. If the passed 'from' key is non-empty, the +first key in the returned slice will be the key that immediately follows the +passed key, in key order. +

    + + + + + + + + +

    type Compression

    +
    type Compression interface {
    +    Writer(dst io.Writer) (io.WriteCloser, error)
    +    Reader(src io.Reader) (io.ReadCloser, error)
    +}
    +

    +Compression is an interface that Diskv uses to implement compression of +data. Writer takes a destination io.Writer and returns a WriteCloser that +compresses all data written through it. Reader takes a source io.Reader and +returns a ReadCloser that decompresses all data read through it. You may +define these methods on your own type, or use one of the NewCompression +helpers. +

    + + + + + + + + + + + + +

    func NewGzipCompression

    +
    func NewGzipCompression() Compression
    +

    +NewGzipCompression returns a Gzip-based Compression. +

    + + + + + +

    func NewGzipCompressionLevel

    +
    func NewGzipCompressionLevel(level int) Compression
    +

    +NewGzipCompressionLevel returns a Gzip-based Compression with the given level. +

    + + + + + +

    func NewZlibCompression

    +
    func NewZlibCompression() Compression
    +

    +NewZlibCompression returns a Zlib-based Compression. +

    + + + + + +

    func NewZlibCompressionLevel

    +
    func NewZlibCompressionLevel(level int) Compression
    +

    +NewZlibCompressionLevel returns a Zlib-based Compression with the given level. +

    + + + + + +

    func NewZlibCompressionLevelDict

    +
    func NewZlibCompressionLevelDict(level int, dict []byte) Compression
    +

    +NewZlibCompressionLevelDict returns a Zlib-based Compression with the given +level, based on the given dictionary. +

    + + + + + + + + + +

    type Diskv

    +
    type Diskv struct {
    +    Options
    +    // contains filtered or unexported fields
    +}
    +

    +Diskv implements the Diskv interface. You shouldn't construct Diskv +structures directly; instead, use the New constructor. +

    + + + + + + + + + + + + +

    func New

    +
    func New(o Options) *Diskv
    +

    +New returns an initialized Diskv structure, ready to use. +If the path identified by baseDir already contains data, +it will be accessible, but not yet cached. +

    + + + + + + + +

    func (*Diskv) Erase

    +
    func (d *Diskv) Erase(key string) error
    +

    +Erase synchronously erases the given key from the disk and the cache. +

    + + + + + + +

    func (*Diskv) EraseAll

    +
    func (d *Diskv) EraseAll() error
    +

    +EraseAll will delete all of the data from the store, both in the cache and on +the disk. Note that EraseAll doesn't distinguish diskv-related data from non- +diskv-related data. Care should be taken to always specify a diskv base +directory that is exclusively for diskv data. +

    + + + + + + +

    func (*Diskv) Has

    +
    func (d *Diskv) Has(key string) bool
    +

    +Has returns true if the given key exists. +

    + + + + + + +

    func (*Diskv) Import

    +
    func (d *Diskv) Import(srcFilename, dstKey string, move bool) (err error)
    +

    +Import imports the source file into diskv under the destination key. If the +destination key already exists, it's overwritten. If move is true, the +source file is removed after a successful import. +

    + + + + + + +

    func (*Diskv) Keys

    +
    func (d *Diskv) Keys(cancel <-chan struct{}) <-chan string
    +

    +Keys returns a channel that will yield every key accessible by the store, +in undefined order. If a cancel channel is provided, closing it will +terminate and close the keys channel. +

    + + + + + + +

    func (*Diskv) KeysPrefix

    +
    func (d *Diskv) KeysPrefix(prefix string, cancel <-chan struct{}) <-chan string
    +

    +KeysPrefix returns a channel that will yield every key accessible by the +store with the given prefix, in undefined order. If a cancel channel is +provided, closing it will terminate and close the keys channel. If the +provided prefix is the empty string, all keys will be yielded. +

    + + + + + + +

    func (*Diskv) Read

    +
    func (d *Diskv) Read(key string) ([]byte, error)
    +

    +Read reads the key and returns the value. +If the key is available in the cache, Read won't touch the disk. +If the key is not in the cache, Read will have the side-effect of +lazily caching the value. +

    + + + + + + +

    func (*Diskv) ReadStream

    +
    func (d *Diskv) ReadStream(key string, direct bool) (io.ReadCloser, error)
    +

    +ReadStream reads the key and returns the value (data) as an io.ReadCloser. +If the value is cached from a previous read, and direct is false, +ReadStream will use the cached value. Otherwise, it will return a handle to +the file on disk, and cache the data on read. +

    +

    +If direct is true, ReadStream will lazily delete any cached value for the +key, and return a direct handle to the file on disk. +

    +

    +If compression is enabled, ReadStream taps into the io.Reader stream prior +to decompression, and caches the compressed data. +

    + + + + + + +

    func (*Diskv) Write

    +
    func (d *Diskv) Write(key string, val []byte) error
    +

    +Write synchronously writes the key-value pair to disk, making it immediately +available for reads. Write relies on the filesystem to perform an eventual +sync to physical media. If you need stronger guarantees, see WriteStream. +

    + + + + + + +

    func (*Diskv) WriteStream

    +
    func (d *Diskv) WriteStream(key string, r io.Reader, sync bool) error
    +

    +WriteStream writes the data represented by the io.Reader to the disk, under +the provided key. If sync is true, WriteStream performs an explicit sync on +the file as soon as it's written. +

    +

    +bytes.Buffer provides io.Reader semantics for basic data types. +

    + + + + + + + + +

    type Index

    +
    type Index interface {
    +    Initialize(less LessFunction, keys <-chan string)
    +    Insert(key string)
    +    Delete(key string)
    +    Keys(from string, n int) []string
    +}
    +

    +Index is a generic interface for things that can +provide an ordered list of keys. +

    + + + + + + + + + + + + + + + + +

    type LessFunction

    +
    type LessFunction func(string, string) bool
    +

    +LessFunction is used to initialize an Index of keys in a specific order. +

    + + + + + + + + + + + + + + + + +

    type Options

    +
    type Options struct {
    +    BasePath     string
    +    Transform    TransformFunction
    +    CacheSizeMax uint64 // bytes
    +    PathPerm     os.FileMode
    +    FilePerm     os.FileMode
    +
    +    Index     Index
    +    IndexLess LessFunction
    +
    +    Compression Compression
    +}
    +

    +Options define a set of properties that dictate Diskv behavior. +All values are optional. +

    + + + + + + + + + + + + + + + + +

    type TransformFunction

    +
    type TransformFunction func(s string) []string
    +

    +TransformFunction transforms a key into a slice of strings, with each +element in the slice representing a directory in the file path where the +key's entry will eventually be stored. +

    +

    +For example, if TransformFunc transforms "abcdef" to ["ab", "cde", "f"], +the final location of the data file will be <basedir>/ab/cde/f/abcdef +

    + + + + + + + + + + + + + + + + + + + + + + + + +

    Subdirectories

    + + + + +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    NameSynopsis
    ..
    + examples + + +
    + content-addressable-store + + +
    + super-simple-store + + +
    +
    + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/github.com/peterbourgon/index.html b/pkg/github.com/peterbourgon/index.html new file mode 100644 index 0000000..9eb9e7e --- /dev/null +++ b/pkg/github.com/peterbourgon/index.html @@ -0,0 +1,163 @@ + + + + + + + + /src/github.com/peterbourgon - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Directory /src/github.com/peterbourgon

    + + + + + + + + + + + + + + + + + + + +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    NameSynopsis
    ..
    + diskv + + +
    + examples + + +
    + content-addressable-store + + +
    + super-simple-store + + +
    +
    + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/github.com/prometheus/client_golang/api/index.html b/pkg/github.com/prometheus/client_golang/api/index.html new file mode 100644 index 0000000..d55ebca --- /dev/null +++ b/pkg/github.com/prometheus/client_golang/api/index.html @@ -0,0 +1,130 @@ + + + + + + + + /src/github.com/prometheus/client_golang/api - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Directory /src/github.com/prometheus/client_golang/api

    + + + + + + + + + + + + + + + + + + + +
    + + + + + + + + + + + + + + + + + + + + +
    NameSynopsis
    ..
    + prometheus + + Package prometheus provides bindings to the Prometheus HTTP API: http://prometheus.io/docs/querying/api/ +
    +
    + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/github.com/prometheus/client_golang/api/prometheus/index.html b/pkg/github.com/prometheus/client_golang/api/prometheus/index.html new file mode 100644 index 0000000..250bade --- /dev/null +++ b/pkg/github.com/prometheus/client_golang/api/prometheus/index.html @@ -0,0 +1,482 @@ + + + + + + + + prometheus - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Package prometheus

    + + + + + + + + + + + + + + +
    +
    +
    import "github.com/prometheus/client_golang/api/prometheus"
    +
    +
    +
    Overview
    +
    Index
    + + +
    +
    + +
    + +
    +

    Overview ▾

    +

    +Package prometheus provides bindings to the Prometheus HTTP API: +http://prometheus.io/docs/querying/api/ +

    + +
    +
    + + +
    + +
    +

    Index ▾

    + + +
    +
    + + + + + +
    type CancelableTransport
    + + + + +
    type Client
    + + +
        func New(cfg Config) (Client, error)
    + + + + +
    type Config
    + + + + +
    type Error
    + + + +
        func (e *Error) Error() string
    + + + +
    type ErrorType
    + + + + +
    type QueryAPI
    + + +
        func NewQueryAPI(c Client) QueryAPI
    + + + + +
    type Range
    + + + + +
    +
    + + + + +

    Package files

    +

    + + + api.go + + +

    + +
    +
    + + + + + + + + + +

    type CancelableTransport

    +
    type CancelableTransport interface {
    +    http.RoundTripper
    +    CancelRequest(req *http.Request)
    +}
    +

    +CancelableTransport is like net.Transport but provides +per-request cancelation functionality. +

    + + + + + +
    var DefaultTransport CancelableTransport = &http.Transport{
    +    Proxy: http.ProxyFromEnvironment,
    +    Dial: (&net.Dialer{
    +        Timeout:   30 * time.Second,
    +        KeepAlive: 30 * time.Second,
    +    }).Dial,
    +    TLSHandshakeTimeout: 10 * time.Second,
    +}
    +

    +DefaultTransport is used if no Transport is set in Config. +

    + + + + + + + + + + + + + +

    type Client

    +
    type Client interface {
    +    // contains filtered or unexported methods
    +}
    +

    +Client is the interface for an API client. +

    + + + + + + + + + + + + +

    func New

    +
    func New(cfg Config) (Client, error)
    +

    +New returns a new Client. +

    +

    +It is safe to use the returned Client from multiple goroutines. +

    + + + + + + + + + +

    type Config

    +
    type Config struct {
    +    // The address of the Prometheus to connect to.
    +    Address string
    +
    +    // Transport is used by the Client to drive HTTP requests. If not
    +    // provided, DefaultTransport will be used.
    +    Transport CancelableTransport
    +}
    +

    +Config defines configuration parameters for a new client. +

    + + + + + + + + + + + + + + + + +

    type Error

    +
    type Error struct {
    +    Type ErrorType
    +    Msg  string
    +}
    +

    +Error is an error returned by the API. +

    + + + + + + + + + + + + + + +

    func (*Error) Error

    +
    func (e *Error) Error() string
    + + + + + + + + +

    type ErrorType

    +
    type ErrorType string
    +

    +ErrorType models the different API error types. +

    + + + +
    const (
    +    ErrBadData     ErrorType = "bad_data"
    +    ErrTimeout               = "timeout"
    +    ErrCanceled              = "canceled"
    +    ErrExec                  = "execution"
    +    ErrBadResponse           = "bad_response"
    +)
    +

    +Possible values for ErrorType. +

    + + + + + + + + + + + + + + + +

    type QueryAPI

    +
    type QueryAPI interface {
    +    // Query performs a query for the given time.
    +    Query(ctx context.Context, query string, ts time.Time) (model.Value, error)
    +    // Query performs a query for the given range.
    +    QueryRange(ctx context.Context, query string, r Range) (model.Value, error)
    +}
    +

    +QueryAPI provides bindings the Prometheus's query API. +

    + + + + + + + + + + + + +

    func NewQueryAPI

    +
    func NewQueryAPI(c Client) QueryAPI
    +

    +NewQueryAPI returns a new QueryAPI for the client. +

    +

    +It is safe to use the returned QueryAPI from multiple goroutines. +

    + + + + + + + + + +

    type Range

    +
    type Range struct {
    +    // The boundaries of the time range.
    +    Start, End time.Time
    +    // The maximum time between two slices within the boundaries.
    +    Step time.Duration
    +}
    +

    +Range represents a sliced time range. +

    + + + + + + + + + + + + + + + + + + + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/github.com/prometheus/client_golang/examples/index.html b/pkg/github.com/prometheus/client_golang/examples/index.html new file mode 100644 index 0000000..6a63e6f --- /dev/null +++ b/pkg/github.com/prometheus/client_golang/examples/index.html @@ -0,0 +1,141 @@ + + + + + + + + /src/github.com/prometheus/client_golang/examples - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Directory /src/github.com/prometheus/client_golang/examples

    + + + + + + + + + + + + + + + + + + + +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    NameSynopsis
    ..
    + random + + A simple example exposing fictional RPC latencies with different types of random distributions (uniform, normal, and exponential) as Prometheus metrics. +
    + simple + + A minimal example of how to include Prometheus instrumentation. +
    +
    + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/github.com/prometheus/client_golang/examples/random/index.html b/pkg/github.com/prometheus/client_golang/examples/random/index.html new file mode 100644 index 0000000..783276a --- /dev/null +++ b/pkg/github.com/prometheus/client_golang/examples/random/index.html @@ -0,0 +1,111 @@ + + + + + + + + random - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Command random

    + + + + + + + + + + + + + + +

    +A simple example exposing fictional RPC latencies with different types of +random distributions (uniform, normal, and exponential) as Prometheus +metrics. +

    + + + + + + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/github.com/prometheus/client_golang/examples/simple/index.html b/pkg/github.com/prometheus/client_golang/examples/simple/index.html new file mode 100644 index 0000000..f77ea7c --- /dev/null +++ b/pkg/github.com/prometheus/client_golang/examples/simple/index.html @@ -0,0 +1,109 @@ + + + + + + + + simple - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Command simple

    + + + + + + + + + + + + + + +

    +A minimal example of how to include Prometheus instrumentation. +

    + + + + + + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/github.com/prometheus/client_golang/index.html b/pkg/github.com/prometheus/client_golang/index.html new file mode 100644 index 0000000..16381f6 --- /dev/null +++ b/pkg/github.com/prometheus/client_golang/index.html @@ -0,0 +1,207 @@ + + + + + + + + /src/github.com/prometheus/client_golang - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Directory /src/github.com/prometheus/client_golang

    + + + + + + + + + + + + + + + + + + + +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    NameSynopsis
    ..
    + api + + +
    + prometheus + + Package prometheus provides bindings to the Prometheus HTTP API: http://prometheus.io/docs/querying/api/ +
    + examples + + +
    + random + + A simple example exposing fictional RPC latencies with different types of random distributions (uniform, normal, and exponential) as Prometheus metrics. +
    + simple + + A minimal example of how to include Prometheus instrumentation. +
    + prometheus + + Package prometheus provides metrics primitives to instrument code for monitoring. +
    + promhttp + + Package promhttp contains functions to create http.Handler instances to expose Prometheus metrics via HTTP. +
    + push + + Package push provides functions to push metrics to a Pushgateway. +
    +
    + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/github.com/prometheus/client_golang/prometheus/index.html b/pkg/github.com/prometheus/client_golang/prometheus/index.html new file mode 100644 index 0000000..c865a80 --- /dev/null +++ b/pkg/github.com/prometheus/client_golang/prometheus/index.html @@ -0,0 +1,4672 @@ + + + + + + + + prometheus - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Package prometheus

    + + + + + + + + + + + + + + +
    +
    +
    import "github.com/prometheus/client_golang/prometheus"
    +
    +
    +
    Overview
    +
    Index
    + +
    Examples
    + + +
    Subdirectories
    + +
    +
    + +
    + +
    +

    Overview ▾

    +

    +Package prometheus provides metrics primitives to instrument code for +monitoring. It also offers a registry for metrics. Sub-packages allow to +expose the registered metrics via HTTP (package promhttp) or push them to a +Pushgateway (package push). +

    +

    +All exported functions and methods are safe to be used concurrently unless +specified otherwise. +

    +

    A Basic Example

    +

    +As a starting point, a very basic usage example: +

    +
    package main
    +
    +import (
    +	"net/http"
    +
    +	"github.com/prometheus/client_golang/prometheus"
    +	"github.com/prometheus/client_golang/prometheus/promhttp"
    +)
    +
    +var (
    +	cpuTemp = prometheus.NewGauge(prometheus.GaugeOpts{
    +		Name: "cpu_temperature_celsius",
    +		Help: "Current temperature of the CPU.",
    +	})
    +	hdFailures = prometheus.NewCounterVec(
    +		prometheus.CounterOpts{
    +			Name: "hd_errors_total",
    +			Help: "Number of hard-disk errors.",
    +		},
    +		[]string{"device"},
    +	)
    +)
    +
    +func init() {
    +	// Metrics have to be registered to be exposed:
    +	prometheus.MustRegister(cpuTemp)
    +	prometheus.MustRegister(hdFailures)
    +}
    +
    +func main() {
    +	cpuTemp.Set(65.3)
    +	hdFailures.With(prometheus.Labels{"device":"/dev/sda"}).Inc()
    +
    +	// The Handler function provides a default handler to expose metrics
    +	// via an HTTP server. "/metrics" is the usual endpoint for that.
    +	http.Handle("/metrics", promhttp.Handler())
    +	http.ListenAndServe(":8080", nil)
    +}
    +
    +

    +This is a complete program that exports two metrics, a Gauge and a Counter, +the latter with a label attached to turn it into a (one-dimensional) vector. +

    +

    Metrics

    +

    +The number of exported identifiers in this package might appear a bit +overwhelming. Hovever, in addition to the basic plumbing shown in the example +above, you only need to understand the different metric types and their +vector versions for basic usage. +

    +

    +Above, you have already touched the Counter and the Gauge. There are two more +advanced metric types: the Summary and Histogram. A more thorough description +of those four metric types can be found in the Prometheus docs: +https://prometheus.io/docs/concepts/metric_types/ +

    +

    +A fifth "type" of metric is Untyped. It behaves like a Gauge, but signals the +Prometheus server not to assume anything about its type. +

    +

    +In addition to the fundamental metric types Gauge, Counter, Summary, +Histogram, and Untyped, a very important part of the Prometheus data model is +the partitioning of samples along dimensions called labels, which results in +metric vectors. The fundamental types are GaugeVec, CounterVec, SummaryVec, +HistogramVec, and UntypedVec. +

    +

    +While only the fundamental metric types implement the Metric interface, both +the metrics and their vector versions implement the Collector interface. A +Collector manages the collection of a number of Metrics, but for convenience, +a Metric can also “collect itself”. Note that Gauge, Counter, Summary, +Histogram, and Untyped are interfaces themselves while GaugeVec, CounterVec, +SummaryVec, HistogramVec, and UntypedVec are not. +

    +

    +To create instances of Metrics and their vector versions, you need a suitable +…Opts struct, i.e. GaugeOpts, CounterOpts, SummaryOpts, +HistogramOpts, or UntypedOpts. +

    +

    Custom Collectors and constant Metrics

    +

    +While you could create your own implementations of Metric, most likely you +will only ever implement the Collector interface on your own. At a first +glance, a custom Collector seems handy to bundle Metrics for common +registration (with the prime example of the different metric vectors above, +which bundle all the metrics of the same name but with different labels). +

    +

    +There is a more involved use case, too: If you already have metrics +available, created outside of the Prometheus context, you don't need the +interface of the various Metric types. You essentially want to mirror the +existing numbers into Prometheus Metrics during collection. An own +implementation of the Collector interface is perfect for that. You can create +Metric instances “on the fly” using NewConstMetric, NewConstHistogram, and +NewConstSummary (and their respective Must… versions). That will happen in +the Collect method. The Describe method has to return separate Desc +instances, representative of the “throw-away” metrics to be created +later. NewDesc comes in handy to create those Desc instances. +

    +

    +The Collector example illustrates the use case. You can also look at the +source code of the processCollector (mirroring process metrics), the +goCollector (mirroring Go metrics), or the expvarCollector (mirroring expvar +metrics) as examples that are used in this package itself. +

    +

    +If you just need to call a function to get a single float value to collect as +a metric, GaugeFunc, CounterFunc, or UntypedFunc might be interesting +shortcuts. +

    +

    Advanced Uses of the Registry

    +

    +While MustRegister is the by far most common way of registering a Collector, +sometimes you might want to handle the errors the registration might +cause. As suggested by the name, MustRegister panics if an error occurs. With +the Register function, the error is returned and can be handled. +

    +

    +An error is returned if the registered Collector is incompatible or +inconsistent with already registered metrics. The registry aims for +consistency of the collected metrics according to the Prometheus data +model. Inconsistencies are ideally detected at registration time, not at +collect time. The former will usually be detected at start-up time of a +program, while the latter will only happen at scrape time, possibly not even +on the first scrape if the inconsistency only becomes relevant later. That is +the main reason why a Collector and a Metric have to describe themselves to +the registry. +

    +

    +So far, everything we did operated on the so-called default registry, as it +can be found in the global DefaultRegistry variable. With NewRegistry, you +can create a custom registry, or you can even implement the Registerer or +Gatherer interfaces yourself. The methods Register and Unregister work in +the same way on a custom registry as the global functions Register and +Unregister on the default registry. +

    +

    +There are a number of uses for custom registries: You can use registries +with special properties, see NewPedanticRegistry. You can avoid global state, +as it is imposed by the DefaultRegistry. You can use multiple registries at +the same time to expose different metrics in different ways. You can use +separate registries for testing purposes. +

    +

    +Also note that the DefaultRegistry comes registered with a Collector for Go +runtime metrics (via NewGoCollector) and a Collector for process metrics (via +NewProcessCollector). With a custom registry, you are in control and decide +yourself about the Collectors to register. +

    +

    HTTP Exposition

    +

    +The Registry implements the Gatherer interface. The caller of the Gather +method can then expose the gathered metrics in some way. Usually, the metrics +are served via HTTP on the /metrics endpoint. That's happening in the example +above. The tools to expose metrics via HTTP are in the promhttp +sub-package. (The top-level functions in the prometheus package are +deprecated.) +

    +

    Pushing to the Pushgateway

    +

    +Function for pushing to the Pushgateway can be found in the push sub-package. +

    +

    Other Means of Exposition

    +

    +More ways of exposing metrics can easily be added. Sending metrics to +Graphite would be an example that will soon be implemented. +

    + +
    +
    + + +
    + +
    +

    Index ▾

    + + +
    +
    + +
    Constants
    + + +
    Variables
    + + + +
    func BuildFQName(namespace, subsystem, name string) string
    + + +
    func ExponentialBuckets(start, factor float64, count int) []float64
    + + +
    func Handler() http.Handler
    + + +
    func InstrumentHandler(handlerName string, handler http.Handler) http.HandlerFunc
    + + +
    func InstrumentHandlerFunc(handlerName string, handlerFunc func(http.ResponseWriter, *http.Request)) http.HandlerFunc
    + + +
    func InstrumentHandlerFuncWithOpts(opts SummaryOpts, handlerFunc func(http.ResponseWriter, *http.Request)) http.HandlerFunc
    + + +
    func InstrumentHandlerWithOpts(opts SummaryOpts, handler http.Handler) http.HandlerFunc
    + + +
    func LinearBuckets(start, width float64, count int) []float64
    + + +
    func MustRegister(cs ...Collector)
    + + +
    func Register(c Collector) error
    + + +
    func SetMetricFamilyInjectionHook(hook func() []*dto.MetricFamily)
    + + +
    func UninstrumentedHandler() http.Handler
    + + +
    func Unregister(c Collector) bool
    + + + +
    type AlreadyRegisteredError
    + + + +
        func (err AlreadyRegisteredError) Error() string
    + + + +
    type Collector
    + + +
        func MustRegisterOrGet(c Collector) Collector
    + + +
        func NewExpvarCollector(exports map[string]*Desc) Collector
    + + +
        func NewGoCollector() Collector
    + + +
        func NewProcessCollector(pid int, namespace string) Collector
    + + +
        func NewProcessCollectorPIDFn(pidFn func() (int, error), namespace string) Collector
    + + +
        func RegisterOrGet(c Collector) (Collector, error)
    + + + + +
    type Counter
    + + +
        func NewCounter(opts CounterOpts) Counter
    + + + + +
    type CounterFunc
    + + +
        func NewCounterFunc(opts CounterOpts, function func() float64) CounterFunc
    + + + + +
    type CounterOpts
    + + + + +
    type CounterVec
    + + +
        func NewCounterVec(opts CounterOpts, labelNames []string) *CounterVec
    + + + +
        func (m *CounterVec) GetMetricWith(labels Labels) (Counter, error)
    + + +
        func (m *CounterVec) GetMetricWithLabelValues(lvs ...string) (Counter, error)
    + + +
        func (m *CounterVec) With(labels Labels) Counter
    + + +
        func (m *CounterVec) WithLabelValues(lvs ...string) Counter
    + + + +
    type Desc
    + + +
        func NewDesc(fqName, help string, variableLabels []string, constLabels Labels) *Desc
    + + +
        func NewInvalidDesc(err error) *Desc
    + + + +
        func (d *Desc) String() string
    + + + +
    type Gatherer
    + + + + +
    type GathererFunc
    + + + +
        func (gf GathererFunc) Gather() ([]*dto.MetricFamily, error)
    + + + +
    type Gatherers
    + + + +
        func (gs Gatherers) Gather() ([]*dto.MetricFamily, error)
    + + + +
    type Gauge
    + + +
        func NewGauge(opts GaugeOpts) Gauge
    + + + + +
    type GaugeFunc
    + + +
        func NewGaugeFunc(opts GaugeOpts, function func() float64) GaugeFunc
    + + + + +
    type GaugeOpts
    + + + + +
    type GaugeVec
    + + +
        func NewGaugeVec(opts GaugeOpts, labelNames []string) *GaugeVec
    + + + +
        func (m *GaugeVec) GetMetricWith(labels Labels) (Gauge, error)
    + + +
        func (m *GaugeVec) GetMetricWithLabelValues(lvs ...string) (Gauge, error)
    + + +
        func (m *GaugeVec) With(labels Labels) Gauge
    + + +
        func (m *GaugeVec) WithLabelValues(lvs ...string) Gauge
    + + + +
    type Histogram
    + + +
        func NewHistogram(opts HistogramOpts) Histogram
    + + + + +
    type HistogramOpts
    + + + + +
    type HistogramVec
    + + +
        func NewHistogramVec(opts HistogramOpts, labelNames []string) *HistogramVec
    + + + +
        func (m *HistogramVec) GetMetricWith(labels Labels) (Histogram, error)
    + + +
        func (m *HistogramVec) GetMetricWithLabelValues(lvs ...string) (Histogram, error)
    + + +
        func (m *HistogramVec) With(labels Labels) Histogram
    + + +
        func (m *HistogramVec) WithLabelValues(lvs ...string) Histogram
    + + + +
    type LabelPairSorter
    + + + +
        func (s LabelPairSorter) Len() int
    + + +
        func (s LabelPairSorter) Less(i, j int) bool
    + + +
        func (s LabelPairSorter) Swap(i, j int)
    + + + +
    type Labels
    + + + + +
    type Metric
    + + +
        func MustNewConstHistogram(desc *Desc, count uint64, sum float64, buckets map[float64]uint64, labelValues ...string) Metric
    + + +
        func MustNewConstMetric(desc *Desc, valueType ValueType, value float64, labelValues ...string) Metric
    + + +
        func MustNewConstSummary(desc *Desc, count uint64, sum float64, quantiles map[float64]float64, labelValues ...string) Metric
    + + +
        func NewConstHistogram(desc *Desc, count uint64, sum float64, buckets map[float64]uint64, labelValues ...string) (Metric, error)
    + + +
        func NewConstMetric(desc *Desc, valueType ValueType, value float64, labelValues ...string) (Metric, error)
    + + +
        func NewConstSummary(desc *Desc, count uint64, sum float64, quantiles map[float64]float64, labelValues ...string) (Metric, error)
    + + +
        func NewInvalidMetric(desc *Desc, err error) Metric
    + + + + +
    type MetricVec
    + + + +
        func (m *MetricVec) Collect(ch chan<- Metric)
    + + +
        func (m *MetricVec) Delete(labels Labels) bool
    + + +
        func (m *MetricVec) DeleteLabelValues(lvs ...string) bool
    + + +
        func (m *MetricVec) Describe(ch chan<- *Desc)
    + + +
        func (m *MetricVec) GetMetricWith(labels Labels) (Metric, error)
    + + +
        func (m *MetricVec) GetMetricWithLabelValues(lvs ...string) (Metric, error)
    + + +
        func (m *MetricVec) Reset()
    + + +
        func (m *MetricVec) With(labels Labels) Metric
    + + +
        func (m *MetricVec) WithLabelValues(lvs ...string) Metric
    + + + +
    type MultiError
    + + + +
        func (errs MultiError) Error() string
    + + +
        func (errs MultiError) MaybeUnwrap() error
    + + + +
    type Opts
    + + + + +
    type Registerer
    + + + + +
    type Registry
    + + +
        func NewPedanticRegistry() *Registry
    + + +
        func NewRegistry() *Registry
    + + + +
        func (r *Registry) Gather() ([]*dto.MetricFamily, error)
    + + +
        func (r *Registry) MustRegister(cs ...Collector)
    + + +
        func (r *Registry) Register(c Collector) error
    + + +
        func (r *Registry) Unregister(c Collector) bool
    + + + +
    type Summary
    + + +
        func NewSummary(opts SummaryOpts) Summary
    + + + + +
    type SummaryOpts
    + + + + +
    type SummaryVec
    + + +
        func NewSummaryVec(opts SummaryOpts, labelNames []string) *SummaryVec
    + + + +
        func (m *SummaryVec) GetMetricWith(labels Labels) (Summary, error)
    + + +
        func (m *SummaryVec) GetMetricWithLabelValues(lvs ...string) (Summary, error)
    + + +
        func (m *SummaryVec) With(labels Labels) Summary
    + + +
        func (m *SummaryVec) WithLabelValues(lvs ...string) Summary
    + + + +
    type Untyped
    + + +
        func NewUntyped(opts UntypedOpts) Untyped
    + + + + +
    type UntypedFunc
    + + +
        func NewUntypedFunc(opts UntypedOpts, function func() float64) UntypedFunc
    + + + + +
    type UntypedOpts
    + + + + +
    type UntypedVec
    + + +
        func NewUntypedVec(opts UntypedOpts, labelNames []string) *UntypedVec
    + + + +
        func (m *UntypedVec) GetMetricWith(labels Labels) (Untyped, error)
    + + +
        func (m *UntypedVec) GetMetricWithLabelValues(lvs ...string) (Untyped, error)
    + + +
        func (m *UntypedVec) With(labels Labels) Untyped
    + + +
        func (m *UntypedVec) WithLabelValues(lvs ...string) Untyped
    + + + +
    type ValueType
    + + + + +
    +
    + + + + + + +

    Package files

    +

    + + + collector.go + + counter.go + + desc.go + + doc.go + + expvar_collector.go + + fnv.go + + gauge.go + + go_collector.go + + histogram.go + + http.go + + metric.go + + process_collector.go + + registry.go + + summary.go + + untyped.go + + value.go + + vec.go + + +

    + +
    +
    + + + + +

    Constants

    + +
    const (
    +    // DefMaxAge is the default duration for which observations stay
    +    // relevant.
    +    DefMaxAge time.Duration = 10 * time.Minute
    +    // DefAgeBuckets is the default number of buckets used to calculate the
    +    // age of observations.
    +    DefAgeBuckets = 5
    +    // DefBufCap is the standard buffer size for collecting Summary observations.
    +    DefBufCap = 500
    +)
    +

    +Default values for SummaryOpts. +

    + + + + +

    Variables

    + +
    var (
    +    DefaultRegisterer Registerer = defaultRegistry
    +    DefaultGatherer   Gatherer   = defaultRegistry
    +)
    +

    +DefaultRegisterer and DefaultGatherer are the implementations of the +Registerer and Gatherer interface a number of convenience functions in this +package act on. Initially, both variables point to the same Registry, which +has a process collector (see NewProcessCollector) and a Go collector (see +NewGoCollector) already registered. This approach to keep default instances +as global state mirrors the approach of other packages in the Go standard +library. Note that there are caveats. Change the variables with caution and +only if you understand the consequences. Users who want to avoid global state +altogether should not use the convenience function and act on custom +instances instead. +

    + + +
    var (
    +    DefBuckets = []float64{.005, .01, .025, .05, .1, .25, .5, 1, 2.5, 5, 10}
    +)
    +

    +DefBuckets are the default Histogram buckets. The default buckets are +tailored to broadly measure the response time (in seconds) of a network +service. Most likely, however, you will be required to define buckets +customized to your use case. +

    + + +
    var (
    +    DefObjectives = map[float64]float64{0.5: 0.05, 0.9: 0.01, 0.99: 0.001}
    +)
    +

    +DefObjectives are the default Summary quantile values. +

    + + + + + + +

    func BuildFQName

    +
    func BuildFQName(namespace, subsystem, name string) string
    +

    +BuildFQName joins the given three name components by "_". Empty name +components are ignored. If the name parameter itself is empty, an empty +string is returned, no matter what. Metric implementations included in this +library use this function internally to generate the fully-qualified metric +name from the name component in their Opts. Users of the library will only +need this function if they implement their own Metric or instantiate a Desc +(with NewDesc) directly. +

    + + + + + + + +

    func ExponentialBuckets

    +
    func ExponentialBuckets(start, factor float64, count int) []float64
    +

    +ExponentialBuckets creates 'count' buckets, where the lowest bucket has an +upper bound of 'start' and each following bucket's upper bound is 'factor' +times the previous bucket's upper bound. The final +Inf bucket is not counted +and not included in the returned slice. The returned slice is meant to be +used for the Buckets field of HistogramOpts. +

    +

    +The function panics if 'count' is 0 or negative, if 'start' is 0 or negative, +or if 'factor' is less than or equal 1. +

    + + + + + + + +

    func Handler

    +
    func Handler() http.Handler
    +

    +Handler returns an HTTP handler for the DefaultGatherer. It is +already instrumented with InstrumentHandler (using "prometheus" as handler +name). +

    +

    +Deprecated: Please note the issues described in the doc comment of +InstrumentHandler. You might want to consider using promhttp.Handler instead +(which is non instrumented). +

    + + + + + + + +

    func InstrumentHandler

    +
    func InstrumentHandler(handlerName string, handler http.Handler) http.HandlerFunc
    +

    +InstrumentHandler wraps the given HTTP handler for instrumentation. It +registers four metric collectors (if not already done) and reports HTTP +metrics to the (newly or already) registered collectors: http_requests_total +(CounterVec), http_request_duration_microseconds (Summary), +http_request_size_bytes (Summary), http_response_size_bytes (Summary). Each +has a constant label named "handler" with the provided handlerName as +value. http_requests_total is a metric vector partitioned by HTTP method +(label name "method") and HTTP status code (label name "code"). +

    +

    +Deprecated: InstrumentHandler has several issues: +

    +

    +- It uses Summaries rather than Histograms. Summaries are not useful if +aggregation across multiple instances is required. +

    +

    +- It uses microseconds as unit, which is deprecated and should be replaced by +seconds. +

    +

    +- The size of the request is calculated in a separate goroutine. Since this +calculator requires access to the request header, it creates a race with +any writes to the header performed during request handling. +httputil.ReverseProxy is a prominent example for a handler +performing such writes. +

    +

    +Upcoming versions of this package will provide ways of instrumenting HTTP +handlers that are more flexible and have fewer issues. Please prefer direct +instrumentation in the meantime. +

    + +
    + +
    +

    Example

    + + + +

    Code:

    +
    +// Handle the "/doc" endpoint with the standard http.FileServer handler.
    +// By wrapping the handler with InstrumentHandler, request count,
    +// request and response sizes, and request latency are automatically
    +// exported to Prometheus, partitioned by HTTP status code and method
    +// and by the handler name (here "fileserver").
    +http.Handle("/doc", prometheus.InstrumentHandler(
    +    "fileserver", http.FileServer(http.Dir("/usr/share/doc")),
    +))
    +// The Prometheus handler still has to be registered to handle the
    +// "/metrics" endpoint. The handler returned by prometheus.Handler() is
    +// already instrumented - with "prometheus" as the handler name. In this
    +// example, we want the handler name to be "metrics", so we instrument
    +// the uninstrumented Prometheus handler ourselves.
    +http.Handle("/metrics", prometheus.InstrumentHandler(
    +    "metrics", prometheus.UninstrumentedHandler(),
    +))
    +
    + + +
    +
    + + + + + + +

    func InstrumentHandlerFunc

    +
    func InstrumentHandlerFunc(handlerName string, handlerFunc func(http.ResponseWriter, *http.Request)) http.HandlerFunc
    +

    +InstrumentHandlerFunc wraps the given function for instrumentation. It +otherwise works in the same way as InstrumentHandler (and shares the same +issues). +

    +

    +Deprecated: InstrumentHandlerFunc is deprecated for the same reasons as +InstrumentHandler is. +

    + + + + + + + +

    func InstrumentHandlerFuncWithOpts

    +
    func InstrumentHandlerFuncWithOpts(opts SummaryOpts, handlerFunc func(http.ResponseWriter, *http.Request)) http.HandlerFunc
    +

    +InstrumentHandlerFuncWithOpts works like InstrumentHandlerFunc (and shares +the same issues) but provides more flexibility (at the cost of a more complex +call syntax). See InstrumentHandlerWithOpts for details how the provided +SummaryOpts are used. +

    +

    +Deprecated: InstrumentHandlerFuncWithOpts is deprecated for the same reasons +as InstrumentHandler is. +

    + + + + + + + +

    func InstrumentHandlerWithOpts

    +
    func InstrumentHandlerWithOpts(opts SummaryOpts, handler http.Handler) http.HandlerFunc
    +

    +InstrumentHandlerWithOpts works like InstrumentHandler (and shares the same +issues) but provides more flexibility (at the cost of a more complex call +syntax). As InstrumentHandler, this function registers four metric +collectors, but it uses the provided SummaryOpts to create them. However, the +fields "Name" and "Help" in the SummaryOpts are ignored. "Name" is replaced +by "requests_total", "request_duration_microseconds", "request_size_bytes", +and "response_size_bytes", respectively. "Help" is replaced by an appropriate +help string. The names of the variable labels of the http_requests_total +CounterVec are "method" (get, post, etc.), and "code" (HTTP status code). +

    +

    +If InstrumentHandlerWithOpts is called as follows, it mimics exactly the +behavior of InstrumentHandler: +

    +
    prometheus.InstrumentHandlerWithOpts(
    +    prometheus.SummaryOpts{
    +         Subsystem:   "http",
    +         ConstLabels: prometheus.Labels{"handler": handlerName},
    +    },
    +    handler,
    +)
    +
    +

    +Technical detail: "requests_total" is a CounterVec, not a SummaryVec, so it +cannot use SummaryOpts. Instead, a CounterOpts struct is created internally, +and all its fields are set to the equally named fields in the provided +SummaryOpts. +

    +

    +Deprecated: InstrumentHandlerWithOpts is deprecated for the same reasons as +InstrumentHandler is. +

    + + + + + + + +

    func LinearBuckets

    +
    func LinearBuckets(start, width float64, count int) []float64
    +

    +LinearBuckets creates 'count' buckets, each 'width' wide, where the lowest +bucket has an upper bound of 'start'. The final +Inf bucket is not counted +and not included in the returned slice. The returned slice is meant to be +used for the Buckets field of HistogramOpts. +

    +

    +The function panics if 'count' is zero or negative. +

    + + + + + + + +

    func MustRegister

    +
    func MustRegister(cs ...Collector)
    +

    +MustRegister registers the provided Collectors with the DefaultRegisterer and +panics if any error occurs. +

    +

    +MustRegister is a shortcut for DefaultRegisterer.MustRegister(cs...). See +there for more details. +

    + + + + + + + +

    func Register

    +
    func Register(c Collector) error
    +

    +Register registers the provided Collector with the DefaultRegisterer. +

    +

    +Register is a shortcut for DefaultRegisterer.Register(c). See there for more +details. +

    + +
    + +
    +

    Example

    + + + +

    Code:

    +
    // Imagine you have a worker pool and want to count the tasks completed.
    +taskCounter := prometheus.NewCounter(prometheus.CounterOpts{
    +    Subsystem: "worker_pool",
    +    Name:      "completed_tasks_total",
    +    Help:      "Total number of tasks completed.",
    +})
    +// This will register fine.
    +if err := prometheus.Register(taskCounter); err != nil {
    +    fmt.Println(err)
    +} else {
    +    fmt.Println("taskCounter registered.")
    +}
    +// Don't forget to tell the HTTP server about the Prometheus handler.
    +// (In a real program, you still need to start the HTTP server...)
    +http.Handle("/metrics", prometheus.Handler())
    +
    +// Now you can start workers and give every one of them a pointer to
    +// taskCounter and let it increment it whenever it completes a task.
    +taskCounter.Inc() // This has to happen somewhere in the worker code.
    +
    +// But wait, you want to see how individual workers perform. So you need
    +// a vector of counters, with one element for each worker.
    +taskCounterVec := prometheus.NewCounterVec(
    +    prometheus.CounterOpts{
    +        Subsystem: "worker_pool",
    +        Name:      "completed_tasks_total",
    +        Help:      "Total number of tasks completed.",
    +    },
    +    []string{"worker_id"},
    +)
    +
    +// Registering will fail because we already have a metric of that name.
    +if err := prometheus.Register(taskCounterVec); err != nil {
    +    fmt.Println("taskCounterVec not registered:", err)
    +} else {
    +    fmt.Println("taskCounterVec registered.")
    +}
    +
    +// To fix, first unregister the old taskCounter.
    +if prometheus.Unregister(taskCounter) {
    +    fmt.Println("taskCounter unregistered.")
    +}
    +
    +// Try registering taskCounterVec again.
    +if err := prometheus.Register(taskCounterVec); err != nil {
    +    fmt.Println("taskCounterVec not registered:", err)
    +} else {
    +    fmt.Println("taskCounterVec registered.")
    +}
    +// Bummer! Still doesn't work.
    +
    +// Prometheus will not allow you to ever export metrics with
    +// inconsistent help strings or label names. After unregistering, the
    +// unregistered metrics will cease to show up in the /metrics HTTP
    +// response, but the registry still remembers that those metrics had
    +// been exported before. For this example, we will now choose a
    +// different name. (In a real program, you would obviously not export
    +// the obsolete metric in the first place.)
    +taskCounterVec = prometheus.NewCounterVec(
    +    prometheus.CounterOpts{
    +        Subsystem: "worker_pool",
    +        Name:      "completed_tasks_by_id",
    +        Help:      "Total number of tasks completed.",
    +    },
    +    []string{"worker_id"},
    +)
    +if err := prometheus.Register(taskCounterVec); err != nil {
    +    fmt.Println("taskCounterVec not registered:", err)
    +} else {
    +    fmt.Println("taskCounterVec registered.")
    +}
    +// Finally it worked!
    +
    +// The workers have to tell taskCounterVec their id to increment the
    +// right element in the metric vector.
    +taskCounterVec.WithLabelValues("42").Inc() // Code from worker 42.
    +
    +// Each worker could also keep a reference to their own counter element
    +// around. Pick the counter at initialization time of the worker.
    +myCounter := taskCounterVec.WithLabelValues("42") // From worker 42 initialization code.
    +myCounter.Inc()                                   // Somewhere in the code of that worker.
    +
    +// Note that something like WithLabelValues("42", "spurious arg") would
    +// panic (because you have provided too many label values). If you want
    +// to get an error instead, use GetMetricWithLabelValues(...) instead.
    +notMyCounter, err := taskCounterVec.GetMetricWithLabelValues("42", "spurious arg")
    +if err != nil {
    +    fmt.Println("Worker initialization failed:", err)
    +}
    +if notMyCounter == nil {
    +    fmt.Println("notMyCounter is nil.")
    +}
    +
    +// A different (and somewhat tricky) approach is to use
    +// ConstLabels. ConstLabels are pairs of label names and label values
    +// that never change. You might ask what those labels are good for (and
    +// rightfully so - if they never change, they could as well be part of
    +// the metric name). There are essentially two use-cases: The first is
    +// if labels are constant throughout the lifetime of a binary execution,
    +// but they vary over time or between different instances of a running
    +// binary. The second is what we have here: Each worker creates and
    +// registers an own Counter instance where the only difference is in the
    +// value of the ConstLabels. Those Counters can all be registered
    +// because the different ConstLabel values guarantee that each worker
    +// will increment a different Counter metric.
    +counterOpts := prometheus.CounterOpts{
    +    Subsystem:   "worker_pool",
    +    Name:        "completed_tasks",
    +    Help:        "Total number of tasks completed.",
    +    ConstLabels: prometheus.Labels{"worker_id": "42"},
    +}
    +taskCounterForWorker42 := prometheus.NewCounter(counterOpts)
    +if err := prometheus.Register(taskCounterForWorker42); err != nil {
    +    fmt.Println("taskCounterVForWorker42 not registered:", err)
    +} else {
    +    fmt.Println("taskCounterForWorker42 registered.")
    +}
    +// Obviously, in real code, taskCounterForWorker42 would be a member
    +// variable of a worker struct, and the "42" would be retrieved with a
    +// GetId() method or something. The Counter would be created and
    +// registered in the initialization code of the worker.
    +
    +// For the creation of the next Counter, we can recycle
    +// counterOpts. Just change the ConstLabels.
    +counterOpts.ConstLabels = prometheus.Labels{"worker_id": "2001"}
    +taskCounterForWorker2001 := prometheus.NewCounter(counterOpts)
    +if err := prometheus.Register(taskCounterForWorker2001); err != nil {
    +    fmt.Println("taskCounterVForWorker2001 not registered:", err)
    +} else {
    +    fmt.Println("taskCounterForWorker2001 registered.")
    +}
    +
    +taskCounterForWorker2001.Inc()
    +taskCounterForWorker42.Inc()
    +taskCounterForWorker2001.Inc()
    +
    +// Yet another approach would be to turn the workers themselves into
    +// Collectors and register them. See the Collector example for details.
    +
    +
    + +

    Output:

    +
    taskCounter registered.
    +taskCounterVec not registered: a previously registered descriptor with the same fully-qualified name as Desc{fqName: "worker_pool_completed_tasks_total", help: "Total number of tasks completed.", constLabels: {}, variableLabels: [worker_id]} has different label names or a different help string
    +taskCounter unregistered.
    +taskCounterVec not registered: a previously registered descriptor with the same fully-qualified name as Desc{fqName: "worker_pool_completed_tasks_total", help: "Total number of tasks completed.", constLabels: {}, variableLabels: [worker_id]} has different label names or a different help string
    +taskCounterVec registered.
    +Worker initialization failed: inconsistent label cardinality
    +notMyCounter is nil.
    +taskCounterForWorker42 registered.
    +taskCounterForWorker2001 registered.
    +
    + + +
    +
    + + + + + + +

    func SetMetricFamilyInjectionHook

    +
    func SetMetricFamilyInjectionHook(hook func() []*dto.MetricFamily)
    +

    +SetMetricFamilyInjectionHook replaces the DefaultGatherer with one that +gathers from the previous DefaultGatherers but then merges the MetricFamily +protobufs returned from the provided hook function with the MetricFamily +protobufs returned from the original DefaultGatherer. +

    +

    +Deprecated: This function manipulates the DefaultGatherer variable. Consider +the implications, i.e. don't do this concurrently with any uses of the +DefaultGatherer. In the rare cases where you need to inject MetricFamily +protobufs directly, it is recommended to use a custom Registry and combine it +with a custom Gatherer using the Gatherers type (see +there). SetMetricFamilyInjectionHook only exists for compatibility reasons +with previous versions of this package. +

    + + + + + + + +

    func UninstrumentedHandler

    +
    func UninstrumentedHandler() http.Handler
    +

    +UninstrumentedHandler returns an HTTP handler for the DefaultGatherer. +

    +

    +Deprecated: Use promhttp.Handler instead. See there for further documentation. +

    + + + + + + + +

    func Unregister

    +
    func Unregister(c Collector) bool
    +

    +Unregister removes the registration of the provided Collector from the +DefaultRegisterer. +

    +

    +Unregister is a shortcut for DefaultRegisterer.Unregister(c). See there for +more details. +

    + + + + + + + + +

    type AlreadyRegisteredError

    +
    type AlreadyRegisteredError struct {
    +    ExistingCollector, NewCollector Collector
    +}
    +

    +AlreadyRegisteredError is returned by the Register method if the Collector to +be registered has already been registered before, or a different Collector +that collects the same metrics has been registered before. Registration fails +in that case, but you can detect from the kind of error what has +happened. The error contains fields for the existing Collector and the +(rejected) new Collector that equals the existing one. This can be used to +find out if an equal Collector has been registered before and switch over to +using the old one, as demonstrated in the example. +

    + + + + + + +
    + +
    +

    Example

    + + + +

    Code:

    +
    +reqCounter := prometheus.NewCounter(prometheus.CounterOpts{
    +    Name: "requests_total",
    +    Help: "The total number of requests served.",
    +})
    +if err := prometheus.Register(reqCounter); err != nil {
    +    if are, ok := err.(prometheus.AlreadyRegisteredError); ok {
    +        // A counter for that metric has been registered before.
    +        // Use the old counter from now on.
    +        reqCounter = are.ExistingCollector.(prometheus.Counter)
    +    } else {
    +        // Something else went wrong!
    +        panic(err)
    +    }
    +}
    +reqCounter.Inc()
    +
    + + +
    +
    + + + + + + + + +

    func (AlreadyRegisteredError) Error

    +
    func (err AlreadyRegisteredError) Error() string
    + + + + + + + + +

    type Collector

    +
    type Collector interface {
    +    // Describe sends the super-set of all possible descriptors of metrics
    +    // collected by this Collector to the provided channel and returns once
    +    // the last descriptor has been sent. The sent descriptors fulfill the
    +    // consistency and uniqueness requirements described in the Desc
    +    // documentation. (It is valid if one and the same Collector sends
    +    // duplicate descriptors. Those duplicates are simply ignored. However,
    +    // two different Collectors must not send duplicate descriptors.) This
    +    // method idempotently sends the same descriptors throughout the
    +    // lifetime of the Collector. If a Collector encounters an error while
    +    // executing this method, it must send an invalid descriptor (created
    +    // with NewInvalidDesc) to signal the error to the registry.
    +    Describe(chan<- *Desc)
    +    // Collect is called by the Prometheus registry when collecting
    +    // metrics. The implementation sends each collected metric via the
    +    // provided channel and returns once the last metric has been sent. The
    +    // descriptor of each sent metric is one of those returned by
    +    // Describe. Returned metrics that share the same descriptor must differ
    +    // in their variable label values. This method may be called
    +    // concurrently and must therefore be implemented in a concurrency safe
    +    // way. Blocking occurs at the expense of total performance of rendering
    +    // all registered metrics. Ideally, Collector implementations support
    +    // concurrent readers.
    +    Collect(chan<- Metric)
    +}
    +

    +Collector is the interface implemented by anything that can be used by +Prometheus to collect metrics. A Collector has to be registered for +collection. See Registerer.Register. +

    +

    +The stock metrics provided by this package (Gauge, Counter, Summary, +Histogram, Untyped) are also Collectors (which only ever collect one metric, +namely itself). An implementer of Collector may, however, collect multiple +metrics in a coordinated fashion and/or create metrics on the fly. Examples +for collectors already implemented in this library are the metric vectors +(i.e. collection of multiple instances of the same Metric but with different +label values) like GaugeVec or SummaryVec, and the ExpvarCollector. +

    + + + + + + +
    + +
    +

    Example

    + + + +

    Code:

    +
    package prometheus_test
    +
    +import "github.com/prometheus/client_golang/prometheus"
    +
    +// ClusterManager is an example for a system that might have been built without
    +// Prometheus in mind. It models a central manager of jobs running in a
    +// cluster. To turn it into something that collects Prometheus metrics, we
    +// simply add the two methods required for the Collector interface.
    +//
    +// An additional challenge is that multiple instances of the ClusterManager are
    +// run within the same binary, each in charge of a different zone. We need to
    +// make use of ConstLabels to be able to register each ClusterManager instance
    +// with Prometheus.
    +type ClusterManager struct {
    +    Zone         string
    +    OOMCountDesc *prometheus.Desc
    +    RAMUsageDesc *prometheus.Desc
    +    // ... many more fields
    +}
    +
    +// ReallyExpensiveAssessmentOfTheSystemState is a mock for the data gathering a
    +// real cluster manager would have to do. Since it may actually be really
    +// expensive, it must only be called once per collection. This implementation,
    +// obviously, only returns some made-up data.
    +func (c *ClusterManager) ReallyExpensiveAssessmentOfTheSystemState() (
    +    oomCountByHost map[string]int, ramUsageByHost map[string]float64,
    +) {
    +    // Just example fake data.
    +    oomCountByHost = map[string]int{
    +        "foo.example.org": 42,
    +        "bar.example.org": 2001,
    +    }
    +    ramUsageByHost = map[string]float64{
    +        "foo.example.org": 6.023e23,
    +        "bar.example.org": 3.14,
    +    }
    +    return
    +}
    +
    +// Describe simply sends the two Descs in the struct to the channel.
    +func (c *ClusterManager) Describe(ch chan<- *prometheus.Desc) {
    +    ch <- c.OOMCountDesc
    +    ch <- c.RAMUsageDesc
    +}
    +
    +// Collect first triggers the ReallyExpensiveAssessmentOfTheSystemState. Then it
    +// creates constant metrics for each host on the fly based on the returned data.
    +//
    +// Note that Collect could be called concurrently, so we depend on
    +// ReallyExpensiveAssessmentOfTheSystemState to be concurrency-safe.
    +func (c *ClusterManager) Collect(ch chan<- prometheus.Metric) {
    +    oomCountByHost, ramUsageByHost := c.ReallyExpensiveAssessmentOfTheSystemState()
    +    for host, oomCount := range oomCountByHost {
    +        ch <- prometheus.MustNewConstMetric(
    +            c.OOMCountDesc,
    +            prometheus.CounterValue,
    +            float64(oomCount),
    +            host,
    +        )
    +    }
    +    for host, ramUsage := range ramUsageByHost {
    +        ch <- prometheus.MustNewConstMetric(
    +            c.RAMUsageDesc,
    +            prometheus.GaugeValue,
    +            ramUsage,
    +            host,
    +        )
    +    }
    +}
    +
    +// NewClusterManager creates the two Descs OOMCountDesc and RAMUsageDesc. Note
    +// that the zone is set as a ConstLabel. (It's different in each instance of the
    +// ClusterManager, but constant over the lifetime of an instance.) Then there is
    +// a variable label "host", since we want to partition the collected metrics by
    +// host. Since all Descs created in this way are consistent across instances,
    +// with a guaranteed distinction by the "zone" label, we can register different
    +// ClusterManager instances with the same registry.
    +func NewClusterManager(zone string) *ClusterManager {
    +    return &ClusterManager{
    +        Zone: zone,
    +        OOMCountDesc: prometheus.NewDesc(
    +            "clustermanager_oom_crashes_total",
    +            "Number of OOM crashes.",
    +            []string{"host"},
    +            prometheus.Labels{"zone": zone},
    +        ),
    +        RAMUsageDesc: prometheus.NewDesc(
    +            "clustermanager_ram_usage_bytes",
    +            "RAM usage as reported to the cluster manager.",
    +            []string{"host"},
    +            prometheus.Labels{"zone": zone},
    +        ),
    +    }
    +}
    +
    +func ExampleCollector() {
    +    workerDB := NewClusterManager("db")
    +    workerCA := NewClusterManager("ca")
    +
    +    // Since we are dealing with custom Collector implementations, it might
    +    // be a good idea to try it out with a pedantic registry.
    +    reg := prometheus.NewPedanticRegistry()
    +    reg.MustRegister(workerDB)
    +    reg.MustRegister(workerCA)
    +}
    +
    + + +
    +
    + + + + + + +

    func MustRegisterOrGet

    +
    func MustRegisterOrGet(c Collector) Collector
    +

    +MustRegisterOrGet behaves like RegisterOrGet but panics instead of returning +an error. +

    +

    +Deprecated: This is deprecated for the same reason RegisterOrGet is. See +there for details. +

    + + + + + +

    func NewExpvarCollector

    +
    func NewExpvarCollector(exports map[string]*Desc) Collector
    +

    +NewExpvarCollector returns a newly allocated expvar Collector that still has +to be registered with a Prometheus registry. +

    +

    +An expvar Collector collects metrics from the expvar interface. It provides a +quick way to expose numeric values that are already exported via expvar as +Prometheus metrics. Note that the data models of expvar and Prometheus are +fundamentally different, and that the expvar Collector is inherently slower +than native Prometheus metrics. Thus, the expvar Collector is probably great +for experiments and prototying, but you should seriously consider a more +direct implementation of Prometheus metrics for monitoring production +systems. +

    +

    +The exports map has the following meaning: +

    +

    +The keys in the map correspond to expvar keys, i.e. for every expvar key you +want to export as Prometheus metric, you need an entry in the exports +map. The descriptor mapped to each key describes how to export the expvar +value. It defines the name and the help string of the Prometheus metric +proxying the expvar value. The type will always be Untyped. +

    +

    +For descriptors without variable labels, the expvar value must be a number or +a bool. The number is then directly exported as the Prometheus sample +value. (For a bool, 'false' translates to 0 and 'true' to 1). Expvar values +that are not numbers or bools are silently ignored. +

    +

    +If the descriptor has one variable label, the expvar value must be an expvar +map. The keys in the expvar map become the various values of the one +Prometheus label. The values in the expvar map must be numbers or bools again +as above. +

    +

    +For descriptors with more than one variable label, the expvar must be a +nested expvar map, i.e. where the values of the topmost map are maps again +etc. until a depth is reached that corresponds to the number of labels. The +leaves of that structure must be numbers or bools as above to serve as the +sample values. +

    +

    +Anything that does not fit into the scheme above is silently ignored. +

    + +
    + +
    +

    Example

    + + + +

    Code:

    +
    expvarCollector := prometheus.NewExpvarCollector(map[string]*prometheus.Desc{
    +    "memstats": prometheus.NewDesc(
    +        "expvar_memstats",
    +        "All numeric memstats as one metric family. Not a good role-model, actually... ;-)",
    +        []string{"type"}, nil,
    +    ),
    +    "lone-int": prometheus.NewDesc(
    +        "expvar_lone_int",
    +        "Just an expvar int as an example.",
    +        nil, nil,
    +    ),
    +    "http-request-map": prometheus.NewDesc(
    +        "expvar_http_request_total",
    +        "How many http requests processed, partitioned by status code and http method.",
    +        []string{"code", "method"}, nil,
    +    ),
    +})
    +prometheus.MustRegister(expvarCollector)
    +
    +// The Prometheus part is done here. But to show that this example is
    +// doing anything, we have to manually export something via expvar.  In
    +// real-life use-cases, some library would already have exported via
    +// expvar what we want to re-export as Prometheus metrics.
    +expvar.NewInt("lone-int").Set(42)
    +expvarMap := expvar.NewMap("http-request-map")
    +var (
    +    expvarMap1, expvarMap2                             expvar.Map
    +    expvarInt11, expvarInt12, expvarInt21, expvarInt22 expvar.Int
    +)
    +expvarMap1.Init()
    +expvarMap2.Init()
    +expvarInt11.Set(3)
    +expvarInt12.Set(13)
    +expvarInt21.Set(11)
    +expvarInt22.Set(212)
    +expvarMap1.Set("POST", &expvarInt11)
    +expvarMap1.Set("GET", &expvarInt12)
    +expvarMap2.Set("POST", &expvarInt21)
    +expvarMap2.Set("GET", &expvarInt22)
    +expvarMap.Set("404", &expvarMap1)
    +expvarMap.Set("200", &expvarMap2)
    +// Results in the following expvar map:
    +// "http-request-count": {"200": {"POST": 11, "GET": 212}, "404": {"POST": 3, "GET": 13}}
    +
    +// Let's see what the scrape would yield, but exclude the memstats metrics.
    +metricStrings := []string{}
    +metric := dto.Metric{}
    +metricChan := make(chan prometheus.Metric)
    +go func() {
    +    expvarCollector.Collect(metricChan)
    +    close(metricChan)
    +}()
    +for m := range metricChan {
    +    if strings.Index(m.Desc().String(), "expvar_memstats") == -1 {
    +        metric.Reset()
    +        m.Write(&metric)
    +        metricStrings = append(metricStrings, metric.String())
    +    }
    +}
    +sort.Strings(metricStrings)
    +for _, s := range metricStrings {
    +    fmt.Println(strings.TrimRight(s, " "))
    +}
    +
    + +

    Output:

    +
    label:<name:"code" value:"200" > label:<name:"method" value:"GET" > untyped:<value:212 >
    +label:<name:"code" value:"200" > label:<name:"method" value:"POST" > untyped:<value:11 >
    +label:<name:"code" value:"404" > label:<name:"method" value:"GET" > untyped:<value:13 >
    +label:<name:"code" value:"404" > label:<name:"method" value:"POST" > untyped:<value:3 >
    +untyped:<value:42 >
    +
    + + +
    +
    + + + + +

    func NewGoCollector

    +
    func NewGoCollector() Collector
    +

    +NewGoCollector returns a collector which exports metrics about the current +go process. +

    + + + + + +

    func NewProcessCollector

    +
    func NewProcessCollector(pid int, namespace string) Collector
    +

    +NewProcessCollector returns a collector which exports the current state of +process metrics including cpu, memory and file descriptor usage as well as +the process start time for the given process id under the given namespace. +

    + + + + + +

    func NewProcessCollectorPIDFn

    +
    func NewProcessCollectorPIDFn(
    +    pidFn func() (int, error),
    +    namespace string,
    +) Collector
    +

    +NewProcessCollectorPIDFn returns a collector which exports the current state +of process metrics including cpu, memory and file descriptor usage as well +as the process start time under the given namespace. The given pidFn is +called on each collect and is used to determine the process to export +metrics for. +

    + + + + + +

    func RegisterOrGet

    +
    func RegisterOrGet(c Collector) (Collector, error)
    +

    +RegisterOrGet registers the provided Collector with the DefaultRegisterer and +returns the Collector, unless an equal Collector was registered before, in +which case that Collector is returned. +

    +

    +Deprecated: RegisterOrGet is merely a convenience function for the +implementation as described in the documentation for +AlreadyRegisteredError. As the use case is relatively rare, this function +will be removed in a future version of this package to clean up the +namespace. +

    + + + + + + + + + +

    type Counter

    +
    type Counter interface {
    +    Metric
    +    Collector
    +
    +    // Set is used to set the Counter to an arbitrary value. It is only used
    +    // if you have to transfer a value from an external counter into this
    +    // Prometheus metric. Do not use it for regular handling of a
    +    // Prometheus counter (as it can be used to break the contract of
    +    // monotonically increasing values).
    +    //
    +    // Deprecated: Use NewConstMetric to create a counter for an external
    +    // value. A Counter should never be set.
    +    Set(float64)
    +    // Inc increments the counter by 1.
    +    Inc()
    +    // Add adds the given value to the counter. It panics if the value is <
    +    // 0.
    +    Add(float64)
    +}
    +

    +Counter is a Metric that represents a single numerical value that only ever +goes up. That implies that it cannot be used to count items whose number can +also go down, e.g. the number of currently running goroutines. Those +"counters" are represented by Gauges. +

    +

    +A Counter is typically used to count requests served, tasks completed, errors +occurred, etc. +

    +

    +To create Counter instances, use NewCounter. +

    + + + + + + +
    + +
    +

    Example

    + + + +

    Code:

    +
    pushCounter := prometheus.NewCounter(prometheus.CounterOpts{
    +    Name: "repository_pushes", // Note: No help string...
    +})
    +err := prometheus.Register(pushCounter) // ... so this will return an error.
    +if err != nil {
    +    fmt.Println("Push counter couldn't be registered, no counting will happen:", err)
    +    return
    +}
    +
    +// Try it once more, this time with a help string.
    +pushCounter = prometheus.NewCounter(prometheus.CounterOpts{
    +    Name: "repository_pushes",
    +    Help: "Number of pushes to external repository.",
    +})
    +err = prometheus.Register(pushCounter)
    +if err != nil {
    +    fmt.Println("Push counter couldn't be registered AGAIN, no counting will happen:", err)
    +    return
    +}
    +
    +pushComplete := make(chan struct{})
    +// TODO: Start a goroutine that performs repository pushes and reports
    +// each completion via the channel.
    +for range pushComplete {
    +    pushCounter.Inc()
    +}
    +
    + +

    Output:

    +
    Push counter couldn't be registered, no counting will happen: descriptor Desc{fqName: "repository_pushes", help: "", constLabels: {}, variableLabels: []} is invalid: empty help string
    +
    + + +
    +
    + + + + + + +

    func NewCounter

    +
    func NewCounter(opts CounterOpts) Counter
    +

    +NewCounter creates a new Counter based on the provided CounterOpts. +

    + + + + + + + + + +

    type CounterFunc

    +
    type CounterFunc interface {
    +    Metric
    +    Collector
    +}
    +

    +CounterFunc is a Counter whose value is determined at collect time by calling a +provided function. +

    +

    +To create CounterFunc instances, use NewCounterFunc. +

    + + + + + + + + + + + + +

    func NewCounterFunc

    +
    func NewCounterFunc(opts CounterOpts, function func() float64) CounterFunc
    +

    +NewCounterFunc creates a new CounterFunc based on the provided +CounterOpts. The value reported is determined by calling the given function +from within the Write method. Take into account that metric collection may +happen concurrently. If that results in concurrent calls to Write, like in +the case where a CounterFunc is directly registered with Prometheus, the +provided function must be concurrency-safe. The function should also honor +the contract for a Counter (values only go up, not down), but compliance will +not be checked. +

    + + + + + + + + + +

    type CounterOpts

    +
    type CounterOpts Opts
    +

    +CounterOpts is an alias for Opts. See there for doc comments. +

    + + + + + + + + + + + + + + + + +

    type CounterVec

    +
    type CounterVec struct {
    +    *MetricVec
    +}
    +

    +CounterVec is a Collector that bundles a set of Counters that all share the +same Desc, but have different values for their variable labels. This is used +if you want to count the same thing partitioned by various dimensions +(e.g. number of HTTP requests, partitioned by response code and +method). Create instances with NewCounterVec. +

    +

    +CounterVec embeds MetricVec. See there for a full list of methods with +detailed documentation. +

    + + + + + + +
    + +
    +

    Example

    + + + +

    Code:

    +
    +httpReqs := prometheus.NewCounterVec(
    +    prometheus.CounterOpts{
    +        Name: "http_requests_total",
    +        Help: "How many HTTP requests processed, partitioned by status code and HTTP method.",
    +    },
    +    []string{"code", "method"},
    +)
    +prometheus.MustRegister(httpReqs)
    +
    +httpReqs.WithLabelValues("404", "POST").Add(42)
    +
    +// If you have to access the same set of labels very frequently, it
    +// might be good to retrieve the metric only once and keep a handle to
    +// it. But beware of deletion of that metric, see below!
    +m := httpReqs.WithLabelValues("200", "GET")
    +for i := 0; i < 1000000; i++ {
    +    m.Inc()
    +}
    +// Delete a metric from the vector. If you have previously kept a handle
    +// to that metric (as above), future updates via that handle will go
    +// unseen (even if you re-create a metric with the same label set
    +// later).
    +httpReqs.DeleteLabelValues("200", "GET")
    +// Same thing with the more verbose Labels syntax.
    +httpReqs.Delete(prometheus.Labels{"method": "GET", "code": "200"})
    +
    + + +
    +
    + + + + + + +

    func NewCounterVec

    +
    func NewCounterVec(opts CounterOpts, labelNames []string) *CounterVec
    +

    +NewCounterVec creates a new CounterVec based on the provided CounterOpts and +partitioned by the given label names. At least one label name must be +provided. +

    + + + + + + + +

    func (*CounterVec) GetMetricWith

    +
    func (m *CounterVec) GetMetricWith(labels Labels) (Counter, error)
    +

    +GetMetricWith replaces the method of the same name in MetricVec. The +difference is that this method returns a Counter and not a Metric so that no +type conversion is required. +

    + + + + + + +

    func (*CounterVec) GetMetricWithLabelValues

    +
    func (m *CounterVec) GetMetricWithLabelValues(lvs ...string) (Counter, error)
    +

    +GetMetricWithLabelValues replaces the method of the same name in +MetricVec. The difference is that this method returns a Counter and not a +Metric so that no type conversion is required. +

    + + + + + + +

    func (*CounterVec) With

    +
    func (m *CounterVec) With(labels Labels) Counter
    +

    +With works as GetMetricWith, but panics where GetMetricWithLabels would have +returned an error. By not returning an error, With allows shortcuts like +

    +
    myVec.With(Labels{"code": "404", "method": "GET"}).Add(42)
    +
    + + + + + + +

    func (*CounterVec) WithLabelValues

    +
    func (m *CounterVec) WithLabelValues(lvs ...string) Counter
    +

    +WithLabelValues works as GetMetricWithLabelValues, but panics where +GetMetricWithLabelValues would have returned an error. By not returning an +error, WithLabelValues allows shortcuts like +

    +
    myVec.WithLabelValues("404", "GET").Add(42)
    +
    + + + + + + + + +

    type Desc

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

    +Desc is the descriptor used by every Prometheus Metric. It is essentially +the immutable meta-data of a Metric. The normal Metric implementations +included in this package manage their Desc under the hood. Users only have to +deal with Desc if they use advanced features like the ExpvarCollector or +custom Collectors and Metrics. +

    +

    +Descriptors registered with the same registry have to fulfill certain +consistency and uniqueness criteria if they share the same fully-qualified +name: They must have the same help string and the same label names (aka label +dimensions) in each, constLabels and variableLabels, but they must differ in +the values of the constLabels. +

    +

    +Descriptors that share the same fully-qualified names and the same label +values of their constLabels are considered equal. +

    +

    +Use NewDesc to create new Desc instances. +

    + + + + + + + + + + + + +

    func NewDesc

    +
    func NewDesc(fqName, help string, variableLabels []string, constLabels Labels) *Desc
    +

    +NewDesc allocates and initializes a new Desc. Errors are recorded in the Desc +and will be reported on registration time. variableLabels and constLabels can +be nil if no such labels should be set. fqName and help must not be empty. +

    +

    +variableLabels only contain the label names. Their label values are variable +and therefore not part of the Desc. (They are managed within the Metric.) +

    +

    +For constLabels, the label values are constant. Therefore, they are fully +specified in the Desc. See the Opts documentation for the implications of +constant labels. +

    + + + + + +

    func NewInvalidDesc

    +
    func NewInvalidDesc(err error) *Desc
    +

    +NewInvalidDesc returns an invalid descriptor, i.e. a descriptor with the +provided error set. If a collector returning such a descriptor is registered, +registration will fail with the provided error. NewInvalidDesc can be used by +a Collector to signal inability to describe itself. +

    + + + + + + + +

    func (*Desc) String

    +
    func (d *Desc) String() string
    + + + + + + + + +

    type Gatherer

    +
    type Gatherer interface {
    +    // Gather calls the Collect method of the registered Collectors and then
    +    // gathers the collected metrics into a lexicographically sorted slice
    +    // of MetricFamily protobufs. Even if an error occurs, Gather attempts
    +    // to gather as many metrics as possible. Hence, if a non-nil error is
    +    // returned, the returned MetricFamily slice could be nil (in case of a
    +    // fatal error that prevented any meaningful metric collection) or
    +    // contain a number of MetricFamily protobufs, some of which might be
    +    // incomplete, and some might be missing altogether. The returned error
    +    // (which might be a MultiError) explains the details. In scenarios
    +    // where complete collection is critical, the returned MetricFamily
    +    // protobufs should be disregarded if the returned error is non-nil.
    +    Gather() ([]*dto.MetricFamily, error)
    +}
    +

    +Gatherer is the interface for the part of a registry in charge of gathering +the collected metrics into a number of MetricFamilies. The Gatherer interface +comes with the same general implication as described for the Registerer +interface. +

    + + + + + + + + + + + + + + + + +

    type GathererFunc

    +
    type GathererFunc func() ([]*dto.MetricFamily, error)
    +

    +GathererFunc turns a function into a Gatherer. +

    + + + + + + + + + + + + + + +

    func (GathererFunc) Gather

    +
    func (gf GathererFunc) Gather() ([]*dto.MetricFamily, error)
    +

    +Gather implements Gatherer. +

    + + + + + + + + +

    type Gatherers

    +
    type Gatherers []Gatherer
    +

    +Gatherers is a slice of Gatherer instances that implements the Gatherer +interface itself. Its Gather method calls Gather on all Gatherers in the +slice in order and returns the merged results. Errors returned from the +Gather calles are all returned in a flattened MultiError. Duplicate and +inconsistent Metrics are skipped (first occurrence in slice order wins) and +reported in the returned error. +

    +

    +Gatherers can be used to merge the Gather results from multiple +Registries. It also provides a way to directly inject existing MetricFamily +protobufs into the gathering by creating a custom Gatherer with a Gather +method that simply returns the existing MetricFamily protobufs. Note that no +registration is involved (in contrast to Collector registration), so +obviously registration-time checks cannot happen. Any inconsistencies between +the gathered MetricFamilies are reported as errors by the Gather method, and +inconsistent Metrics are dropped. Invalid parts of the MetricFamilies +(e.g. syntactically invalid metric or label names) will go undetected. +

    + + + + + + +
    + +
    +

    Example

    + + + +

    Code:

    +
    reg := prometheus.NewRegistry()
    +temp := prometheus.NewGaugeVec(
    +    prometheus.GaugeOpts{
    +        Name: "temperature_kelvin",
    +        Help: "Temperature in Kelvin.",
    +    },
    +    []string{"location"},
    +)
    +reg.MustRegister(temp)
    +temp.WithLabelValues("outside").Set(273.14)
    +temp.WithLabelValues("inside").Set(298.44)
    +
    +var parser expfmt.TextParser
    +
    +text := `
    +# TYPE humidity_percent gauge
    +# HELP humidity_percent Humidity in %.
    +humidity_percent{location="outside"} 45.4
    +humidity_percent{location="inside"} 33.2
    +# TYPE temperature_kelvin gauge
    +# HELP temperature_kelvin Temperature in Kelvin.
    +temperature_kelvin{location="somewhere else"} 4.5
    +`
    +
    +parseText := func() ([]*dto.MetricFamily, error) {
    +    parsed, err := parser.TextToMetricFamilies(strings.NewReader(text))
    +    if err != nil {
    +        return nil, err
    +    }
    +    var result []*dto.MetricFamily
    +    for _, mf := range parsed {
    +        result = append(result, mf)
    +    }
    +    return result, nil
    +}
    +
    +gatherers := prometheus.Gatherers{
    +    reg,
    +    prometheus.GathererFunc(parseText),
    +}
    +
    +gathering, err := gatherers.Gather()
    +if err != nil {
    +    fmt.Println(err)
    +}
    +
    +out := &bytes.Buffer{}
    +for _, mf := range gathering {
    +    if _, err := expfmt.MetricFamilyToText(out, mf); err != nil {
    +        panic(err)
    +    }
    +}
    +fmt.Print(out.String())
    +fmt.Println("----------")
    +
    +// Note how the temperature_kelvin metric family has been merged from
    +// different sources. Now try
    +text = `
    +# TYPE humidity_percent gauge
    +# HELP humidity_percent Humidity in %.
    +humidity_percent{location="outside"} 45.4
    +humidity_percent{location="inside"} 33.2
    +# TYPE temperature_kelvin gauge
    +# HELP temperature_kelvin Temperature in Kelvin.
    +# Duplicate metric:
    +temperature_kelvin{location="outside"} 265.3
    + # Wrong labels:
    +temperature_kelvin 4.5
    +`
    +
    +gathering, err = gatherers.Gather()
    +if err != nil {
    +    fmt.Println(err)
    +}
    +// Note that still as many metrics as possible are returned:
    +out.Reset()
    +for _, mf := range gathering {
    +    if _, err := expfmt.MetricFamilyToText(out, mf); err != nil {
    +        panic(err)
    +    }
    +}
    +fmt.Print(out.String())
    +
    +
    + +

    Output:

    +
    # HELP humidity_percent Humidity in %.
    +# TYPE humidity_percent gauge
    +humidity_percent{location="inside"} 33.2
    +humidity_percent{location="outside"} 45.4
    +# HELP temperature_kelvin Temperature in Kelvin.
    +# TYPE temperature_kelvin gauge
    +temperature_kelvin{location="inside"} 298.44
    +temperature_kelvin{location="outside"} 273.14
    +temperature_kelvin{location="somewhere else"} 4.5
    +----------
    +2 error(s) occurred:
    +* collected metric temperature_kelvin label:<name:"location" value:"outside" > gauge:<value:265.3 >  was collected before with the same name and label values
    +* collected metric temperature_kelvin gauge:<value:4.5 >  has label dimensions inconsistent with previously collected metrics in the same metric family
    +# HELP humidity_percent Humidity in %.
    +# TYPE humidity_percent gauge
    +humidity_percent{location="inside"} 33.2
    +humidity_percent{location="outside"} 45.4
    +# HELP temperature_kelvin Temperature in Kelvin.
    +# TYPE temperature_kelvin gauge
    +temperature_kelvin{location="inside"} 298.44
    +temperature_kelvin{location="outside"} 273.14
    +
    + + +
    +
    + + + + + + + + +

    func (Gatherers) Gather

    +
    func (gs Gatherers) Gather() ([]*dto.MetricFamily, error)
    +

    +Gather implements Gatherer. +

    + + + + + + + + +

    type Gauge

    +
    type Gauge interface {
    +    Metric
    +    Collector
    +
    +    // Set sets the Gauge to an arbitrary value.
    +    Set(float64)
    +    // Inc increments the Gauge by 1.
    +    Inc()
    +    // Dec decrements the Gauge by 1.
    +    Dec()
    +    // Add adds the given value to the Gauge. (The value can be
    +    // negative, resulting in a decrease of the Gauge.)
    +    Add(float64)
    +    // Sub subtracts the given value from the Gauge. (The value can be
    +    // negative, resulting in an increase of the Gauge.)
    +    Sub(float64)
    +}
    +

    +Gauge is a Metric that represents a single numerical value that can +arbitrarily go up and down. +

    +

    +A Gauge is typically used for measured values like temperatures or current +memory usage, but also "counts" that can go up and down, like the number of +running goroutines. +

    +

    +To create Gauge instances, use NewGauge. +

    + + + + + + +
    + +
    +

    Example

    + + + +

    Code:

    +
    +opsQueued := prometheus.NewGauge(prometheus.GaugeOpts{
    +    Namespace: "our_company",
    +    Subsystem: "blob_storage",
    +    Name:      "ops_queued",
    +    Help:      "Number of blob storage operations waiting to be processed.",
    +})
    +prometheus.MustRegister(opsQueued)
    +
    +// 10 operations queued by the goroutine managing incoming requests.
    +opsQueued.Add(10)
    +// A worker goroutine has picked up a waiting operation.
    +opsQueued.Dec()
    +// And once more...
    +opsQueued.Dec()
    +
    + + +
    +
    + + + + + + +

    func NewGauge

    +
    func NewGauge(opts GaugeOpts) Gauge
    +

    +NewGauge creates a new Gauge based on the provided GaugeOpts. +

    + + + + + + + + + +

    type GaugeFunc

    +
    type GaugeFunc interface {
    +    Metric
    +    Collector
    +}
    +

    +GaugeFunc is a Gauge whose value is determined at collect time by calling a +provided function. +

    +

    +To create GaugeFunc instances, use NewGaugeFunc. +

    + + + + + + +
    + +
    +

    Example

    + + + +

    Code:

    +
    if err := prometheus.Register(prometheus.NewGaugeFunc(
    +    prometheus.GaugeOpts{
    +        Subsystem: "runtime",
    +        Name:      "goroutines_count",
    +        Help:      "Number of goroutines that currently exist.",
    +    },
    +    func() float64 { return float64(runtime.NumGoroutine()) },
    +)); err == nil {
    +    fmt.Println("GaugeFunc 'goroutines_count' registered.")
    +}
    +// Note that the count of goroutines is a gauge (and not a counter) as
    +// it can go up and down.
    +
    +
    + +

    Output:

    +
    GaugeFunc 'goroutines_count' registered.
    +
    + + +
    +
    + + + + + + +

    func NewGaugeFunc

    +
    func NewGaugeFunc(opts GaugeOpts, function func() float64) GaugeFunc
    +

    +NewGaugeFunc creates a new GaugeFunc based on the provided GaugeOpts. The +value reported is determined by calling the given function from within the +Write method. Take into account that metric collection may happen +concurrently. If that results in concurrent calls to Write, like in the case +where a GaugeFunc is directly registered with Prometheus, the provided +function must be concurrency-safe. +

    + + + + + + + + + +

    type GaugeOpts

    +
    type GaugeOpts Opts
    +

    +GaugeOpts is an alias for Opts. See there for doc comments. +

    + + + + + + + + + + + + + + + + +

    type GaugeVec

    +
    type GaugeVec struct {
    +    *MetricVec
    +}
    +

    +GaugeVec is a Collector that bundles a set of Gauges that all share the same +Desc, but have different values for their variable labels. This is used if +you want to count the same thing partitioned by various dimensions +(e.g. number of operations queued, partitioned by user and operation +type). Create instances with NewGaugeVec. +

    + + + + + + +
    + +
    +

    Example

    + + + +

    Code:

    +
    +opsQueued := prometheus.NewGaugeVec(
    +    prometheus.GaugeOpts{
    +        Namespace: "our_company",
    +        Subsystem: "blob_storage",
    +        Name:      "ops_queued",
    +        Help:      "Number of blob storage operations waiting to be processed, partitioned by user and type.",
    +    },
    +    []string{
    +        // Which user has requested the operation?
    +        "user",
    +        // Of what type is the operation?
    +        "type",
    +    },
    +)
    +prometheus.MustRegister(opsQueued)
    +
    +// Increase a value using compact (but order-sensitive!) WithLabelValues().
    +opsQueued.WithLabelValues("bob", "put").Add(4)
    +// Increase a value with a map using WithLabels. More verbose, but order
    +// doesn't matter anymore.
    +opsQueued.With(prometheus.Labels{"type": "delete", "user": "alice"}).Inc()
    +
    + + +
    +
    + + + + + + +

    func NewGaugeVec

    +
    func NewGaugeVec(opts GaugeOpts, labelNames []string) *GaugeVec
    +

    +NewGaugeVec creates a new GaugeVec based on the provided GaugeOpts and +partitioned by the given label names. At least one label name must be +provided. +

    + + + + + + + +

    func (*GaugeVec) GetMetricWith

    +
    func (m *GaugeVec) GetMetricWith(labels Labels) (Gauge, error)
    +

    +GetMetricWith replaces the method of the same name in MetricVec. The +difference is that this method returns a Gauge and not a Metric so that no +type conversion is required. +

    + + + + + + +

    func (*GaugeVec) GetMetricWithLabelValues

    +
    func (m *GaugeVec) GetMetricWithLabelValues(lvs ...string) (Gauge, error)
    +

    +GetMetricWithLabelValues replaces the method of the same name in +MetricVec. The difference is that this method returns a Gauge and not a +Metric so that no type conversion is required. +

    + + + + + + +

    func (*GaugeVec) With

    +
    func (m *GaugeVec) With(labels Labels) Gauge
    +

    +With works as GetMetricWith, but panics where GetMetricWithLabels would have +returned an error. By not returning an error, With allows shortcuts like +

    +
    myVec.With(Labels{"code": "404", "method": "GET"}).Add(42)
    +
    + + + + + + +

    func (*GaugeVec) WithLabelValues

    +
    func (m *GaugeVec) WithLabelValues(lvs ...string) Gauge
    +

    +WithLabelValues works as GetMetricWithLabelValues, but panics where +GetMetricWithLabelValues would have returned an error. By not returning an +error, WithLabelValues allows shortcuts like +

    +
    myVec.WithLabelValues("404", "GET").Add(42)
    +
    + + + + + + + + +

    type Histogram

    +
    type Histogram interface {
    +    Metric
    +    Collector
    +
    +    // Observe adds a single observation to the histogram.
    +    Observe(float64)
    +}
    +

    +A Histogram counts individual observations from an event or sample stream in +configurable buckets. Similar to a summary, it also provides a sum of +observations and an observation count. +

    +

    +On the Prometheus server, quantiles can be calculated from a Histogram using +the histogram_quantile function in the query language. +

    +

    +Note that Histograms, in contrast to Summaries, can be aggregated with the +Prometheus query language (see the documentation for detailed +procedures). However, Histograms require the user to pre-define suitable +buckets, and they are in general less accurate. The Observe method of a +Histogram has a very low performance overhead in comparison with the Observe +method of a Summary. +

    +

    +To create Histogram instances, use NewHistogram. +

    + + + + + + +
    + +
    +

    Example

    + + + +

    Code:

    +
    temps := prometheus.NewHistogram(prometheus.HistogramOpts{
    +    Name:    "pond_temperature_celsius",
    +    Help:    "The temperature of the frog pond.", // Sorry, we can't measure how badly it smells.
    +    Buckets: prometheus.LinearBuckets(20, 5, 5),  // 5 buckets, each 5 centigrade wide.
    +})
    +
    +// Simulate some observations.
    +for i := 0; i < 1000; i++ {
    +    temps.Observe(30 + math.Floor(120*math.Sin(float64(i)*0.1))/10)
    +}
    +
    +// Just for demonstration, let's check the state of the histogram by
    +// (ab)using its Write method (which is usually only used by Prometheus
    +// internally).
    +metric := &dto.Metric{}
    +temps.Write(metric)
    +fmt.Println(proto.MarshalTextString(metric))
    +
    +
    + +

    Output:

    +
    histogram: <
    +  sample_count: 1000
    +  sample_sum: 29969.50000000001
    +  bucket: <
    +    cumulative_count: 192
    +    upper_bound: 20
    +  >
    +  bucket: <
    +    cumulative_count: 366
    +    upper_bound: 25
    +  >
    +  bucket: <
    +    cumulative_count: 501
    +    upper_bound: 30
    +  >
    +  bucket: <
    +    cumulative_count: 638
    +    upper_bound: 35
    +  >
    +  bucket: <
    +    cumulative_count: 816
    +    upper_bound: 40
    +  >
    +>
    +
    + + +
    +
    + + + + + + +

    func NewHistogram

    +
    func NewHistogram(opts HistogramOpts) Histogram
    +

    +NewHistogram creates a new Histogram based on the provided HistogramOpts. It +panics if the buckets in HistogramOpts are not in strictly increasing order. +

    + + + + + + + + + +

    type HistogramOpts

    +
    type HistogramOpts struct {
    +    // Namespace, Subsystem, and Name are components of the fully-qualified
    +    // name of the Histogram (created by joining these components with
    +    // "_"). Only Name is mandatory, the others merely help structuring the
    +    // name. Note that the fully-qualified name of the Histogram must be a
    +    // valid Prometheus metric name.
    +    Namespace string
    +    Subsystem string
    +    Name      string
    +
    +    // Help provides information about this Histogram. Mandatory!
    +    //
    +    // Metrics with the same fully-qualified name must have the same Help
    +    // string.
    +    Help string
    +
    +    // ConstLabels are used to attach fixed labels to this
    +    // Histogram. Histograms with the same fully-qualified name must have the
    +    // same label names in their ConstLabels.
    +    //
    +    // Note that in most cases, labels have a value that varies during the
    +    // lifetime of a process. Those labels are usually managed with a
    +    // HistogramVec. ConstLabels serve only special purposes. One is for the
    +    // special case where the value of a label does not change during the
    +    // lifetime of a process, e.g. if the revision of the running binary is
    +    // put into a label. Another, more advanced purpose is if more than one
    +    // Collector needs to collect Histograms with the same fully-qualified
    +    // name. In that case, those Summaries must differ in the values of
    +    // their ConstLabels. See the Collector examples.
    +    //
    +    // If the value of a label never changes (not even between binaries),
    +    // that label most likely should not be a label at all (but part of the
    +    // metric name).
    +    ConstLabels Labels
    +
    +    // Buckets defines the buckets into which observations are counted. Each
    +    // element in the slice is the upper inclusive bound of a bucket. The
    +    // values must be sorted in strictly increasing order. There is no need
    +    // to add a highest bucket with +Inf bound, it will be added
    +    // implicitly. The default value is DefBuckets.
    +    Buckets []float64
    +}
    +

    +HistogramOpts bundles the options for creating a Histogram metric. It is +mandatory to set Name and Help to a non-empty string. All other fields are +optional and can safely be left at their zero value. +

    + + + + + + + + + + + + + + + + +

    type HistogramVec

    +
    type HistogramVec struct {
    +    *MetricVec
    +}
    +

    +HistogramVec is a Collector that bundles a set of Histograms that all share the +same Desc, but have different values for their variable labels. This is used +if you want to count the same thing partitioned by various dimensions +(e.g. HTTP request latencies, partitioned by status code and method). Create +instances with NewHistogramVec. +

    + + + + + + + + + + + + +

    func NewHistogramVec

    +
    func NewHistogramVec(opts HistogramOpts, labelNames []string) *HistogramVec
    +

    +NewHistogramVec creates a new HistogramVec based on the provided HistogramOpts and +partitioned by the given label names. At least one label name must be +provided. +

    + + + + + + + +

    func (*HistogramVec) GetMetricWith

    +
    func (m *HistogramVec) GetMetricWith(labels Labels) (Histogram, error)
    +

    +GetMetricWith replaces the method of the same name in MetricVec. The +difference is that this method returns a Histogram and not a Metric so that no +type conversion is required. +

    + + + + + + +

    func (*HistogramVec) GetMetricWithLabelValues

    +
    func (m *HistogramVec) GetMetricWithLabelValues(lvs ...string) (Histogram, error)
    +

    +GetMetricWithLabelValues replaces the method of the same name in +MetricVec. The difference is that this method returns a Histogram and not a +Metric so that no type conversion is required. +

    + + + + + + +

    func (*HistogramVec) With

    +
    func (m *HistogramVec) With(labels Labels) Histogram
    +

    +With works as GetMetricWith, but panics where GetMetricWithLabels would have +returned an error. By not returning an error, With allows shortcuts like +

    +
    myVec.With(Labels{"code": "404", "method": "GET"}).Observe(42.21)
    +
    + + + + + + +

    func (*HistogramVec) WithLabelValues

    +
    func (m *HistogramVec) WithLabelValues(lvs ...string) Histogram
    +

    +WithLabelValues works as GetMetricWithLabelValues, but panics where +GetMetricWithLabelValues would have returned an error. By not returning an +error, WithLabelValues allows shortcuts like +

    +
    myVec.WithLabelValues("404", "GET").Observe(42.21)
    +
    + + + + + + + + +

    type LabelPairSorter

    +
    type LabelPairSorter []*dto.LabelPair
    +

    +LabelPairSorter implements sort.Interface. It is used to sort a slice of +dto.LabelPair pointers. This is useful for implementing the Write method of +custom metrics. +

    + + + + + + +
    + +
    +

    Example

    + + + +

    Code:

    +
    labelPairs := []*dto.LabelPair{
    +    {Name: proto.String("status"), Value: proto.String("404")},
    +    {Name: proto.String("method"), Value: proto.String("get")},
    +}
    +
    +sort.Sort(prometheus.LabelPairSorter(labelPairs))
    +
    +fmt.Println(labelPairs)
    +
    + +

    Output:

    +
    [name:"method" value:"get"  name:"status" value:"404" ]
    +
    + + +
    +
    + + + + + + + + +

    func (LabelPairSorter) Len

    +
    func (s LabelPairSorter) Len() int
    + + + + + + +

    func (LabelPairSorter) Less

    +
    func (s LabelPairSorter) Less(i, j int) bool
    + + + + + + +

    func (LabelPairSorter) Swap

    +
    func (s LabelPairSorter) Swap(i, j int)
    + + + + + + + + +

    type Labels

    +
    type Labels map[string]string
    +

    +Labels represents a collection of label name -> value mappings. This type is +commonly used with the With(Labels) and GetMetricWith(Labels) methods of +metric vector Collectors, e.g.: +

    +
    myVec.With(Labels{"code": "404", "method": "GET"}).Add(42)
    +
    +

    +The other use-case is the specification of constant label pairs in Opts or to +create a Desc. +

    + + + + + + + + + + + + + + + + +

    type Metric

    +
    type Metric interface {
    +    // Desc returns the descriptor for the Metric. This method idempotently
    +    // returns the same descriptor throughout the lifetime of the
    +    // Metric. The returned descriptor is immutable by contract. A Metric
    +    // unable to describe itself must return an invalid descriptor (created
    +    // with NewInvalidDesc).
    +    Desc() *Desc
    +    // Write encodes the Metric into a "Metric" Protocol Buffer data
    +    // transmission object.
    +    //
    +    // Metric implementations must observe concurrency safety as reads of
    +    // this metric may occur at any time, and any blocking occurs at the
    +    // expense of total performance of rendering all registered
    +    // metrics. Ideally, Metric implementations should support concurrent
    +    // readers.
    +    //
    +    // While populating dto.Metric, it is the responsibility of the
    +    // implementation to ensure validity of the Metric protobuf (like valid
    +    // UTF-8 strings or syntactically valid metric and label names). It is
    +    // recommended to sort labels lexicographically. (Implementers may find
    +    // LabelPairSorter useful for that.) Callers of Write should still make
    +    // sure of sorting if they depend on it.
    +    Write(*dto.Metric) error
    +}
    +

    +A Metric models a single sample value with its meta data being exported to +Prometheus. Implementations of Metric in this package are Gauge, Counter, +Histogram, Summary, and Untyped. +

    + + + + + + + + + + + + +

    func MustNewConstHistogram

    +
    func MustNewConstHistogram(
    +    desc *Desc,
    +    count uint64,
    +    sum float64,
    +    buckets map[float64]uint64,
    +    labelValues ...string,
    +) Metric
    +

    +MustNewConstHistogram is a version of NewConstHistogram that panics where +NewConstMetric would have returned an error. +

    + + + + + +

    func MustNewConstMetric

    +
    func MustNewConstMetric(desc *Desc, valueType ValueType, value float64, labelValues ...string) Metric
    +

    +MustNewConstMetric is a version of NewConstMetric that panics where +NewConstMetric would have returned an error. +

    + + + + + +

    func MustNewConstSummary

    +
    func MustNewConstSummary(
    +    desc *Desc,
    +    count uint64,
    +    sum float64,
    +    quantiles map[float64]float64,
    +    labelValues ...string,
    +) Metric
    +

    +MustNewConstSummary is a version of NewConstSummary that panics where +NewConstMetric would have returned an error. +

    + + + + + +

    func NewConstHistogram

    +
    func NewConstHistogram(
    +    desc *Desc,
    +    count uint64,
    +    sum float64,
    +    buckets map[float64]uint64,
    +    labelValues ...string,
    +) (Metric, error)
    +

    +NewConstHistogram returns a metric representing a Prometheus histogram with +fixed values for the count, sum, and bucket counts. As those parameters +cannot be changed, the returned value does not implement the Histogram +interface (but only the Metric interface). Users of this package will not +have much use for it in regular operations. However, when implementing custom +Collectors, it is useful as a throw-away metric that is generated on the fly +to send it to Prometheus in the Collect method. +

    +

    +buckets is a map of upper bounds to cumulative counts, excluding the +Inf +bucket. +

    +

    +NewConstHistogram returns an error if the length of labelValues is not +consistent with the variable labels in Desc. +

    + +
    + +
    +

    Example

    + + + +

    Code:

    +
    desc := prometheus.NewDesc(
    +    "http_request_duration_seconds",
    +    "A histogram of the HTTP request durations.",
    +    []string{"code", "method"},
    +    prometheus.Labels{"owner": "example"},
    +)
    +
    +// Create a constant histogram from values we got from a 3rd party telemetry system.
    +h := prometheus.MustNewConstHistogram(
    +    desc,
    +    4711, 403.34,
    +    map[float64]uint64{25: 121, 50: 2403, 100: 3221, 200: 4233},
    +    "200", "get",
    +)
    +
    +// Just for demonstration, let's check the state of the histogram by
    +// (ab)using its Write method (which is usually only used by Prometheus
    +// internally).
    +metric := &dto.Metric{}
    +h.Write(metric)
    +fmt.Println(proto.MarshalTextString(metric))
    +
    +
    + +

    Output:

    +
    label: <
    +  name: "code"
    +  value: "200"
    +>
    +label: <
    +  name: "method"
    +  value: "get"
    +>
    +label: <
    +  name: "owner"
    +  value: "example"
    +>
    +histogram: <
    +  sample_count: 4711
    +  sample_sum: 403.34
    +  bucket: <
    +    cumulative_count: 121
    +    upper_bound: 25
    +  >
    +  bucket: <
    +    cumulative_count: 2403
    +    upper_bound: 50
    +  >
    +  bucket: <
    +    cumulative_count: 3221
    +    upper_bound: 100
    +  >
    +  bucket: <
    +    cumulative_count: 4233
    +    upper_bound: 200
    +  >
    +>
    +
    + + +
    +
    + + + + +

    func NewConstMetric

    +
    func NewConstMetric(desc *Desc, valueType ValueType, value float64, labelValues ...string) (Metric, error)
    +

    +NewConstMetric returns a metric with one fixed value that cannot be +changed. Users of this package will not have much use for it in regular +operations. However, when implementing custom Collectors, it is useful as a +throw-away metric that is generated on the fly to send it to Prometheus in +the Collect method. NewConstMetric returns an error if the length of +labelValues is not consistent with the variable labels in Desc. +

    + + + + + +

    func NewConstSummary

    +
    func NewConstSummary(
    +    desc *Desc,
    +    count uint64,
    +    sum float64,
    +    quantiles map[float64]float64,
    +    labelValues ...string,
    +) (Metric, error)
    +

    +NewConstSummary returns a metric representing a Prometheus summary with fixed +values for the count, sum, and quantiles. As those parameters cannot be +changed, the returned value does not implement the Summary interface (but +only the Metric interface). Users of this package will not have much use for +it in regular operations. However, when implementing custom Collectors, it is +useful as a throw-away metric that is generated on the fly to send it to +Prometheus in the Collect method. +

    +

    +quantiles maps ranks to quantile values. For example, a median latency of +0.23s and a 99th percentile latency of 0.56s would be expressed as: +

    +
    map[float64]float64{0.5: 0.23, 0.99: 0.56}
    +
    +

    +NewConstSummary returns an error if the length of labelValues is not +consistent with the variable labels in Desc. +

    + +
    + +
    +

    Example

    + + + +

    Code:

    +
    desc := prometheus.NewDesc(
    +    "http_request_duration_seconds",
    +    "A summary of the HTTP request durations.",
    +    []string{"code", "method"},
    +    prometheus.Labels{"owner": "example"},
    +)
    +
    +// Create a constant summary from values we got from a 3rd party telemetry system.
    +s := prometheus.MustNewConstSummary(
    +    desc,
    +    4711, 403.34,
    +    map[float64]float64{0.5: 42.3, 0.9: 323.3},
    +    "200", "get",
    +)
    +
    +// Just for demonstration, let's check the state of the summary by
    +// (ab)using its Write method (which is usually only used by Prometheus
    +// internally).
    +metric := &dto.Metric{}
    +s.Write(metric)
    +fmt.Println(proto.MarshalTextString(metric))
    +
    +
    + +

    Output:

    +
    label: <
    +  name: "code"
    +  value: "200"
    +>
    +label: <
    +  name: "method"
    +  value: "get"
    +>
    +label: <
    +  name: "owner"
    +  value: "example"
    +>
    +summary: <
    +  sample_count: 4711
    +  sample_sum: 403.34
    +  quantile: <
    +    quantile: 0.5
    +    value: 42.3
    +  >
    +  quantile: <
    +    quantile: 0.9
    +    value: 323.3
    +  >
    +>
    +
    + + +
    +
    + + + + +

    func NewInvalidMetric

    +
    func NewInvalidMetric(desc *Desc, err error) Metric
    +

    +NewInvalidMetric returns a metric whose Write method always returns the +provided error. It is useful if a Collector finds itself unable to collect +a metric and wishes to report an error to the registry. +

    + + + + + + + + + +

    type MetricVec

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

    +MetricVec is a Collector to bundle metrics of the same name that +differ in their label values. MetricVec is usually not used directly but as a +building block for implementations of vectors of a given metric +type. GaugeVec, CounterVec, SummaryVec, and UntypedVec are examples already +provided in this package. +

    + + + + + + + + + + + + + + +

    func (*MetricVec) Collect

    +
    func (m *MetricVec) Collect(ch chan<- Metric)
    +

    +Collect implements Collector. +

    + + + + + + +

    func (*MetricVec) Delete

    +
    func (m *MetricVec) Delete(labels Labels) bool
    +

    +Delete deletes the metric where the variable labels are the same as those +passed in as labels. It returns true if a metric was deleted. +

    +

    +It is not an error if the number and names of the Labels are inconsistent +with those of the VariableLabels in the Desc of the MetricVec. However, such +inconsistent Labels can never match an actual Metric, so the method will +always return false in that case. +

    +

    +This method is used for the same purpose as DeleteLabelValues(...string). See +there for pros and cons of the two methods. +

    + + + + + + +

    func (*MetricVec) DeleteLabelValues

    +
    func (m *MetricVec) DeleteLabelValues(lvs ...string) bool
    +

    +DeleteLabelValues removes the metric where the variable labels are the same +as those passed in as labels (same order as the VariableLabels in Desc). It +returns true if a metric was deleted. +

    +

    +It is not an error if the number of label values is not the same as the +number of VariableLabels in Desc. However, such inconsistent label count can +never match an actual Metric, so the method will always return false in that +case. +

    +

    +Note that for more than one label value, this method is prone to mistakes +caused by an incorrect order of arguments. Consider Delete(Labels) as an +alternative to avoid that type of mistake. For higher label numbers, the +latter has a much more readable (albeit more verbose) syntax, but it comes +with a performance overhead (for creating and processing the Labels map). +See also the CounterVec example. +

    + + + + + + +

    func (*MetricVec) Describe

    +
    func (m *MetricVec) Describe(ch chan<- *Desc)
    +

    +Describe implements Collector. The length of the returned slice +is always one. +

    + + + + + + +

    func (*MetricVec) GetMetricWith

    +
    func (m *MetricVec) GetMetricWith(labels Labels) (Metric, error)
    +

    +GetMetricWith returns the Metric for the given Labels map (the label names +must match those of the VariableLabels in Desc). If that label map is +accessed for the first time, a new Metric is created. Implications of +creating a Metric without using it and keeping the Metric for later use are +the same as for GetMetricWithLabelValues. +

    +

    +An error is returned if the number and names of the Labels are inconsistent +with those of the VariableLabels in Desc. +

    +

    +This method is used for the same purpose as +GetMetricWithLabelValues(...string). See there for pros and cons of the two +methods. +

    + + + + + + +

    func (*MetricVec) GetMetricWithLabelValues

    +
    func (m *MetricVec) GetMetricWithLabelValues(lvs ...string) (Metric, error)
    +

    +GetMetricWithLabelValues returns the Metric for the given slice of label +values (same order as the VariableLabels in Desc). If that combination of +label values is accessed for the first time, a new Metric is created. +

    +

    +It is possible to call this method without using the returned Metric to only +create the new Metric but leave it at its start value (e.g. a Summary or +Histogram without any observations). See also the SummaryVec example. +

    +

    +Keeping the Metric for later use is possible (and should be considered if +performance is critical), but keep in mind that Reset, DeleteLabelValues and +Delete can be used to delete the Metric from the MetricVec. In that case, the +Metric will still exist, but it will not be exported anymore, even if a +Metric with the same label values is created later. See also the CounterVec +example. +

    +

    +An error is returned if the number of label values is not the same as the +number of VariableLabels in Desc. +

    +

    +Note that for more than one label value, this method is prone to mistakes +caused by an incorrect order of arguments. Consider GetMetricWith(Labels) as +an alternative to avoid that type of mistake. For higher label numbers, the +latter has a much more readable (albeit more verbose) syntax, but it comes +with a performance overhead (for creating and processing the Labels map). +See also the GaugeVec example. +

    + + + + + + +

    func (*MetricVec) Reset

    +
    func (m *MetricVec) Reset()
    +

    +Reset deletes all metrics in this vector. +

    + + + + + + +

    func (*MetricVec) With

    +
    func (m *MetricVec) With(labels Labels) Metric
    +

    +With works as GetMetricWith, but panics if an error occurs. The method allows +neat syntax like: +

    +
    httpReqs.With(Labels{"status":"404", "method":"POST"}).Inc()
    +
    + + + + + + +

    func (*MetricVec) WithLabelValues

    +
    func (m *MetricVec) WithLabelValues(lvs ...string) Metric
    +

    +WithLabelValues works as GetMetricWithLabelValues, but panics if an error +occurs. The method allows neat syntax like: +

    +
    httpReqs.WithLabelValues("404", "POST").Inc()
    +
    + + + + + + + + +

    type MultiError

    +
    type MultiError []error
    +

    +MultiError is a slice of errors implementing the error interface. It is used +by a Gatherer to report multiple errors during MetricFamily gathering. +

    + + + + + + + + + + + + + + +

    func (MultiError) Error

    +
    func (errs MultiError) Error() string
    + + + + + + +

    func (MultiError) MaybeUnwrap

    +
    func (errs MultiError) MaybeUnwrap() error
    +

    +MaybeUnwrap returns nil if len(errs) is 0. It returns the first and only +contained error as error if len(errs is 1). In all other cases, it returns +the MultiError directly. This is helpful for returning a MultiError in a way +that only uses the MultiError if needed. +

    + + + + + + + + +

    type Opts

    +
    type Opts struct {
    +    // Namespace, Subsystem, and Name are components of the fully-qualified
    +    // name of the Metric (created by joining these components with
    +    // "_"). Only Name is mandatory, the others merely help structuring the
    +    // name. Note that the fully-qualified name of the metric must be a
    +    // valid Prometheus metric name.
    +    Namespace string
    +    Subsystem string
    +    Name      string
    +
    +    // Help provides information about this metric. Mandatory!
    +    //
    +    // Metrics with the same fully-qualified name must have the same Help
    +    // string.
    +    Help string
    +
    +    // ConstLabels are used to attach fixed labels to this metric. Metrics
    +    // with the same fully-qualified name must have the same label names in
    +    // their ConstLabels.
    +    //
    +    // Note that in most cases, labels have a value that varies during the
    +    // lifetime of a process. Those labels are usually managed with a metric
    +    // vector collector (like CounterVec, GaugeVec, UntypedVec). ConstLabels
    +    // serve only special purposes. One is for the special case where the
    +    // value of a label does not change during the lifetime of a process,
    +    // e.g. if the revision of the running binary is put into a
    +    // label. Another, more advanced purpose is if more than one Collector
    +    // needs to collect Metrics with the same fully-qualified name. In that
    +    // case, those Metrics must differ in the values of their
    +    // ConstLabels. See the Collector examples.
    +    //
    +    // If the value of a label never changes (not even between binaries),
    +    // that label most likely should not be a label at all (but part of the
    +    // metric name).
    +    ConstLabels Labels
    +}
    +

    +Opts bundles the options for creating most Metric types. Each metric +implementation XXX has its own XXXOpts type, but in most cases, it is just be +an alias of this type (which might change when the requirement arises.) +

    +

    +It is mandatory to set Name and Help to a non-empty string. All other fields +are optional and can safely be left at their zero value. +

    + + + + + + + + + + + + + + + + +

    type Registerer

    +
    type Registerer interface {
    +    // Register registers a new Collector to be included in metrics
    +    // collection. It returns an error if the descriptors provided by the
    +    // Collector are invalid or if they — in combination with descriptors of
    +    // already registered Collectors — do not fulfill the consistency and
    +    // uniqueness criteria described in the documentation of metric.Desc.
    +    //
    +    // If the provided Collector is equal to a Collector already registered
    +    // (which includes the case of re-registering the same Collector), the
    +    // returned error is an instance of AlreadyRegisteredError, which
    +    // contains the previously registered Collector.
    +    //
    +    // It is in general not safe to register the same Collector multiple
    +    // times concurrently.
    +    Register(Collector) error
    +    // MustRegister works like Register but registers any number of
    +    // Collectors and panics upon the first registration that causes an
    +    // error.
    +    MustRegister(...Collector)
    +    // Unregister unregisters the Collector that equals the Collector passed
    +    // in as an argument.  (Two Collectors are considered equal if their
    +    // Describe method yields the same set of descriptors.) The function
    +    // returns whether a Collector was unregistered.
    +    //
    +    // Note that even after unregistering, it will not be possible to
    +    // register a new Collector that is inconsistent with the unregistered
    +    // Collector, e.g. a Collector collecting metrics with the same name but
    +    // a different help string. The rationale here is that the same registry
    +    // instance must only collect consistent metrics throughout its
    +    // lifetime.
    +    Unregister(Collector) bool
    +}
    +

    +Registerer is the interface for the part of a registry in charge of +registering and unregistering. Users of custom registries should use +Registerer as type for registration purposes (rather then the Registry type +directly). In that way, they are free to use custom Registerer implementation +(e.g. for testing purposes). +

    + + + + + + + + + + + + + + + + +

    type Registry

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

    +Registry registers Prometheus collectors, collects their metrics, and gathers +them into MetricFamilies for exposition. It implements both Registerer and +Gatherer. The zero value is not usable. Create instances with NewRegistry or +NewPedanticRegistry. +

    + + + + + + + + + + + + +

    func NewPedanticRegistry

    +
    func NewPedanticRegistry() *Registry
    +

    +NewPedanticRegistry returns a registry that checks during collection if each +collected Metric is consistent with its reported Desc, and if the Desc has +actually been registered with the registry. +

    +

    +Usually, a Registry will be happy as long as the union of all collected +Metrics is consistent and valid even if some metrics are not consistent with +their own Desc or a Desc provided by their registered Collector. Well-behaved +Collectors and Metrics will only provide consistent Descs. This Registry is +useful to test the implementation of Collectors and Metrics. +

    + + + + + +

    func NewRegistry

    +
    func NewRegistry() *Registry
    +

    +NewRegistry creates a new vanilla Registry without any Collectors +pre-registered. +

    + + + + + + + +

    func (*Registry) Gather

    +
    func (r *Registry) Gather() ([]*dto.MetricFamily, error)
    +

    +Gather implements Gatherer. +

    + + + + + + +

    func (*Registry) MustRegister

    +
    func (r *Registry) MustRegister(cs ...Collector)
    +

    +MustRegister implements Registerer. +

    + + + + + + +

    func (*Registry) Register

    +
    func (r *Registry) Register(c Collector) error
    +

    +Register implements Registerer. +

    + + + + + + +

    func (*Registry) Unregister

    +
    func (r *Registry) Unregister(c Collector) bool
    +

    +Unregister implements Registerer. +

    + + + + + + + + +

    type Summary

    +
    type Summary interface {
    +    Metric
    +    Collector
    +
    +    // Observe adds a single observation to the summary.
    +    Observe(float64)
    +}
    +

    +A Summary captures individual observations from an event or sample stream and +summarizes them in a manner similar to traditional summary statistics: 1. sum +of observations, 2. observation count, 3. rank estimations. +

    +

    +A typical use-case is the observation of request latencies. By default, a +Summary provides the median, the 90th and the 99th percentile of the latency +as rank estimations. +

    +

    +Note that the rank estimations cannot be aggregated in a meaningful way with +the Prometheus query language (i.e. you cannot average or add them). If you +need aggregatable quantiles (e.g. you want the 99th percentile latency of all +queries served across all instances of a service), consider the Histogram +metric type. See the Prometheus documentation for more details. +

    +

    +To create Summary instances, use NewSummary. +

    + + + + + + +
    + +
    +

    Example

    + + + +

    Code:

    +
    temps := prometheus.NewSummary(prometheus.SummaryOpts{
    +    Name: "pond_temperature_celsius",
    +    Help: "The temperature of the frog pond.", // Sorry, we can't measure how badly it smells.
    +})
    +
    +// Simulate some observations.
    +for i := 0; i < 1000; i++ {
    +    temps.Observe(30 + math.Floor(120*math.Sin(float64(i)*0.1))/10)
    +}
    +
    +// Just for demonstration, let's check the state of the summary by
    +// (ab)using its Write method (which is usually only used by Prometheus
    +// internally).
    +metric := &dto.Metric{}
    +temps.Write(metric)
    +fmt.Println(proto.MarshalTextString(metric))
    +
    +
    + +

    Output:

    +
    summary: <
    +  sample_count: 1000
    +  sample_sum: 29969.50000000001
    +  quantile: <
    +    quantile: 0.5
    +    value: 31.1
    +  >
    +  quantile: <
    +    quantile: 0.9
    +    value: 41.3
    +  >
    +  quantile: <
    +    quantile: 0.99
    +    value: 41.9
    +  >
    +>
    +
    + + +
    +
    + + + + + + +

    func NewSummary

    +
    func NewSummary(opts SummaryOpts) Summary
    +

    +NewSummary creates a new Summary based on the provided SummaryOpts. +

    + + + + + + + + + +

    type SummaryOpts

    +
    type SummaryOpts struct {
    +    // Namespace, Subsystem, and Name are components of the fully-qualified
    +    // name of the Summary (created by joining these components with
    +    // "_"). Only Name is mandatory, the others merely help structuring the
    +    // name. Note that the fully-qualified name of the Summary must be a
    +    // valid Prometheus metric name.
    +    Namespace string
    +    Subsystem string
    +    Name      string
    +
    +    // Help provides information about this Summary. Mandatory!
    +    //
    +    // Metrics with the same fully-qualified name must have the same Help
    +    // string.
    +    Help string
    +
    +    // ConstLabels are used to attach fixed labels to this
    +    // Summary. Summaries with the same fully-qualified name must have the
    +    // same label names in their ConstLabels.
    +    //
    +    // Note that in most cases, labels have a value that varies during the
    +    // lifetime of a process. Those labels are usually managed with a
    +    // SummaryVec. ConstLabels serve only special purposes. One is for the
    +    // special case where the value of a label does not change during the
    +    // lifetime of a process, e.g. if the revision of the running binary is
    +    // put into a label. Another, more advanced purpose is if more than one
    +    // Collector needs to collect Summaries with the same fully-qualified
    +    // name. In that case, those Summaries must differ in the values of
    +    // their ConstLabels. See the Collector examples.
    +    //
    +    // If the value of a label never changes (not even between binaries),
    +    // that label most likely should not be a label at all (but part of the
    +    // metric name).
    +    ConstLabels Labels
    +
    +    // Objectives defines the quantile rank estimates with their respective
    +    // absolute error. If Objectives[q] = e, then the value reported
    +    // for q will be the φ-quantile value for some φ between q-e and q+e.
    +    // The default value is DefObjectives.
    +    Objectives map[float64]float64
    +
    +    // MaxAge defines the duration for which an observation stays relevant
    +    // for the summary. Must be positive. The default value is DefMaxAge.
    +    MaxAge time.Duration
    +
    +    // AgeBuckets is the number of buckets used to exclude observations that
    +    // are older than MaxAge from the summary. A higher number has a
    +    // resource penalty, so only increase it if the higher resolution is
    +    // really required. For very high observation rates, you might want to
    +    // reduce the number of age buckets. With only one age bucket, you will
    +    // effectively see a complete reset of the summary each time MaxAge has
    +    // passed. The default value is DefAgeBuckets.
    +    AgeBuckets uint32
    +
    +    // BufCap defines the default sample stream buffer size.  The default
    +    // value of DefBufCap should suffice for most uses. If there is a need
    +    // to increase the value, a multiple of 500 is recommended (because that
    +    // is the internal buffer size of the underlying package
    +    // "github.com/bmizerany/perks/quantile").
    +    BufCap uint32
    +}
    +

    +SummaryOpts bundles the options for creating a Summary metric. It is +mandatory to set Name and Help to a non-empty string. All other fields are +optional and can safely be left at their zero value. +

    + + + + + + + + + + + + + + + + +

    type SummaryVec

    +
    type SummaryVec struct {
    +    *MetricVec
    +}
    +

    +SummaryVec is a Collector that bundles a set of Summaries that all share the +same Desc, but have different values for their variable labels. This is used +if you want to count the same thing partitioned by various dimensions +(e.g. HTTP request latencies, partitioned by status code and method). Create +instances with NewSummaryVec. +

    + + + + + + +
    + +
    +

    Example

    + + + +

    Code:

    +
    temps := prometheus.NewSummaryVec(
    +    prometheus.SummaryOpts{
    +        Name: "pond_temperature_celsius",
    +        Help: "The temperature of the frog pond.", // Sorry, we can't measure how badly it smells.
    +    },
    +    []string{"species"},
    +)
    +
    +// Simulate some observations.
    +for i := 0; i < 1000; i++ {
    +    temps.WithLabelValues("litoria-caerulea").Observe(30 + math.Floor(120*math.Sin(float64(i)*0.1))/10)
    +    temps.WithLabelValues("lithobates-catesbeianus").Observe(32 + math.Floor(100*math.Cos(float64(i)*0.11))/10)
    +}
    +
    +// Create a Summary without any observations.
    +temps.WithLabelValues("leiopelma-hochstetteri")
    +
    +// Just for demonstration, let's check the state of the summary vector
    +// by registering it with a custom registry and then let it collect the
    +// metrics.
    +reg := prometheus.NewRegistry()
    +reg.MustRegister(temps)
    +
    +metricFamilies, err := reg.Gather()
    +if err != nil || len(metricFamilies) != 1 {
    +    panic("unexpected behavior of custom test registry")
    +}
    +fmt.Println(proto.MarshalTextString(metricFamilies[0]))
    +
    +
    + +

    Output:

    +
    name: "pond_temperature_celsius"
    +help: "The temperature of the frog pond."
    +type: SUMMARY
    +metric: <
    +  label: <
    +    name: "species"
    +    value: "leiopelma-hochstetteri"
    +  >
    +  summary: <
    +    sample_count: 0
    +    sample_sum: 0
    +    quantile: <
    +      quantile: 0.5
    +      value: nan
    +    >
    +    quantile: <
    +      quantile: 0.9
    +      value: nan
    +    >
    +    quantile: <
    +      quantile: 0.99
    +      value: nan
    +    >
    +  >
    +>
    +metric: <
    +  label: <
    +    name: "species"
    +    value: "lithobates-catesbeianus"
    +  >
    +  summary: <
    +    sample_count: 1000
    +    sample_sum: 31956.100000000017
    +    quantile: <
    +      quantile: 0.5
    +      value: 32.4
    +    >
    +    quantile: <
    +      quantile: 0.9
    +      value: 41.4
    +    >
    +    quantile: <
    +      quantile: 0.99
    +      value: 41.9
    +    >
    +  >
    +>
    +metric: <
    +  label: <
    +    name: "species"
    +    value: "litoria-caerulea"
    +  >
    +  summary: <
    +    sample_count: 1000
    +    sample_sum: 29969.50000000001
    +    quantile: <
    +      quantile: 0.5
    +      value: 31.1
    +    >
    +    quantile: <
    +      quantile: 0.9
    +      value: 41.3
    +    >
    +    quantile: <
    +      quantile: 0.99
    +      value: 41.9
    +    >
    +  >
    +>
    +
    + + +
    +
    + + + + + + +

    func NewSummaryVec

    +
    func NewSummaryVec(opts SummaryOpts, labelNames []string) *SummaryVec
    +

    +NewSummaryVec creates a new SummaryVec based on the provided SummaryOpts and +partitioned by the given label names. At least one label name must be +provided. +

    + + + + + + + +

    func (*SummaryVec) GetMetricWith

    +
    func (m *SummaryVec) GetMetricWith(labels Labels) (Summary, error)
    +

    +GetMetricWith replaces the method of the same name in MetricVec. The +difference is that this method returns a Summary and not a Metric so that no +type conversion is required. +

    + + + + + + +

    func (*SummaryVec) GetMetricWithLabelValues

    +
    func (m *SummaryVec) GetMetricWithLabelValues(lvs ...string) (Summary, error)
    +

    +GetMetricWithLabelValues replaces the method of the same name in +MetricVec. The difference is that this method returns a Summary and not a +Metric so that no type conversion is required. +

    + + + + + + +

    func (*SummaryVec) With

    +
    func (m *SummaryVec) With(labels Labels) Summary
    +

    +With works as GetMetricWith, but panics where GetMetricWithLabels would have +returned an error. By not returning an error, With allows shortcuts like +

    +
    myVec.With(Labels{"code": "404", "method": "GET"}).Observe(42.21)
    +
    + + + + + + +

    func (*SummaryVec) WithLabelValues

    +
    func (m *SummaryVec) WithLabelValues(lvs ...string) Summary
    +

    +WithLabelValues works as GetMetricWithLabelValues, but panics where +GetMetricWithLabelValues would have returned an error. By not returning an +error, WithLabelValues allows shortcuts like +

    +
    myVec.WithLabelValues("404", "GET").Observe(42.21)
    +
    + + + + + + + + +

    type Untyped

    +
    type Untyped interface {
    +    Metric
    +    Collector
    +
    +    // Set sets the Untyped metric to an arbitrary value.
    +    Set(float64)
    +    // Inc increments the Untyped metric by 1.
    +    Inc()
    +    // Dec decrements the Untyped metric by 1.
    +    Dec()
    +    // Add adds the given value to the Untyped metric. (The value can be
    +    // negative, resulting in a decrease.)
    +    Add(float64)
    +    // Sub subtracts the given value from the Untyped metric. (The value can
    +    // be negative, resulting in an increase.)
    +    Sub(float64)
    +}
    +

    +Untyped is a Metric that represents a single numerical value that can +arbitrarily go up and down. +

    +

    +An Untyped metric works the same as a Gauge. The only difference is that to +no type information is implied. +

    +

    +To create Untyped instances, use NewUntyped. +

    + + + + + + + + + + + + +

    func NewUntyped

    +
    func NewUntyped(opts UntypedOpts) Untyped
    +

    +NewUntyped creates a new Untyped metric from the provided UntypedOpts. +

    + + + + + + + + + +

    type UntypedFunc

    +
    type UntypedFunc interface {
    +    Metric
    +    Collector
    +}
    +

    +UntypedFunc is an Untyped whose value is determined at collect time by +calling a provided function. +

    +

    +To create UntypedFunc instances, use NewUntypedFunc. +

    + + + + + + + + + + + + +

    func NewUntypedFunc

    +
    func NewUntypedFunc(opts UntypedOpts, function func() float64) UntypedFunc
    +

    +NewUntypedFunc creates a new UntypedFunc based on the provided +UntypedOpts. The value reported is determined by calling the given function +from within the Write method. Take into account that metric collection may +happen concurrently. If that results in concurrent calls to Write, like in +the case where an UntypedFunc is directly registered with Prometheus, the +provided function must be concurrency-safe. +

    + + + + + + + + + +

    type UntypedOpts

    +
    type UntypedOpts Opts
    +

    +UntypedOpts is an alias for Opts. See there for doc comments. +

    + + + + + + + + + + + + + + + + +

    type UntypedVec

    +
    type UntypedVec struct {
    +    *MetricVec
    +}
    +

    +UntypedVec is a Collector that bundles a set of Untyped metrics that all +share the same Desc, but have different values for their variable +labels. This is used if you want to count the same thing partitioned by +various dimensions. Create instances with NewUntypedVec. +

    + + + + + + + + + + + + +

    func NewUntypedVec

    +
    func NewUntypedVec(opts UntypedOpts, labelNames []string) *UntypedVec
    +

    +NewUntypedVec creates a new UntypedVec based on the provided UntypedOpts and +partitioned by the given label names. At least one label name must be +provided. +

    + + + + + + + +

    func (*UntypedVec) GetMetricWith

    +
    func (m *UntypedVec) GetMetricWith(labels Labels) (Untyped, error)
    +

    +GetMetricWith replaces the method of the same name in MetricVec. The +difference is that this method returns an Untyped and not a Metric so that no +type conversion is required. +

    + + + + + + +

    func (*UntypedVec) GetMetricWithLabelValues

    +
    func (m *UntypedVec) GetMetricWithLabelValues(lvs ...string) (Untyped, error)
    +

    +GetMetricWithLabelValues replaces the method of the same name in +MetricVec. The difference is that this method returns an Untyped and not a +Metric so that no type conversion is required. +

    + + + + + + +

    func (*UntypedVec) With

    +
    func (m *UntypedVec) With(labels Labels) Untyped
    +

    +With works as GetMetricWith, but panics where GetMetricWithLabels would have +returned an error. By not returning an error, With allows shortcuts like +

    +
    myVec.With(Labels{"code": "404", "method": "GET"}).Add(42)
    +
    + + + + + + +

    func (*UntypedVec) WithLabelValues

    +
    func (m *UntypedVec) WithLabelValues(lvs ...string) Untyped
    +

    +WithLabelValues works as GetMetricWithLabelValues, but panics where +GetMetricWithLabelValues would have returned an error. By not returning an +error, WithLabelValues allows shortcuts like +

    +
    myVec.WithLabelValues("404", "GET").Add(42)
    +
    + + + + + + + + +

    type ValueType

    +
    type ValueType int
    +

    +ValueType is an enumeration of metric types that represent a simple value. +

    + + + +
    const (
    +    CounterValue ValueType
    +    GaugeValue
    +    UntypedValue
    +)
    +

    +Possible values for the ValueType enum. +

    + + + + + + + + + + + + + + + + + + + + + + + +

    Subdirectories

    + + + + +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    NameSynopsis
    ..
    + promhttp + + Package promhttp contains functions to create http.Handler instances to expose Prometheus metrics via HTTP. +
    + push + + Package push provides functions to push metrics to a Pushgateway. +
    +
    + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/github.com/prometheus/client_golang/prometheus/promhttp/index.html b/pkg/github.com/prometheus/client_golang/prometheus/promhttp/index.html new file mode 100644 index 0000000..67f5de4 --- /dev/null +++ b/pkg/github.com/prometheus/client_golang/prometheus/promhttp/index.html @@ -0,0 +1,367 @@ + + + + + + + + promhttp - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Package promhttp

    + + + + + + + + + + + + + + +
    +
    +
    import "github.com/prometheus/client_golang/prometheus/promhttp"
    +
    +
    +
    Overview
    +
    Index
    + + +
    +
    + +
    + +
    +

    Overview ▾

    +

    +Package promhttp contains functions to create http.Handler instances to +expose Prometheus metrics via HTTP. In later versions of this package, it +will also contain tooling to instrument instances of http.Handler and +http.RoundTripper. +

    +

    +promhttp.Handler acts on the prometheus.DefaultGatherer. With HandlerFor, +you can create a handler for a custom registry or anything that implements +the Gatherer interface. It also allows to create handlers that act +differently on errors or allow to log errors. +

    + +
    +
    + + +
    + +
    +

    Index ▾

    + + + + + + + +

    Package files

    +

    + + + http.go + + +

    + +
    +
    + + + + + + + + +

    func Handler

    +
    func Handler() http.Handler
    +

    +Handler returns an HTTP handler for the prometheus.DefaultGatherer. The +Handler uses the default HandlerOpts, i.e. report the first error as an HTTP +error, no error logging, and compression if requested by the client. +

    +

    +If you want to create a Handler for the DefaultGatherer with different +HandlerOpts, create it with HandlerFor with prometheus.DefaultGatherer and +your desired HandlerOpts. +

    + + + + + + + +

    func HandlerFor

    +
    func HandlerFor(reg prometheus.Gatherer, opts HandlerOpts) http.Handler
    +

    +HandlerFor returns an http.Handler for the provided Gatherer. The behavior +of the Handler is defined by the provided HandlerOpts. +

    + + + + + + + + +

    type HandlerErrorHandling

    +
    type HandlerErrorHandling int
    +

    +HandlerErrorHandling defines how a Handler serving metrics will handle +errors. +

    + + + +
    const (
    +    // Serve an HTTP status code 500 upon the first error
    +    // encountered. Report the error message in the body.
    +    HTTPErrorOnError HandlerErrorHandling = iota
    +    // Ignore errors and try to serve as many metrics as possible.  However,
    +    // if no metrics can be served, serve an HTTP status code 500 and the
    +    // last error message in the body. Only use this in deliberate "best
    +    // effort" metrics collection scenarios. It is recommended to at least
    +    // log errors (by providing an ErrorLog in HandlerOpts) to not mask
    +    // errors completely.
    +    ContinueOnError
    +    // Panic upon the first error encountered (useful for "crash only" apps).
    +    PanicOnError
    +)
    +

    +These constants cause handlers serving metrics to behave as described if +errors are encountered. +

    + + + + + + + + + + + + + + + +

    type HandlerOpts

    +
    type HandlerOpts struct {
    +    // ErrorLog specifies an optional logger for errors collecting and
    +    // serving metrics. If nil, errors are not logged at all.
    +    ErrorLog Logger
    +    // ErrorHandling defines how errors are handled. Note that errors are
    +    // logged regardless of the configured ErrorHandling provided ErrorLog
    +    // is not nil.
    +    ErrorHandling HandlerErrorHandling
    +    // If DisableCompression is true, the handler will never compress the
    +    // response, even if requested by the client.
    +    DisableCompression bool
    +}
    +

    +HandlerOpts specifies options how to serve metrics via an http.Handler. The +zero value of HandlerOpts is a reasonable default. +

    + + + + + + + + + + + + + + + + +

    type Logger

    +
    type Logger interface {
    +    Println(v ...interface{})
    +}
    +

    +Logger is the minimal interface HandlerOpts needs for logging. Note that +log.Logger from the standard library implements this interface, and it is +easy to implement by custom loggers, if they don't do so already anyway. +

    + + + + + + + + + + + + + + + + + + + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/github.com/prometheus/client_golang/prometheus/push/index.html b/pkg/github.com/prometheus/client_golang/prometheus/push/index.html new file mode 100644 index 0000000..89f6367 --- /dev/null +++ b/pkg/github.com/prometheus/client_golang/prometheus/push/index.html @@ -0,0 +1,388 @@ + + + + + + + + push - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Package push

    + + + + + + + + + + + + + + +
    +
    +
    import "github.com/prometheus/client_golang/prometheus/push"
    +
    +
    +
    Overview
    +
    Index
    + +
    Examples
    + + +
    +
    + +
    + +
    +

    Overview ▾

    +

    +Package push provides functions to push metrics to a Pushgateway. The metrics +to push are either collected from a provided registry, or from explicitly +listed collectors. +

    +

    +See the documentation of the Pushgateway to understand the meaning of the +grouping parameters and the differences between push.Registry and +push.Collectors on the one hand and push.AddRegistry and push.AddCollectors +on the other hand: https://github.com/prometheus/pushgateway +

    + +
    +
    + + + + + + + + + + + +

    func AddCollectors

    +
    func AddCollectors(job string, grouping map[string]string, url string, collectors ...prometheus.Collector) error
    +

    +AddCollectors works like AddFromGatherer, but it does not use a Gatherer. +Instead, it collects from the provided collectors directly. It is a +convenient way to push only a few metrics. +

    + + + + + + + +

    func AddFromGatherer

    +
    func AddFromGatherer(job string, grouping map[string]string, url string, g prometheus.Gatherer) error
    +

    +AddFromGatherer works like FromGatherer, but only previously pushed metrics +with the same name (and the same job and other grouping labels) will be +replaced. (It uses HTTP method 'POST' to push to the Pushgateway.) +

    + + + + + + + +

    func Collectors

    +
    func Collectors(job string, grouping map[string]string, url string, collectors ...prometheus.Collector) error
    +

    +Collectors works like FromGatherer, but it does not use a Gatherer. Instead, +it collects from the provided collectors directly. It is a convenient way to +push only a few metrics. +

    + +
    + +
    +

    Example

    + + + +

    Code:

    +
    +completionTime := prometheus.NewGauge(prometheus.GaugeOpts{
    +    Name: "db_backup_last_completion_timestamp_seconds",
    +    Help: "The timestamp of the last successful completion of a DB backup.",
    +})
    +completionTime.Set(float64(time.Now().Unix()))
    +if err := push.Collectors(
    +    "db_backup", push.HostnameGroupingKey(),
    +    "http://pushgateway:9091",
    +    completionTime,
    +); err != nil {
    +    fmt.Println("Could not push completion time to Pushgateway:", err)
    +}
    +
    + + +
    +
    + + + + + + +

    func FromGatherer

    +
    func FromGatherer(job string, grouping map[string]string, url string, g prometheus.Gatherer) error
    +

    +FromGatherer triggers a metric collection by the provided Gatherer (which is +usually implemented by a prometheus.Registry) and pushes all gathered metrics +to the Pushgateway specified by url, using the provided job name and the +(optional) further grouping labels (the grouping map may be nil). See the +Pushgateway documentation for detailed implications of the job and other +grouping labels. Neither the job name nor any grouping label value may +contain a "/". The metrics pushed must not contain a job label of their own +nor any of the grouping labels. +

    +

    +You can use just host:port or ip:port as url, in which case 'http://' is +added automatically. You can also include the schema in the URL. However, do +not include the '/metrics/jobs/...' part. +

    +

    +Note that all previously pushed metrics with the same job and other grouping +labels will be replaced with the metrics pushed by this call. (It uses HTTP +method 'PUT' to push to the Pushgateway.) +

    + +
    + +
    +

    Example

    + + + +

    Code:

    +
    +registry := prometheus.NewRegistry()
    +
    +completionTime := prometheus.NewGauge(prometheus.GaugeOpts{
    +    Name: "db_backup_last_completion_timestamp_seconds",
    +    Help: "The timestamp of the last successful completion of a DB backup.",
    +})
    +registry.MustRegister(completionTime)
    +
    +completionTime.Set(float64(time.Now().Unix()))
    +if err := push.FromGatherer(
    +    "db_backup", push.HostnameGroupingKey(),
    +    "http://pushgateway:9091",
    +    registry,
    +); err != nil {
    +    fmt.Println("Could not push completion time to Pushgateway:", err)
    +}
    +
    + + +
    +
    + + + + + + +

    func HostnameGroupingKey

    +
    func HostnameGroupingKey() map[string]string
    +

    +HostnameGroupingKey returns a label map with the only entry +{instance="<hostname>"}. This can be conveniently used as the grouping +parameter if metrics should be pushed with the hostname as label. The +returned map is created upon each call so that the caller is free to add more +labels to the map. +

    + + + + + + + + + + + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/github.com/prometheus/client_model/go/index.html b/pkg/github.com/prometheus/client_model/go/index.html new file mode 100644 index 0000000..6493f59 --- /dev/null +++ b/pkg/github.com/prometheus/client_model/go/index.html @@ -0,0 +1,1204 @@ + + + + + + + + io_prometheus_client - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Package io_prometheus_client

    + + + + + + + + + + + + + + +
    +
    +
    import "github.com/prometheus/client_model/go"
    +
    +
    +
    Overview
    +
    Index
    + + +
    +
    + +
    + +
    +

    Overview ▾

    +

    +Package io_prometheus_client is a generated protocol buffer package. +

    +

    +It is generated from these files: +

    +
    metrics.proto
    +
    +

    +It has these top-level messages: +

    +
    LabelPair
    +Gauge
    +Counter
    +Quantile
    +Summary
    +Untyped
    +Histogram
    +Bucket
    +Metric
    +MetricFamily
    +
    + +
    +
    + + +
    + +
    +

    Index ▾

    + + +
    +
    + + +
    Variables
    + + + + +
    type Bucket
    + + + +
        func (m *Bucket) GetCumulativeCount() uint64
    + + +
        func (m *Bucket) GetUpperBound() float64
    + + +
        func (*Bucket) ProtoMessage()
    + + +
        func (m *Bucket) Reset()
    + + +
        func (m *Bucket) String() string
    + + + +
    type Counter
    + + + +
        func (m *Counter) GetValue() float64
    + + +
        func (*Counter) ProtoMessage()
    + + +
        func (m *Counter) Reset()
    + + +
        func (m *Counter) String() string
    + + + +
    type Gauge
    + + + +
        func (m *Gauge) GetValue() float64
    + + +
        func (*Gauge) ProtoMessage()
    + + +
        func (m *Gauge) Reset()
    + + +
        func (m *Gauge) String() string
    + + + +
    type Histogram
    + + + +
        func (m *Histogram) GetBucket() []*Bucket
    + + +
        func (m *Histogram) GetSampleCount() uint64
    + + +
        func (m *Histogram) GetSampleSum() float64
    + + +
        func (*Histogram) ProtoMessage()
    + + +
        func (m *Histogram) Reset()
    + + +
        func (m *Histogram) String() string
    + + + +
    type LabelPair
    + + + +
        func (m *LabelPair) GetName() string
    + + +
        func (m *LabelPair) GetValue() string
    + + +
        func (*LabelPair) ProtoMessage()
    + + +
        func (m *LabelPair) Reset()
    + + +
        func (m *LabelPair) String() string
    + + + +
    type Metric
    + + + +
        func (m *Metric) GetCounter() *Counter
    + + +
        func (m *Metric) GetGauge() *Gauge
    + + +
        func (m *Metric) GetHistogram() *Histogram
    + + +
        func (m *Metric) GetLabel() []*LabelPair
    + + +
        func (m *Metric) GetSummary() *Summary
    + + +
        func (m *Metric) GetTimestampMs() int64
    + + +
        func (m *Metric) GetUntyped() *Untyped
    + + +
        func (*Metric) ProtoMessage()
    + + +
        func (m *Metric) Reset()
    + + +
        func (m *Metric) String() string
    + + + +
    type MetricFamily
    + + + +
        func (m *MetricFamily) GetHelp() string
    + + +
        func (m *MetricFamily) GetMetric() []*Metric
    + + +
        func (m *MetricFamily) GetName() string
    + + +
        func (m *MetricFamily) GetType() MetricType
    + + +
        func (*MetricFamily) ProtoMessage()
    + + +
        func (m *MetricFamily) Reset()
    + + +
        func (m *MetricFamily) String() string
    + + + +
    type MetricType
    + + + +
        func (x MetricType) Enum() *MetricType
    + + +
        func (x MetricType) String() string
    + + +
        func (x *MetricType) UnmarshalJSON(data []byte) error
    + + + +
    type Quantile
    + + + +
        func (m *Quantile) GetQuantile() float64
    + + +
        func (m *Quantile) GetValue() float64
    + + +
        func (*Quantile) ProtoMessage()
    + + +
        func (m *Quantile) Reset()
    + + +
        func (m *Quantile) String() string
    + + + +
    type Summary
    + + + +
        func (m *Summary) GetQuantile() []*Quantile
    + + +
        func (m *Summary) GetSampleCount() uint64
    + + +
        func (m *Summary) GetSampleSum() float64
    + + +
        func (*Summary) ProtoMessage()
    + + +
        func (m *Summary) Reset()
    + + +
        func (m *Summary) String() string
    + + + +
    type Untyped
    + + + +
        func (m *Untyped) GetValue() float64
    + + +
        func (*Untyped) ProtoMessage()
    + + +
        func (m *Untyped) Reset()
    + + +
        func (m *Untyped) String() string
    + + + +
    +
    + + + + +

    Package files

    +

    + + + metrics.pb.go + + +

    + +
    +
    + + + + + +

    Variables

    + +
    var MetricType_name = map[int32]string{
    +    0: "COUNTER",
    +    1: "GAUGE",
    +    2: "SUMMARY",
    +    3: "UNTYPED",
    +    4: "HISTOGRAM",
    +}
    + + +
    var MetricType_value = map[string]int32{
    +    "COUNTER":   0,
    +    "GAUGE":     1,
    +    "SUMMARY":   2,
    +    "UNTYPED":   3,
    +    "HISTOGRAM": 4,
    +}
    + + + + + + + +

    type Bucket

    +
    type Bucket struct {
    +    CumulativeCount  *uint64  `protobuf:"varint,1,opt,name=cumulative_count" json:"cumulative_count,omitempty"`
    +    UpperBound       *float64 `protobuf:"fixed64,2,opt,name=upper_bound" json:"upper_bound,omitempty"`
    +    XXX_unrecognized []byte   `json:"-"`
    +}
    + + + + + + + + + + + + + + +

    func (*Bucket) GetCumulativeCount

    +
    func (m *Bucket) GetCumulativeCount() uint64
    + + + + + + +

    func (*Bucket) GetUpperBound

    +
    func (m *Bucket) GetUpperBound() float64
    + + + + + + +

    func (*Bucket) ProtoMessage

    +
    func (*Bucket) ProtoMessage()
    + + + + + + +

    func (*Bucket) Reset

    +
    func (m *Bucket) Reset()
    + + + + + + +

    func (*Bucket) String

    +
    func (m *Bucket) String() string
    + + + + + + + + +

    type Counter

    +
    type Counter struct {
    +    Value            *float64 `protobuf:"fixed64,1,opt,name=value" json:"value,omitempty"`
    +    XXX_unrecognized []byte   `json:"-"`
    +}
    + + + + + + + + + + + + + + +

    func (*Counter) GetValue

    +
    func (m *Counter) GetValue() float64
    + + + + + + +

    func (*Counter) ProtoMessage

    +
    func (*Counter) ProtoMessage()
    + + + + + + +

    func (*Counter) Reset

    +
    func (m *Counter) Reset()
    + + + + + + +

    func (*Counter) String

    +
    func (m *Counter) String() string
    + + + + + + + + +

    type Gauge

    +
    type Gauge struct {
    +    Value            *float64 `protobuf:"fixed64,1,opt,name=value" json:"value,omitempty"`
    +    XXX_unrecognized []byte   `json:"-"`
    +}
    + + + + + + + + + + + + + + +

    func (*Gauge) GetValue

    +
    func (m *Gauge) GetValue() float64
    + + + + + + +

    func (*Gauge) ProtoMessage

    +
    func (*Gauge) ProtoMessage()
    + + + + + + +

    func (*Gauge) Reset

    +
    func (m *Gauge) Reset()
    + + + + + + +

    func (*Gauge) String

    +
    func (m *Gauge) String() string
    + + + + + + + + +

    type Histogram

    +
    type Histogram struct {
    +    SampleCount      *uint64   `protobuf:"varint,1,opt,name=sample_count" json:"sample_count,omitempty"`
    +    SampleSum        *float64  `protobuf:"fixed64,2,opt,name=sample_sum" json:"sample_sum,omitempty"`
    +    Bucket           []*Bucket `protobuf:"bytes,3,rep,name=bucket" json:"bucket,omitempty"`
    +    XXX_unrecognized []byte    `json:"-"`
    +}
    + + + + + + + + + + + + + + +

    func (*Histogram) GetBucket

    +
    func (m *Histogram) GetBucket() []*Bucket
    + + + + + + +

    func (*Histogram) GetSampleCount

    +
    func (m *Histogram) GetSampleCount() uint64
    + + + + + + +

    func (*Histogram) GetSampleSum

    +
    func (m *Histogram) GetSampleSum() float64
    + + + + + + +

    func (*Histogram) ProtoMessage

    +
    func (*Histogram) ProtoMessage()
    + + + + + + +

    func (*Histogram) Reset

    +
    func (m *Histogram) Reset()
    + + + + + + +

    func (*Histogram) String

    +
    func (m *Histogram) String() string
    + + + + + + + + +

    type LabelPair

    +
    type LabelPair struct {
    +    Name             *string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"`
    +    Value            *string `protobuf:"bytes,2,opt,name=value" json:"value,omitempty"`
    +    XXX_unrecognized []byte  `json:"-"`
    +}
    + + + + + + + + + + + + + + +

    func (*LabelPair) GetName

    +
    func (m *LabelPair) GetName() string
    + + + + + + +

    func (*LabelPair) GetValue

    +
    func (m *LabelPair) GetValue() string
    + + + + + + +

    func (*LabelPair) ProtoMessage

    +
    func (*LabelPair) ProtoMessage()
    + + + + + + +

    func (*LabelPair) Reset

    +
    func (m *LabelPair) Reset()
    + + + + + + +

    func (*LabelPair) String

    +
    func (m *LabelPair) String() string
    + + + + + + + + +

    type Metric

    +
    type Metric struct {
    +    Label            []*LabelPair `protobuf:"bytes,1,rep,name=label" json:"label,omitempty"`
    +    Gauge            *Gauge       `protobuf:"bytes,2,opt,name=gauge" json:"gauge,omitempty"`
    +    Counter          *Counter     `protobuf:"bytes,3,opt,name=counter" json:"counter,omitempty"`
    +    Summary          *Summary     `protobuf:"bytes,4,opt,name=summary" json:"summary,omitempty"`
    +    Untyped          *Untyped     `protobuf:"bytes,5,opt,name=untyped" json:"untyped,omitempty"`
    +    Histogram        *Histogram   `protobuf:"bytes,7,opt,name=histogram" json:"histogram,omitempty"`
    +    TimestampMs      *int64       `protobuf:"varint,6,opt,name=timestamp_ms" json:"timestamp_ms,omitempty"`
    +    XXX_unrecognized []byte       `json:"-"`
    +}
    + + + + + + + + + + + + + + +

    func (*Metric) GetCounter

    +
    func (m *Metric) GetCounter() *Counter
    + + + + + + +

    func (*Metric) GetGauge

    +
    func (m *Metric) GetGauge() *Gauge
    + + + + + + +

    func (*Metric) GetHistogram

    +
    func (m *Metric) GetHistogram() *Histogram
    + + + + + + +

    func (*Metric) GetLabel

    +
    func (m *Metric) GetLabel() []*LabelPair
    + + + + + + +

    func (*Metric) GetSummary

    +
    func (m *Metric) GetSummary() *Summary
    + + + + + + +

    func (*Metric) GetTimestampMs

    +
    func (m *Metric) GetTimestampMs() int64
    + + + + + + +

    func (*Metric) GetUntyped

    +
    func (m *Metric) GetUntyped() *Untyped
    + + + + + + +

    func (*Metric) ProtoMessage

    +
    func (*Metric) ProtoMessage()
    + + + + + + +

    func (*Metric) Reset

    +
    func (m *Metric) Reset()
    + + + + + + +

    func (*Metric) String

    +
    func (m *Metric) String() string
    + + + + + + + + +

    type MetricFamily

    +
    type MetricFamily struct {
    +    Name             *string     `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"`
    +    Help             *string     `protobuf:"bytes,2,opt,name=help" json:"help,omitempty"`
    +    Type             *MetricType `protobuf:"varint,3,opt,name=type,enum=io.prometheus.client.MetricType" json:"type,omitempty"`
    +    Metric           []*Metric   `protobuf:"bytes,4,rep,name=metric" json:"metric,omitempty"`
    +    XXX_unrecognized []byte      `json:"-"`
    +}
    + + + + + + + + + + + + + + +

    func (*MetricFamily) GetHelp

    +
    func (m *MetricFamily) GetHelp() string
    + + + + + + +

    func (*MetricFamily) GetMetric

    +
    func (m *MetricFamily) GetMetric() []*Metric
    + + + + + + +

    func (*MetricFamily) GetName

    +
    func (m *MetricFamily) GetName() string
    + + + + + + +

    func (*MetricFamily) GetType

    +
    func (m *MetricFamily) GetType() MetricType
    + + + + + + +

    func (*MetricFamily) ProtoMessage

    +
    func (*MetricFamily) ProtoMessage()
    + + + + + + +

    func (*MetricFamily) Reset

    +
    func (m *MetricFamily) Reset()
    + + + + + + +

    func (*MetricFamily) String

    +
    func (m *MetricFamily) String() string
    + + + + + + + + +

    type MetricType

    +
    type MetricType int32
    + + + +
    const (
    +    MetricType_COUNTER   MetricType = 0
    +    MetricType_GAUGE     MetricType = 1
    +    MetricType_SUMMARY   MetricType = 2
    +    MetricType_UNTYPED   MetricType = 3
    +    MetricType_HISTOGRAM MetricType = 4
    +)
    + + + + + + + + + + + + + +

    func (MetricType) Enum

    +
    func (x MetricType) Enum() *MetricType
    + + + + + + +

    func (MetricType) String

    +
    func (x MetricType) String() string
    + + + + + + +

    func (*MetricType) UnmarshalJSON

    +
    func (x *MetricType) UnmarshalJSON(data []byte) error
    + + + + + + + + +

    type Quantile

    +
    type Quantile struct {
    +    Quantile         *float64 `protobuf:"fixed64,1,opt,name=quantile" json:"quantile,omitempty"`
    +    Value            *float64 `protobuf:"fixed64,2,opt,name=value" json:"value,omitempty"`
    +    XXX_unrecognized []byte   `json:"-"`
    +}
    + + + + + + + + + + + + + + +

    func (*Quantile) GetQuantile

    +
    func (m *Quantile) GetQuantile() float64
    + + + + + + +

    func (*Quantile) GetValue

    +
    func (m *Quantile) GetValue() float64
    + + + + + + +

    func (*Quantile) ProtoMessage

    +
    func (*Quantile) ProtoMessage()
    + + + + + + +

    func (*Quantile) Reset

    +
    func (m *Quantile) Reset()
    + + + + + + +

    func (*Quantile) String

    +
    func (m *Quantile) String() string
    + + + + + + + + +

    type Summary

    +
    type Summary struct {
    +    SampleCount      *uint64     `protobuf:"varint,1,opt,name=sample_count" json:"sample_count,omitempty"`
    +    SampleSum        *float64    `protobuf:"fixed64,2,opt,name=sample_sum" json:"sample_sum,omitempty"`
    +    Quantile         []*Quantile `protobuf:"bytes,3,rep,name=quantile" json:"quantile,omitempty"`
    +    XXX_unrecognized []byte      `json:"-"`
    +}
    + + + + + + + + + + + + + + +

    func (*Summary) GetQuantile

    +
    func (m *Summary) GetQuantile() []*Quantile
    + + + + + + +

    func (*Summary) GetSampleCount

    +
    func (m *Summary) GetSampleCount() uint64
    + + + + + + +

    func (*Summary) GetSampleSum

    +
    func (m *Summary) GetSampleSum() float64
    + + + + + + +

    func (*Summary) ProtoMessage

    +
    func (*Summary) ProtoMessage()
    + + + + + + +

    func (*Summary) Reset

    +
    func (m *Summary) Reset()
    + + + + + + +

    func (*Summary) String

    +
    func (m *Summary) String() string
    + + + + + + + + +

    type Untyped

    +
    type Untyped struct {
    +    Value            *float64 `protobuf:"fixed64,1,opt,name=value" json:"value,omitempty"`
    +    XXX_unrecognized []byte   `json:"-"`
    +}
    + + + + + + + + + + + + + + +

    func (*Untyped) GetValue

    +
    func (m *Untyped) GetValue() float64
    + + + + + + +

    func (*Untyped) ProtoMessage

    +
    func (*Untyped) ProtoMessage()
    + + + + + + +

    func (*Untyped) Reset

    +
    func (m *Untyped) Reset()
    + + + + + + +

    func (*Untyped) String

    +
    func (m *Untyped) String() string
    + + + + + + + + + + + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/github.com/prometheus/client_model/index.html b/pkg/github.com/prometheus/client_model/index.html new file mode 100644 index 0000000..501924c --- /dev/null +++ b/pkg/github.com/prometheus/client_model/index.html @@ -0,0 +1,130 @@ + + + + + + + + /src/github.com/prometheus/client_model - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Directory /src/github.com/prometheus/client_model

    + + + + + + + + + + + + + + + + + + + +
    + + + + + + + + + + + + + + + + + + + + +
    NameSynopsis
    ..
    + go + + Package io_prometheus_client is a generated protocol buffer package. +
    +
    + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/github.com/prometheus/common/expfmt/index.html b/pkg/github.com/prometheus/common/expfmt/index.html new file mode 100644 index 0000000..9d1c929 --- /dev/null +++ b/pkg/github.com/prometheus/common/expfmt/index.html @@ -0,0 +1,597 @@ + + + + + + + + expfmt - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Package expfmt

    + + + + + + + + + + + + + + +
    +
    +
    import "github.com/prometheus/common/expfmt"
    +
    +
    +
    Overview
    +
    Index
    + + +
    +
    + +
    + +
    +

    Overview ▾

    +

    +A package for reading and writing Prometheus metrics. +

    + +
    +
    + + + + + + + +

    Constants

    + +
    const (
    +    TextVersion = "0.0.4"
    +
    +    ProtoType     = `application/vnd.google.protobuf`
    +    ProtoProtocol = `io.prometheus.client.MetricFamily`
    +    ProtoFmt      = ProtoType + "; proto=" + ProtoProtocol + ";"
    +
    +    // The Content-Type values for the different wire protocols.
    +    FmtUnknown      Format = `<unknown>`
    +    FmtText         Format = `text/plain; version=` + TextVersion
    +    FmtProtoDelim   Format = ProtoFmt + ` encoding=delimited`
    +    FmtProtoText    Format = ProtoFmt + ` encoding=text`
    +    FmtProtoCompact Format = ProtoFmt + ` encoding=compact-text`
    +)
    + + + + + + + +

    func ExtractSamples

    +
    func ExtractSamples(o *DecodeOptions, fams ...*dto.MetricFamily) model.Vector
    +

    +Extract samples builds a slice of samples from the provided metric families. +

    + + + + + + + +

    func MetricFamilyToText

    +
    func MetricFamilyToText(out io.Writer, in *dto.MetricFamily) (int, error)
    +

    +MetricFamilyToText converts a MetricFamily proto message into text format and +writes the resulting lines to 'out'. It returns the number of bytes written +and any error encountered. The output will have the same order as the input, +no further sorting is performed. Furthermore, this function assumes the input +is already sanitized and does not perform any sanity checks. If the input +contains duplicate metrics or invalid metric or label names, the conversion +will result in invalid text format output. +

    +

    +This method fulfills the type 'prometheus.encoder'. +

    + + + + + + + + +

    type DecodeOptions

    +
    type DecodeOptions struct {
    +    // Timestamp is added to each value from the stream that has no explicit timestamp set.
    +    Timestamp model.Time
    +}
    + + + + + + + + + + + + + + + + +

    type Decoder

    +
    type Decoder interface {
    +    Decode(*dto.MetricFamily) error
    +}
    +

    +Decoder types decode an input stream into metric families. +

    + + + + + + + + + + + + +

    func NewDecoder

    +
    func NewDecoder(r io.Reader, format Format) Decoder
    +

    +NewDecoder returns a new decoder based on the given input format. +If the input format does not imply otherwise, a text format decoder is returned. +

    + + + + + + + + + +

    type Encoder

    +
    type Encoder interface {
    +    Encode(*dto.MetricFamily) error
    +}
    +

    +Encoder types encode metric families into an underlying wire protocol. +

    + + + + + + + + + + + + +

    func NewEncoder

    +
    func NewEncoder(w io.Writer, format Format) Encoder
    +

    +NewEncoder returns a new encoder based on content type negotiation. +

    + + + + + + + + + +

    type Format

    +
    type Format string
    + + + + + + + + + + + + +

    func Negotiate

    +
    func Negotiate(h http.Header) Format
    +

    +Negotiate returns the Content-Type based on the given Accept header. +If no appropriate accepted type is found, FmtText is returned. +

    + + + + + +

    func ResponseFormat

    +
    func ResponseFormat(h http.Header) Format
    +

    +ResponseFormat extracts the correct format from a HTTP response header. +If no matching format can be found FormatUnknown is returned. +

    + + + + + + + + + +

    type ParseError

    +
    type ParseError struct {
    +    Line int
    +    Msg  string
    +}
    +

    +ParseError signals errors while parsing the simple and flat text-based +exchange format. +

    + + + + + + + + + + + + + + +

    func (ParseError) Error

    +
    func (e ParseError) Error() string
    +

    +Error implements the error interface. +

    + + + + + + + + +

    type SampleDecoder

    +
    type SampleDecoder struct {
    +    Dec  Decoder
    +    Opts *DecodeOptions
    +    // contains filtered or unexported fields
    +}
    + + + + + + + + + + + + + + +

    func (*SampleDecoder) Decode

    +
    func (sd *SampleDecoder) Decode(s *model.Vector) error
    + + + + + + + + +

    type TextParser

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

    +TextParser is used to parse the simple and flat text-based exchange format. Its +zero value is ready to use. +

    + + + + + + + + + + + + + + +

    func (*TextParser) TextToMetricFamilies

    +
    func (p *TextParser) TextToMetricFamilies(in io.Reader) (map[string]*dto.MetricFamily, error)
    +

    +TextToMetricFamilies reads 'in' as the simple and flat text-based exchange +format and creates MetricFamily proto messages. It returns the MetricFamily +proto messages in a map where the metric names are the keys, along with any +error encountered. +

    +

    +If the input contains duplicate metrics (i.e. lines with the same metric name +and exactly the same label set), the resulting MetricFamily will contain +duplicate Metric proto messages. Similar is true for duplicate label +names. Checks for duplicates have to be performed separately, if required. +Also note that neither the metrics within each MetricFamily are sorted nor +the label pairs within each Metric. Sorting is not required for the most +frequent use of this method, which is sample ingestion in the Prometheus +server. However, for presentation purposes, you might want to sort the +metrics, and in some cases, you must sort the labels, e.g. for consumption by +the metric family injection hook of the Prometheus registry. +

    +

    +Summaries and histograms are rather special beasts. You would probably not +use them in the simple text format anyway. This method can deal with +summaries and histograms if they are presented in exactly the way the +text.Create function creates them. +

    +

    +This method must not be called concurrently. If you want to parse different +input concurrently, instantiate a separate Parser for each goroutine. +

    + + + + + + + + + + +

    Bugs

    +
      + +
    • Update other names to "quantile". +
    • + +
    + + + + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/github.com/prometheus/common/index.html b/pkg/github.com/prometheus/common/index.html new file mode 100644 index 0000000..03465e1 --- /dev/null +++ b/pkg/github.com/prometheus/common/index.html @@ -0,0 +1,141 @@ + + + + + + + + /src/github.com/prometheus/common - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Directory /src/github.com/prometheus/common

    + + + + + + + + + + + + + + + + + + + +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    NameSynopsis
    ..
    + expfmt + + A package for reading and writing Prometheus metrics. +
    + model + + Package model contains common data structures that are shared across Prometheus components and libraries. +
    +
    + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/github.com/prometheus/common/model/index.html b/pkg/github.com/prometheus/common/model/index.html new file mode 100644 index 0000000..ac33906 --- /dev/null +++ b/pkg/github.com/prometheus/common/model/index.html @@ -0,0 +1,2692 @@ + + + + + + + + model - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Package model

    + + + + + + + + + + + + + + +
    +
    +
    import "github.com/prometheus/common/model"
    +
    +
    +
    Overview
    +
    Index
    + + +
    +
    + +
    + +
    +

    Overview ▾

    +

    +Package model contains common data structures that are shared across +Prometheus components and libraries. +

    + +
    +
    + + +
    + +
    +

    Index ▾

    + + +
    +
    + +
    Constants
    + + +
    Variables
    + + + +
    func IsValidMetricName(n LabelValue) bool
    + + +
    func LabelsToSignature(labels map[string]string) uint64
    + + +
    func SignatureForLabels(m Metric, labels ...LabelName) uint64
    + + +
    func SignatureWithoutLabels(m Metric, labels map[LabelName]struct{}) uint64
    + + + +
    type Alert
    + + + +
        func (a *Alert) Fingerprint() Fingerprint
    + + +
        func (a *Alert) Name() string
    + + +
        func (a *Alert) Resolved() bool
    + + +
        func (a *Alert) ResolvedAt(ts time.Time) bool
    + + +
        func (a *Alert) Status() AlertStatus
    + + +
        func (a *Alert) String() string
    + + +
        func (a *Alert) Validate() error
    + + + +
    type AlertStatus
    + + + + +
    type Alerts
    + + + +
        func (as Alerts) HasFiring() bool
    + + +
        func (as Alerts) Len() int
    + + +
        func (as Alerts) Less(i, j int) bool
    + + +
        func (as Alerts) Status() AlertStatus
    + + +
        func (as Alerts) Swap(i, j int)
    + + + +
    type Duration
    + + +
        func ParseDuration(durationStr string) (Duration, error)
    + + + +
        func (d Duration) MarshalYAML() (interface{}, error)
    + + +
        func (d Duration) String() string
    + + +
        func (d *Duration) UnmarshalYAML(unmarshal func(interface{}) error) error
    + + + +
    type Fingerprint
    + + +
        func FingerprintFromString(s string) (Fingerprint, error)
    + + +
        func ParseFingerprint(s string) (Fingerprint, error)
    + + + +
        func (f Fingerprint) String() string
    + + + +
    type FingerprintSet
    + + + +
        func (s FingerprintSet) Equal(o FingerprintSet) bool
    + + +
        func (s FingerprintSet) Intersection(o FingerprintSet) FingerprintSet
    + + + +
    type Fingerprints
    + + + +
        func (f Fingerprints) Len() int
    + + +
        func (f Fingerprints) Less(i, j int) bool
    + + +
        func (f Fingerprints) Swap(i, j int)
    + + + +
    type Interval
    + + + + +
    type LabelName
    + + + +
        func (ln LabelName) IsValid() bool
    + + +
        func (ln *LabelName) UnmarshalJSON(b []byte) error
    + + +
        func (ln *LabelName) UnmarshalYAML(unmarshal func(interface{}) error) error
    + + + +
    type LabelNames
    + + + +
        func (l LabelNames) Len() int
    + + +
        func (l LabelNames) Less(i, j int) bool
    + + +
        func (l LabelNames) String() string
    + + +
        func (l LabelNames) Swap(i, j int)
    + + + +
    type LabelPair
    + + + + +
    type LabelPairs
    + + + +
        func (l LabelPairs) Len() int
    + + +
        func (l LabelPairs) Less(i, j int) bool
    + + +
        func (l LabelPairs) Swap(i, j int)
    + + + +
    type LabelSet
    + + + +
        func (ls LabelSet) Before(o LabelSet) bool
    + + +
        func (ls LabelSet) Clone() LabelSet
    + + +
        func (ls LabelSet) Equal(o LabelSet) bool
    + + +
        func (ls LabelSet) FastFingerprint() Fingerprint
    + + +
        func (ls LabelSet) Fingerprint() Fingerprint
    + + +
        func (l LabelSet) Merge(other LabelSet) LabelSet
    + + +
        func (l LabelSet) String() string
    + + +
        func (l *LabelSet) UnmarshalJSON(b []byte) error
    + + +
        func (ls LabelSet) Validate() error
    + + + +
    type LabelValue
    + + + +
        func (lv LabelValue) IsValid() bool
    + + + +
    type LabelValues
    + + + +
        func (l LabelValues) Len() int
    + + +
        func (l LabelValues) Less(i, j int) bool
    + + +
        func (l LabelValues) Swap(i, j int)
    + + + +
    type Matcher
    + + + +
        func (m *Matcher) UnmarshalJSON(b []byte) error
    + + +
        func (m *Matcher) Validate() error
    + + + +
    type Matrix
    + + + +
        func (m Matrix) Len() int
    + + +
        func (m Matrix) Less(i, j int) bool
    + + +
        func (mat Matrix) String() string
    + + +
        func (m Matrix) Swap(i, j int)
    + + +
        func (Matrix) Type() ValueType
    + + + +
    type Metric
    + + + +
        func (m Metric) Before(o Metric) bool
    + + +
        func (m Metric) Clone() Metric
    + + +
        func (m Metric) Equal(o Metric) bool
    + + +
        func (m Metric) FastFingerprint() Fingerprint
    + + +
        func (m Metric) Fingerprint() Fingerprint
    + + +
        func (m Metric) String() string
    + + + +
    type Sample
    + + + +
        func (s *Sample) Equal(o *Sample) bool
    + + +
        func (s Sample) MarshalJSON() ([]byte, error)
    + + +
        func (s Sample) String() string
    + + +
        func (s *Sample) UnmarshalJSON(b []byte) error
    + + + +
    type SamplePair
    + + + +
        func (s *SamplePair) Equal(o *SamplePair) bool
    + + +
        func (s SamplePair) MarshalJSON() ([]byte, error)
    + + +
        func (s SamplePair) String() string
    + + +
        func (s *SamplePair) UnmarshalJSON(b []byte) error
    + + + +
    type SampleStream
    + + + +
        func (ss SampleStream) String() string
    + + + +
    type SampleValue
    + + + +
        func (v SampleValue) Equal(o SampleValue) bool
    + + +
        func (v SampleValue) MarshalJSON() ([]byte, error)
    + + +
        func (v SampleValue) String() string
    + + +
        func (v *SampleValue) UnmarshalJSON(b []byte) error
    + + + +
    type Samples
    + + + +
        func (s Samples) Equal(o Samples) bool
    + + +
        func (s Samples) Len() int
    + + +
        func (s Samples) Less(i, j int) bool
    + + +
        func (s Samples) Swap(i, j int)
    + + + +
    type Scalar
    + + + +
        func (s Scalar) MarshalJSON() ([]byte, error)
    + + +
        func (s Scalar) String() string
    + + +
        func (*Scalar) Type() ValueType
    + + +
        func (s *Scalar) UnmarshalJSON(b []byte) error
    + + + +
    type Silence
    + + + +
        func (s *Silence) Validate() error
    + + + +
    type String
    + + + +
        func (s String) MarshalJSON() ([]byte, error)
    + + +
        func (s *String) String() string
    + + +
        func (*String) Type() ValueType
    + + +
        func (s *String) UnmarshalJSON(b []byte) error
    + + + +
    type Time
    + + +
        func Now() Time
    + + +
        func TimeFromUnix(t int64) Time
    + + +
        func TimeFromUnixNano(t int64) Time
    + + + +
        func (t Time) Add(d time.Duration) Time
    + + +
        func (t Time) After(o Time) bool
    + + +
        func (t Time) Before(o Time) bool
    + + +
        func (t Time) Equal(o Time) bool
    + + +
        func (t Time) MarshalJSON() ([]byte, error)
    + + +
        func (t Time) String() string
    + + +
        func (t Time) Sub(o Time) time.Duration
    + + +
        func (t Time) Time() time.Time
    + + +
        func (t Time) Unix() int64
    + + +
        func (t Time) UnixNano() int64
    + + +
        func (t *Time) UnmarshalJSON(b []byte) error
    + + + +
    type Value
    + + + + +
    type ValueType
    + + + +
        func (et ValueType) MarshalJSON() ([]byte, error)
    + + +
        func (e ValueType) String() string
    + + +
        func (et *ValueType) UnmarshalJSON(b []byte) error
    + + + +
    type Vector
    + + + +
        func (vec Vector) Equal(o Vector) bool
    + + +
        func (vec Vector) Len() int
    + + +
        func (vec Vector) Less(i, j int) bool
    + + +
        func (vec Vector) String() string
    + + +
        func (vec Vector) Swap(i, j int)
    + + +
        func (Vector) Type() ValueType
    + + + +
    +
    + + + + +

    Package files

    +

    + + + alert.go + + fingerprinting.go + + fnv.go + + labels.go + + labelset.go + + metric.go + + model.go + + signature.go + + silence.go + + time.go + + value.go + + +

    + +
    +
    + + + + +

    Constants

    + +
    const (
    +    // AlertNameLabel is the name of the label containing the an alert's name.
    +    AlertNameLabel = "alertname"
    +
    +    // ExportedLabelPrefix is the prefix to prepend to the label names present in
    +    // exported metrics if a label of the same name is added by the server.
    +    ExportedLabelPrefix = "exported_"
    +
    +    // MetricNameLabel is the label name indicating the metric name of a
    +    // timeseries.
    +    MetricNameLabel = "__name__"
    +
    +    // SchemeLabel is the name of the label that holds the scheme on which to
    +    // scrape a target.
    +    SchemeLabel = "__scheme__"
    +
    +    // AddressLabel is the name of the label that holds the address of
    +    // a scrape target.
    +    AddressLabel = "__address__"
    +
    +    // MetricsPathLabel is the name of the label that holds the path on which to
    +    // scrape a target.
    +    MetricsPathLabel = "__metrics_path__"
    +
    +    // ReservedLabelPrefix is a prefix which is not legal in user-supplied
    +    // label names.
    +    ReservedLabelPrefix = "__"
    +
    +    // MetaLabelPrefix is a prefix for labels that provide meta information.
    +    // Labels with this prefix are used for intermediate label processing and
    +    // will not be attached to time series.
    +    MetaLabelPrefix = "__meta_"
    +
    +    // TmpLabelPrefix is a prefix for temporary labels as part of relabelling.
    +    // Labels with this prefix are used for intermediate label processing and
    +    // will not be attached to time series. This is reserved for use in
    +    // Prometheus configuration files by users.
    +    TmpLabelPrefix = "__tmp_"
    +
    +    // ParamLabelPrefix is a prefix for labels that provide URL parameters
    +    // used to scrape a target.
    +    ParamLabelPrefix = "__param_"
    +
    +    // JobLabel is the label name indicating the job from which a timeseries
    +    // was scraped.
    +    JobLabel = "job"
    +
    +    // InstanceLabel is the label name used for the instance label.
    +    InstanceLabel = "instance"
    +
    +    // BucketLabel is used for the label that defines the upper bound of a
    +    // bucket of a histogram ("le" -> "less or equal").
    +    BucketLabel = "le"
    +
    +    // QuantileLabel is used for the label that defines the quantile in a
    +    // summary.
    +    QuantileLabel = "quantile"
    +)
    + + +
    const (
    +
    +    // Earliest is the earliest Time representable. Handy for
    +    // initializing a high watermark.
    +    Earliest = Time(math.MinInt64)
    +    // Latest is the latest Time representable. Handy for initializing
    +    // a low watermark.
    +    Latest = Time(math.MaxInt64)
    +)
    + + +
    const SeparatorByte byte = 255
    +

    +SeparatorByte is a byte that cannot occur in valid UTF-8 sequences and is +used to separate label names, label values, and other strings from each other +when calculating their combined hash value (aka signature aka fingerprint). +

    + + + + +

    Variables

    + +
    var (
    +    // ZeroSamplePair is the pseudo zero-value of SamplePair used to signal a
    +    // non-existing sample pair. It is a SamplePair with timestamp Earliest and
    +    // value 0.0. Note that the natural zero value of SamplePair has a timestamp
    +    // of 0, which is possible to appear in a real SamplePair and thus not
    +    // suitable to signal a non-existing SamplePair.
    +    ZeroSamplePair = SamplePair{Timestamp: Earliest}
    +
    +    // ZeroSample is the pseudo zero-value of Sample used to signal a
    +    // non-existing sample. It is a Sample with timestamp Earliest, value 0.0,
    +    // and metric nil. Note that the natural zero value of Sample has a timestamp
    +    // of 0, which is possible to appear in a real Sample and thus not suitable
    +    // to signal a non-existing Sample.
    +    ZeroSample = Sample{Timestamp: Earliest}
    +)
    + + +
    var LabelNameRE = regexp.MustCompile("^[a-zA-Z_][a-zA-Z0-9_]*$")
    +

    +LabelNameRE is a regular expression matching valid label names. +

    + + +
    var (
    +    MetricNameRE = regexp.MustCompile(`^[a-zA-Z_][a-zA-Z0-9_:]*$`)
    +)
    + + + + + + +

    func IsValidMetricName

    +
    func IsValidMetricName(n LabelValue) bool
    +

    +IsValidMetricName returns true iff name matches the pattern of MetricNameRE. +

    + + + + + + + +

    func LabelsToSignature

    +
    func LabelsToSignature(labels map[string]string) uint64
    +

    +LabelsToSignature returns a quasi-unique signature (i.e., fingerprint) for a +given label set. (Collisions are possible but unlikely if the number of label +sets the function is applied to is small.) +

    + + + + + + + +

    func SignatureForLabels

    +
    func SignatureForLabels(m Metric, labels ...LabelName) uint64
    +

    +SignatureForLabels works like LabelsToSignature but takes a Metric as +parameter (rather than a label map) and only includes the labels with the +specified LabelNames into the signature calculation. The labels passed in +will be sorted by this function. +

    + + + + + + + +

    func SignatureWithoutLabels

    +
    func SignatureWithoutLabels(m Metric, labels map[LabelName]struct{}) uint64
    +

    +SignatureWithoutLabels works like LabelsToSignature but takes a Metric as +parameter (rather than a label map) and excludes the labels with any of the +specified LabelNames from the signature calculation. +

    + + + + + + + + +

    type Alert

    +
    type Alert struct {
    +    // Label value pairs for purpose of aggregation, matching, and disposition
    +    // dispatching. This must minimally include an "alertname" label.
    +    Labels LabelSet `json:"labels"`
    +
    +    // Extra key/value information which does not define alert identity.
    +    Annotations LabelSet `json:"annotations"`
    +
    +    // The known time range for this alert. Both ends are optional.
    +    StartsAt     time.Time `json:"startsAt,omitempty"`
    +    EndsAt       time.Time `json:"endsAt,omitempty"`
    +    GeneratorURL string    `json:"generatorURL"`
    +}
    +

    +Alert is a generic representation of an alert in the Prometheus eco-system. +

    + + + + + + + + + + + + + + +

    func (*Alert) Fingerprint

    +
    func (a *Alert) Fingerprint() Fingerprint
    +

    +Fingerprint returns a unique hash for the alert. It is equivalent to +the fingerprint of the alert's label set. +

    + + + + + + +

    func (*Alert) Name

    +
    func (a *Alert) Name() string
    +

    +Name returns the name of the alert. It is equivalent to the "alertname" label. +

    + + + + + + +

    func (*Alert) Resolved

    +
    func (a *Alert) Resolved() bool
    +

    +Resolved returns true iff the activity interval ended in the past. +

    + + + + + + +

    func (*Alert) ResolvedAt

    +
    func (a *Alert) ResolvedAt(ts time.Time) bool
    +

    +ResolvedAt returns true off the activity interval ended before +the given timestamp. +

    + + + + + + +

    func (*Alert) Status

    +
    func (a *Alert) Status() AlertStatus
    +

    +Status returns the status of the alert. +

    + + + + + + +

    func (*Alert) String

    +
    func (a *Alert) String() string
    + + + + + + +

    func (*Alert) Validate

    +
    func (a *Alert) Validate() error
    +

    +Validate checks whether the alert data is inconsistent. +

    + + + + + + + + +

    type AlertStatus

    +
    type AlertStatus string
    + + + +
    const (
    +    AlertFiring   AlertStatus = "firing"
    +    AlertResolved AlertStatus = "resolved"
    +)
    + + + + + + + + + + + + + + + +

    type Alerts

    +
    type Alerts []*Alert
    +

    +Alert is a list of alerts that can be sorted in chronological order. +

    + + + + + + + + + + + + + + +

    func (Alerts) HasFiring

    +
    func (as Alerts) HasFiring() bool
    +

    +HasFiring returns true iff one of the alerts is not resolved. +

    + + + + + + +

    func (Alerts) Len

    +
    func (as Alerts) Len() int
    + + + + + + +

    func (Alerts) Less

    +
    func (as Alerts) Less(i, j int) bool
    + + + + + + +

    func (Alerts) Status

    +
    func (as Alerts) Status() AlertStatus
    +

    +Status returns StatusFiring iff at least one of the alerts is firing. +

    + + + + + + +

    func (Alerts) Swap

    +
    func (as Alerts) Swap(i, j int)
    + + + + + + + + +

    type Duration

    +
    type Duration time.Duration
    +

    +Duration wraps time.Duration. It is used to parse the custom duration format +from YAML. +This type should not propagate beyond the scope of input/output processing. +

    + + + + + + + + + + + + +

    func ParseDuration

    +
    func ParseDuration(durationStr string) (Duration, error)
    +

    +StringToDuration parses a string into a time.Duration, assuming that a year +always has 365d, a week always has 7d, and a day always has 24h. +

    + + + + + + + +

    func (Duration) MarshalYAML

    +
    func (d Duration) MarshalYAML() (interface{}, error)
    +

    +MarshalYAML implements the yaml.Marshaler interface. +

    + + + + + + +

    func (Duration) String

    +
    func (d Duration) String() string
    + + + + + + +

    func (*Duration) UnmarshalYAML

    +
    func (d *Duration) UnmarshalYAML(unmarshal func(interface{}) error) error
    +

    +UnmarshalYAML implements the yaml.Unmarshaler interface. +

    + + + + + + + + +

    type Fingerprint

    +
    type Fingerprint uint64
    +

    +Fingerprint provides a hash-capable representation of a Metric. +For our purposes, FNV-1A 64-bit is used. +

    + + + + + + + + + + + + +

    func FingerprintFromString

    +
    func FingerprintFromString(s string) (Fingerprint, error)
    +

    +FingerprintFromString transforms a string representation into a Fingerprint. +

    + + + + + +

    func ParseFingerprint

    +
    func ParseFingerprint(s string) (Fingerprint, error)
    +

    +ParseFingerprint parses the input string into a fingerprint. +

    + + + + + + + +

    func (Fingerprint) String

    +
    func (f Fingerprint) String() string
    + + + + + + + + +

    type FingerprintSet

    +
    type FingerprintSet map[Fingerprint]struct{}
    +

    +FingerprintSet is a set of Fingerprints. +

    + + + + + + + + + + + + + + +

    func (FingerprintSet) Equal

    +
    func (s FingerprintSet) Equal(o FingerprintSet) bool
    +

    +Equal returns true if both sets contain the same elements (and not more). +

    + + + + + + +

    func (FingerprintSet) Intersection

    +
    func (s FingerprintSet) Intersection(o FingerprintSet) FingerprintSet
    +

    +Intersection returns the elements contained in both sets. +

    + + + + + + + + +

    type Fingerprints

    +
    type Fingerprints []Fingerprint
    +

    +Fingerprints represents a collection of Fingerprint subject to a given +natural sorting scheme. It implements sort.Interface. +

    + + + + + + + + + + + + + + +

    func (Fingerprints) Len

    +
    func (f Fingerprints) Len() int
    +

    +Len implements sort.Interface. +

    + + + + + + +

    func (Fingerprints) Less

    +
    func (f Fingerprints) Less(i, j int) bool
    +

    +Less implements sort.Interface. +

    + + + + + + +

    func (Fingerprints) Swap

    +
    func (f Fingerprints) Swap(i, j int)
    +

    +Swap implements sort.Interface. +

    + + + + + + + + +

    type Interval

    +
    type Interval struct {
    +    Start, End Time
    +}
    +

    +Interval describes and interval between two timestamps. +

    + + + + + + + + + + + + + + + + +

    type LabelName

    +
    type LabelName string
    +

    +A LabelName is a key for a LabelSet or Metric. It has a value associated +therewith. +

    + + + + + + + + + + + + + + +

    func (LabelName) IsValid

    +
    func (ln LabelName) IsValid() bool
    +

    +IsValid is true iff the label name matches the pattern of LabelNameRE. +

    + + + + + + +

    func (*LabelName) UnmarshalJSON

    +
    func (ln *LabelName) UnmarshalJSON(b []byte) error
    +

    +UnmarshalJSON implements the json.Unmarshaler interface. +

    + + + + + + +

    func (*LabelName) UnmarshalYAML

    +
    func (ln *LabelName) UnmarshalYAML(unmarshal func(interface{}) error) error
    +

    +UnmarshalYAML implements the yaml.Unmarshaler interface. +

    + + + + + + + + +

    type LabelNames

    +
    type LabelNames []LabelName
    +

    +LabelNames is a sortable LabelName slice. In implements sort.Interface. +

    + + + + + + + + + + + + + + +

    func (LabelNames) Len

    +
    func (l LabelNames) Len() int
    + + + + + + +

    func (LabelNames) Less

    +
    func (l LabelNames) Less(i, j int) bool
    + + + + + + +

    func (LabelNames) String

    +
    func (l LabelNames) String() string
    + + + + + + +

    func (LabelNames) Swap

    +
    func (l LabelNames) Swap(i, j int)
    + + + + + + + + +

    type LabelPair

    +
    type LabelPair struct {
    +    Name  LabelName
    +    Value LabelValue
    +}
    +

    +LabelPair pairs a name with a value. +

    + + + + + + + + + + + + + + + + +

    type LabelPairs

    +
    type LabelPairs []*LabelPair
    +

    +LabelPairs is a sortable slice of LabelPair pointers. It implements +sort.Interface. +

    + + + + + + + + + + + + + + +

    func (LabelPairs) Len

    +
    func (l LabelPairs) Len() int
    + + + + + + +

    func (LabelPairs) Less

    +
    func (l LabelPairs) Less(i, j int) bool
    + + + + + + +

    func (LabelPairs) Swap

    +
    func (l LabelPairs) Swap(i, j int)
    + + + + + + + + +

    type LabelSet

    +
    type LabelSet map[LabelName]LabelValue
    +

    +A LabelSet is a collection of LabelName and LabelValue pairs. The LabelSet +may be fully-qualified down to the point where it may resolve to a single +Metric in the data store or not. All operations that occur within the realm +of a LabelSet can emit a vector of Metric entities to which the LabelSet may +match. +

    + + + + + + + + + + + + + + +

    func (LabelSet) Before

    +
    func (ls LabelSet) Before(o LabelSet) bool
    +

    +Before compares the metrics, using the following criteria: +

    +

    +If m has fewer labels than o, it is before o. If it has more, it is not. +

    +

    +If the number of labels is the same, the superset of all label names is +sorted alphanumerically. The first differing label pair found in that order +determines the outcome: If the label does not exist at all in m, then m is +before o, and vice versa. Otherwise the label value is compared +alphanumerically. +

    +

    +If m and o are equal, the method returns false. +

    + + + + + + +

    func (LabelSet) Clone

    +
    func (ls LabelSet) Clone() LabelSet
    +

    +Clone returns a copy of the label set. +

    + + + + + + +

    func (LabelSet) Equal

    +
    func (ls LabelSet) Equal(o LabelSet) bool
    +

    +Equal returns true iff both label sets have exactly the same key/value pairs. +

    + + + + + + +

    func (LabelSet) FastFingerprint

    +
    func (ls LabelSet) FastFingerprint() Fingerprint
    +

    +FastFingerprint returns the LabelSet's Fingerprint calculated by a faster hashing +algorithm, which is, however, more susceptible to hash collisions. +

    + + + + + + +

    func (LabelSet) Fingerprint

    +
    func (ls LabelSet) Fingerprint() Fingerprint
    +

    +Fingerprint returns the LabelSet's fingerprint. +

    + + + + + + +

    func (LabelSet) Merge

    +
    func (l LabelSet) Merge(other LabelSet) LabelSet
    +

    +Merge is a helper function to non-destructively merge two label sets. +

    + + + + + + +

    func (LabelSet) String

    +
    func (l LabelSet) String() string
    + + + + + + +

    func (*LabelSet) UnmarshalJSON

    +
    func (l *LabelSet) UnmarshalJSON(b []byte) error
    +

    +UnmarshalJSON implements the json.Unmarshaler interface. +

    + + + + + + +

    func (LabelSet) Validate

    +
    func (ls LabelSet) Validate() error
    +

    +Validate checks whether all names and values in the label set +are valid. +

    + + + + + + + + +

    type LabelValue

    +
    type LabelValue string
    +

    +A LabelValue is an associated value for a LabelName. +

    + + + + + + + + + + + + + + +

    func (LabelValue) IsValid

    +
    func (lv LabelValue) IsValid() bool
    +

    +IsValid returns true iff the string is a valid UTF8. +

    + + + + + + + + +

    type LabelValues

    +
    type LabelValues []LabelValue
    +

    +LabelValues is a sortable LabelValue slice. It implements sort.Interface. +

    + + + + + + + + + + + + + + +

    func (LabelValues) Len

    +
    func (l LabelValues) Len() int
    + + + + + + +

    func (LabelValues) Less

    +
    func (l LabelValues) Less(i, j int) bool
    + + + + + + +

    func (LabelValues) Swap

    +
    func (l LabelValues) Swap(i, j int)
    + + + + + + + + +

    type Matcher

    +
    type Matcher struct {
    +    Name    LabelName `json:"name"`
    +    Value   string    `json:"value"`
    +    IsRegex bool      `json:"isRegex"`
    +}
    +

    +Matcher describes a matches the value of a given label. +

    + + + + + + + + + + + + + + +

    func (*Matcher) UnmarshalJSON

    +
    func (m *Matcher) UnmarshalJSON(b []byte) error
    + + + + + + +

    func (*Matcher) Validate

    +
    func (m *Matcher) Validate() error
    +

    +Validate returns true iff all fields of the matcher have valid values. +

    + + + + + + + + +

    type Matrix

    +
    type Matrix []*SampleStream
    +

    +Matrix is a list of time series. +

    + + + + + + + + + + + + + + +

    func (Matrix) Len

    +
    func (m Matrix) Len() int
    + + + + + + +

    func (Matrix) Less

    +
    func (m Matrix) Less(i, j int) bool
    + + + + + + +

    func (Matrix) String

    +
    func (mat Matrix) String() string
    + + + + + + +

    func (Matrix) Swap

    +
    func (m Matrix) Swap(i, j int)
    + + + + + + +

    func (Matrix) Type

    +
    func (Matrix) Type() ValueType
    + + + + + + + + +

    type Metric

    +
    type Metric LabelSet
    +

    +A Metric is similar to a LabelSet, but the key difference is that a Metric is +a singleton and refers to one and only one stream of samples. +

    + + + + + + + + + + + + + + +

    func (Metric) Before

    +
    func (m Metric) Before(o Metric) bool
    +

    +Before compares the metrics' underlying label sets. +

    + + + + + + +

    func (Metric) Clone

    +
    func (m Metric) Clone() Metric
    +

    +Clone returns a copy of the Metric. +

    + + + + + + +

    func (Metric) Equal

    +
    func (m Metric) Equal(o Metric) bool
    +

    +Equal compares the metrics. +

    + + + + + + +

    func (Metric) FastFingerprint

    +
    func (m Metric) FastFingerprint() Fingerprint
    +

    +FastFingerprint returns a Metric's Fingerprint calculated by a faster hashing +algorithm, which is, however, more susceptible to hash collisions. +

    + + + + + + +

    func (Metric) Fingerprint

    +
    func (m Metric) Fingerprint() Fingerprint
    +

    +Fingerprint returns a Metric's Fingerprint. +

    + + + + + + +

    func (Metric) String

    +
    func (m Metric) String() string
    + + + + + + + + +

    type Sample

    +
    type Sample struct {
    +    Metric    Metric      `json:"metric"`
    +    Value     SampleValue `json:"value"`
    +    Timestamp Time        `json:"timestamp"`
    +}
    +

    +Sample is a sample pair associated with a metric. +

    + + + + + + + + + + + + + + +

    func (*Sample) Equal

    +
    func (s *Sample) Equal(o *Sample) bool
    +

    +Equal compares first the metrics, then the timestamp, then the value. The +sematics of value equality is defined by SampleValue.Equal. +

    + + + + + + +

    func (Sample) MarshalJSON

    +
    func (s Sample) MarshalJSON() ([]byte, error)
    +

    +MarshalJSON implements json.Marshaler. +

    + + + + + + +

    func (Sample) String

    +
    func (s Sample) String() string
    + + + + + + +

    func (*Sample) UnmarshalJSON

    +
    func (s *Sample) UnmarshalJSON(b []byte) error
    +

    +UnmarshalJSON implements json.Unmarshaler. +

    + + + + + + + + +

    type SamplePair

    +
    type SamplePair struct {
    +    Timestamp Time
    +    Value     SampleValue
    +}
    +

    +SamplePair pairs a SampleValue with a Timestamp. +

    + + + + + + + + + + + + + + +

    func (*SamplePair) Equal

    +
    func (s *SamplePair) Equal(o *SamplePair) bool
    +

    +Equal returns true if this SamplePair and o have equal Values and equal +Timestamps. The sematics of Value equality is defined by SampleValue.Equal. +

    + + + + + + +

    func (SamplePair) MarshalJSON

    +
    func (s SamplePair) MarshalJSON() ([]byte, error)
    +

    +MarshalJSON implements json.Marshaler. +

    + + + + + + +

    func (SamplePair) String

    +
    func (s SamplePair) String() string
    + + + + + + +

    func (*SamplePair) UnmarshalJSON

    +
    func (s *SamplePair) UnmarshalJSON(b []byte) error
    +

    +UnmarshalJSON implements json.Unmarshaler. +

    + + + + + + + + +

    type SampleStream

    +
    type SampleStream struct {
    +    Metric Metric       `json:"metric"`
    +    Values []SamplePair `json:"values"`
    +}
    +

    +SampleStream is a stream of Values belonging to an attached COWMetric. +

    + + + + + + + + + + + + + + +

    func (SampleStream) String

    +
    func (ss SampleStream) String() string
    + + + + + + + + +

    type SampleValue

    +
    type SampleValue float64
    +

    +A SampleValue is a representation of a value for a given sample at a given +time. +

    + + + + + + + + + + + + + + +

    func (SampleValue) Equal

    +
    func (v SampleValue) Equal(o SampleValue) bool
    +

    +Equal returns true if the value of v and o is equal or if both are NaN. Note +that v==o is false if both are NaN. If you want the conventional float +behavior, use == to compare two SampleValues. +

    + + + + + + +

    func (SampleValue) MarshalJSON

    +
    func (v SampleValue) MarshalJSON() ([]byte, error)
    +

    +MarshalJSON implements json.Marshaler. +

    + + + + + + +

    func (SampleValue) String

    +
    func (v SampleValue) String() string
    + + + + + + +

    func (*SampleValue) UnmarshalJSON

    +
    func (v *SampleValue) UnmarshalJSON(b []byte) error
    +

    +UnmarshalJSON implements json.Unmarshaler. +

    + + + + + + + + +

    type Samples

    +
    type Samples []*Sample
    +

    +Samples is a sortable Sample slice. It implements sort.Interface. +

    + + + + + + + + + + + + + + +

    func (Samples) Equal

    +
    func (s Samples) Equal(o Samples) bool
    +

    +Equal compares two sets of samples and returns true if they are equal. +

    + + + + + + +

    func (Samples) Len

    +
    func (s Samples) Len() int
    + + + + + + +

    func (Samples) Less

    +
    func (s Samples) Less(i, j int) bool
    +

    +Less compares first the metrics, then the timestamp. +

    + + + + + + +

    func (Samples) Swap

    +
    func (s Samples) Swap(i, j int)
    + + + + + + + + +

    type Scalar

    +
    type Scalar struct {
    +    Value     SampleValue `json:"value"`
    +    Timestamp Time        `json:"timestamp"`
    +}
    +

    +Scalar is a scalar value evaluated at the set timestamp. +

    + + + + + + + + + + + + + + +

    func (Scalar) MarshalJSON

    +
    func (s Scalar) MarshalJSON() ([]byte, error)
    +

    +MarshalJSON implements json.Marshaler. +

    + + + + + + +

    func (Scalar) String

    +
    func (s Scalar) String() string
    + + + + + + +

    func (*Scalar) Type

    +
    func (*Scalar) Type() ValueType
    + + + + + + +

    func (*Scalar) UnmarshalJSON

    +
    func (s *Scalar) UnmarshalJSON(b []byte) error
    +

    +UnmarshalJSON implements json.Unmarshaler. +

    + + + + + + + + +

    type Silence

    +
    type Silence struct {
    +    ID uint64 `json:"id,omitempty"`
    +
    +    Matchers []*Matcher `json:"matchers"`
    +
    +    StartsAt time.Time `json:"startsAt"`
    +    EndsAt   time.Time `json:"endsAt"`
    +
    +    CreatedAt time.Time `json:"createdAt,omitempty"`
    +    CreatedBy string    `json:"createdBy"`
    +    Comment   string    `json:"comment,omitempty"`
    +}
    +

    +Silence defines the representation of a silence definiton +in the Prometheus eco-system. +

    + + + + + + + + + + + + + + +

    func (*Silence) Validate

    +
    func (s *Silence) Validate() error
    +

    +Validate returns true iff all fields of the silence have valid values. +

    + + + + + + + + +

    type String

    +
    type String struct {
    +    Value     string `json:"value"`
    +    Timestamp Time   `json:"timestamp"`
    +}
    +

    +String is a string value evaluated at the set timestamp. +

    + + + + + + + + + + + + + + +

    func (String) MarshalJSON

    +
    func (s String) MarshalJSON() ([]byte, error)
    +

    +MarshalJSON implements json.Marshaler. +

    + + + + + + +

    func (*String) String

    +
    func (s *String) String() string
    + + + + + + +

    func (*String) Type

    +
    func (*String) Type() ValueType
    + + + + + + +

    func (*String) UnmarshalJSON

    +
    func (s *String) UnmarshalJSON(b []byte) error
    +

    +UnmarshalJSON implements json.Unmarshaler. +

    + + + + + + + + +

    type Time

    +
    type Time int64
    +

    +Time is the number of milliseconds since the epoch +(1970-01-01 00:00 UTC) excluding leap seconds. +

    + + + + + + + + + + + + +

    func Now

    +
    func Now() Time
    +

    +Now returns the current time as a Time. +

    + + + + + +

    func TimeFromUnix

    +
    func TimeFromUnix(t int64) Time
    +

    +TimeFromUnix returns the Time equivalent to the Unix Time t +provided in seconds. +

    + + + + + +

    func TimeFromUnixNano

    +
    func TimeFromUnixNano(t int64) Time
    +

    +TimeFromUnixNano returns the Time equivalent to the Unix Time +t provided in nanoseconds. +

    + + + + + + + +

    func (Time) Add

    +
    func (t Time) Add(d time.Duration) Time
    +

    +Add returns the Time t + d. +

    + + + + + + +

    func (Time) After

    +
    func (t Time) After(o Time) bool
    +

    +After reports whether the Time t is after o. +

    + + + + + + +

    func (Time) Before

    +
    func (t Time) Before(o Time) bool
    +

    +Before reports whether the Time t is before o. +

    + + + + + + +

    func (Time) Equal

    +
    func (t Time) Equal(o Time) bool
    +

    +Equal reports whether two Times represent the same instant. +

    + + + + + + +

    func (Time) MarshalJSON

    +
    func (t Time) MarshalJSON() ([]byte, error)
    +

    +MarshalJSON implements the json.Marshaler interface. +

    + + + + + + +

    func (Time) String

    +
    func (t Time) String() string
    +

    +String returns a string representation of the Time. +

    + + + + + + +

    func (Time) Sub

    +
    func (t Time) Sub(o Time) time.Duration
    +

    +Sub returns the Duration t - o. +

    + + + + + + +

    func (Time) Time

    +
    func (t Time) Time() time.Time
    +

    +Time returns the time.Time representation of t. +

    + + + + + + +

    func (Time) Unix

    +
    func (t Time) Unix() int64
    +

    +Unix returns t as a Unix time, the number of seconds elapsed +since January 1, 1970 UTC. +

    + + + + + + +

    func (Time) UnixNano

    +
    func (t Time) UnixNano() int64
    +

    +UnixNano returns t as a Unix time, the number of nanoseconds elapsed +since January 1, 1970 UTC. +

    + + + + + + +

    func (*Time) UnmarshalJSON

    +
    func (t *Time) UnmarshalJSON(b []byte) error
    +

    +UnmarshalJSON implements the json.Unmarshaler interface. +

    + + + + + + + + +

    type Value

    +
    type Value interface {
    +    Type() ValueType
    +    String() string
    +}
    +

    +Value is a generic interface for values resulting from a query evaluation. +

    + + + + + + + + + + + + + + + + +

    type ValueType

    +
    type ValueType int
    + + + +
    const (
    +    ValNone ValueType = iota
    +    ValScalar
    +    ValVector
    +    ValMatrix
    +    ValString
    +)
    + + + + + + + + + + + + + +

    func (ValueType) MarshalJSON

    +
    func (et ValueType) MarshalJSON() ([]byte, error)
    +

    +MarshalJSON implements json.Marshaler. +

    + + + + + + +

    func (ValueType) String

    +
    func (e ValueType) String() string
    + + + + + + +

    func (*ValueType) UnmarshalJSON

    +
    func (et *ValueType) UnmarshalJSON(b []byte) error
    + + + + + + + + +

    type Vector

    +
    type Vector []*Sample
    +

    +Vector is basically only an alias for Samples, but the +contract is that in a Vector, all Samples have the same timestamp. +

    + + + + + + + + + + + + + + +

    func (Vector) Equal

    +
    func (vec Vector) Equal(o Vector) bool
    +

    +Equal compares two sets of samples and returns true if they are equal. +

    + + + + + + +

    func (Vector) Len

    +
    func (vec Vector) Len() int
    + + + + + + +

    func (Vector) Less

    +
    func (vec Vector) Less(i, j int) bool
    +

    +Less compares first the metrics, then the timestamp. +

    + + + + + + +

    func (Vector) String

    +
    func (vec Vector) String() string
    + + + + + + +

    func (Vector) Swap

    +
    func (vec Vector) Swap(i, j int)
    + + + + + + +

    func (Vector) Type

    +
    func (Vector) Type() ValueType
    + + + + + + + + + + + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/github.com/prometheus/index.html b/pkg/github.com/prometheus/index.html new file mode 100644 index 0000000..8e29ae7 --- /dev/null +++ b/pkg/github.com/prometheus/index.html @@ -0,0 +1,284 @@ + + + + + + + + /src/github.com/prometheus - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Directory /src/github.com/prometheus

    + + + + + + + + + + + + + + + + + + + +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    NameSynopsis
    ..
    + client_golang + + +
    + api + + +
    + prometheus + + Package prometheus provides bindings to the Prometheus HTTP API: http://prometheus.io/docs/querying/api/ +
    + examples + + +
    + random + + A simple example exposing fictional RPC latencies with different types of random distributions (uniform, normal, and exponential) as Prometheus metrics. +
    + simple + + A minimal example of how to include Prometheus instrumentation. +
    + prometheus + + Package prometheus provides metrics primitives to instrument code for monitoring. +
    + promhttp + + Package promhttp contains functions to create http.Handler instances to expose Prometheus metrics via HTTP. +
    + push + + Package push provides functions to push metrics to a Pushgateway. +
    + client_model + + +
    + go + + Package io_prometheus_client is a generated protocol buffer package. +
    + common + + +
    + expfmt + + A package for reading and writing Prometheus metrics. +
    + model + + Package model contains common data structures that are shared across Prometheus components and libraries. +
    + procfs + + Package procfs provides functions to retrieve system, kernel and process metrics from the pseudo-filesystem proc. +
    +
    + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/github.com/prometheus/procfs/index.html b/pkg/github.com/prometheus/procfs/index.html new file mode 100644 index 0000000..40edf9c --- /dev/null +++ b/pkg/github.com/prometheus/procfs/index.html @@ -0,0 +1,1116 @@ + + + + + + + + procfs - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Package procfs

    + + + + + + + + + + + + + + +
    +
    +
    import "github.com/prometheus/procfs"
    +
    +
    +
    Overview
    +
    Index
    + + +
    +
    + +
    + +
    +

    Overview ▾

    +

    +Package procfs provides functions to retrieve system, kernel and process +metrics from the pseudo-filesystem proc. +

    +

    +Example: +

    +
    package main
    +
    +import (
    +	"fmt"
    +	"log"
    +
    +	"github.com/prometheus/procfs"
    +)
    +
    +func main() {
    +	p, err := procfs.Self()
    +	if err != nil {
    +		log.Fatalf("could not get process: %s", err)
    +	}
    +
    +	stat, err := p.NewStat()
    +	if err != nil {
    +		log.Fatalf("could not get process stat: %s", err)
    +	}
    +
    +	fmt.Printf("command:  %s\n", stat.Comm)
    +	fmt.Printf("cpu time: %fs\n", stat.CPUTime())
    +	fmt.Printf("vsize:    %dB\n", stat.VirtualMemory())
    +	fmt.Printf("rss:      %dB\n", stat.ResidentMemory())
    +}
    +
    + +
    +
    + + +
    + +
    +

    Index ▾

    + + +
    +
    + +
    Constants
    + + + + +
    func NewIPVSBackendStatus() ([]IPVSBackendStatus, error)
    + + + +
    type FS
    + + +
        func NewFS(mountPoint string) (FS, error)
    + + + +
        func (fs FS) AllProcs() (Procs, error)
    + + +
        func (fs FS) NewIPVSBackendStatus() ([]IPVSBackendStatus, error)
    + + +
        func (fs FS) NewIPVSStats() (IPVSStats, error)
    + + +
        func (fs FS) NewProc(pid int) (Proc, error)
    + + +
        func (fs FS) NewStat() (Stat, error)
    + + +
        func (fs FS) ParseMDStat() (mdstates []MDStat, err error)
    + + +
        func (fs FS) Path(p ...string) string
    + + +
        func (fs FS) Self() (Proc, error)
    + + + +
    type IPVSBackendStatus
    + + + + +
    type IPVSStats
    + + +
        func NewIPVSStats() (IPVSStats, error)
    + + + + +
    type MDStat
    + + + + +
    type Proc
    + + +
        func NewProc(pid int) (Proc, error)
    + + +
        func Self() (Proc, error)
    + + + +
        func (p Proc) CmdLine() ([]string, error)
    + + +
        func (p Proc) Comm() (string, error)
    + + +
        func (p Proc) Executable() (string, error)
    + + +
        func (p Proc) FileDescriptorTargets() ([]string, error)
    + + +
        func (p Proc) FileDescriptors() ([]uintptr, error)
    + + +
        func (p Proc) FileDescriptorsLen() (int, error)
    + + +
        func (p Proc) NewIO() (ProcIO, error)
    + + +
        func (p Proc) NewLimits() (ProcLimits, error)
    + + +
        func (p Proc) NewStat() (ProcStat, error)
    + + + +
    type ProcIO
    + + + + +
    type ProcLimits
    + + + + +
    type ProcStat
    + + + +
        func (s ProcStat) CPUTime() float64
    + + +
        func (s ProcStat) ResidentMemory() int
    + + +
        func (s ProcStat) StartTime() (float64, error)
    + + +
        func (s ProcStat) VirtualMemory() int
    + + + +
    type Procs
    + + +
        func AllProcs() (Procs, error)
    + + + +
        func (p Procs) Len() int
    + + +
        func (p Procs) Less(i, j int) bool
    + + +
        func (p Procs) Swap(i, j int)
    + + + +
    type Stat
    + + +
        func NewStat() (Stat, error)
    + + + + +
    +
    + + + + +

    Package files

    +

    + + + doc.go + + fs.go + + ipvs.go + + mdstat.go + + proc.go + + proc_io.go + + proc_limits.go + + proc_stat.go + + stat.go + + +

    + +
    +
    + + + + +

    Constants

    + +
    const DefaultMountPoint = "/proc"
    +

    +DefaultMountPoint is the common mount point of the proc filesystem. +

    + + + + + + + +

    func NewIPVSBackendStatus

    +
    func NewIPVSBackendStatus() ([]IPVSBackendStatus, error)
    +

    +NewIPVSBackendStatus reads and returns the status of all (virtual,real) server pairs. +

    + + + + + + + + +

    type FS

    +
    type FS string
    +

    +FS represents the pseudo-filesystem proc, which provides an interface to +kernel data structures. +

    + + + + + + + + + + + + +

    func NewFS

    +
    func NewFS(mountPoint string) (FS, error)
    +

    +NewFS returns a new FS mounted under the given mountPoint. It will error +if the mount point can't be read. +

    + + + + + + + +

    func (FS) AllProcs

    +
    func (fs FS) AllProcs() (Procs, error)
    +

    +AllProcs returns a list of all currently available processes. +

    + + + + + + +

    func (FS) NewIPVSBackendStatus

    +
    func (fs FS) NewIPVSBackendStatus() ([]IPVSBackendStatus, error)
    +

    +NewIPVSBackendStatus reads and returns the status of all (virtual,real) server pairs from the specified `proc` filesystem. +

    + + + + + + +

    func (FS) NewIPVSStats

    +
    func (fs FS) NewIPVSStats() (IPVSStats, error)
    +

    +NewIPVSStats reads the IPVS statistics from the specified `proc` filesystem. +

    + + + + + + +

    func (FS) NewProc

    +
    func (fs FS) NewProc(pid int) (Proc, error)
    +

    +NewProc returns a process for the given pid. +

    + + + + + + +

    func (FS) NewStat

    +
    func (fs FS) NewStat() (Stat, error)
    +

    +NewStat returns an information about current kernel/system statistics. +

    + + + + + + +

    func (FS) ParseMDStat

    +
    func (fs FS) ParseMDStat() (mdstates []MDStat, err error)
    +

    +ParseMDStat parses an mdstat-file and returns a struct with the relevant infos. +

    + + + + + + +

    func (FS) Path

    +
    func (fs FS) Path(p ...string) string
    +

    +Path returns the path of the given subsystem relative to the procfs root. +

    + + + + + + +

    func (FS) Self

    +
    func (fs FS) Self() (Proc, error)
    +

    +Self returns a process for the current process. +

    + + + + + + + + +

    type IPVSBackendStatus

    +
    type IPVSBackendStatus struct {
    +    // The local (virtual) IP address.
    +    LocalAddress net.IP
    +    // The local (virtual) port.
    +    LocalPort uint16
    +    // The transport protocol (TCP, UDP).
    +    Proto string
    +    // The remote (real) IP address.
    +    RemoteAddress net.IP
    +    // The remote (real) port.
    +    RemotePort uint16
    +    // The current number of active connections for this virtual/real address pair.
    +    ActiveConn uint64
    +    // The current number of inactive connections for this virtual/real address pair.
    +    InactConn uint64
    +    // The current weight of this virtual/real address pair.
    +    Weight uint64
    +}
    +

    +IPVSBackendStatus holds current metrics of one virtual / real address pair. +

    + + + + + + + + + + + + + + + + +

    type IPVSStats

    +
    type IPVSStats struct {
    +    // Total count of connections.
    +    Connections uint64
    +    // Total incoming packages processed.
    +    IncomingPackets uint64
    +    // Total outgoing packages processed.
    +    OutgoingPackets uint64
    +    // Total incoming traffic.
    +    IncomingBytes uint64
    +    // Total outgoing traffic.
    +    OutgoingBytes uint64
    +}
    +

    +IPVSStats holds IPVS statistics, as exposed by the kernel in `/proc/net/ip_vs_stats`. +

    + + + + + + + + + + + + +

    func NewIPVSStats

    +
    func NewIPVSStats() (IPVSStats, error)
    +

    +NewIPVSStats reads the IPVS statistics. +

    + + + + + + + + + +

    type MDStat

    +
    type MDStat struct {
    +    // Name of the device.
    +    Name string
    +    // activity-state of the device.
    +    ActivityState string
    +    // Number of active disks.
    +    DisksActive int64
    +    // Total number of disks the device consists of.
    +    DisksTotal int64
    +    // Number of blocks the device holds.
    +    BlocksTotal int64
    +    // Number of blocks on the device that are in sync.
    +    BlocksSynced int64
    +}
    +

    +MDStat holds info parsed from /proc/mdstat. +

    + + + + + + + + + + + + + + + + +

    type Proc

    +
    type Proc struct {
    +    // The process ID.
    +    PID int
    +    // contains filtered or unexported fields
    +}
    +

    +Proc provides information about a running process. +

    + + + + + + + + + + + + +

    func NewProc

    +
    func NewProc(pid int) (Proc, error)
    +

    +NewProc returns a process for the given pid under /proc. +

    + + + + + +

    func Self

    +
    func Self() (Proc, error)
    +

    +Self returns a process for the current process read via /proc/self. +

    + + + + + + + +

    func (Proc) CmdLine

    +
    func (p Proc) CmdLine() ([]string, error)
    +

    +CmdLine returns the command line of a process. +

    + + + + + + +

    func (Proc) Comm

    +
    func (p Proc) Comm() (string, error)
    +

    +Comm returns the command name of a process. +

    + + + + + + +

    func (Proc) Executable

    +
    func (p Proc) Executable() (string, error)
    +

    +Executable returns the absolute path of the executable command of a process. +

    + + + + + + +

    func (Proc) FileDescriptorTargets

    +
    func (p Proc) FileDescriptorTargets() ([]string, error)
    +

    +FileDescriptorTargets returns the targets of all file descriptors of a process. +If a file descriptor is not a symlink to a file (like a socket), that value will be the empty string. +

    + + + + + + +

    func (Proc) FileDescriptors

    +
    func (p Proc) FileDescriptors() ([]uintptr, error)
    +

    +FileDescriptors returns the currently open file descriptors of a process. +

    + + + + + + +

    func (Proc) FileDescriptorsLen

    +
    func (p Proc) FileDescriptorsLen() (int, error)
    +

    +FileDescriptorsLen returns the number of currently open file descriptors of +a process. +

    + + + + + + +

    func (Proc) NewIO

    +
    func (p Proc) NewIO() (ProcIO, error)
    +

    +NewIO creates a new ProcIO instance from a given Proc instance. +

    + + + + + + +

    func (Proc) NewLimits

    +
    func (p Proc) NewLimits() (ProcLimits, error)
    +

    +NewLimits returns the current soft limits of the process. +

    + + + + + + +

    func (Proc) NewStat

    +
    func (p Proc) NewStat() (ProcStat, error)
    +

    +NewStat returns the current status information of the process. +

    + + + + + + + + +

    type ProcIO

    +
    type ProcIO struct {
    +    // Chars read.
    +    RChar uint64
    +    // Chars written.
    +    WChar uint64
    +    // Read syscalls.
    +    SyscR uint64
    +    // Write syscalls.
    +    SyscW uint64
    +    // Bytes read.
    +    ReadBytes uint64
    +    // Bytes written.
    +    WriteBytes uint64
    +    // Bytes written, but taking into account truncation. See
    +    // Documentation/filesystems/proc.txt in the kernel sources for
    +    // detailed explanation.
    +    CancelledWriteBytes int64
    +}
    +

    +ProcIO models the content of /proc/<pid>/io. +

    + + + + + + + + + + + + + + + + +

    type ProcLimits

    +
    type ProcLimits struct {
    +    // CPU time limit in seconds.
    +    CPUTime int
    +    // Maximum size of files that the process may create.
    +    FileSize int
    +    // Maximum size of the process's data segment (initialized data,
    +    // uninitialized data, and heap).
    +    DataSize int
    +    // Maximum size of the process stack in bytes.
    +    StackSize int
    +    // Maximum size of a core file.
    +    CoreFileSize int
    +    // Limit of the process's resident set in pages.
    +    ResidentSet int
    +    // Maximum number of processes that can be created for the real user ID of
    +    // the calling process.
    +    Processes int
    +    // Value one greater than the maximum file descriptor number that can be
    +    // opened by this process.
    +    OpenFiles int
    +    // Maximum number of bytes of memory that may be locked into RAM.
    +    LockedMemory int
    +    // Maximum size of the process's virtual memory address space in bytes.
    +    AddressSpace int
    +    // Limit on the combined number of flock(2) locks and fcntl(2) leases that
    +    // this process may establish.
    +    FileLocks int
    +    // Limit of signals that may be queued for the real user ID of the calling
    +    // process.
    +    PendingSignals int
    +    // Limit on the number of bytes that can be allocated for POSIX message
    +    // queues for the real user ID of the calling process.
    +    MsqqueueSize int
    +    // Limit of the nice priority set using setpriority(2) or nice(2).
    +    NicePriority int
    +    // Limit of the real-time priority set using sched_setscheduler(2) or
    +    // sched_setparam(2).
    +    RealtimePriority int
    +    // Limit (in microseconds) on the amount of CPU time that a process
    +    // scheduled under a real-time scheduling policy may consume without making
    +    // a blocking system call.
    +    RealtimeTimeout int
    +}
    +

    +ProcLimits represents the soft limits for each of the process's resource +limits. For more information see getrlimit(2): +http://man7.org/linux/man-pages/man2/getrlimit.2.html. +

    + + + + + + + + + + + + + + + + +

    type ProcStat

    +
    type ProcStat struct {
    +    // The process ID.
    +    PID int
    +    // The filename of the executable.
    +    Comm string
    +    // The process state.
    +    State string
    +    // The PID of the parent of this process.
    +    PPID int
    +    // The process group ID of the process.
    +    PGRP int
    +    // The session ID of the process.
    +    Session int
    +    // The controlling terminal of the process.
    +    TTY int
    +    // The ID of the foreground process group of the controlling terminal of
    +    // the process.
    +    TPGID int
    +    // The kernel flags word of the process.
    +    Flags uint
    +    // The number of minor faults the process has made which have not required
    +    // loading a memory page from disk.
    +    MinFlt uint
    +    // The number of minor faults that the process's waited-for children have
    +    // made.
    +    CMinFlt uint
    +    // The number of major faults the process has made which have required
    +    // loading a memory page from disk.
    +    MajFlt uint
    +    // The number of major faults that the process's waited-for children have
    +    // made.
    +    CMajFlt uint
    +    // Amount of time that this process has been scheduled in user mode,
    +    // measured in clock ticks.
    +    UTime uint
    +    // Amount of time that this process has been scheduled in kernel mode,
    +    // measured in clock ticks.
    +    STime uint
    +    // Amount of time that this process's waited-for children have been
    +    // scheduled in user mode, measured in clock ticks.
    +    CUTime uint
    +    // Amount of time that this process's waited-for children have been
    +    // scheduled in kernel mode, measured in clock ticks.
    +    CSTime uint
    +    // For processes running a real-time scheduling policy, this is the negated
    +    // scheduling priority, minus one.
    +    Priority int
    +    // The nice value, a value in the range 19 (low priority) to -20 (high
    +    // priority).
    +    Nice int
    +    // Number of threads in this process.
    +    NumThreads int
    +    // The time the process started after system boot, the value is expressed
    +    // in clock ticks.
    +    Starttime uint64
    +    // Virtual memory size in bytes.
    +    VSize int
    +    // Resident set size in pages.
    +    RSS int
    +    // contains filtered or unexported fields
    +}
    +

    +ProcStat provides status information about the process, +read from /proc/[pid]/stat. +

    + + + + + + + + + + + + + + +

    func (ProcStat) CPUTime

    +
    func (s ProcStat) CPUTime() float64
    +

    +CPUTime returns the total CPU user and system time in seconds. +

    + + + + + + +

    func (ProcStat) ResidentMemory

    +
    func (s ProcStat) ResidentMemory() int
    +

    +ResidentMemory returns the resident memory size in bytes. +

    + + + + + + +

    func (ProcStat) StartTime

    +
    func (s ProcStat) StartTime() (float64, error)
    +

    +StartTime returns the unix timestamp of the process in seconds. +

    + + + + + + +

    func (ProcStat) VirtualMemory

    +
    func (s ProcStat) VirtualMemory() int
    +

    +VirtualMemory returns the virtual memory size in bytes. +

    + + + + + + + + +

    type Procs

    +
    type Procs []Proc
    +

    +Procs represents a list of Proc structs. +

    + + + + + + + + + + + + +

    func AllProcs

    +
    func AllProcs() (Procs, error)
    +

    +AllProcs returns a list of all currently available processes under /proc. +

    + + + + + + + +

    func (Procs) Len

    +
    func (p Procs) Len() int
    + + + + + + +

    func (Procs) Less

    +
    func (p Procs) Less(i, j int) bool
    + + + + + + +

    func (Procs) Swap

    +
    func (p Procs) Swap(i, j int)
    + + + + + + + + +

    type Stat

    +
    type Stat struct {
    +    // Boot time in seconds since the Epoch.
    +    BootTime int64
    +}
    +

    +Stat represents kernel/system statistics. +

    + + + + + + + + + + + + +

    func NewStat

    +
    func NewStat() (Stat, error)
    +

    +NewStat returns kernel/system statistics read from /proc/stat. +

    + + + + + + + + + + + + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/github.com/syndtr/goleveldb/index.html b/pkg/github.com/syndtr/goleveldb/index.html new file mode 100644 index 0000000..5c3df2c --- /dev/null +++ b/pkg/github.com/syndtr/goleveldb/index.html @@ -0,0 +1,262 @@ + + + + + + + + /src/github.com/syndtr/goleveldb - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Directory /src/github.com/syndtr/goleveldb

    + + + + + + + + + + + + + + + + + + + +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    NameSynopsis
    ..
    + leveldb + + Package leveldb provides implementation of LevelDB key/value database. +
    + cache + + Package cache provides interface and implementation of a cache algorithms. +
    + comparer + + Package comparer provides interface and implementation for ordering sets of data. +
    + errors + + Package errors provides common error types used throughout leveldb. +
    + filter + + Package filter provides interface and implementation of probabilistic data structure. +
    + iterator + + Package iterator provides interface and implementation to traverse over contents of a database. +
    + journal + + Package journal reads and writes sequences of journals. +
    + memdb + + Package memdb provides in-memory key/value database implementation. +
    + opt + + Package opt provides sets of options used by LevelDB. +
    + storage + + Package storage provides storage abstraction for LevelDB. +
    + table + + Package table allows read and write sorted key/value. +
    + testutil + + +
    + util + + Package util provides utilities used throughout leveldb. +
    +
    + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/github.com/syndtr/goleveldb/leveldb/cache/index.html b/pkg/github.com/syndtr/goleveldb/leveldb/cache/index.html new file mode 100644 index 0000000..32e571e --- /dev/null +++ b/pkg/github.com/syndtr/goleveldb/leveldb/cache/index.html @@ -0,0 +1,729 @@ + + + + + + + + cache - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Package cache

    + + + + + + + + + + + + + + +
    +
    +
    import "github.com/syndtr/goleveldb/leveldb/cache"
    +
    +
    +
    Overview
    +
    Index
    + + +
    +
    + +
    + +
    +

    Overview ▾

    +

    +Package cache provides interface and implementation of a cache algorithms. +

    + +
    +
    + + + + + + + + + + + + +

    type Cache

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

    +Cache is a 'cache map'. +

    + + + + + + + + + + + + +

    func NewCache

    +
    func NewCache(cacher Cacher) *Cache
    +

    +NewCache creates a new 'cache map'. The cacher is optional and +may be nil. +

    + + + + + + + +

    func (*Cache) Capacity

    +
    func (r *Cache) Capacity() int
    +

    +Capacity returns cache capacity. +

    + + + + + + +

    func (*Cache) Close

    +
    func (r *Cache) Close() error
    +

    +Close closes the 'cache map' and forcefully releases all 'cache node'. +

    + + + + + + +

    func (*Cache) CloseWeak

    +
    func (r *Cache) CloseWeak() error
    +

    +CloseWeak closes the 'cache map' and evict all 'cache node' from cacher, but +unlike Close it doesn't forcefully releases 'cache node'. +

    + + + + + + +

    func (*Cache) Delete

    +
    func (r *Cache) Delete(ns, key uint64, onDel func()) bool
    +

    +Delete removes and ban 'cache node' with the given namespace and key. +A banned 'cache node' will never inserted into the 'cache tree'. Ban +only attributed to the particular 'cache node', so when a 'cache node' +is recreated it will not be banned. +

    +

    +If onDel is not nil, then it will be executed if such 'cache node' +doesn't exist or once the 'cache node' is released. +

    +

    +Delete return true is such 'cache node' exist. +

    + + + + + + +

    func (*Cache) Evict

    +
    func (r *Cache) Evict(ns, key uint64) bool
    +

    +Evict evicts 'cache node' with the given namespace and key. This will +simply call Cacher.Evict. +

    +

    +Evict return true is such 'cache node' exist. +

    + + + + + + +

    func (*Cache) EvictAll

    +
    func (r *Cache) EvictAll()
    +

    +EvictAll evicts all 'cache node'. This will simply call Cacher.EvictAll. +

    + + + + + + +

    func (*Cache) EvictNS

    +
    func (r *Cache) EvictNS(ns uint64)
    +

    +EvictNS evicts 'cache node' with the given namespace. This will +simply call Cacher.EvictNS. +

    + + + + + + +

    func (*Cache) Get

    +
    func (r *Cache) Get(ns, key uint64, setFunc func() (size int, value Value)) *Handle
    +

    +Get gets 'cache node' with the given namespace and key. +If cache node is not found and setFunc is not nil, Get will atomically creates +the 'cache node' by calling setFunc. Otherwise Get will returns nil. +

    +

    +The returned 'cache handle' should be released after use by calling Release +method. +

    + + + + + + +

    func (*Cache) Nodes

    +
    func (r *Cache) Nodes() int
    +

    +Nodes returns number of 'cache node' in the map. +

    + + + + + + +

    func (*Cache) SetCapacity

    +
    func (r *Cache) SetCapacity(capacity int)
    +

    +SetCapacity sets cache capacity. +

    + + + + + + +

    func (*Cache) Size

    +
    func (r *Cache) Size() int
    +

    +Size returns sums of 'cache node' size in the map. +

    + + + + + + + + +

    type Cacher

    +
    type Cacher interface {
    +    // Capacity returns cache capacity.
    +    Capacity() int
    +
    +    // SetCapacity sets cache capacity.
    +    SetCapacity(capacity int)
    +
    +    // Promote promotes the 'cache node'.
    +    Promote(n *Node)
    +
    +    // Ban evicts the 'cache node' and prevent subsequent 'promote'.
    +    Ban(n *Node)
    +
    +    // Evict evicts the 'cache node'.
    +    Evict(n *Node)
    +
    +    // EvictNS evicts 'cache node' with the given namespace.
    +    EvictNS(ns uint64)
    +
    +    // EvictAll evicts all 'cache node'.
    +    EvictAll()
    +
    +    // Close closes the 'cache tree'
    +    Close() error
    +}
    +

    +Cacher provides interface to implements a caching functionality. +An implementation must be safe for concurrent use. +

    + + + + + + + + + + + + +

    func NewLRU

    +
    func NewLRU(capacity int) Cacher
    +

    +NewLRU create a new LRU-cache. +

    + + + + + + + + + +

    type Handle

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

    +Handle is a 'cache handle' of a 'cache node'. +

    + + + + + + + + + + + + + + +

    func (*Handle) Release

    +
    func (h *Handle) Release()
    +

    +Release releases this 'cache handle'. +It is safe to call release multiple times. +

    + + + + + + +

    func (*Handle) Value

    +
    func (h *Handle) Value() Value
    +

    +Value returns the value of the 'cache node'. +

    + + + + + + + + +

    type NamespaceGetter

    +
    type NamespaceGetter struct {
    +    Cache *Cache
    +    NS    uint64
    +}
    +

    +NamespaceGetter provides convenient wrapper for namespace. +

    + + + + + + + + + + + + + + +

    func (*NamespaceGetter) Get

    +
    func (g *NamespaceGetter) Get(key uint64, setFunc func() (size int, value Value)) *Handle
    +

    +Get simply calls Cache.Get() method. +

    + + + + + + + + +

    type Node

    +
    type Node struct {
    +    CacheData unsafe.Pointer
    +    // contains filtered or unexported fields
    +}
    +

    +Node is a 'cache node'. +

    + + + + + + + + + + + + + + +

    func (*Node) GetHandle

    +
    func (n *Node) GetHandle() *Handle
    +

    +GetHandle returns an handle for this 'cache node'. +

    + + + + + + +

    func (*Node) Key

    +
    func (n *Node) Key() uint64
    +

    +Key returns this 'cache node' key. +

    + + + + + + +

    func (*Node) NS

    +
    func (n *Node) NS() uint64
    +

    +NS returns this 'cache node' namespace. +

    + + + + + + +

    func (*Node) Ref

    +
    func (n *Node) Ref() int32
    +

    +Ref returns this 'cache node' ref counter. +

    + + + + + + +

    func (*Node) Size

    +
    func (n *Node) Size() int
    +

    +Size returns this 'cache node' size. +

    + + + + + + +

    func (*Node) Value

    +
    func (n *Node) Value() Value
    +

    +Value returns this 'cache node' value. +

    + + + + + + + + +

    type Value

    +
    type Value interface{}
    +

    +Value is a 'cacheable object'. It may implements util.Releaser, if +so the the Release method will be called once object is released. +

    + + + + + + + + + + + + + + + + + + + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/github.com/syndtr/goleveldb/leveldb/comparer/index.html b/pkg/github.com/syndtr/goleveldb/leveldb/comparer/index.html new file mode 100644 index 0000000..a14a4fe --- /dev/null +++ b/pkg/github.com/syndtr/goleveldb/leveldb/comparer/index.html @@ -0,0 +1,311 @@ + + + + + + + + comparer - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Package comparer

    + + + + + + + + + + + + + + +
    +
    +
    import "github.com/syndtr/goleveldb/leveldb/comparer"
    +
    +
    +
    Overview
    +
    Index
    + + +
    +
    + +
    + +
    +

    Overview ▾

    +

    +Package comparer provides interface and implementation for ordering +sets of data. +

    + +
    +
    + + +
    + +
    +

    Index ▾

    + + +
    +
    + + +
    Variables
    + + + + +
    type BasicComparer
    + + + + +
    type Comparer
    + + + + +
    +
    + + + + +

    Package files

    +

    + + + bytes_comparer.go + + comparer.go + + +

    + +
    +
    + + + + + +

    Variables

    + +
    var DefaultComparer = bytesComparer{}
    +

    +DefaultComparer are default implementation of the Comparer interface. +It uses the natural ordering, consistent with bytes.Compare. +

    + + + + + + + +

    type BasicComparer

    +
    type BasicComparer interface {
    +    // Compare returns -1, 0, or +1 depending on whether a is 'less than',
    +    // 'equal to' or 'greater than' b. The two arguments can only be 'equal'
    +    // if their contents are exactly equal. Furthermore, the empty slice
    +    // must be 'less than' any non-empty slice.
    +    Compare(a, b []byte) int
    +}
    +

    +BasicComparer is the interface that wraps the basic Compare method. +

    + + + + + + + + + + + + + + + + +

    type Comparer

    +
    type Comparer interface {
    +    BasicComparer
    +
    +    // Name returns name of the comparer.
    +    //
    +    // The Level-DB on-disk format stores the comparer name, and opening a
    +    // database with a different comparer from the one it was created with
    +    // will result in an error.
    +    //
    +    // An implementation to a new name whenever the comparer implementation
    +    // changes in a way that will cause the relative ordering of any two keys
    +    // to change.
    +    //
    +    // Names starting with "leveldb." are reserved and should not be used
    +    // by any users of this package.
    +    Name() string
    +
    +    // Separator appends a sequence of bytes x to dst such that a <= x && x < b,
    +    // where 'less than' is consistent with Compare. An implementation should
    +    // return nil if x equal to a.
    +    //
    +    // Either contents of a or b should not by any means modified. Doing so
    +    // may cause corruption on the internal state.
    +    Separator(dst, a, b []byte) []byte
    +
    +    // Successor appends a sequence of bytes x to dst such that x >= b, where
    +    // 'less than' is consistent with Compare. An implementation should return
    +    // nil if x equal to b.
    +    //
    +    // Contents of b should not by any means modified. Doing so may cause
    +    // corruption on the internal state.
    +    Successor(dst, b []byte) []byte
    +}
    +

    +Comparer defines a total ordering over the space of []byte keys: a 'less +than' relationship. +

    + + + + + + + + + + + + + + + + + + + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/github.com/syndtr/goleveldb/leveldb/errors/index.html b/pkg/github.com/syndtr/goleveldb/leveldb/errors/index.html new file mode 100644 index 0000000..b7a6939 --- /dev/null +++ b/pkg/github.com/syndtr/goleveldb/leveldb/errors/index.html @@ -0,0 +1,363 @@ + + + + + + + + errors - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Package errors

    + + + + + + + + + + + + + + +
    +
    +
    import "github.com/syndtr/goleveldb/leveldb/errors"
    +
    +
    +
    Overview
    +
    Index
    + + +
    +
    + +
    + +
    +

    Overview ▾

    +

    +Package errors provides common error types used throughout leveldb. +

    + +
    +
    + + + + + + + + +

    Variables

    + +
    var (
    +    ErrNotFound    = New("leveldb: not found")
    +    ErrReleased    = util.ErrReleased
    +    ErrHasReleaser = util.ErrHasReleaser
    +)
    +

    +Common errors. +

    + + + + + + +

    func IsCorrupted

    +
    func IsCorrupted(err error) bool
    +

    +IsCorrupted returns a boolean indicating whether the error is indicating +a corruption. +

    + + + + + + + +

    func New

    +
    func New(text string) error
    +

    +New returns an error that formats as the given text. +

    + + + + + + + +

    func NewErrCorrupted

    +
    func NewErrCorrupted(fd storage.FileDesc, err error) error
    +

    +NewErrCorrupted creates new ErrCorrupted error. +

    + + + + + + + +

    func SetFd

    +
    func SetFd(err error, fd storage.FileDesc) error
    +

    +SetFd sets 'file info' of the given error with the given file. +Currently only ErrCorrupted is supported, otherwise will do nothing. +

    + + + + + + + + +

    type ErrCorrupted

    +
    type ErrCorrupted struct {
    +    Fd  storage.FileDesc
    +    Err error
    +}
    +

    +ErrCorrupted is the type that wraps errors that indicate corruption in +the database. +

    + + + + + + + + + + + + + + +

    func (*ErrCorrupted) Error

    +
    func (e *ErrCorrupted) Error() string
    + + + + + + + + +

    type ErrMissingFiles

    +
    type ErrMissingFiles struct {
    +    Fds []storage.FileDesc
    +}
    +

    +ErrMissingFiles is the type that indicating a corruption due to missing +files. ErrMissingFiles always wrapped with ErrCorrupted. +

    + + + + + + + + + + + + + + +

    func (*ErrMissingFiles) Error

    +
    func (e *ErrMissingFiles) Error() string
    + + + + + + + + + + + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/github.com/syndtr/goleveldb/leveldb/filter/index.html b/pkg/github.com/syndtr/goleveldb/leveldb/filter/index.html new file mode 100644 index 0000000..ce5ad55 --- /dev/null +++ b/pkg/github.com/syndtr/goleveldb/leveldb/filter/index.html @@ -0,0 +1,350 @@ + + + + + + + + filter - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Package filter

    + + + + + + + + + + + + + + +
    +
    +
    import "github.com/syndtr/goleveldb/leveldb/filter"
    +
    +
    +
    Overview
    +
    Index
    + + +
    +
    + +
    + +
    +

    Overview ▾

    +

    +Package filter provides interface and implementation of probabilistic +data structure. +

    +

    +The filter is resposible for creating small filter from a set of keys. +These filter will then used to test whether a key is a member of the set. +In many cases, a filter can cut down the number of disk seeks from a +handful to a single disk seek per DB.Get call. +

    + +
    +
    + + +
    + +
    +

    Index ▾

    + + +
    +
    + + + + + +
    type Buffer
    + + + + +
    type Filter
    + + +
        func NewBloomFilter(bitsPerKey int) Filter
    + + + + +
    type FilterGenerator
    + + + + +
    +
    + + + + +

    Package files

    +

    + + + bloom.go + + filter.go + + +

    + +
    +
    + + + + + + + + + +

    type Buffer

    +
    type Buffer interface {
    +    // Alloc allocs n bytes of slice from the buffer. This also advancing
    +    // write offset.
    +    Alloc(n int) []byte
    +
    +    // Write appends the contents of p to the buffer.
    +    Write(p []byte) (n int, err error)
    +
    +    // WriteByte appends the byte c to the buffer.
    +    WriteByte(c byte) error
    +}
    +

    +Buffer is the interface that wraps basic Alloc, Write and WriteByte methods. +

    + + + + + + + + + + + + + + + + +

    type Filter

    +
    type Filter interface {
    +    // Name returns the name of this policy.
    +    //
    +    // Note that if the filter encoding changes in an incompatible way,
    +    // the name returned by this method must be changed. Otherwise, old
    +    // incompatible filters may be passed to methods of this type.
    +    Name() string
    +
    +    // NewGenerator creates a new filter generator.
    +    NewGenerator() FilterGenerator
    +
    +    // Contains returns true if the filter contains the given key.
    +    //
    +    // The filter are filters generated by the filter generator.
    +    Contains(filter, key []byte) bool
    +}
    +

    +Filter is the filter. +

    + + + + + + + + + + + + +

    func NewBloomFilter

    +
    func NewBloomFilter(bitsPerKey int) Filter
    +

    +NewBloomFilter creates a new initialized bloom filter for given +bitsPerKey. +

    +

    +Since bitsPerKey is persisted individually for each bloom filter +serialization, bloom filters are backwards compatible with respect to +changing bitsPerKey. This means that no big performance penalty will +be experienced when changing the parameter. See documentation for +opt.Options.Filter for more information. +

    + + + + + + + + + +

    type FilterGenerator

    +
    type FilterGenerator interface {
    +    // Add adds a key to the filter generator.
    +    //
    +    // The key may become invalid after call to this method end, therefor
    +    // key must be copied if implementation require keeping key for later
    +    // use. The key should not modified directly, doing so may cause
    +    // undefined results.
    +    Add(key []byte)
    +
    +    // Generate generates filters based on keys passed so far. After call
    +    // to Generate the filter generator maybe resetted, depends on implementation.
    +    Generate(b Buffer)
    +}
    +

    +FilterGenerator is the filter generator. +

    + + + + + + + + + + + + + + + + + + + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/github.com/syndtr/goleveldb/leveldb/index.html b/pkg/github.com/syndtr/goleveldb/leveldb/index.html new file mode 100644 index 0000000..78e3b78 --- /dev/null +++ b/pkg/github.com/syndtr/goleveldb/leveldb/index.html @@ -0,0 +1,1598 @@ + + + + + + + + leveldb - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Package leveldb

    + + + + + + + + + + + + + + +
    +
    +
    import "github.com/syndtr/goleveldb/leveldb"
    +
    +
    +
    Overview
    +
    Index
    + + +
    Subdirectories
    + +
    +
    + +
    + +
    +

    Overview ▾

    +

    +Package leveldb provides implementation of LevelDB key/value database. +

    +

    +Create or open a database: +

    +
    db, err := leveldb.OpenFile("path/to/db", nil)
    +...
    +defer db.Close()
    +...
    +
    +

    +Read or modify the database content: +

    +
    // Remember that the contents of the returned slice should not be modified.
    +data, err := db.Get([]byte("key"), nil)
    +...
    +err = db.Put([]byte("key"), []byte("value"), nil)
    +...
    +err = db.Delete([]byte("key"), nil)
    +...
    +
    +

    +Iterate over database content: +

    +
    iter := db.NewIterator(nil, nil)
    +for iter.Next() {
    +	// Remember that the contents of the returned slice should not be modified, and
    +	// only valid until the next call to Next.
    +	key := iter.Key()
    +	value := iter.Value()
    +	...
    +}
    +iter.Release()
    +err = iter.Error()
    +...
    +
    +

    +Iterate over subset of database content with a particular prefix: +

    +
    iter := db.NewIterator(util.BytesPrefix([]byte("foo-")), nil)
    +for iter.Next() {
    +	// Use key/value.
    +	...
    +}
    +iter.Release()
    +err = iter.Error()
    +...
    +
    +

    +Seek-then-Iterate: +

    +
    iter := db.NewIterator(nil, nil)
    +for ok := iter.Seek(key); ok; ok = iter.Next() {
    +	// Use key/value.
    +	...
    +}
    +iter.Release()
    +err = iter.Error()
    +...
    +
    +

    +Iterate over subset of database content: +

    +
    iter := db.NewIterator(&util.Range{Start: []byte("foo"), Limit: []byte("xoo")}, nil)
    +for iter.Next() {
    +	// Use key/value.
    +	...
    +}
    +iter.Release()
    +err = iter.Error()
    +...
    +
    +

    +Batch writes: +

    +
    batch := new(leveldb.Batch)
    +batch.Put([]byte("foo"), []byte("value"))
    +batch.Put([]byte("bar"), []byte("another value"))
    +batch.Delete([]byte("baz"))
    +err = db.Write(batch, nil)
    +...
    +
    +

    +Use bloom filter: +

    +
    o := &opt.Options{
    +	Filter: filter.NewBloomFilter(10),
    +}
    +db, err := leveldb.OpenFile("path/to/db", o)
    +...
    +defer db.Close()
    +...
    +
    + +
    +
    + + +
    + +
    +

    Index ▾

    + + +
    +
    + + +
    Variables
    + + + + +
    type Batch
    + + + +
        func (b *Batch) Delete(key []byte)
    + + +
        func (b *Batch) Dump() []byte
    + + +
        func (b *Batch) Len() int
    + + +
        func (b *Batch) Load(data []byte) error
    + + +
        func (b *Batch) Put(key, value []byte)
    + + +
        func (b *Batch) Replay(r BatchReplay) error
    + + +
        func (b *Batch) Reset()
    + + + +
    type BatchReplay
    + + + + +
    type DB
    + + +
        func Open(stor storage.Storage, o *opt.Options) (db *DB, err error)
    + + +
        func OpenFile(path string, o *opt.Options) (db *DB, err error)
    + + +
        func Recover(stor storage.Storage, o *opt.Options) (db *DB, err error)
    + + +
        func RecoverFile(path string, o *opt.Options) (db *DB, err error)
    + + + +
        func (db *DB) Close() error
    + + +
        func (db *DB) CompactRange(r util.Range) error
    + + +
        func (db *DB) Delete(key []byte, wo *opt.WriteOptions) error
    + + +
        func (db *DB) Get(key []byte, ro *opt.ReadOptions) (value []byte, err error)
    + + +
        func (db *DB) GetProperty(name string) (value string, err error)
    + + +
        func (db *DB) GetSnapshot() (*Snapshot, error)
    + + +
        func (db *DB) Has(key []byte, ro *opt.ReadOptions) (ret bool, err error)
    + + +
        func (db *DB) NewIterator(slice *util.Range, ro *opt.ReadOptions) iterator.Iterator
    + + +
        func (db *DB) OpenTransaction() (*Transaction, error)
    + + +
        func (db *DB) Put(key, value []byte, wo *opt.WriteOptions) error
    + + +
        func (db *DB) SetReadOnly() error
    + + +
        func (db *DB) SizeOf(ranges []util.Range) (Sizes, error)
    + + +
        func (db *DB) Write(batch *Batch, wo *opt.WriteOptions) error
    + + + +
    type ErrBatchCorrupted
    + + + +
        func (e *ErrBatchCorrupted) Error() string
    + + + +
    type ErrInternalKeyCorrupted
    + + + +
        func (e *ErrInternalKeyCorrupted) Error() string
    + + + +
    type ErrManifestCorrupted
    + + + +
        func (e *ErrManifestCorrupted) Error() string
    + + + +
    type Reader
    + + + + +
    type Sizes
    + + + +
        func (sizes Sizes) Sum() int64
    + + + +
    type Snapshot
    + + + +
        func (snap *Snapshot) Get(key []byte, ro *opt.ReadOptions) (value []byte, err error)
    + + +
        func (snap *Snapshot) Has(key []byte, ro *opt.ReadOptions) (ret bool, err error)
    + + +
        func (snap *Snapshot) NewIterator(slice *util.Range, ro *opt.ReadOptions) iterator.Iterator
    + + +
        func (snap *Snapshot) Release()
    + + +
        func (snap *Snapshot) String() string
    + + + +
    type Transaction
    + + + +
        func (tr *Transaction) Commit() error
    + + +
        func (tr *Transaction) Delete(key []byte, wo *opt.WriteOptions) error
    + + +
        func (tr *Transaction) Discard()
    + + +
        func (tr *Transaction) Get(key []byte, ro *opt.ReadOptions) ([]byte, error)
    + + +
        func (tr *Transaction) Has(key []byte, ro *opt.ReadOptions) (bool, error)
    + + +
        func (tr *Transaction) NewIterator(slice *util.Range, ro *opt.ReadOptions) iterator.Iterator
    + + +
        func (tr *Transaction) Put(key, value []byte, wo *opt.WriteOptions) error
    + + +
        func (tr *Transaction) Write(b *Batch, wo *opt.WriteOptions) error
    + + + +
    +
    + + + + +

    Package files

    +

    + + + batch.go + + comparer.go + + db.go + + db_compaction.go + + db_iter.go + + db_snapshot.go + + db_state.go + + db_transaction.go + + db_util.go + + db_write.go + + doc.go + + errors.go + + filter.go + + key.go + + options.go + + session.go + + session_compaction.go + + session_record.go + + session_util.go + + table.go + + util.go + + version.go + + +

    + +
    +
    + + + + + +

    Variables

    + +
    var (
    +    ErrNotFound         = errors.ErrNotFound
    +    ErrReadOnly         = errors.New("leveldb: read-only mode")
    +    ErrSnapshotReleased = errors.New("leveldb: snapshot released")
    +    ErrIterReleased     = errors.New("leveldb: iterator released")
    +    ErrClosed           = errors.New("leveldb: closed")
    +)
    +

    +Common errors. +

    + + + + + + + +

    type Batch

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

    +Batch is a write batch. +

    + + + + + + + + + + + + + + +

    func (*Batch) Delete

    +
    func (b *Batch) Delete(key []byte)
    +

    +Delete appends 'delete operation' of the given key to the batch. +It is safe to modify the contents of the argument after Delete returns but +not before. +

    + + + + + + +

    func (*Batch) Dump

    +
    func (b *Batch) Dump() []byte
    +

    +Dump dumps batch contents. The returned slice can be loaded into the +batch using Load method. +The returned slice is not its own copy, so the contents should not be +modified. +

    + + + + + + +

    func (*Batch) Len

    +
    func (b *Batch) Len() int
    +

    +Len returns number of records in the batch. +

    + + + + + + +

    func (*Batch) Load

    +
    func (b *Batch) Load(data []byte) error
    +

    +Load loads given slice into the batch. Previous contents of the batch +will be discarded. +The given slice will not be copied and will be used as batch buffer, so +it is not safe to modify the contents of the slice. +

    + + + + + + +

    func (*Batch) Put

    +
    func (b *Batch) Put(key, value []byte)
    +

    +Put appends 'put operation' of the given key/value pair to the batch. +It is safe to modify the contents of the argument after Put returns but not +before. +

    + + + + + + +

    func (*Batch) Replay

    +
    func (b *Batch) Replay(r BatchReplay) error
    +

    +Replay replays batch contents. +

    + + + + + + +

    func (*Batch) Reset

    +
    func (b *Batch) Reset()
    +

    +Reset resets the batch. +

    + + + + + + + + +

    type BatchReplay

    +
    type BatchReplay interface {
    +    Put(key, value []byte)
    +    Delete(key []byte)
    +}
    +

    +BatchReplay wraps basic batch operations. +

    + + + + + + + + + + + + + + + + +

    type DB

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

    +DB is a LevelDB database. +

    + + + + + + + + + + + + +

    func Open

    +
    func Open(stor storage.Storage, o *opt.Options) (db *DB, err error)
    +

    +Open opens or creates a DB for the given storage. +The DB will be created if not exist, unless ErrorIfMissing is true. +Also, if ErrorIfExist is true and the DB exist Open will returns +os.ErrExist error. +

    +

    +Open will return an error with type of ErrCorrupted if corruption +detected in the DB. Use errors.IsCorrupted to test whether an error is +due to corruption. Corrupted DB can be recovered with Recover function. +

    +

    +The returned DB instance is safe for concurrent use. +The DB must be closed after use, by calling Close method. +

    + + + + + +

    func OpenFile

    +
    func OpenFile(path string, o *opt.Options) (db *DB, err error)
    +

    +OpenFile opens or creates a DB for the given path. +The DB will be created if not exist, unless ErrorIfMissing is true. +Also, if ErrorIfExist is true and the DB exist OpenFile will returns +os.ErrExist error. +

    +

    +OpenFile uses standard file-system backed storage implementation as +described in the leveldb/storage package. +

    +

    +OpenFile will return an error with type of ErrCorrupted if corruption +detected in the DB. Use errors.IsCorrupted to test whether an error is +due to corruption. Corrupted DB can be recovered with Recover function. +

    +

    +The returned DB instance is safe for concurrent use. +The DB must be closed after use, by calling Close method. +

    + + + + + +

    func Recover

    +
    func Recover(stor storage.Storage, o *opt.Options) (db *DB, err error)
    +

    +Recover recovers and opens a DB with missing or corrupted manifest files +for the given storage. It will ignore any manifest files, valid or not. +The DB must already exist or it will returns an error. +Also, Recover will ignore ErrorIfMissing and ErrorIfExist options. +

    +

    +The returned DB instance is safe for concurrent use. +The DB must be closed after use, by calling Close method. +

    + + + + + +

    func RecoverFile

    +
    func RecoverFile(path string, o *opt.Options) (db *DB, err error)
    +

    +RecoverFile recovers and opens a DB with missing or corrupted manifest files +for the given path. It will ignore any manifest files, valid or not. +The DB must already exist or it will returns an error. +Also, Recover will ignore ErrorIfMissing and ErrorIfExist options. +

    +

    +RecoverFile uses standard file-system backed storage implementation as described +in the leveldb/storage package. +

    +

    +The returned DB instance is safe for concurrent use. +The DB must be closed after use, by calling Close method. +

    + + + + + + + +

    func (*DB) Close

    +
    func (db *DB) Close() error
    +

    +Close closes the DB. This will also releases any outstanding snapshot, +abort any in-flight compaction and discard open transaction. +

    +

    +It is not safe to close a DB until all outstanding iterators are released. +It is valid to call Close multiple times. Other methods should not be +called after the DB has been closed. +

    + + + + + + +

    func (*DB) CompactRange

    +
    func (db *DB) CompactRange(r util.Range) error
    +

    +CompactRange compacts the underlying DB for the given key range. +In particular, deleted and overwritten versions are discarded, +and the data is rearranged to reduce the cost of operations +needed to access the data. This operation should typically only +be invoked by users who understand the underlying implementation. +

    +

    +A nil Range.Start is treated as a key before all keys in the DB. +And a nil Range.Limit is treated as a key after all keys in the DB. +Therefore if both is nil then it will compact entire DB. +

    + + + + + + +

    func (*DB) Delete

    +
    func (db *DB) Delete(key []byte, wo *opt.WriteOptions) error
    +

    +Delete deletes the value for the given key. Delete will not returns error if +key doesn't exist. Write merge also applies for Delete, see Write. +

    +

    +It is safe to modify the contents of the arguments after Delete returns but +not before. +

    + + + + + + +

    func (*DB) Get

    +
    func (db *DB) Get(key []byte, ro *opt.ReadOptions) (value []byte, err error)
    +

    +Get gets the value for the given key. It returns ErrNotFound if the +DB does not contains the key. +

    +

    +The returned slice is its own copy, it is safe to modify the contents +of the returned slice. +It is safe to modify the contents of the argument after Get returns. +

    + + + + + + +

    func (*DB) GetProperty

    +
    func (db *DB) GetProperty(name string) (value string, err error)
    +

    +GetProperty returns value of the given property name. +

    +

    +Property names: +

    +
    leveldb.num-files-at-level{n}
    +	Returns the number of files at level 'n'.
    +leveldb.stats
    +	Returns statistics of the underlying DB.
    +leveldb.sstables
    +	Returns sstables list for each level.
    +leveldb.blockpool
    +	Returns block pool stats.
    +leveldb.cachedblock
    +	Returns size of cached block.
    +leveldb.openedtables
    +	Returns number of opened tables.
    +leveldb.alivesnaps
    +	Returns number of alive snapshots.
    +leveldb.aliveiters
    +	Returns number of alive iterators.
    +
    + + + + + + +

    func (*DB) GetSnapshot

    +
    func (db *DB) GetSnapshot() (*Snapshot, error)
    +

    +GetSnapshot returns a latest snapshot of the underlying DB. A snapshot +is a frozen snapshot of a DB state at a particular point in time. The +content of snapshot are guaranteed to be consistent. +

    +

    +The snapshot must be released after use, by calling Release method. +

    + + + + + + +

    func (*DB) Has

    +
    func (db *DB) Has(key []byte, ro *opt.ReadOptions) (ret bool, err error)
    +

    +Has returns true if the DB does contains the given key. +

    +

    +It is safe to modify the contents of the argument after Get returns. +

    + + + + + + +

    func (*DB) NewIterator

    +
    func (db *DB) NewIterator(slice *util.Range, ro *opt.ReadOptions) iterator.Iterator
    +

    +NewIterator returns an iterator for the latest snapshot of the +underlying DB. +The returned iterator is not safe for concurrent use, but it is safe to use +multiple iterators concurrently, with each in a dedicated goroutine. +It is also safe to use an iterator concurrently with modifying its +underlying DB. The resultant key/value pairs are guaranteed to be +consistent. +

    +

    +Slice allows slicing the iterator to only contains keys in the given +range. A nil Range.Start is treated as a key before all keys in the +DB. And a nil Range.Limit is treated as a key after all keys in +the DB. +

    +

    +The iterator must be released after use, by calling Release method. +

    +

    +Also read Iterator documentation of the leveldb/iterator package. +

    + + + + + + +

    func (*DB) OpenTransaction

    +
    func (db *DB) OpenTransaction() (*Transaction, error)
    +

    +OpenTransaction opens an atomic DB transaction. Only one transaction can be +opened at a time. Subsequent call to Write and OpenTransaction will be blocked +until in-flight transaction is committed or discarded. +The returned transaction handle is safe for concurrent use. +

    +

    +Transaction is expensive and can overwhelm compaction, especially if +transaction size is small. Use with caution. +

    +

    +The transaction must be closed once done, either by committing or discarding +the transaction. +Closing the DB will discard open transaction. +

    + + + + + + +

    func (*DB) Put

    +
    func (db *DB) Put(key, value []byte, wo *opt.WriteOptions) error
    +

    +Put sets the value for the given key. It overwrites any previous value +for that key; a DB is not a multi-map. Write merge also applies for Put, see +Write. +

    +

    +It is safe to modify the contents of the arguments after Put returns but not +before. +

    + + + + + + +

    func (*DB) SetReadOnly

    +
    func (db *DB) SetReadOnly() error
    +

    +SetReadOnly makes DB read-only. It will stay read-only until reopened. +

    + + + + + + +

    func (*DB) SizeOf

    +
    func (db *DB) SizeOf(ranges []util.Range) (Sizes, error)
    +

    +SizeOf calculates approximate sizes of the given key ranges. +The length of the returned sizes are equal with the length of the given +ranges. The returned sizes measure storage space usage, so if the user +data compresses by a factor of ten, the returned sizes will be one-tenth +the size of the corresponding user data size. +The results may not include the sizes of recently written data. +

    + + + + + + +

    func (*DB) Write

    +
    func (db *DB) Write(batch *Batch, wo *opt.WriteOptions) error
    +

    +Write apply the given batch to the DB. The batch records will be applied +sequentially. Write might be used concurrently, when used concurrently and +batch is small enough, write will try to merge the batches. Set NoWriteMerge +option to true to disable write merge. +

    +

    +It is safe to modify the contents of the arguments after Write returns but +not before. Write will not modify content of the batch. +

    + + + + + + + + +

    type ErrBatchCorrupted

    +
    type ErrBatchCorrupted struct {
    +    Reason string
    +}
    +

    +ErrBatchCorrupted records reason of batch corruption. This error will be +wrapped with errors.ErrCorrupted. +

    + + + + + + + + + + + + + + +

    func (*ErrBatchCorrupted) Error

    +
    func (e *ErrBatchCorrupted) Error() string
    + + + + + + + + +

    type ErrInternalKeyCorrupted

    +
    type ErrInternalKeyCorrupted struct {
    +    Ikey   []byte
    +    Reason string
    +}
    +

    +ErrInternalKeyCorrupted records internal key corruption. +

    + + + + + + + + + + + + + + +

    func (*ErrInternalKeyCorrupted) Error

    +
    func (e *ErrInternalKeyCorrupted) Error() string
    + + + + + + + + +

    type ErrManifestCorrupted

    +
    type ErrManifestCorrupted struct {
    +    Field  string
    +    Reason string
    +}
    +

    +ErrManifestCorrupted records manifest corruption. This error will be +wrapped with errors.ErrCorrupted. +

    + + + + + + + + + + + + + + +

    func (*ErrManifestCorrupted) Error

    +
    func (e *ErrManifestCorrupted) Error() string
    + + + + + + + + +

    type Reader

    +
    type Reader interface {
    +    Get(key []byte, ro *opt.ReadOptions) (value []byte, err error)
    +    NewIterator(slice *util.Range, ro *opt.ReadOptions) iterator.Iterator
    +}
    +

    +Reader is the interface that wraps basic Get and NewIterator methods. +This interface implemented by both DB and Snapshot. +

    + + + + + + + + + + + + + + + + +

    type Sizes

    +
    type Sizes []int64
    +

    +Sizes is list of size. +

    + + + + + + + + + + + + + + +

    func (Sizes) Sum

    +
    func (sizes Sizes) Sum() int64
    +

    +Sum returns sum of the sizes. +

    + + + + + + + + +

    type Snapshot

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

    +Snapshot is a DB snapshot. +

    + + + + + + + + + + + + + + +

    func (*Snapshot) Get

    +
    func (snap *Snapshot) Get(key []byte, ro *opt.ReadOptions) (value []byte, err error)
    +

    +Get gets the value for the given key. It returns ErrNotFound if +the DB does not contains the key. +

    +

    +The caller should not modify the contents of the returned slice, but +it is safe to modify the contents of the argument after Get returns. +

    + + + + + + +

    func (*Snapshot) Has

    +
    func (snap *Snapshot) Has(key []byte, ro *opt.ReadOptions) (ret bool, err error)
    +

    +Has returns true if the DB does contains the given key. +

    +

    +It is safe to modify the contents of the argument after Get returns. +

    + + + + + + +

    func (*Snapshot) NewIterator

    +
    func (snap *Snapshot) NewIterator(slice *util.Range, ro *opt.ReadOptions) iterator.Iterator
    +

    +NewIterator returns an iterator for the snapshot of the underlying DB. +The returned iterator is not safe for concurrent use, but it is safe to use +multiple iterators concurrently, with each in a dedicated goroutine. +It is also safe to use an iterator concurrently with modifying its +underlying DB. The resultant key/value pairs are guaranteed to be +consistent. +

    +

    +Slice allows slicing the iterator to only contains keys in the given +range. A nil Range.Start is treated as a key before all keys in the +DB. And a nil Range.Limit is treated as a key after all keys in +the DB. +

    +

    +The iterator must be released after use, by calling Release method. +Releasing the snapshot doesn't mean releasing the iterator too, the +iterator would be still valid until released. +

    +

    +Also read Iterator documentation of the leveldb/iterator package. +

    + + + + + + +

    func (*Snapshot) Release

    +
    func (snap *Snapshot) Release()
    +

    +Release releases the snapshot. This will not release any returned +iterators, the iterators would still be valid until released or the +underlying DB is closed. +

    +

    +Other methods should not be called after the snapshot has been released. +

    + + + + + + +

    func (*Snapshot) String

    +
    func (snap *Snapshot) String() string
    + + + + + + + + +

    type Transaction

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

    +Transaction is the transaction handle. +

    + + + + + + + + + + + + + + +

    func (*Transaction) Commit

    +
    func (tr *Transaction) Commit() error
    +

    +Commit commits the transaction. If error is not nil, then the transaction is +not committed, it can then either be retried or discarded. +

    +

    +Other methods should not be called after transaction has been committed. +

    + + + + + + +

    func (*Transaction) Delete

    +
    func (tr *Transaction) Delete(key []byte, wo *opt.WriteOptions) error
    +

    +Delete deletes the value for the given key. +Please note that the transaction is not compacted until committed, so if you +writes 10 same keys, then those 10 same keys are in the transaction. +

    +

    +It is safe to modify the contents of the arguments after Delete returns. +

    + + + + + + +

    func (*Transaction) Discard

    +
    func (tr *Transaction) Discard()
    +

    +Discard discards the transaction. +

    +

    +Other methods should not be called after transaction has been discarded. +

    + + + + + + +

    func (*Transaction) Get

    +
    func (tr *Transaction) Get(key []byte, ro *opt.ReadOptions) ([]byte, error)
    +

    +Get gets the value for the given key. It returns ErrNotFound if the +DB does not contains the key. +

    +

    +The returned slice is its own copy, it is safe to modify the contents +of the returned slice. +It is safe to modify the contents of the argument after Get returns. +

    + + + + + + +

    func (*Transaction) Has

    +
    func (tr *Transaction) Has(key []byte, ro *opt.ReadOptions) (bool, error)
    +

    +Has returns true if the DB does contains the given key. +

    +

    +It is safe to modify the contents of the argument after Has returns. +

    + + + + + + +

    func (*Transaction) NewIterator

    +
    func (tr *Transaction) NewIterator(slice *util.Range, ro *opt.ReadOptions) iterator.Iterator
    +

    +NewIterator returns an iterator for the latest snapshot of the transaction. +The returned iterator is not safe for concurrent use, but it is safe to use +multiple iterators concurrently, with each in a dedicated goroutine. +It is also safe to use an iterator concurrently while writes to the +transaction. The resultant key/value pairs are guaranteed to be consistent. +

    +

    +Slice allows slicing the iterator to only contains keys in the given +range. A nil Range.Start is treated as a key before all keys in the +DB. And a nil Range.Limit is treated as a key after all keys in +the DB. +

    +

    +The iterator must be released after use, by calling Release method. +

    +

    +Also read Iterator documentation of the leveldb/iterator package. +

    + + + + + + +

    func (*Transaction) Put

    +
    func (tr *Transaction) Put(key, value []byte, wo *opt.WriteOptions) error
    +

    +Put sets the value for the given key. It overwrites any previous value +for that key; a DB is not a multi-map. +Please note that the transaction is not compacted until committed, so if you +writes 10 same keys, then those 10 same keys are in the transaction. +

    +

    +It is safe to modify the contents of the arguments after Put returns. +

    + + + + + + +

    func (*Transaction) Write

    +
    func (tr *Transaction) Write(b *Batch, wo *opt.WriteOptions) error
    +

    +Write apply the given batch to the transaction. The batch will be applied +sequentially. +Please note that the transaction is not compacted until committed, so if you +writes 10 same keys, then those 10 same keys are in the transaction. +

    +

    +It is safe to modify the contents of the arguments after Write returns. +

    + + + + + + + + + + + + + + + + +

    Subdirectories

    + + + + +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    NameSynopsis
    ..
    + cache + + Package cache provides interface and implementation of a cache algorithms. +
    + comparer + + Package comparer provides interface and implementation for ordering sets of data. +
    + errors + + Package errors provides common error types used throughout leveldb. +
    + filter + + Package filter provides interface and implementation of probabilistic data structure. +
    + iterator + + Package iterator provides interface and implementation to traverse over contents of a database. +
    + journal + + Package journal reads and writes sequences of journals. +
    + memdb + + Package memdb provides in-memory key/value database implementation. +
    + opt + + Package opt provides sets of options used by LevelDB. +
    + storage + + Package storage provides storage abstraction for LevelDB. +
    + table + + Package table allows read and write sorted key/value. +
    + testutil + + +
    + util + + Package util provides utilities used throughout leveldb. +
    +
    + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/github.com/syndtr/goleveldb/leveldb/iterator/index.html b/pkg/github.com/syndtr/goleveldb/leveldb/iterator/index.html new file mode 100644 index 0000000..6d2309f --- /dev/null +++ b/pkg/github.com/syndtr/goleveldb/leveldb/iterator/index.html @@ -0,0 +1,615 @@ + + + + + + + + iterator - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Package iterator

    + + + + + + + + + + + + + + +
    +
    +
    import "github.com/syndtr/goleveldb/leveldb/iterator"
    +
    +
    +
    Overview
    +
    Index
    + + +
    +
    + +
    + +
    +

    Overview ▾

    +

    +Package iterator provides interface and implementation to traverse over +contents of a database. +

    + +
    +
    + + + + + + + + +

    Variables

    + +
    var (
    +    ErrIterReleased = errors.New("leveldb/iterator: iterator released")
    +)
    + + + + + + + +

    type Array

    +
    type Array interface {
    +    BasicArray
    +
    +    // Index returns key/value pair with index of i.
    +    Index(i int) (key, value []byte)
    +}
    +

    +Array is the interface that wraps BasicArray and basic Index method. +

    + + + + + + + + + + + + + + + + +

    type ArrayIndexer

    +
    type ArrayIndexer interface {
    +    BasicArray
    +
    +    // Get returns a new data iterator with index of i.
    +    Get(i int) Iterator
    +}
    +

    +Array is the interface that wraps BasicArray and basic Get method. +

    + + + + + + + + + + + + + + + + +

    type BasicArray

    +
    type BasicArray interface {
    +    // Len returns length of the array.
    +    Len() int
    +
    +    // Search finds smallest index that point to a key that is greater
    +    // than or equal to the given key.
    +    Search(key []byte) int
    +}
    +

    +BasicArray is the interface that wraps basic Len and Search method. +

    + + + + + + + + + + + + + + + + +

    type CommonIterator

    +
    type CommonIterator interface {
    +    IteratorSeeker
    +
    +    // util.Releaser is the interface that wraps basic Release method.
    +    // When called Release will releases any resources associated with the
    +    // iterator.
    +    util.Releaser
    +
    +    // util.ReleaseSetter is the interface that wraps the basic SetReleaser
    +    // method.
    +    util.ReleaseSetter
    +
    +    // TODO: Remove this when ready.
    +    Valid() bool
    +
    +    // Error returns any accumulated error. Exhausting all the key/value pairs
    +    // is not considered to be an error.
    +    Error() error
    +}
    +

    +CommonIterator is the interface that wraps common iterator methods. +

    + + + + + + + + + + + + + + + + +

    type ErrorCallbackSetter

    +
    type ErrorCallbackSetter interface {
    +    // SetErrorCallback allows set an error callback of the corresponding
    +    // iterator. Use nil to clear the callback.
    +    SetErrorCallback(f func(err error))
    +}
    +

    +ErrorCallbackSetter is the interface that wraps basic SetErrorCallback +method. +

    +

    +ErrorCallbackSetter implemented by indexed and merged iterator. +

    + + + + + + + + + + + + + + + + +

    type Iterator

    +
    type Iterator interface {
    +    CommonIterator
    +
    +    // Key returns the key of the current key/value pair, or nil if done.
    +    // The caller should not modify the contents of the returned slice, and
    +    // its contents may change on the next call to any 'seeks method'.
    +    Key() []byte
    +
    +    // Value returns the key of the current key/value pair, or nil if done.
    +    // The caller should not modify the contents of the returned slice, and
    +    // its contents may change on the next call to any 'seeks method'.
    +    Value() []byte
    +}
    +

    +Iterator iterates over a DB's key/value pairs in key order. +

    +

    +When encounter an error any 'seeks method' will return false and will +yield no key/value pairs. The error can be queried by calling the Error +method. Calling Release is still necessary. +

    +

    +An iterator must be released after use, but it is not necessary to read +an iterator until exhaustion. +Also, an iterator is not necessarily safe for concurrent use, but it is +safe to use multiple iterators concurrently, with each in a dedicated +goroutine. +

    + + + + + + + + + + + + +

    func NewArrayIterator

    +
    func NewArrayIterator(array Array) Iterator
    +

    +NewArrayIterator returns an iterator from the given array. +

    + + + + + +

    func NewEmptyIterator

    +
    func NewEmptyIterator(err error) Iterator
    +

    +NewEmptyIterator creates an empty iterator. The err parameter can be +nil, but if not nil the given err will be returned by Error method. +

    + + + + + +

    func NewIndexedIterator

    +
    func NewIndexedIterator(index IteratorIndexer, strict bool) Iterator
    +

    +NewIndexedIterator returns an 'indexed iterator'. An index is iterator +that returns another iterator, a 'data iterator'. A 'data iterator' is the +iterator that contains actual key/value pairs. +

    +

    +If strict is true the any 'corruption errors' (i.e errors.IsCorrupted(err) == true) +won't be ignored and will halt 'indexed iterator', otherwise the iterator will +continue to the next 'data iterator'. Corruption on 'index iterator' will not be +ignored and will halt the iterator. +

    + + + + + +

    func NewMergedIterator

    +
    func NewMergedIterator(iters []Iterator, cmp comparer.Comparer, strict bool) Iterator
    +

    +NewMergedIterator returns an iterator that merges its input. Walking the +resultant iterator will return all key/value pairs of all input iterators +in strictly increasing key order, as defined by cmp. +The input's key ranges may overlap, but there are assumed to be no duplicate +keys: if iters[i] contains a key k then iters[j] will not contain that key k. +None of the iters may be nil. +

    +

    +If strict is true the any 'corruption errors' (i.e errors.IsCorrupted(err) == true) +won't be ignored and will halt 'merged iterator', otherwise the iterator will +continue to the next 'input iterator'. +

    + + + + + + + + + +

    type IteratorIndexer

    +
    type IteratorIndexer interface {
    +    CommonIterator
    +
    +    // Get returns a new data iterator for the current position, or nil if
    +    // done.
    +    Get() Iterator
    +}
    +

    +IteratorIndexer is the interface that wraps CommonIterator and basic Get +method. IteratorIndexer provides index for indexed iterator. +

    + + + + + + + + + + + + +

    func NewArrayIndexer

    +
    func NewArrayIndexer(array ArrayIndexer) IteratorIndexer
    +

    +NewArrayIndexer returns an index iterator from the given array. +

    + + + + + + + + + +

    type IteratorSeeker

    +
    type IteratorSeeker interface {
    +    // First moves the iterator to the first key/value pair. If the iterator
    +    // only contains one key/value pair then First and Last would moves
    +    // to the same key/value pair.
    +    // It returns whether such pair exist.
    +    First() bool
    +
    +    // Last moves the iterator to the last key/value pair. If the iterator
    +    // only contains one key/value pair then First and Last would moves
    +    // to the same key/value pair.
    +    // It returns whether such pair exist.
    +    Last() bool
    +
    +    // Seek moves the iterator to the first key/value pair whose key is greater
    +    // than or equal to the given key.
    +    // It returns whether such pair exist.
    +    //
    +    // It is safe to modify the contents of the argument after Seek returns.
    +    Seek(key []byte) bool
    +
    +    // Next moves the iterator to the next key/value pair.
    +    // It returns whether the iterator is exhausted.
    +    Next() bool
    +
    +    // Prev moves the iterator to the previous key/value pair.
    +    // It returns whether the iterator is exhausted.
    +    Prev() bool
    +}
    +

    +IteratorSeeker is the interface that wraps the 'seeks method'. +

    + + + + + + + + + + + + + + + + + + + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/github.com/syndtr/goleveldb/leveldb/journal/index.html b/pkg/github.com/syndtr/goleveldb/leveldb/journal/index.html new file mode 100644 index 0000000..16bb219 --- /dev/null +++ b/pkg/github.com/syndtr/goleveldb/leveldb/journal/index.html @@ -0,0 +1,525 @@ + + + + + + + + journal - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Package journal

    + + + + + + + + + + + + + + +
    +
    +
    import "github.com/syndtr/goleveldb/leveldb/journal"
    +
    +
    +
    Overview
    +
    Index
    + + +
    +
    + +
    + +
    +

    Overview ▾

    +

    +Package journal reads and writes sequences of journals. Each journal is a stream +of bytes that completes before the next journal starts. +

    +

    +When reading, call Next to obtain an io.Reader for the next journal. Next will +return io.EOF when there are no more journals. It is valid to call Next +without reading the current journal to exhaustion. +

    +

    +When writing, call Next to obtain an io.Writer for the next journal. Calling +Next finishes the current journal. Call Close to finish the final journal. +

    +

    +Optionally, call Flush to finish the current journal and flush the underlying +writer without starting a new journal. To start a new journal after flushing, +call Next. +

    +

    +Neither Readers or Writers are safe to use concurrently. +

    +

    +Example code: +

    +
    func read(r io.Reader) ([]string, error) {
    +	var ss []string
    +	journals := journal.NewReader(r, nil, true, true)
    +	for {
    +		j, err := journals.Next()
    +		if err == io.EOF {
    +			break
    +		}
    +		if err != nil {
    +			return nil, err
    +		}
    +		s, err := ioutil.ReadAll(j)
    +		if err != nil {
    +			return nil, err
    +		}
    +		ss = append(ss, string(s))
    +	}
    +	return ss, nil
    +}
    +
    +func write(w io.Writer, ss []string) error {
    +	journals := journal.NewWriter(w)
    +	for _, s := range ss {
    +		j, err := journals.Next()
    +		if err != nil {
    +			return err
    +		}
    +		if _, err := j.Write([]byte(s)), err != nil {
    +			return err
    +		}
    +	}
    +	return journals.Close()
    +}
    +
    +

    +The wire format is that the stream is divided into 32KiB blocks, and each +block contains a number of tightly packed chunks. Chunks cannot cross block +boundaries. The last block may be shorter than 32 KiB. Any unused bytes in a +block must be zero. +

    +

    +A journal maps to one or more chunks. Each chunk has a 7 byte header (a 4 +byte checksum, a 2 byte little-endian uint16 length, and a 1 byte chunk type) +followed by a payload. The checksum is over the chunk type and the payload. +

    +

    +There are four chunk types: whether the chunk is the full journal, or the +first, middle or last chunk of a multi-chunk journal. A multi-chunk journal +has one first chunk, zero or more middle chunks, and one last chunk. +

    +

    +The wire format allows for limited recovery in the face of data corruption: +on a format error (such as a checksum mismatch), the reader moves to the +next block and looks for the next full or first chunk. +

    + +
    +
    + + + + + + + + + + + + +

    type Dropper

    +
    type Dropper interface {
    +    Drop(err error)
    +}
    +

    +Dropper is the interface that wrap simple Drop method. The Drop +method will be called when the journal reader dropping a block or chunk. +

    + + + + + + + + + + + + + + + + +

    type ErrCorrupted

    +
    type ErrCorrupted struct {
    +    Size   int
    +    Reason string
    +}
    +

    +ErrCorrupted is the error type that generated by corrupted block or chunk. +

    + + + + + + + + + + + + + + +

    func (*ErrCorrupted) Error

    +
    func (e *ErrCorrupted) Error() string
    + + + + + + + + +

    type Reader

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

    +Reader reads journals from an underlying io.Reader. +

    + + + + + + + + + + + + +

    func NewReader

    +
    func NewReader(r io.Reader, dropper Dropper, strict, checksum bool) *Reader
    +

    +NewReader returns a new reader. The dropper may be nil, and if +strict is true then corrupted or invalid chunk will halt the journal +reader entirely. +

    + + + + + + + +

    func (*Reader) Next

    +
    func (r *Reader) Next() (io.Reader, error)
    +

    +Next returns a reader for the next journal. It returns io.EOF if there are no +more journals. The reader returned becomes stale after the next Next call, +and should no longer be used. If strict is false, the reader will returns +io.ErrUnexpectedEOF error when found corrupted journal. +

    + + + + + + +

    func (*Reader) Reset

    +
    func (r *Reader) Reset(reader io.Reader, dropper Dropper, strict, checksum bool) error
    +

    +Reset resets the journal reader, allows reuse of the journal reader. Reset returns +last accumulated error. +

    + + + + + + + + +

    type Writer

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

    +Writer writes journals to an underlying io.Writer. +

    + + + + + + + + + + + + +

    func NewWriter

    +
    func NewWriter(w io.Writer) *Writer
    +

    +NewWriter returns a new Writer. +

    + + + + + + + +

    func (*Writer) Close

    +
    func (w *Writer) Close() error
    +

    +Close finishes the current journal and closes the writer. +

    + + + + + + +

    func (*Writer) Flush

    +
    func (w *Writer) Flush() error
    +

    +Flush finishes the current journal, writes to the underlying writer, and +flushes it if that writer implements interface{ Flush() error }. +

    + + + + + + +

    func (*Writer) Next

    +
    func (w *Writer) Next() (io.Writer, error)
    +

    +Next returns a writer for the next journal. The writer returned becomes stale +after the next Close, Flush or Next call, and should no longer be used. +

    + + + + + + +

    func (*Writer) Reset

    +
    func (w *Writer) Reset(writer io.Writer) (err error)
    +

    +Reset resets the journal writer, allows reuse of the journal writer. Reset +will also closes the journal writer if not already. +

    + + + + + + + + + + + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/github.com/syndtr/goleveldb/leveldb/memdb/index.html b/pkg/github.com/syndtr/goleveldb/leveldb/memdb/index.html new file mode 100644 index 0000000..d893fdd --- /dev/null +++ b/pkg/github.com/syndtr/goleveldb/leveldb/memdb/index.html @@ -0,0 +1,464 @@ + + + + + + + + memdb - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Package memdb

    + + + + + + + + + + + + + + +
    +
    +
    import "github.com/syndtr/goleveldb/leveldb/memdb"
    +
    +
    +
    Overview
    +
    Index
    + + +
    +
    + +
    + +
    +

    Overview ▾

    +

    +Package memdb provides in-memory key/value database implementation. +

    + +
    +
    + + + + + + + + +

    Variables

    + +
    var (
    +    ErrNotFound     = errors.ErrNotFound
    +    ErrIterReleased = errors.New("leveldb/memdb: iterator released")
    +)
    +

    +Common errors. +

    + + + + + + + +

    type DB

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

    +DB is an in-memory key/value database. +

    + + + + + + + + + + + + +

    func New

    +
    func New(cmp comparer.BasicComparer, capacity int) *DB
    +

    +New creates a new initialized in-memory key/value DB. The capacity +is the initial key/value buffer capacity. The capacity is advisory, +not enforced. +

    +

    +This DB is append-only, deleting an entry would remove entry node but not +reclaim KV buffer. +

    +

    +The returned DB instance is safe for concurrent use. +

    + + + + + + + +

    func (*DB) Capacity

    +
    func (p *DB) Capacity() int
    +

    +Capacity returns keys/values buffer capacity. +

    + + + + + + +

    func (*DB) Contains

    +
    func (p *DB) Contains(key []byte) bool
    +

    +Contains returns true if the given key are in the DB. +

    +

    +It is safe to modify the contents of the arguments after Contains returns. +

    + + + + + + +

    func (*DB) Delete

    +
    func (p *DB) Delete(key []byte) error
    +

    +Delete deletes the value for the given key. It returns ErrNotFound if +the DB does not contain the key. +

    +

    +It is safe to modify the contents of the arguments after Delete returns. +

    + + + + + + +

    func (*DB) Find

    +
    func (p *DB) Find(key []byte) (rkey, value []byte, err error)
    +

    +Find finds key/value pair whose key is greater than or equal to the +given key. It returns ErrNotFound if the table doesn't contain +such pair. +

    +

    +The caller should not modify the contents of the returned slice, but +it is safe to modify the contents of the argument after Find returns. +

    + + + + + + +

    func (*DB) Free

    +
    func (p *DB) Free() int
    +

    +Free returns keys/values free buffer before need to grow. +

    + + + + + + +

    func (*DB) Get

    +
    func (p *DB) Get(key []byte) (value []byte, err error)
    +

    +Get gets the value for the given key. It returns error.ErrNotFound if the +DB does not contain the key. +

    +

    +The caller should not modify the contents of the returned slice, but +it is safe to modify the contents of the argument after Get returns. +

    + + + + + + +

    func (*DB) Len

    +
    func (p *DB) Len() int
    +

    +Len returns the number of entries in the DB. +

    + + + + + + +

    func (*DB) NewIterator

    +
    func (p *DB) NewIterator(slice *util.Range) iterator.Iterator
    +

    +NewIterator returns an iterator of the DB. +The returned iterator is not safe for concurrent use, but it is safe to use +multiple iterators concurrently, with each in a dedicated goroutine. +It is also safe to use an iterator concurrently with modifying its +underlying DB. However, the resultant key/value pairs are not guaranteed +to be a consistent snapshot of the DB at a particular point in time. +

    +

    +Slice allows slicing the iterator to only contains keys in the given +range. A nil Range.Start is treated as a key before all keys in the +DB. And a nil Range.Limit is treated as a key after all keys in +the DB. +

    +

    +The iterator must be released after use, by calling Release method. +

    +

    +Also read Iterator documentation of the leveldb/iterator package. +

    + + + + + + +

    func (*DB) Put

    +
    func (p *DB) Put(key []byte, value []byte) error
    +

    +Put sets the value for the given key. It overwrites any previous value +for that key; a DB is not a multi-map. +

    +

    +It is safe to modify the contents of the arguments after Put returns. +

    + + + + + + +

    func (*DB) Reset

    +
    func (p *DB) Reset()
    +

    +Reset resets the DB to initial empty state. Allows reuse the buffer. +

    + + + + + + +

    func (*DB) Size

    +
    func (p *DB) Size() int
    +

    +Size returns sum of keys and values length. Note that deleted +key/value will not be accounted for, but it will still consume +the buffer, since the buffer is append only. +

    + + + + + + + + + + + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/github.com/syndtr/goleveldb/leveldb/opt/index.html b/pkg/github.com/syndtr/goleveldb/leveldb/opt/index.html new file mode 100644 index 0000000..50edb5f --- /dev/null +++ b/pkg/github.com/syndtr/goleveldb/leveldb/opt/index.html @@ -0,0 +1,1147 @@ + + + + + + + + opt - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Package opt

    + + + + + + + + + + + + + + +
    +
    +
    import "github.com/syndtr/goleveldb/leveldb/opt"
    +
    +
    +
    Overview
    +
    Index
    + + +
    +
    + +
    + +
    +

    Overview ▾

    +

    +Package opt provides sets of options used by LevelDB. +

    + +
    +
    + + +
    + +
    +

    Index ▾

    + + +
    +
    + +
    Constants
    + + +
    Variables
    + + + +
    func GetStrict(o *Options, ro *ReadOptions, strict Strict) bool
    + + + +
    type Cacher
    + + + + +
    type CacherFunc
    + + + +
        func (f *CacherFunc) New(capacity int) cache.Cacher
    + + + +
    type Compression
    + + + +
        func (c Compression) String() string
    + + + +
    type Options
    + + + +
        func (o *Options) GetAltFilters() []filter.Filter
    + + +
        func (o *Options) GetBlockCacheCapacity() int
    + + +
        func (o *Options) GetBlockCacher() Cacher
    + + +
        func (o *Options) GetBlockRestartInterval() int
    + + +
        func (o *Options) GetBlockSize() int
    + + +
        func (o *Options) GetCompactionExpandLimit(level int) int
    + + +
        func (o *Options) GetCompactionGPOverlaps(level int) int
    + + +
        func (o *Options) GetCompactionL0Trigger() int
    + + +
        func (o *Options) GetCompactionSourceLimit(level int) int
    + + +
        func (o *Options) GetCompactionTableSize(level int) int
    + + +
        func (o *Options) GetCompactionTotalSize(level int) int64
    + + +
        func (o *Options) GetComparer() comparer.Comparer
    + + +
        func (o *Options) GetCompression() Compression
    + + +
        func (o *Options) GetDisableBlockCache() bool
    + + +
        func (o *Options) GetDisableBufferPool() bool
    + + +
        func (o *Options) GetDisableCompactionBackoff() bool
    + + +
        func (o *Options) GetDisableLargeBatchTransaction() bool
    + + +
        func (o *Options) GetErrorIfExist() bool
    + + +
        func (o *Options) GetErrorIfMissing() bool
    + + +
        func (o *Options) GetFilter() filter.Filter
    + + +
        func (o *Options) GetIteratorSamplingRate() int
    + + +
        func (o *Options) GetNoSync() bool
    + + +
        func (o *Options) GetNoWriteMerge() bool
    + + +
        func (o *Options) GetOpenFilesCacheCapacity() int
    + + +
        func (o *Options) GetOpenFilesCacher() Cacher
    + + +
        func (o *Options) GetReadOnly() bool
    + + +
        func (o *Options) GetStrict(strict Strict) bool
    + + +
        func (o *Options) GetWriteBuffer() int
    + + +
        func (o *Options) GetWriteL0PauseTrigger() int
    + + +
        func (o *Options) GetWriteL0SlowdownTrigger() int
    + + + +
    type ReadOptions
    + + + +
        func (ro *ReadOptions) GetDontFillCache() bool
    + + +
        func (ro *ReadOptions) GetStrict(strict Strict) bool
    + + + +
    type Strict
    + + + + +
    type WriteOptions
    + + + +
        func (wo *WriteOptions) GetNoWriteMerge() bool
    + + +
        func (wo *WriteOptions) GetSync() bool
    + + + +
    +
    + + + + +

    Package files

    +

    + + + options.go + + +

    + +
    +
    + + + + +

    Constants

    + +
    const (
    +    KiB = 1024
    +    MiB = KiB * 1024
    +    GiB = MiB * 1024
    +)
    + + + + +

    Variables

    + +
    var (
    +    DefaultBlockCacher                   = LRUCacher
    +    DefaultBlockCacheCapacity            = 8 * MiB
    +    DefaultBlockRestartInterval          = 16
    +    DefaultBlockSize                     = 4 * KiB
    +    DefaultCompactionExpandLimitFactor   = 25
    +    DefaultCompactionGPOverlapsFactor    = 10
    +    DefaultCompactionL0Trigger           = 4
    +    DefaultCompactionSourceLimitFactor   = 1
    +    DefaultCompactionTableSize           = 2 * MiB
    +    DefaultCompactionTableSizeMultiplier = 1.0
    +    DefaultCompactionTotalSize           = 10 * MiB
    +    DefaultCompactionTotalSizeMultiplier = 10.0
    +    DefaultCompressionType               = SnappyCompression
    +    DefaultIteratorSamplingRate          = 1 * MiB
    +    DefaultOpenFilesCacher               = LRUCacher
    +    DefaultOpenFilesCacheCapacity        = 500
    +    DefaultWriteBuffer                   = 4 * MiB
    +    DefaultWriteL0PauseTrigger           = 12
    +    DefaultWriteL0SlowdownTrigger        = 8
    +)
    + + +
    var (
    +    // LRUCacher is the LRU-cache algorithm.
    +    LRUCacher = &CacherFunc{cache.NewLRU}
    +
    +    // NoCacher is the value to disable caching algorithm.
    +    NoCacher = &CacherFunc{}
    +)
    + + + + + + +

    func GetStrict

    +
    func GetStrict(o *Options, ro *ReadOptions, strict Strict) bool
    + + + + + + + + +

    type Cacher

    +
    type Cacher interface {
    +    New(capacity int) cache.Cacher
    +}
    +

    +Cacher is a caching algorithm. +

    + + + + + + + + + + + + + + + + +

    type CacherFunc

    +
    type CacherFunc struct {
    +    NewFunc func(capacity int) cache.Cacher
    +}
    + + + + + + + + + + + + + + +

    func (*CacherFunc) New

    +
    func (f *CacherFunc) New(capacity int) cache.Cacher
    + + + + + + + + +

    type Compression

    +
    type Compression uint
    +

    +Compression is the 'sorted table' block compression algorithm to use. +

    + + + +
    const (
    +    DefaultCompression Compression = iota
    +    NoCompression
    +    SnappyCompression
    +)
    + + + + + + + + + + + + + +

    func (Compression) String

    +
    func (c Compression) String() string
    + + + + + + + + +

    type Options

    +
    type Options struct {
    +    // AltFilters defines one or more 'alternative filters'.
    +    // 'alternative filters' will be used during reads if a filter block
    +    // does not match with the 'effective filter'.
    +    //
    +    // The default value is nil
    +    AltFilters []filter.Filter
    +
    +    // BlockCacher provides cache algorithm for LevelDB 'sorted table' block caching.
    +    // Specify NoCacher to disable caching algorithm.
    +    //
    +    // The default value is LRUCacher.
    +    BlockCacher Cacher
    +
    +    // BlockCacheCapacity defines the capacity of the 'sorted table' block caching.
    +    // Use -1 for zero, this has same effect as specifying NoCacher to BlockCacher.
    +    //
    +    // The default value is 8MiB.
    +    BlockCacheCapacity int
    +
    +    // BlockRestartInterval is the number of keys between restart points for
    +    // delta encoding of keys.
    +    //
    +    // The default value is 16.
    +    BlockRestartInterval int
    +
    +    // BlockSize is the minimum uncompressed size in bytes of each 'sorted table'
    +    // block.
    +    //
    +    // The default value is 4KiB.
    +    BlockSize int
    +
    +    // CompactionExpandLimitFactor limits compaction size after expanded.
    +    // This will be multiplied by table size limit at compaction target level.
    +    //
    +    // The default value is 25.
    +    CompactionExpandLimitFactor int
    +
    +    // CompactionGPOverlapsFactor limits overlaps in grandparent (Level + 2) that a
    +    // single 'sorted table' generates.
    +    // This will be multiplied by table size limit at grandparent level.
    +    //
    +    // The default value is 10.
    +    CompactionGPOverlapsFactor int
    +
    +    // CompactionL0Trigger defines number of 'sorted table' at level-0 that will
    +    // trigger compaction.
    +    //
    +    // The default value is 4.
    +    CompactionL0Trigger int
    +
    +    // CompactionSourceLimitFactor limits compaction source size. This doesn't apply to
    +    // level-0.
    +    // This will be multiplied by table size limit at compaction target level.
    +    //
    +    // The default value is 1.
    +    CompactionSourceLimitFactor int
    +
    +    // CompactionTableSize limits size of 'sorted table' that compaction generates.
    +    // The limits for each level will be calculated as:
    +    //   CompactionTableSize * (CompactionTableSizeMultiplier ^ Level)
    +    // The multiplier for each level can also fine-tuned using CompactionTableSizeMultiplierPerLevel.
    +    //
    +    // The default value is 2MiB.
    +    CompactionTableSize int
    +
    +    // CompactionTableSizeMultiplier defines multiplier for CompactionTableSize.
    +    //
    +    // The default value is 1.
    +    CompactionTableSizeMultiplier float64
    +
    +    // CompactionTableSizeMultiplierPerLevel defines per-level multiplier for
    +    // CompactionTableSize.
    +    // Use zero to skip a level.
    +    //
    +    // The default value is nil.
    +    CompactionTableSizeMultiplierPerLevel []float64
    +
    +    // CompactionTotalSize limits total size of 'sorted table' for each level.
    +    // The limits for each level will be calculated as:
    +    //   CompactionTotalSize * (CompactionTotalSizeMultiplier ^ Level)
    +    // The multiplier for each level can also fine-tuned using
    +    // CompactionTotalSizeMultiplierPerLevel.
    +    //
    +    // The default value is 10MiB.
    +    CompactionTotalSize int
    +
    +    // CompactionTotalSizeMultiplier defines multiplier for CompactionTotalSize.
    +    //
    +    // The default value is 10.
    +    CompactionTotalSizeMultiplier float64
    +
    +    // CompactionTotalSizeMultiplierPerLevel defines per-level multiplier for
    +    // CompactionTotalSize.
    +    // Use zero to skip a level.
    +    //
    +    // The default value is nil.
    +    CompactionTotalSizeMultiplierPerLevel []float64
    +
    +    // Comparer defines a total ordering over the space of []byte keys: a 'less
    +    // than' relationship. The same comparison algorithm must be used for reads
    +    // and writes over the lifetime of the DB.
    +    //
    +    // The default value uses the same ordering as bytes.Compare.
    +    Comparer comparer.Comparer
    +
    +    // Compression defines the 'sorted table' block compression to use.
    +    //
    +    // The default value (DefaultCompression) uses snappy compression.
    +    Compression Compression
    +
    +    // DisableBufferPool allows disable use of util.BufferPool functionality.
    +    //
    +    // The default value is false.
    +    DisableBufferPool bool
    +
    +    // DisableBlockCache allows disable use of cache.Cache functionality on
    +    // 'sorted table' block.
    +    //
    +    // The default value is false.
    +    DisableBlockCache bool
    +
    +    // DisableCompactionBackoff allows disable compaction retry backoff.
    +    //
    +    // The default value is false.
    +    DisableCompactionBackoff bool
    +
    +    // DisableLargeBatchTransaction allows disabling switch-to-transaction mode
    +    // on large batch write. If enable batch writes large than WriteBuffer will
    +    // use transaction.
    +    //
    +    // The default is false.
    +    DisableLargeBatchTransaction bool
    +
    +    // ErrorIfExist defines whether an error should returned if the DB already
    +    // exist.
    +    //
    +    // The default value is false.
    +    ErrorIfExist bool
    +
    +    // ErrorIfMissing defines whether an error should returned if the DB is
    +    // missing. If false then the database will be created if missing, otherwise
    +    // an error will be returned.
    +    //
    +    // The default value is false.
    +    ErrorIfMissing bool
    +
    +    // Filter defines an 'effective filter' to use. An 'effective filter'
    +    // if defined will be used to generate per-table filter block.
    +    // The filter name will be stored on disk.
    +    // During reads LevelDB will try to find matching filter from
    +    // 'effective filter' and 'alternative filters'.
    +    //
    +    // Filter can be changed after a DB has been created. It is recommended
    +    // to put old filter to the 'alternative filters' to mitigate lack of
    +    // filter during transition period.
    +    //
    +    // A filter is used to reduce disk reads when looking for a specific key.
    +    //
    +    // The default value is nil.
    +    Filter filter.Filter
    +
    +    // IteratorSamplingRate defines approximate gap (in bytes) between read
    +    // sampling of an iterator. The samples will be used to determine when
    +    // compaction should be triggered.
    +    //
    +    // The default is 1MiB.
    +    IteratorSamplingRate int
    +
    +    // NoSync allows completely disable fsync.
    +    //
    +    // The default is false.
    +    NoSync bool
    +
    +    // NoWriteMerge allows disabling write merge.
    +    //
    +    // The default is false.
    +    NoWriteMerge bool
    +
    +    // OpenFilesCacher provides cache algorithm for open files caching.
    +    // Specify NoCacher to disable caching algorithm.
    +    //
    +    // The default value is LRUCacher.
    +    OpenFilesCacher Cacher
    +
    +    // OpenFilesCacheCapacity defines the capacity of the open files caching.
    +    // Use -1 for zero, this has same effect as specifying NoCacher to OpenFilesCacher.
    +    //
    +    // The default value is 500.
    +    OpenFilesCacheCapacity int
    +
    +    // If true then opens DB in read-only mode.
    +    //
    +    // The default value is false.
    +    ReadOnly bool
    +
    +    // Strict defines the DB strict level.
    +    Strict Strict
    +
    +    // WriteBuffer defines maximum size of a 'memdb' before flushed to
    +    // 'sorted table'. 'memdb' is an in-memory DB backed by an on-disk
    +    // unsorted journal.
    +    //
    +    // LevelDB may held up to two 'memdb' at the same time.
    +    //
    +    // The default value is 4MiB.
    +    WriteBuffer int
    +
    +    // WriteL0StopTrigger defines number of 'sorted table' at level-0 that will
    +    // pause write.
    +    //
    +    // The default value is 12.
    +    WriteL0PauseTrigger int
    +
    +    // WriteL0SlowdownTrigger defines number of 'sorted table' at level-0 that
    +    // will trigger write slowdown.
    +    //
    +    // The default value is 8.
    +    WriteL0SlowdownTrigger int
    +}
    +

    +Options holds the optional parameters for the DB at large. +

    + + + + + + + + + + + + + + +

    func (*Options) GetAltFilters

    +
    func (o *Options) GetAltFilters() []filter.Filter
    + + + + + + +

    func (*Options) GetBlockCacheCapacity

    +
    func (o *Options) GetBlockCacheCapacity() int
    + + + + + + +

    func (*Options) GetBlockCacher

    +
    func (o *Options) GetBlockCacher() Cacher
    + + + + + + +

    func (*Options) GetBlockRestartInterval

    +
    func (o *Options) GetBlockRestartInterval() int
    + + + + + + +

    func (*Options) GetBlockSize

    +
    func (o *Options) GetBlockSize() int
    + + + + + + +

    func (*Options) GetCompactionExpandLimit

    +
    func (o *Options) GetCompactionExpandLimit(level int) int
    + + + + + + +

    func (*Options) GetCompactionGPOverlaps

    +
    func (o *Options) GetCompactionGPOverlaps(level int) int
    + + + + + + +

    func (*Options) GetCompactionL0Trigger

    +
    func (o *Options) GetCompactionL0Trigger() int
    + + + + + + +

    func (*Options) GetCompactionSourceLimit

    +
    func (o *Options) GetCompactionSourceLimit(level int) int
    + + + + + + +

    func (*Options) GetCompactionTableSize

    +
    func (o *Options) GetCompactionTableSize(level int) int
    + + + + + + +

    func (*Options) GetCompactionTotalSize

    +
    func (o *Options) GetCompactionTotalSize(level int) int64
    + + + + + + +

    func (*Options) GetComparer

    +
    func (o *Options) GetComparer() comparer.Comparer
    + + + + + + +

    func (*Options) GetCompression

    +
    func (o *Options) GetCompression() Compression
    + + + + + + +

    func (*Options) GetDisableBlockCache

    +
    func (o *Options) GetDisableBlockCache() bool
    + + + + + + +

    func (*Options) GetDisableBufferPool

    +
    func (o *Options) GetDisableBufferPool() bool
    + + + + + + +

    func (*Options) GetDisableCompactionBackoff

    +
    func (o *Options) GetDisableCompactionBackoff() bool
    + + + + + + +

    func (*Options) GetDisableLargeBatchTransaction

    +
    func (o *Options) GetDisableLargeBatchTransaction() bool
    + + + + + + +

    func (*Options) GetErrorIfExist

    +
    func (o *Options) GetErrorIfExist() bool
    + + + + + + +

    func (*Options) GetErrorIfMissing

    +
    func (o *Options) GetErrorIfMissing() bool
    + + + + + + +

    func (*Options) GetFilter

    +
    func (o *Options) GetFilter() filter.Filter
    + + + + + + +

    func (*Options) GetIteratorSamplingRate

    +
    func (o *Options) GetIteratorSamplingRate() int
    + + + + + + +

    func (*Options) GetNoSync

    +
    func (o *Options) GetNoSync() bool
    + + + + + + +

    func (*Options) GetNoWriteMerge

    +
    func (o *Options) GetNoWriteMerge() bool
    + + + + + + +

    func (*Options) GetOpenFilesCacheCapacity

    +
    func (o *Options) GetOpenFilesCacheCapacity() int
    + + + + + + +

    func (*Options) GetOpenFilesCacher

    +
    func (o *Options) GetOpenFilesCacher() Cacher
    + + + + + + +

    func (*Options) GetReadOnly

    +
    func (o *Options) GetReadOnly() bool
    + + + + + + +

    func (*Options) GetStrict

    +
    func (o *Options) GetStrict(strict Strict) bool
    + + + + + + +

    func (*Options) GetWriteBuffer

    +
    func (o *Options) GetWriteBuffer() int
    + + + + + + +

    func (*Options) GetWriteL0PauseTrigger

    +
    func (o *Options) GetWriteL0PauseTrigger() int
    + + + + + + +

    func (*Options) GetWriteL0SlowdownTrigger

    +
    func (o *Options) GetWriteL0SlowdownTrigger() int
    + + + + + + + + +

    type ReadOptions

    +
    type ReadOptions struct {
    +    // DontFillCache defines whether block reads for this 'read operation'
    +    // should be cached. If false then the block will be cached. This does
    +    // not affects already cached block.
    +    //
    +    // The default value is false.
    +    DontFillCache bool
    +
    +    // Strict will be OR'ed with global DB 'strict level' unless StrictOverride
    +    // is present. Currently only StrictReader that has effect here.
    +    Strict Strict
    +}
    +

    +ReadOptions holds the optional parameters for 'read operation'. The +'read operation' includes Get, Find and NewIterator. +

    + + + + + + + + + + + + + + +

    func (*ReadOptions) GetDontFillCache

    +
    func (ro *ReadOptions) GetDontFillCache() bool
    + + + + + + +

    func (*ReadOptions) GetStrict

    +
    func (ro *ReadOptions) GetStrict(strict Strict) bool
    + + + + + + + + +

    type Strict

    +
    type Strict uint
    +

    +Strict is the DB 'strict level'. +

    + + + +
    const (
    +    // If present then a corrupted or invalid chunk or block in manifest
    +    // journal will cause an error instead of being dropped.
    +    // This will prevent database with corrupted manifest to be opened.
    +    StrictManifest Strict = 1 << iota
    +
    +    // If present then journal chunk checksum will be verified.
    +    StrictJournalChecksum
    +
    +    // If present then a corrupted or invalid chunk or block in journal
    +    // will cause an error instead of being dropped.
    +    // This will prevent database with corrupted journal to be opened.
    +    StrictJournal
    +
    +    // If present then 'sorted table' block checksum will be verified.
    +    // This has effect on both 'read operation' and compaction.
    +    StrictBlockChecksum
    +
    +    // If present then a corrupted 'sorted table' will fails compaction.
    +    // The database will enter read-only mode.
    +    StrictCompaction
    +
    +    // If present then a corrupted 'sorted table' will halts 'read operation'.
    +    StrictReader
    +
    +    // If present then leveldb.Recover will drop corrupted 'sorted table'.
    +    StrictRecovery
    +
    +    // This only applicable for ReadOptions, if present then this ReadOptions
    +    // 'strict level' will override global ones.
    +    StrictOverride
    +
    +    // StrictAll enables all strict flags.
    +    StrictAll = StrictManifest | StrictJournalChecksum | StrictJournal | StrictBlockChecksum | StrictCompaction | StrictReader | StrictRecovery
    +
    +    // DefaultStrict is the default strict flags. Specify any strict flags
    +    // will override default strict flags as whole (i.e. not OR'ed).
    +    DefaultStrict = StrictJournalChecksum | StrictBlockChecksum | StrictCompaction | StrictReader
    +
    +    // NoStrict disables all strict flags. Override default strict flags.
    +    NoStrict = ^StrictAll
    +)
    + + + + + + + + + + + + + + + +

    type WriteOptions

    +
    type WriteOptions struct {
    +    // NoWriteMerge allows disabling write merge.
    +    //
    +    // The default is false.
    +    NoWriteMerge bool
    +
    +    // Sync is whether to sync underlying writes from the OS buffer cache
    +    // through to actual disk, if applicable. Setting Sync can result in
    +    // slower writes.
    +    //
    +    // If false, and the machine crashes, then some recent writes may be lost.
    +    // Note that if it is just the process that crashes (and the machine does
    +    // not) then no writes will be lost.
    +    //
    +    // In other words, Sync being false has the same semantics as a write
    +    // system call. Sync being true means write followed by fsync.
    +    //
    +    // The default value is false.
    +    Sync bool
    +}
    +

    +WriteOptions holds the optional parameters for 'write operation'. The +'write operation' includes Write, Put and Delete. +

    + + + + + + + + + + + + + + +

    func (*WriteOptions) GetNoWriteMerge

    +
    func (wo *WriteOptions) GetNoWriteMerge() bool
    + + + + + + +

    func (*WriteOptions) GetSync

    +
    func (wo *WriteOptions) GetSync() bool
    + + + + + + + + + + + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/github.com/syndtr/goleveldb/leveldb/storage/index.html b/pkg/github.com/syndtr/goleveldb/leveldb/storage/index.html new file mode 100644 index 0000000..e8e28c1 --- /dev/null +++ b/pkg/github.com/syndtr/goleveldb/leveldb/storage/index.html @@ -0,0 +1,610 @@ + + + + + + + + storage - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Package storage

    + + + + + + + + + + + + + + +
    +
    +
    import "github.com/syndtr/goleveldb/leveldb/storage"
    +
    +
    +
    Overview
    +
    Index
    + + +
    +
    + +
    + +
    +

    Overview ▾

    +

    +Package storage provides storage abstraction for LevelDB. +

    + +
    +
    + + +
    + + +
    + + + + + +

    Variables

    + +
    var (
    +    ErrInvalidFile = errors.New("leveldb/storage: invalid file for argument")
    +    ErrLocked      = errors.New("leveldb/storage: already locked")
    +    ErrClosed      = errors.New("leveldb/storage: closed")
    +)
    +

    +Common error. +

    + + + + + + +

    func FileDescOk

    +
    func FileDescOk(fd FileDesc) bool
    +

    +FileDescOk returns true if fd is a valid 'file descriptor'. +

    + + + + + + + + +

    type ErrCorrupted

    +
    type ErrCorrupted struct {
    +    Fd  FileDesc
    +    Err error
    +}
    +

    +ErrCorrupted is the type that wraps errors that indicate corruption of +a file. Package storage has its own type instead of using +errors.ErrCorrupted to prevent circular import. +

    + + + + + + + + + + + + + + +

    func (*ErrCorrupted) Error

    +
    func (e *ErrCorrupted) Error() string
    + + + + + + + + +

    type FileDesc

    +
    type FileDesc struct {
    +    Type FileType
    +    Num  int64
    +}
    +

    +FileDesc is a 'file descriptor'. +

    + + + + + + + + + + + + + + +

    func (FileDesc) String

    +
    func (fd FileDesc) String() string
    + + + + + + +

    func (FileDesc) Zero

    +
    func (fd FileDesc) Zero() bool
    +

    +Zero returns true if fd == (FileDesc{}). +

    + + + + + + + + +

    type FileType

    +
    type FileType int
    +

    +FileType represent a file type. +

    + + + +
    const (
    +    TypeManifest FileType = 1 << iota
    +    TypeJournal
    +    TypeTable
    +    TypeTemp
    +
    +    TypeAll = TypeManifest | TypeJournal | TypeTable | TypeTemp
    +)
    +

    +File types. +

    + + + + + + + + + + + + + +

    func (FileType) String

    +
    func (t FileType) String() string
    + + + + + + + + +

    type Locker

    +
    type Locker interface {
    +    Unlock()
    +}
    +

    +Locker is the interface that wraps Unlock method. +

    + + + + + + + + + + + + + + + + +

    type Reader

    +
    type Reader interface {
    +    io.ReadSeeker
    +    io.ReaderAt
    +    io.Closer
    +}
    +

    +Reader is the interface that groups the basic Read, Seek, ReadAt and Close +methods. +

    + + + + + + + + + + + + + + + + +

    type Storage

    +
    type Storage interface {
    +    // Lock locks the storage. Any subsequent attempt to call Lock will fail
    +    // until the last lock released.
    +    // Caller should call Unlock method after use.
    +    Lock() (Locker, error)
    +
    +    // Log logs a string. This is used for logging.
    +    // An implementation may write to a file, stdout or simply do nothing.
    +    Log(str string)
    +
    +    // SetMeta store 'file descriptor' that can later be acquired using GetMeta
    +    // method. The 'file descriptor' should point to a valid file.
    +    // SetMeta should be implemented in such way that changes should happen
    +    // atomically.
    +    SetMeta(fd FileDesc) error
    +
    +    // GetMeta returns 'file descriptor' stored in meta. The 'file descriptor'
    +    // can be updated using SetMeta method.
    +    // Returns os.ErrNotExist if meta doesn't store any 'file descriptor', or
    +    // 'file descriptor' point to nonexistent file.
    +    GetMeta() (FileDesc, error)
    +
    +    // List returns file descriptors that match the given file types.
    +    // The file types may be OR'ed together.
    +    List(ft FileType) ([]FileDesc, error)
    +
    +    // Open opens file with the given 'file descriptor' read-only.
    +    // Returns os.ErrNotExist error if the file does not exist.
    +    // Returns ErrClosed if the underlying storage is closed.
    +    Open(fd FileDesc) (Reader, error)
    +
    +    // Create creates file with the given 'file descriptor', truncate if already
    +    // exist and opens write-only.
    +    // Returns ErrClosed if the underlying storage is closed.
    +    Create(fd FileDesc) (Writer, error)
    +
    +    // Remove removes file with the given 'file descriptor'.
    +    // Returns ErrClosed if the underlying storage is closed.
    +    Remove(fd FileDesc) error
    +
    +    // Rename renames file from oldfd to newfd.
    +    // Returns ErrClosed if the underlying storage is closed.
    +    Rename(oldfd, newfd FileDesc) error
    +
    +    // Close closes the storage.
    +    // It is valid to call Close multiple times. Other methods should not be
    +    // called after the storage has been closed.
    +    Close() error
    +}
    +

    +Storage is the storage. A storage instance must be safe for concurrent use. +

    + + + + + + + + + + + + +

    func NewMemStorage

    +
    func NewMemStorage() Storage
    +

    +NewMemStorage returns a new memory-backed storage implementation. +

    + + + + + +

    func OpenFile

    +
    func OpenFile(path string, readOnly bool) (Storage, error)
    +

    +OpenFile returns a new filesytem-backed storage implementation with the given +path. This also acquire a file lock, so any subsequent attempt to open the +same path will fail. +

    +

    +The storage must be closed after use, by calling Close method. +

    + + + + + + + + + +

    type Syncer

    +
    type Syncer interface {
    +    // Sync commits the current contents of the file to stable storage.
    +    Sync() error
    +}
    +

    +Syncer is the interface that wraps basic Sync method. +

    + + + + + + + + + + + + + + + + +

    type Writer

    +
    type Writer interface {
    +    io.WriteCloser
    +    Syncer
    +}
    +

    +Writer is the interface that groups the basic Write, Sync and Close +methods. +

    + + + + + + + + + + + + + + + + + + + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/github.com/syndtr/goleveldb/leveldb/table/index.html b/pkg/github.com/syndtr/goleveldb/leveldb/table/index.html new file mode 100644 index 0000000..d6607dd --- /dev/null +++ b/pkg/github.com/syndtr/goleveldb/leveldb/table/index.html @@ -0,0 +1,558 @@ + + + + + + + + table - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Package table

    + + + + + + + + + + + + + + +
    +
    +
    import "github.com/syndtr/goleveldb/leveldb/table"
    +
    +
    +
    Overview
    +
    Index
    + + +
    +
    + +
    + +
    +

    Overview ▾

    +

    +Package table allows read and write sorted key/value. +

    + +
    +
    + + + + + + + + +

    Variables

    + +
    var (
    +    ErrNotFound       = errors.ErrNotFound
    +    ErrReaderReleased = errors.New("leveldb/table: reader released")
    +    ErrIterReleased   = errors.New("leveldb/table: iterator released")
    +)
    +

    +Reader errors. +

    + + + + + + + +

    type ErrCorrupted

    +
    type ErrCorrupted struct {
    +    Pos    int64
    +    Size   int64
    +    Kind   string
    +    Reason string
    +}
    +

    +ErrCorrupted describes error due to corruption. This error will be wrapped +with errors.ErrCorrupted. +

    + + + + + + + + + + + + + + +

    func (*ErrCorrupted) Error

    +
    func (e *ErrCorrupted) Error() string
    + + + + + + + + +

    type Reader

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

    +Reader is a table reader. +

    + + + + + + + + + + + + +

    func NewReader

    +
    func NewReader(f io.ReaderAt, size int64, fd storage.FileDesc, cache *cache.NamespaceGetter, bpool *util.BufferPool, o *opt.Options) (*Reader, error)
    +

    +NewReader creates a new initialized table reader for the file. +The fi, cache and bpool is optional and can be nil. +

    +

    +The returned table reader instance is safe for concurrent use. +

    + + + + + + + +

    func (*Reader) Find

    +
    func (r *Reader) Find(key []byte, filtered bool, ro *opt.ReadOptions) (rkey, value []byte, err error)
    +

    +Find finds key/value pair whose key is greater than or equal to the +given key. It returns ErrNotFound if the table doesn't contain +such pair. +If filtered is true then the nearest 'block' will be checked against +'filter data' (if present) and will immediately return ErrNotFound if +'filter data' indicates that such pair doesn't exist. +

    +

    +The caller may modify the contents of the returned slice as it is its +own copy. +It is safe to modify the contents of the argument after Find returns. +

    + + + + + + +

    func (*Reader) FindKey

    +
    func (r *Reader) FindKey(key []byte, filtered bool, ro *opt.ReadOptions) (rkey []byte, err error)
    +

    +FindKey finds key that is greater than or equal to the given key. +It returns ErrNotFound if the table doesn't contain such key. +If filtered is true then the nearest 'block' will be checked against +'filter data' (if present) and will immediately return ErrNotFound if +'filter data' indicates that such key doesn't exist. +

    +

    +The caller may modify the contents of the returned slice as it is its +own copy. +It is safe to modify the contents of the argument after Find returns. +

    + + + + + + +

    func (*Reader) Get

    +
    func (r *Reader) Get(key []byte, ro *opt.ReadOptions) (value []byte, err error)
    +

    +Get gets the value for the given key. It returns errors.ErrNotFound +if the table does not contain the key. +

    +

    +The caller may modify the contents of the returned slice as it is its +own copy. +It is safe to modify the contents of the argument after Find returns. +

    + + + + + + +

    func (*Reader) NewIterator

    +
    func (r *Reader) NewIterator(slice *util.Range, ro *opt.ReadOptions) iterator.Iterator
    +

    +NewIterator creates an iterator from the table. +

    +

    +Slice allows slicing the iterator to only contains keys in the given +range. A nil Range.Start is treated as a key before all keys in the +table. And a nil Range.Limit is treated as a key after all keys in +the table. +

    +

    +The returned iterator is not safe for concurrent use and should be released +after use. +

    +

    +Also read Iterator documentation of the leveldb/iterator package. +

    + + + + + + +

    func (*Reader) OffsetOf

    +
    func (r *Reader) OffsetOf(key []byte) (offset int64, err error)
    +

    +OffsetOf returns approximate offset for the given key. +

    +

    +It is safe to modify the contents of the argument after Get returns. +

    + + + + + + +

    func (*Reader) Release

    +
    func (r *Reader) Release()
    +

    +Release implements util.Releaser. +It also close the file if it is an io.Closer. +

    + + + + + + + + +

    type Writer

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

    +Writer is a table writer. +

    + + + + + + + + + + + + +

    func NewWriter

    +
    func NewWriter(f io.Writer, o *opt.Options) *Writer
    +

    +NewWriter creates a new initialized table writer for the file. +

    +

    +Table writer is not safe for concurrent use. +

    + + + + + + + +

    func (*Writer) Append

    +
    func (w *Writer) Append(key, value []byte) error
    +

    +Append appends key/value pair to the table. The keys passed must +be in increasing order. +

    +

    +It is safe to modify the contents of the arguments after Append returns. +

    + + + + + + +

    func (*Writer) BlocksLen

    +
    func (w *Writer) BlocksLen() int
    +

    +BlocksLen returns number of blocks written so far. +

    + + + + + + +

    func (*Writer) BytesLen

    +
    func (w *Writer) BytesLen() int
    +

    +BytesLen returns number of bytes written so far. +

    + + + + + + +

    func (*Writer) Close

    +
    func (w *Writer) Close() error
    +

    +Close will finalize the table. Calling Append is not possible +after Close, but calling BlocksLen, EntriesLen and BytesLen +is still possible. +

    + + + + + + +

    func (*Writer) EntriesLen

    +
    func (w *Writer) EntriesLen() int
    +

    +EntriesLen returns number of entries added so far. +

    + + + + + + + + + + + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/github.com/syndtr/goleveldb/leveldb/testutil/index.html b/pkg/github.com/syndtr/goleveldb/leveldb/testutil/index.html new file mode 100644 index 0000000..fe4e76b --- /dev/null +++ b/pkg/github.com/syndtr/goleveldb/leveldb/testutil/index.html @@ -0,0 +1,1864 @@ + + + + + + + + testutil - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Package testutil

    + + + + + + + + + + + + + + +
    +
    +
    import "github.com/syndtr/goleveldb/leveldb/testutil"
    +
    +
    +
    Overview
    +
    Index
    + + +
    +
    + +
    + +
    +

    Overview ▾

    + +
    +
    + + +
    + +
    +

    Index ▾

    + + +
    +
    + + + + +
    func AllKeyValueTesting(rnd *rand.Rand, body, setup func(KeyValue) DB, teardown func(DB))
    + + +
    func BytesAfter(b []byte) []byte
    + + +
    func BytesSeparator(a, b []byte) []byte
    + + +
    func Defer(args ...interface{}) bool
    + + +
    func DoDBTesting(t *DBTesting)
    + + +
    func DoIteratorTesting(t *IteratorTesting)
    + + +
    func KeyValueTesting(rnd *rand.Rand, kv KeyValue, p DB, setup func(KeyValue) DB, teardown func(DB))
    + + +
    func Max(x, y int) int
    + + +
    func Min(x, y int) int
    + + +
    func NewRand() *rand.Rand
    + + +
    func RandomIndex(rnd *rand.Rand, n, round int, fn func(i int))
    + + +
    func RandomRange(rnd *rand.Rand, n, round int, fn func(start, limit int))
    + + +
    func RandomSeed() int64
    + + +
    func RunDefer(groups ...string) bool
    + + +
    func RunSuite(t GinkgoTestingT, name string)
    + + +
    func ShuffledIndex(rnd *rand.Rand, n, round int, fn func(i int))
    + + +
    func TestFind(db Find, kv KeyValue)
    + + +
    func TestFindAfterLast(db Find, kv KeyValue)
    + + +
    func TestGet(db Get, kv KeyValue)
    + + +
    func TestHas(db Has, kv KeyValue)
    + + +
    func TestIter(db NewIterator, r *util.Range, kv KeyValue)
    + + + +
    type DB
    + + + + +
    type DBAct
    + + + +
        func (a DBAct) String() string
    + + + +
    type DBTesting
    + + + +
        func (t *DBTesting) Delete(key []byte)
    + + +
        func (t *DBTesting) DeleteRandom() bool
    + + +
        func (t *DBTesting) Put(key, value []byte)
    + + +
        func (t *DBTesting) PutRandom() bool
    + + +
        func (t *DBTesting) RandomAct(round int)
    + + +
        func (t *DBTesting) TestAll()
    + + +
        func (t *DBTesting) TestAllDeleted()
    + + +
        func (t *DBTesting) TestAllPresent()
    + + +
        func (t *DBTesting) TestDeletedKey(key []byte)
    + + +
        func (t *DBTesting) TestPresentKV(key, value []byte)
    + + +
        func (t *DBTesting) Text() string
    + + + +
    type Delete
    + + + + +
    type Find
    + + + + +
    type Get
    + + + + +
    type Has
    + + + + +
    type IterAct
    + + + +
        func (a IterAct) String() string
    + + + +
    type IteratorTesting
    + + + +
        func (t *IteratorTesting) EOI()
    + + +
        func (t *IteratorTesting) First()
    + + +
        func (t *IteratorTesting) IsFirst() bool
    + + +
        func (t *IteratorTesting) IsLast() bool
    + + +
        func (t *IteratorTesting) Last()
    + + +
        func (t *IteratorTesting) Next()
    + + +
        func (t *IteratorTesting) NextAll()
    + + +
        func (t *IteratorTesting) Prev()
    + + +
        func (t *IteratorTesting) PrevAll()
    + + +
        func (t *IteratorTesting) SOI()
    + + +
        func (t *IteratorTesting) Seek(i int)
    + + +
        func (t *IteratorTesting) SeekInexact(i int)
    + + +
        func (t *IteratorTesting) SeekKey(key []byte)
    + + +
        func (t *IteratorTesting) TestKV()
    + + +
        func (t *IteratorTesting) Text() string
    + + +
        func (t *IteratorTesting) WalkNext(fn func(t *IteratorTesting))
    + + +
        func (t *IteratorTesting) WalkPrev(fn func(t *IteratorTesting))
    + + + +
    type KeyValue
    + + +
        func KeyValue_BigValue() *KeyValue
    + + +
        func KeyValue_EmptyKey() *KeyValue
    + + +
        func KeyValue_EmptyValue() *KeyValue
    + + +
        func KeyValue_Generate(rnd *rand.Rand, n, incr, minlen, maxlen, vminlen, vmaxlen int) *KeyValue
    + + +
        func KeyValue_MultipleKeyValue() *KeyValue
    + + +
        func KeyValue_OneKeyValue() *KeyValue
    + + +
        func KeyValue_SpecialKey() *KeyValue
    + + + +
        func (kv KeyValue) Clone() KeyValue
    + + +
        func (kv *KeyValue) Delete(key []byte) (exist bool, value []byte)
    + + +
        func (kv *KeyValue) DeleteIndex(i int) bool
    + + +
        func (kv KeyValue) Get(key []byte) (i int, exist bool)
    + + +
        func (kv KeyValue) GetString(key string) (i int, exist bool)
    + + +
        func (kv KeyValue) Index(i int) (key, value []byte)
    + + +
        func (kv KeyValue) IndexInexact(i int) (key_, key, value []byte)
    + + +
        func (kv KeyValue) IndexOrNil(i int) (key, value []byte)
    + + +
        func (kv KeyValue) IndexString(i int) (key, value string)
    + + +
        func (kv KeyValue) Iterate(fn func(i int, key, value []byte))
    + + +
        func (kv KeyValue) IterateInexact(fn func(i int, key_, key, value []byte))
    + + +
        func (kv KeyValue) IterateInexactString(fn func(i int, key_, key, value string))
    + + +
        func (kv KeyValue) IterateShuffled(rnd *rand.Rand, fn func(i int, key, value []byte))
    + + +
        func (kv KeyValue) IterateShuffledString(rnd *rand.Rand, fn func(i int, key, value string))
    + + +
        func (kv KeyValue) IterateString(fn func(i int, key, value string))
    + + +
        func (kv KeyValue) KeyAt(i int) []byte
    + + +
        func (kv KeyValue) Len() int
    + + +
        func (kv *KeyValue) Put(key, value []byte)
    + + +
        func (kv *KeyValue) PutString(key, value string)
    + + +
        func (kv *KeyValue) PutU(key, value []byte) bool
    + + +
        func (kv *KeyValue) PutUString(key, value string) bool
    + + +
        func (kv KeyValue) Range(start, limit int) (r util.Range)
    + + +
        func (kv KeyValue) Search(key []byte) int
    + + +
        func (kv KeyValue) SearchString(key string) int
    + + +
        func (kv *KeyValue) Size() int
    + + +
        func (kv KeyValue) Slice(start, limit int) KeyValue
    + + +
        func (kv KeyValue) SliceKey(start, limit []byte) KeyValue
    + + +
        func (kv KeyValue) SliceKeyString(start, limit string) KeyValue
    + + +
        func (kv KeyValue) SliceRange(r *util.Range) KeyValue
    + + +
        func (kv KeyValue) ValueAt(i int) []byte
    + + + +
    type KeyValueEntry
    + + + + +
    type NewIterator
    + + + + +
    type Put
    + + + + +
    type Storage
    + + +
        func NewStorage() *Storage
    + + + +
        func (s *Storage) Close() error
    + + +
        func (s *Storage) CloseCheck()
    + + +
        func (s *Storage) Counter(m StorageMode, t storage.FileType) (count int, bytes int64)
    + + +
        func (s *Storage) Create(fd storage.FileDesc) (w storage.Writer, err error)
    + + +
        func (s *Storage) EmulateError(m StorageMode, t storage.FileType, err error)
    + + +
        func (s *Storage) EmulateErrorOnce(m StorageMode, t storage.FileType, err error)
    + + +
        func (s *Storage) EmulateRandomError(m StorageMode, t storage.FileType, prob float64, err error)
    + + +
        func (s *Storage) ForceRemove(fd storage.FileDesc) (err error)
    + + +
        func (s *Storage) ForceRename(oldfd, newfd storage.FileDesc) (err error)
    + + +
        func (s *Storage) GetMeta() (fd storage.FileDesc, err error)
    + + +
        func (s *Storage) List(t storage.FileType) (fds []storage.FileDesc, err error)
    + + +
        func (s *Storage) Lock() (l storage.Locker, err error)
    + + +
        func (s *Storage) Log(str string)
    + + +
        func (s *Storage) OnClose(onClose func() (preserve bool, err error))
    + + +
        func (s *Storage) OnLog(onLog func(log string))
    + + +
        func (s *Storage) Open(fd storage.FileDesc) (r storage.Reader, err error)
    + + +
        func (s *Storage) Release(m StorageMode, t storage.FileType)
    + + +
        func (s *Storage) Remove(fd storage.FileDesc) (err error)
    + + +
        func (s *Storage) Rename(oldfd, newfd storage.FileDesc) (err error)
    + + +
        func (s *Storage) ResetCounter(m StorageMode, t storage.FileType)
    + + +
        func (s *Storage) SetMeta(fd storage.FileDesc) error
    + + +
        func (s *Storage) Stall(m StorageMode, t storage.FileType)
    + + + +
    type StorageMode
    + + + + +
    +
    + + + + +

    Package files

    +

    + + + db.go + + ginkgo.go + + iter.go + + kv.go + + kvtest.go + + storage.go + + util.go + + +

    + +
    +
    + + + + + + + + +

    func AllKeyValueTesting

    +
    func AllKeyValueTesting(rnd *rand.Rand, body, setup func(KeyValue) DB, teardown func(DB))
    + + + + + + + +

    func BytesAfter

    +
    func BytesAfter(b []byte) []byte
    + + + + + + + +

    func BytesSeparator

    +
    func BytesSeparator(a, b []byte) []byte
    + + + + + + + +

    func Defer

    +
    func Defer(args ...interface{}) bool
    + + + + + + + +

    func DoDBTesting

    +
    func DoDBTesting(t *DBTesting)
    + + + + + + + +

    func DoIteratorTesting

    +
    func DoIteratorTesting(t *IteratorTesting)
    + + + + + + + +

    func KeyValueTesting

    +
    func KeyValueTesting(rnd *rand.Rand, kv KeyValue, p DB, setup func(KeyValue) DB, teardown func(DB))
    + + + + + + + +

    func Max

    +
    func Max(x, y int) int
    + + + + + + + +

    func Min

    +
    func Min(x, y int) int
    + + + + + + + +

    func NewRand

    +
    func NewRand() *rand.Rand
    + + + + + + + +

    func RandomIndex

    +
    func RandomIndex(rnd *rand.Rand, n, round int, fn func(i int))
    + + + + + + + +

    func RandomRange

    +
    func RandomRange(rnd *rand.Rand, n, round int, fn func(start, limit int))
    + + + + + + + +

    func RandomSeed

    +
    func RandomSeed() int64
    + + + + + + + +

    func RunDefer

    +
    func RunDefer(groups ...string) bool
    + + + + + + + +

    func RunSuite

    +
    func RunSuite(t GinkgoTestingT, name string)
    + + + + + + + +

    func ShuffledIndex

    +
    func ShuffledIndex(rnd *rand.Rand, n, round int, fn func(i int))
    + + + + + + + +

    func TestFind

    +
    func TestFind(db Find, kv KeyValue)
    + + + + + + + +

    func TestFindAfterLast

    +
    func TestFindAfterLast(db Find, kv KeyValue)
    + + + + + + + +

    func TestGet

    +
    func TestGet(db Get, kv KeyValue)
    + + + + + + + +

    func TestHas

    +
    func TestHas(db Has, kv KeyValue)
    + + + + + + + +

    func TestIter

    +
    func TestIter(db NewIterator, r *util.Range, kv KeyValue)
    + + + + + + + + +

    type DB

    +
    type DB interface{}
    + + + + + + + + + + + + + + + + +

    type DBAct

    +
    type DBAct int
    + + + +
    const (
    +    DBNone DBAct = iota
    +    DBPut
    +    DBOverwrite
    +    DBDelete
    +    DBDeleteNA
    +)
    + + + + + + + + + + + + + +

    func (DBAct) String

    +
    func (a DBAct) String() string
    + + + + + + + + +

    type DBTesting

    +
    type DBTesting struct {
    +    Rand *rand.Rand
    +    DB   interface {
    +        Get
    +        Put
    +        Delete
    +    }
    +    PostFn             func(t *DBTesting)
    +    Deleted, Present   KeyValue
    +    Act, LastAct       DBAct
    +    ActKey, LastActKey []byte
    +}
    + + + + + + + + + + + + + + +

    func (*DBTesting) Delete

    +
    func (t *DBTesting) Delete(key []byte)
    + + + + + + +

    func (*DBTesting) DeleteRandom

    +
    func (t *DBTesting) DeleteRandom() bool
    + + + + + + +

    func (*DBTesting) Put

    +
    func (t *DBTesting) Put(key, value []byte)
    + + + + + + +

    func (*DBTesting) PutRandom

    +
    func (t *DBTesting) PutRandom() bool
    + + + + + + +

    func (*DBTesting) RandomAct

    +
    func (t *DBTesting) RandomAct(round int)
    + + + + + + +

    func (*DBTesting) TestAll

    +
    func (t *DBTesting) TestAll()
    + + + + + + +

    func (*DBTesting) TestAllDeleted

    +
    func (t *DBTesting) TestAllDeleted()
    + + + + + + +

    func (*DBTesting) TestAllPresent

    +
    func (t *DBTesting) TestAllPresent()
    + + + + + + +

    func (*DBTesting) TestDeletedKey

    +
    func (t *DBTesting) TestDeletedKey(key []byte)
    + + + + + + +

    func (*DBTesting) TestPresentKV

    +
    func (t *DBTesting) TestPresentKV(key, value []byte)
    + + + + + + +

    func (*DBTesting) Text

    +
    func (t *DBTesting) Text() string
    + + + + + + + + +

    type Delete

    +
    type Delete interface {
    +    TestDelete(key []byte) error
    +}
    + + + + + + + + + + + + + + + + +

    type Find

    +
    type Find interface {
    +    TestFind(key []byte) (rkey, rvalue []byte, err error)
    +}
    + + + + + + + + + + + + + + + + +

    type Get

    +
    type Get interface {
    +    TestGet(key []byte) (value []byte, err error)
    +}
    + + + + + + + + + + + + + + + + +

    type Has

    +
    type Has interface {
    +    TestHas(key []byte) (ret bool, err error)
    +}
    + + + + + + + + + + + + + + + + +

    type IterAct

    +
    type IterAct int
    + + + +
    const (
    +    IterNone IterAct = iota
    +    IterFirst
    +    IterLast
    +    IterPrev
    +    IterNext
    +    IterSeek
    +    IterSOI
    +    IterEOI
    +)
    + + + + + + + + + + + + + +

    func (IterAct) String

    +
    func (a IterAct) String() string
    + + + + + + + + +

    type IteratorTesting

    +
    type IteratorTesting struct {
    +    KeyValue
    +    Iter         iterator.Iterator
    +    Rand         *rand.Rand
    +    PostFn       func(t *IteratorTesting)
    +    Pos          int
    +    Act, LastAct IterAct
    +    // contains filtered or unexported fields
    +}
    + + + + + + + + + + + + + + +

    func (*IteratorTesting) EOI

    +
    func (t *IteratorTesting) EOI()
    + + + + + + +

    func (*IteratorTesting) First

    +
    func (t *IteratorTesting) First()
    + + + + + + +

    func (*IteratorTesting) IsFirst

    +
    func (t *IteratorTesting) IsFirst() bool
    + + + + + + +

    func (*IteratorTesting) IsLast

    +
    func (t *IteratorTesting) IsLast() bool
    + + + + + + +

    func (*IteratorTesting) Last

    +
    func (t *IteratorTesting) Last()
    + + + + + + +

    func (*IteratorTesting) Next

    +
    func (t *IteratorTesting) Next()
    + + + + + + +

    func (*IteratorTesting) NextAll

    +
    func (t *IteratorTesting) NextAll()
    + + + + + + +

    func (*IteratorTesting) Prev

    +
    func (t *IteratorTesting) Prev()
    + + + + + + +

    func (*IteratorTesting) PrevAll

    +
    func (t *IteratorTesting) PrevAll()
    + + + + + + +

    func (*IteratorTesting) SOI

    +
    func (t *IteratorTesting) SOI()
    + + + + + + +

    func (*IteratorTesting) Seek

    +
    func (t *IteratorTesting) Seek(i int)
    + + + + + + +

    func (*IteratorTesting) SeekInexact

    +
    func (t *IteratorTesting) SeekInexact(i int)
    + + + + + + +

    func (*IteratorTesting) SeekKey

    +
    func (t *IteratorTesting) SeekKey(key []byte)
    + + + + + + +

    func (*IteratorTesting) TestKV

    +
    func (t *IteratorTesting) TestKV()
    + + + + + + +

    func (*IteratorTesting) Text

    +
    func (t *IteratorTesting) Text() string
    + + + + + + +

    func (*IteratorTesting) WalkNext

    +
    func (t *IteratorTesting) WalkNext(fn func(t *IteratorTesting))
    + + + + + + +

    func (*IteratorTesting) WalkPrev

    +
    func (t *IteratorTesting) WalkPrev(fn func(t *IteratorTesting))
    + + + + + + + + +

    type KeyValue

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

    func KeyValue_BigValue

    +
    func KeyValue_BigValue() *KeyValue
    + + + + + +

    func KeyValue_EmptyKey

    +
    func KeyValue_EmptyKey() *KeyValue
    + + + + + +

    func KeyValue_EmptyValue

    +
    func KeyValue_EmptyValue() *KeyValue
    + + + + + +

    func KeyValue_Generate

    +
    func KeyValue_Generate(rnd *rand.Rand, n, incr, minlen, maxlen, vminlen, vmaxlen int) *KeyValue
    + + + + + +

    func KeyValue_MultipleKeyValue

    +
    func KeyValue_MultipleKeyValue() *KeyValue
    + + + + + +

    func KeyValue_OneKeyValue

    +
    func KeyValue_OneKeyValue() *KeyValue
    + + + + + +

    func KeyValue_SpecialKey

    +
    func KeyValue_SpecialKey() *KeyValue
    + + + + + + + +

    func (KeyValue) Clone

    +
    func (kv KeyValue) Clone() KeyValue
    + + + + + + +

    func (*KeyValue) Delete

    +
    func (kv *KeyValue) Delete(key []byte) (exist bool, value []byte)
    + + + + + + +

    func (*KeyValue) DeleteIndex

    +
    func (kv *KeyValue) DeleteIndex(i int) bool
    + + + + + + +

    func (KeyValue) Get

    +
    func (kv KeyValue) Get(key []byte) (i int, exist bool)
    + + + + + + +

    func (KeyValue) GetString

    +
    func (kv KeyValue) GetString(key string) (i int, exist bool)
    + + + + + + +

    func (KeyValue) Index

    +
    func (kv KeyValue) Index(i int) (key, value []byte)
    + + + + + + +

    func (KeyValue) IndexInexact

    +
    func (kv KeyValue) IndexInexact(i int) (key_, key, value []byte)
    + + + + + + +

    func (KeyValue) IndexOrNil

    +
    func (kv KeyValue) IndexOrNil(i int) (key, value []byte)
    + + + + + + +

    func (KeyValue) IndexString

    +
    func (kv KeyValue) IndexString(i int) (key, value string)
    + + + + + + +

    func (KeyValue) Iterate

    +
    func (kv KeyValue) Iterate(fn func(i int, key, value []byte))
    + + + + + + +

    func (KeyValue) IterateInexact

    +
    func (kv KeyValue) IterateInexact(fn func(i int, key_, key, value []byte))
    + + + + + + +

    func (KeyValue) IterateInexactString

    +
    func (kv KeyValue) IterateInexactString(fn func(i int, key_, key, value string))
    + + + + + + +

    func (KeyValue) IterateShuffled

    +
    func (kv KeyValue) IterateShuffled(rnd *rand.Rand, fn func(i int, key, value []byte))
    + + + + + + +

    func (KeyValue) IterateShuffledString

    +
    func (kv KeyValue) IterateShuffledString(rnd *rand.Rand, fn func(i int, key, value string))
    + + + + + + +

    func (KeyValue) IterateString

    +
    func (kv KeyValue) IterateString(fn func(i int, key, value string))
    + + + + + + +

    func (KeyValue) KeyAt

    +
    func (kv KeyValue) KeyAt(i int) []byte
    + + + + + + +

    func (KeyValue) Len

    +
    func (kv KeyValue) Len() int
    + + + + + + +

    func (*KeyValue) Put

    +
    func (kv *KeyValue) Put(key, value []byte)
    + + + + + + +

    func (*KeyValue) PutString

    +
    func (kv *KeyValue) PutString(key, value string)
    + + + + + + +

    func (*KeyValue) PutU

    +
    func (kv *KeyValue) PutU(key, value []byte) bool
    + + + + + + +

    func (*KeyValue) PutUString

    +
    func (kv *KeyValue) PutUString(key, value string) bool
    + + + + + + +

    func (KeyValue) Range

    +
    func (kv KeyValue) Range(start, limit int) (r util.Range)
    + + + + + + +

    func (KeyValue) Search

    +
    func (kv KeyValue) Search(key []byte) int
    + + + + + + +

    func (KeyValue) SearchString

    +
    func (kv KeyValue) SearchString(key string) int
    + + + + + + +

    func (*KeyValue) Size

    +
    func (kv *KeyValue) Size() int
    + + + + + + +

    func (KeyValue) Slice

    +
    func (kv KeyValue) Slice(start, limit int) KeyValue
    + + + + + + +

    func (KeyValue) SliceKey

    +
    func (kv KeyValue) SliceKey(start, limit []byte) KeyValue
    + + + + + + +

    func (KeyValue) SliceKeyString

    +
    func (kv KeyValue) SliceKeyString(start, limit string) KeyValue
    + + + + + + +

    func (KeyValue) SliceRange

    +
    func (kv KeyValue) SliceRange(r *util.Range) KeyValue
    + + + + + + +

    func (KeyValue) ValueAt

    +
    func (kv KeyValue) ValueAt(i int) []byte
    + + + + + + + + +

    type KeyValueEntry

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

    type NewIterator

    +
    type NewIterator interface {
    +    TestNewIterator(slice *util.Range) iterator.Iterator
    +}
    + + + + + + + + + + + + + + + + +

    type Put

    +
    type Put interface {
    +    TestPut(key []byte, value []byte) error
    +}
    + + + + + + + + + + + + + + + + +

    type Storage

    +
    type Storage struct {
    +    storage.Storage
    +    // contains filtered or unexported fields
    +}
    + + + + + + + + + + + + +

    func NewStorage

    +
    func NewStorage() *Storage
    + + + + + + + +

    func (*Storage) Close

    +
    func (s *Storage) Close() error
    + + + + + + +

    func (*Storage) CloseCheck

    +
    func (s *Storage) CloseCheck()
    + + + + + + +

    func (*Storage) Counter

    +
    func (s *Storage) Counter(m StorageMode, t storage.FileType) (count int, bytes int64)
    + + + + + + +

    func (*Storage) Create

    +
    func (s *Storage) Create(fd storage.FileDesc) (w storage.Writer, err error)
    + + + + + + +

    func (*Storage) EmulateError

    +
    func (s *Storage) EmulateError(m StorageMode, t storage.FileType, err error)
    + + + + + + +

    func (*Storage) EmulateErrorOnce

    +
    func (s *Storage) EmulateErrorOnce(m StorageMode, t storage.FileType, err error)
    + + + + + + +

    func (*Storage) EmulateRandomError

    +
    func (s *Storage) EmulateRandomError(m StorageMode, t storage.FileType, prob float64, err error)
    + + + + + + +

    func (*Storage) ForceRemove

    +
    func (s *Storage) ForceRemove(fd storage.FileDesc) (err error)
    + + + + + + +

    func (*Storage) ForceRename

    +
    func (s *Storage) ForceRename(oldfd, newfd storage.FileDesc) (err error)
    + + + + + + +

    func (*Storage) GetMeta

    +
    func (s *Storage) GetMeta() (fd storage.FileDesc, err error)
    + + + + + + +

    func (*Storage) List

    +
    func (s *Storage) List(t storage.FileType) (fds []storage.FileDesc, err error)
    + + + + + + +

    func (*Storage) Lock

    +
    func (s *Storage) Lock() (l storage.Locker, err error)
    + + + + + + +

    func (*Storage) Log

    +
    func (s *Storage) Log(str string)
    + + + + + + +

    func (*Storage) OnClose

    +
    func (s *Storage) OnClose(onClose func() (preserve bool, err error))
    + + + + + + +

    func (*Storage) OnLog

    +
    func (s *Storage) OnLog(onLog func(log string))
    + + + + + + +

    func (*Storage) Open

    +
    func (s *Storage) Open(fd storage.FileDesc) (r storage.Reader, err error)
    + + + + + + +

    func (*Storage) Release

    +
    func (s *Storage) Release(m StorageMode, t storage.FileType)
    + + + + + + +

    func (*Storage) Remove

    +
    func (s *Storage) Remove(fd storage.FileDesc) (err error)
    + + + + + + +

    func (*Storage) Rename

    +
    func (s *Storage) Rename(oldfd, newfd storage.FileDesc) (err error)
    + + + + + + +

    func (*Storage) ResetCounter

    +
    func (s *Storage) ResetCounter(m StorageMode, t storage.FileType)
    + + + + + + +

    func (*Storage) SetMeta

    +
    func (s *Storage) SetMeta(fd storage.FileDesc) error
    + + + + + + +

    func (*Storage) Stall

    +
    func (s *Storage) Stall(m StorageMode, t storage.FileType)
    + + + + + + + + +

    type StorageMode

    +
    type StorageMode int
    + + + +
    const (
    +    ModeOpen StorageMode = 1 << iota
    +    ModeCreate
    +    ModeRemove
    +    ModeRename
    +    ModeRead
    +    ModeWrite
    +    ModeSync
    +    ModeClose
    +)
    + + + + + + + + + + + + + + + + + + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/github.com/syndtr/goleveldb/leveldb/util/index.html b/pkg/github.com/syndtr/goleveldb/leveldb/util/index.html new file mode 100644 index 0000000..3adf2f2 --- /dev/null +++ b/pkg/github.com/syndtr/goleveldb/leveldb/util/index.html @@ -0,0 +1,923 @@ + + + + + + + + util - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Package util

    + + + + + + + + + + + + + + +
    +
    +
    import "github.com/syndtr/goleveldb/leveldb/util"
    +
    +
    +
    Overview
    +
    Index
    + + +
    +
    + +
    + +
    +

    Overview ▾

    +

    +Package util provides utilities used throughout leveldb. +

    + +
    +
    + + +
    + +
    +

    Index ▾

    + + +
    +
    + +
    Constants
    + + +
    Variables
    + + + +
    func Hash(data []byte, seed uint32) uint32
    + + + +
    type BasicReleaser
    + + + +
        func (r *BasicReleaser) Release()
    + + +
        func (r *BasicReleaser) Released() bool
    + + +
        func (r *BasicReleaser) SetReleaser(releaser Releaser)
    + + + +
    type Buffer
    + + +
        func NewBuffer(buf []byte) *Buffer
    + + + +
        func (b *Buffer) Alloc(n int) []byte
    + + +
        func (b *Buffer) Bytes() []byte
    + + +
        func (b *Buffer) Grow(n int)
    + + +
        func (b *Buffer) Len() int
    + + +
        func (b *Buffer) Next(n int) []byte
    + + +
        func (b *Buffer) Read(p []byte) (n int, err error)
    + + +
        func (b *Buffer) ReadByte() (c byte, err error)
    + + +
        func (b *Buffer) ReadBytes(delim byte) (line []byte, err error)
    + + +
        func (b *Buffer) ReadFrom(r io.Reader) (n int64, err error)
    + + +
        func (b *Buffer) Reset()
    + + +
        func (b *Buffer) String() string
    + + +
        func (b *Buffer) Truncate(n int)
    + + +
        func (b *Buffer) Write(p []byte) (n int, err error)
    + + +
        func (b *Buffer) WriteByte(c byte) error
    + + +
        func (b *Buffer) WriteTo(w io.Writer) (n int64, err error)
    + + + +
    type BufferPool
    + + +
        func NewBufferPool(baseline int) *BufferPool
    + + + +
        func (p *BufferPool) Close()
    + + +
        func (p *BufferPool) Get(n int) []byte
    + + +
        func (p *BufferPool) Put(b []byte)
    + + +
        func (p *BufferPool) String() string
    + + + +
    type CRC
    + + +
        func NewCRC(b []byte) CRC
    + + + +
        func (c CRC) Update(b []byte) CRC
    + + +
        func (c CRC) Value() uint32
    + + + +
    type NoopReleaser
    + + + +
        func (NoopReleaser) Release()
    + + + +
    type Range
    + + +
        func BytesPrefix(prefix []byte) *Range
    + + + + +
    type ReleaseSetter
    + + + + +
    type Releaser
    + + + + +
    +
    + + + + +

    Package files

    +

    + + + buffer.go + + buffer_pool.go + + crc32.go + + hash.go + + range.go + + util.go + + +

    + +
    +
    + + + + +

    Constants

    + +
    const MinRead = 512
    +

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

    + + + + +

    Variables

    + +
    var (
    +    ErrReleased    = errors.New("leveldb: resource already relesed")
    +    ErrHasReleaser = errors.New("leveldb: releaser already defined")
    +)
    + + + + + + +

    func Hash

    +
    func Hash(data []byte, seed uint32) uint32
    +

    +Hash return hash of the given data. +

    + + + + + + + + +

    type BasicReleaser

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

    +BasicReleaser provides basic implementation of Releaser and ReleaseSetter. +

    + + + + + + + + + + + + + + +

    func (*BasicReleaser) Release

    +
    func (r *BasicReleaser) Release()
    +

    +Release implements Releaser.Release. +

    + + + + + + +

    func (*BasicReleaser) Released

    +
    func (r *BasicReleaser) Released() bool
    +

    +Released returns whether Release method already called. +

    + + + + + + +

    func (*BasicReleaser) SetReleaser

    +
    func (r *BasicReleaser) SetReleaser(releaser Releaser)
    +

    +SetReleaser implements ReleaseSetter.SetReleaser. +

    + + + + + + + + +

    type Buffer

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

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

    + + + + + + + + + + + + +

    func NewBuffer

    +
    func NewBuffer(buf []byte) *Buffer
    +

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

    +

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

    + + + + + + + +

    func (*Buffer) Alloc

    +
    func (b *Buffer) Alloc(n int) []byte
    +

    +Alloc allocs n bytes of slice from the buffer, growing the buffer as +needed. If n is negative, Alloc will panic. +If the buffer can't grow it will panic with bytes.ErrTooLarge. +

    + + + + + + +

    func (*Buffer) Bytes

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

    +Bytes returns a slice of the contents of the unread portion of the buffer; +len(b.Bytes()) == b.Len(). If the caller changes the contents of the +returned slice, the contents of the buffer will change provided there +are no intervening method calls on the Buffer. +

    + + + + + + +

    func (*Buffer) Grow

    +
    func (b *Buffer) Grow(n int)
    +

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

    + + + + + + +

    func (*Buffer) Len

    +
    func (b *Buffer) Len() int
    +

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

    + + + + + + +

    func (*Buffer) Next

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

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

    + + + + + + +

    func (*Buffer) Read

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

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

    + + + + + + +

    func (*Buffer) ReadByte

    +
    func (b *Buffer) ReadByte() (c byte, err error)
    +

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

    + + + + + + +

    func (*Buffer) ReadBytes

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

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

    + + + + + + +

    func (*Buffer) ReadFrom

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

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

    + + + + + + +

    func (*Buffer) Reset

    +
    func (b *Buffer) Reset()
    +

    +Reset resets the buffer so it has no content. +b.Reset() is the same as b.Truncate(0). +

    + + + + + + +

    func (*Buffer) String

    +
    func (b *Buffer) String() string
    +

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

    + + + + + + +

    func (*Buffer) Truncate

    +
    func (b *Buffer) Truncate(n int)
    +

    +Truncate discards all but the first n unread bytes from the buffer. +It panics if n is negative or greater than the length of the buffer. +

    + + + + + + +

    func (*Buffer) Write

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

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

    + + + + + + +

    func (*Buffer) WriteByte

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

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

    + + + + + + +

    func (*Buffer) WriteTo

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

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

    + + + + + + + + +

    type BufferPool

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

    +BufferPool is a 'buffer pool'. +

    + + + + + + + + + + + + +

    func NewBufferPool

    +
    func NewBufferPool(baseline int) *BufferPool
    +

    +NewBufferPool creates a new initialized 'buffer pool'. +

    + + + + + + + +

    func (*BufferPool) Close

    +
    func (p *BufferPool) Close()
    + + + + + + +

    func (*BufferPool) Get

    +
    func (p *BufferPool) Get(n int) []byte
    +

    +Get returns buffer with length of n. +

    + + + + + + +

    func (*BufferPool) Put

    +
    func (p *BufferPool) Put(b []byte)
    +

    +Put adds given buffer to the pool. +

    + + + + + + +

    func (*BufferPool) String

    +
    func (p *BufferPool) String() string
    + + + + + + + + +

    type CRC

    +
    type CRC uint32
    +

    +CRC is a CRC-32 checksum computed using Castagnoli's polynomial. +

    + + + + + + + + + + + + +

    func NewCRC

    +
    func NewCRC(b []byte) CRC
    +

    +NewCRC creates a new crc based on the given bytes. +

    + + + + + + + +

    func (CRC) Update

    +
    func (c CRC) Update(b []byte) CRC
    +

    +Update updates the crc with the given bytes. +

    + + + + + + +

    func (CRC) Value

    +
    func (c CRC) Value() uint32
    +

    +Value returns a masked crc. +

    + + + + + + + + +

    type NoopReleaser

    +
    type NoopReleaser struct{}
    + + + + + + + + + + + + + + +

    func (NoopReleaser) Release

    +
    func (NoopReleaser) Release()
    + + + + + + + + +

    type Range

    +
    type Range struct {
    +    // Start of the key range, include in the range.
    +    Start []byte
    +
    +    // Limit of the key range, not include in the range.
    +    Limit []byte
    +}
    +

    +Range is a key range. +

    + + + + + + + + + + + + +

    func BytesPrefix

    +
    func BytesPrefix(prefix []byte) *Range
    +

    +BytesPrefix returns key range that satisfy the given prefix. +This only applicable for the standard 'bytes comparer'. +

    + + + + + + + + + +

    type ReleaseSetter

    +
    type ReleaseSetter interface {
    +    // SetReleaser associates the given releaser to the resources. The
    +    // releaser will be called once coresponding resources released.
    +    // Calling SetReleaser with nil will clear the releaser.
    +    //
    +    // This will panic if a releaser already present or coresponding
    +    // resource is already released. Releaser should be cleared first
    +    // before assigned a new one.
    +    SetReleaser(releaser Releaser)
    +}
    +

    +ReleaseSetter is the interface that wraps the basic SetReleaser method. +

    + + + + + + + + + + + + + + + + +

    type Releaser

    +
    type Releaser interface {
    +    // Release releases associated resources. Release should always success
    +    // and can be called multipe times without causing error.
    +    Release()
    +}
    +

    +Releaser is the interface that wraps the basic Release method. +

    + + + + + + + + + + + + + + + + + + + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/github.com/syndtr/index.html b/pkg/github.com/syndtr/index.html new file mode 100644 index 0000000..08373a9 --- /dev/null +++ b/pkg/github.com/syndtr/index.html @@ -0,0 +1,273 @@ + + + + + + + + /src/github.com/syndtr - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Directory /src/github.com/syndtr

    + + + + + + + + + + + + + + + + + + + +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    NameSynopsis
    ..
    + goleveldb + + +
    + leveldb + + Package leveldb provides implementation of LevelDB key/value database. +
    + cache + + Package cache provides interface and implementation of a cache algorithms. +
    + comparer + + Package comparer provides interface and implementation for ordering sets of data. +
    + errors + + Package errors provides common error types used throughout leveldb. +
    + filter + + Package filter provides interface and implementation of probabilistic data structure. +
    + iterator + + Package iterator provides interface and implementation to traverse over contents of a database. +
    + journal + + Package journal reads and writes sequences of journals. +
    + memdb + + Package memdb provides in-memory key/value database implementation. +
    + opt + + Package opt provides sets of options used by LevelDB. +
    + storage + + Package storage provides storage abstraction for LevelDB. +
    + table + + Package table allows read and write sorted key/value. +
    + testutil + + +
    + util + + Package util provides utilities used throughout leveldb. +
    +
    + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/golang.org/index.html b/pkg/golang.org/index.html new file mode 100644 index 0000000..01c0d80 --- /dev/null +++ b/pkg/golang.org/index.html @@ -0,0 +1,537 @@ + + + + + + + + /src/golang.org - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Directory /src/golang.org

    + + + + + + + + + + + + + + + + + + + +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    NameSynopsis
    ..
    + x + + +
    + net + + +
    + context + + Package context defines the Context type, which carries deadlines, cancelation signals, and other request-scoped values across API boundaries and between processes. +
    + ctxhttp + + Package ctxhttp provides helper functions for performing context-aware HTTP requests. +
    + html + + Package html implements an HTML5-compliant tokenizer and parser. +
    + atom + + Package atom provides integer codes (also known as atoms) for a fixed set of frequently occurring HTML strings: tag names and attribute keys such as "p" and "id". +
    + charset + + Package charset provides common text encodings for HTML documents. +
    + oauth2 + + Package oauth2 provides support for making OAuth2 authorized and authenticated HTTP requests. +
    + bitbucket + + Package bitbucket provides constants for using OAuth2 to access Bitbucket. +
    + clientcredentials + + Package clientcredentials implements the OAuth2.0 "client credentials" token flow, also known as the "two-legged OAuth 2.0". +
    + facebook + + Package facebook provides constants for using OAuth2 to access Facebook. +
    + fitbit + + Package fitbit provides constants for using OAuth2 to access the Fitbit API. +
    + github + + Package github provides constants for using OAuth2 to access Github. +
    + google + + Package google provides support for making OAuth2 authorized and authenticated HTTP requests to Google APIs. +
    + hipchat + + Package hipchat provides constants for using OAuth2 to access HipChat. +
    + jws + + Package jws provides encoding and decoding utilities for signed JWS messages. +
    + jwt + + Package jwt implements the OAuth 2.0 JSON Web Token flow, commonly known as "two-legged OAuth 2.0". +
    + linkedin + + Package linkedin provides constants for using OAuth2 to access LinkedIn. +
    + microsoft + + Package microsoft provides constants for using OAuth2 to access Windows Live ID. +
    + odnoklassniki + + Package odnoklassniki provides constants for using OAuth2 to access Odnoklassniki. +
    + paypal + + Package paypal provides constants for using OAuth2 to access PayPal. +
    + slack + + Package slack provides constants for using OAuth2 to access Slack. +
    + vk + + Package vk provides constants for using OAuth2 to access VK.com. +
    + text + + +
    + encoding + + Package encoding defines an interface for character encodings, such as Shift JIS and Windows 1252, that can convert to and from UTF-8. +
    + charmap + + Package charmap provides simple character encodings such as IBM Code Page 437 and Windows 1252. +
    + htmlindex + + Package htmlindex maps character set encoding names to Encodings as recommended by the W3C for use in HTML 5. +
    + ianaindex + + Package ianaindex maps names to Encodings as specified by the IANA registry. +
    + japanese + + Package japanese provides Japanese encodings such as EUC-JP and Shift JIS. +
    + korean + + Package korean provides Korean encodings such as EUC-KR. +
    + simplifiedchinese + + Package simplifiedchinese provides Simplified Chinese encodings such as GBK. +
    + traditionalchinese + + Package traditionalchinese provides Traditional Chinese encodings such as Big5. +
    + unicode + + Package unicode provides Unicode encodings such as UTF-16. +
    + utf32 + + Package utf32 provides the UTF-32 Unicode encoding. +
    + language + + Package language implements BCP 47 language tags and related functionality. +
    + display + + Package display provides display names for languages, scripts and regions in a requested language. +
    + runes + + Package runes provide transforms for UTF-8 encoded text. +
    + transform + + Package transform provides reader and writer wrappers that transform the bytes passing through as well as various transformations. +
    +
    + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/golang.org/x/index.html b/pkg/golang.org/x/index.html new file mode 100644 index 0000000..bb99d7d --- /dev/null +++ b/pkg/golang.org/x/index.html @@ -0,0 +1,526 @@ + + + + + + + + /src/golang.org/x - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Directory /src/golang.org/x

    + + + + + + + + + + + + + + + + + + + +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    NameSynopsis
    ..
    + net + + +
    + context + + Package context defines the Context type, which carries deadlines, cancelation signals, and other request-scoped values across API boundaries and between processes. +
    + ctxhttp + + Package ctxhttp provides helper functions for performing context-aware HTTP requests. +
    + html + + Package html implements an HTML5-compliant tokenizer and parser. +
    + atom + + Package atom provides integer codes (also known as atoms) for a fixed set of frequently occurring HTML strings: tag names and attribute keys such as "p" and "id". +
    + charset + + Package charset provides common text encodings for HTML documents. +
    + oauth2 + + Package oauth2 provides support for making OAuth2 authorized and authenticated HTTP requests. +
    + bitbucket + + Package bitbucket provides constants for using OAuth2 to access Bitbucket. +
    + clientcredentials + + Package clientcredentials implements the OAuth2.0 "client credentials" token flow, also known as the "two-legged OAuth 2.0". +
    + facebook + + Package facebook provides constants for using OAuth2 to access Facebook. +
    + fitbit + + Package fitbit provides constants for using OAuth2 to access the Fitbit API. +
    + github + + Package github provides constants for using OAuth2 to access Github. +
    + google + + Package google provides support for making OAuth2 authorized and authenticated HTTP requests to Google APIs. +
    + hipchat + + Package hipchat provides constants for using OAuth2 to access HipChat. +
    + jws + + Package jws provides encoding and decoding utilities for signed JWS messages. +
    + jwt + + Package jwt implements the OAuth 2.0 JSON Web Token flow, commonly known as "two-legged OAuth 2.0". +
    + linkedin + + Package linkedin provides constants for using OAuth2 to access LinkedIn. +
    + microsoft + + Package microsoft provides constants for using OAuth2 to access Windows Live ID. +
    + odnoklassniki + + Package odnoklassniki provides constants for using OAuth2 to access Odnoklassniki. +
    + paypal + + Package paypal provides constants for using OAuth2 to access PayPal. +
    + slack + + Package slack provides constants for using OAuth2 to access Slack. +
    + vk + + Package vk provides constants for using OAuth2 to access VK.com. +
    + text + + +
    + encoding + + Package encoding defines an interface for character encodings, such as Shift JIS and Windows 1252, that can convert to and from UTF-8. +
    + charmap + + Package charmap provides simple character encodings such as IBM Code Page 437 and Windows 1252. +
    + htmlindex + + Package htmlindex maps character set encoding names to Encodings as recommended by the W3C for use in HTML 5. +
    + ianaindex + + Package ianaindex maps names to Encodings as specified by the IANA registry. +
    + japanese + + Package japanese provides Japanese encodings such as EUC-JP and Shift JIS. +
    + korean + + Package korean provides Korean encodings such as EUC-KR. +
    + simplifiedchinese + + Package simplifiedchinese provides Simplified Chinese encodings such as GBK. +
    + traditionalchinese + + Package traditionalchinese provides Traditional Chinese encodings such as Big5. +
    + unicode + + Package unicode provides Unicode encodings such as UTF-16. +
    + utf32 + + Package utf32 provides the UTF-32 Unicode encoding. +
    + language + + Package language implements BCP 47 language tags and related functionality. +
    + display + + Package display provides display names for languages, scripts and regions in a requested language. +
    + runes + + Package runes provide transforms for UTF-8 encoded text. +
    + transform + + Package transform provides reader and writer wrappers that transform the bytes passing through as well as various transformations. +
    +
    + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/golang.org/x/net/context/ctxhttp/index.html b/pkg/golang.org/x/net/context/ctxhttp/index.html new file mode 100644 index 0000000..d9c7503 --- /dev/null +++ b/pkg/golang.org/x/net/context/ctxhttp/index.html @@ -0,0 +1,279 @@ + + + + + + + + ctxhttp - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Package ctxhttp

    + + + + + + + + + + + + + + +
    +
    +
    import "golang.org/x/net/context/ctxhttp"
    +
    +
    +
    Overview
    +
    Index
    + + +
    +
    + +
    + +
    +

    Overview ▾

    + +
    +
    + + + + + + + + + + + +

    func Do

    +
    func Do(ctx context.Context, client *http.Client, req *http.Request) (*http.Response, error)
    +

    +Do sends an HTTP request with the provided http.Client and returns an HTTP response. +If the client is nil, http.DefaultClient is used. +If the context is canceled or times out, ctx.Err() will be returned. +

    + + + + + + + +

    func Get

    +
    func Get(ctx context.Context, client *http.Client, url string) (*http.Response, error)
    +

    +Get issues a GET request via the Do function. +

    + + + + + + + + +
    func Head(ctx context.Context, client *http.Client, url string) (*http.Response, error)
    +

    +Head issues a HEAD request via the Do function. +

    + + + + + + + +

    func Post

    +
    func Post(ctx context.Context, client *http.Client, url string, bodyType string, body io.Reader) (*http.Response, error)
    +

    +Post issues a POST request via the Do function. +

    + + + + + + + +

    func PostForm

    +
    func PostForm(ctx context.Context, client *http.Client, url string, data url.Values) (*http.Response, error)
    +

    +PostForm issues a POST request via the Do function. +

    + + + + + + + + + + + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/golang.org/x/net/context/index.html b/pkg/golang.org/x/net/context/index.html new file mode 100644 index 0000000..bb443b3 --- /dev/null +++ b/pkg/golang.org/x/net/context/index.html @@ -0,0 +1,604 @@ + + + + + + + + context - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Package context

    + + + + + + + + + + + + + + +
    +
    +
    import "golang.org/x/net/context"
    +
    +
    +
    Overview
    +
    Index
    + +
    Examples
    + + +
    Subdirectories
    + +
    +
    + +
    + +
    +

    Overview ▾

    +

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

    +

    +Incoming requests to a server should create a Context, and outgoing calls to +servers should accept a Context. The chain of function calls between must +propagate the Context, optionally replacing it with a modified copy created +using WithDeadline, WithTimeout, WithCancel, or WithValue. +

    +

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

    +

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

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

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

    +

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

    +

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

    +

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

    + +
    +
    + + + + + + + + +

    Variables

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

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

    + + +
    var DeadlineExceeded = errors.New("context deadline exceeded")
    +

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

    + + + + + + + +

    type CancelFunc

    +
    type CancelFunc func()
    +

    +A CancelFunc tells an operation to abandon its work. +A CancelFunc does not wait for the work to stop. +After the first call, subsequent calls to a CancelFunc do nothing. +

    + + + + + + + + + + + + + + + + +

    type Context

    +
    type Context interface {
    +    // Deadline returns the time when work done on behalf of this context
    +    // should be canceled.  Deadline returns ok==false when no deadline is
    +    // set.  Successive calls to Deadline return the same results.
    +    Deadline() (deadline time.Time, ok bool)
    +
    +    // Done returns a channel that's closed when work done on behalf of this
    +    // context should be canceled.  Done may return nil if this context can
    +    // never be canceled.  Successive calls to Done return the same value.
    +    //
    +    // WithCancel arranges for Done to be closed when cancel is called;
    +    // WithDeadline arranges for Done to be closed when the deadline
    +    // expires; WithTimeout arranges for Done to be closed when the timeout
    +    // elapses.
    +    //
    +    // Done is provided for use in select statements:
    +    //
    +    //  // Stream generates values with DoSomething and sends them to out
    +    //  // until DoSomething returns an error or ctx.Done is closed.
    +    //  func Stream(ctx context.Context, out chan<- Value) error {
    +    //  	for {
    +    //  		v, err := DoSomething(ctx)
    +    //  		if err != nil {
    +    //  			return err
    +    //  		}
    +    //  		select {
    +    //  		case <-ctx.Done():
    +    //  			return ctx.Err()
    +    //  		case out <- v:
    +    //  		}
    +    //  	}
    +    //  }
    +    //
    +    // See http://blog.golang.org/pipelines for more examples of how to use
    +    // a Done channel for cancelation.
    +    Done() <-chan struct{}
    +
    +    // Err returns a non-nil error value after Done is closed.  Err returns
    +    // Canceled if the context was canceled or DeadlineExceeded if the
    +    // context's deadline passed.  No other values for Err are defined.
    +    // After Done is closed, successive calls to Err return the same value.
    +    Err() error
    +
    +    // Value returns the value associated with this context for key, or nil
    +    // if no value is associated with key.  Successive calls to Value with
    +    // the same key returns the same result.
    +    //
    +    // Use context values only for request-scoped data that transits
    +    // processes and API boundaries, not for passing optional parameters to
    +    // functions.
    +    //
    +    // A key identifies a specific value in a Context.  Functions that wish
    +    // to store values in Context typically allocate a key in a global
    +    // variable then use that key as the argument to context.WithValue and
    +    // Context.Value.  A key can be any type that supports equality;
    +    // packages should define keys as an unexported type to avoid
    +    // collisions.
    +    //
    +    // Packages that define a Context key should provide type-safe accessors
    +    // for the values stores using that key:
    +    //
    +    // 	// Package user defines a User type that's stored in Contexts.
    +    // 	package user
    +    //
    +    // 	import "golang.org/x/net/context"
    +    //
    +    // 	// User is the type of value stored in the Contexts.
    +    // 	type User struct {...}
    +    //
    +    // 	// key is an unexported type for keys defined in this package.
    +    // 	// This prevents collisions with keys defined in other packages.
    +    // 	type key int
    +    //
    +    // 	// userKey is the key for user.User values in Contexts.  It is
    +    // 	// unexported; clients use user.NewContext and user.FromContext
    +    // 	// instead of using this key directly.
    +    // 	var userKey key = 0
    +    //
    +    // 	// NewContext returns a new Context that carries value u.
    +    // 	func NewContext(ctx context.Context, u *User) context.Context {
    +    // 		return context.WithValue(ctx, userKey, u)
    +    // 	}
    +    //
    +    // 	// FromContext returns the User value stored in ctx, if any.
    +    // 	func FromContext(ctx context.Context) (*User, bool) {
    +    // 		u, ok := ctx.Value(userKey).(*User)
    +    // 		return u, ok
    +    // 	}
    +    Value(key interface{}) interface{}
    +}
    +

    +A Context carries a deadline, a cancelation signal, and other values across +API boundaries. +

    +

    +Context's methods may be called by multiple goroutines simultaneously. +

    + + + + + + + + + + + + +

    func Background

    +
    func Background() Context
    +

    +Background returns a non-nil, empty Context. It is never canceled, has no +values, and has no deadline. It is typically used by the main function, +initialization, and tests, and as the top-level Context for incoming +requests. +

    + + + + + +

    func TODO

    +
    func TODO() Context
    +

    +TODO returns a non-nil, empty Context. Code should use context.TODO when +it's unclear which Context to use or it is not yet available (because the +surrounding function has not yet been extended to accept a Context +parameter). TODO is recognized by static analysis tools that determine +whether Contexts are propagated correctly in a program. +

    + + + + + +

    func WithCancel

    +
    func WithCancel(parent Context) (ctx Context, cancel CancelFunc)
    +

    +WithCancel returns a copy of parent with a new Done channel. The returned +context's Done channel is closed when the returned cancel function is called +or when the parent context's Done channel is closed, whichever happens first. +

    +

    +Canceling this context releases resources associated with it, so code should +call cancel as soon as the operations running in this Context complete. +

    + + + + + +

    func WithDeadline

    +
    func WithDeadline(parent Context, deadline time.Time) (Context, CancelFunc)
    +

    +WithDeadline returns a copy of the parent context with the deadline adjusted +to be no later than d. If the parent's deadline is already earlier than d, +WithDeadline(parent, d) is semantically equivalent to parent. The returned +context's Done channel is closed when the deadline expires, when the returned +cancel function is called, or when the parent context's Done channel is +closed, whichever happens first. +

    +

    +Canceling this context releases resources associated with it, so code should +call cancel as soon as the operations running in this Context complete. +

    + + + + + +

    func WithTimeout

    +
    func WithTimeout(parent Context, timeout time.Duration) (Context, CancelFunc)
    +

    +WithTimeout returns WithDeadline(parent, time.Now().Add(timeout)). +

    +

    +Canceling this context releases resources associated with it, so code should +call cancel as soon as the operations running in this Context complete: +

    +
    func slowOperationWithTimeout(ctx context.Context) (Result, error) {
    +	ctx, cancel := context.WithTimeout(ctx, 100*time.Millisecond)
    +	defer cancel()  // releases resources if slowOperation completes before timeout elapses
    +	return slowOperation(ctx)
    +}
    +
    + +
    + +
    +

    Example

    + + + +

    Code:

    +
    // Pass a context with a timeout to tell a blocking function that it
    +// should abandon its work after the timeout elapses.
    +ctx, _ := context.WithTimeout(context.Background(), 100*time.Millisecond)
    +select {
    +case <-time.After(200 * time.Millisecond):
    +    fmt.Println("overslept")
    +case <-ctx.Done():
    +    fmt.Println(ctx.Err()) // prints "context deadline exceeded"
    +}
    +
    + +

    Output:

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

    func WithValue

    +
    func WithValue(parent Context, key interface{}, val interface{}) Context
    +

    +WithValue returns a copy of parent in which the value associated with key is +val. +

    +

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

    + + + + + + + + + + + + + + + + + +

    Subdirectories

    + + + + +
    + + + + + + + + + + + + + + + + + + + + +
    NameSynopsis
    ..
    + ctxhttp + + Package ctxhttp provides helper functions for performing context-aware HTTP requests. +
    +
    + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/golang.org/x/net/html/atom/index.html b/pkg/golang.org/x/net/html/atom/index.html new file mode 100644 index 0000000..88706df --- /dev/null +++ b/pkg/golang.org/x/net/html/atom/index.html @@ -0,0 +1,631 @@ + + + + + + + + atom - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Package atom

    + + + + + + + + + + + + + + +
    +
    +
    import "golang.org/x/net/html/atom"
    +
    +
    +
    Overview
    +
    Index
    + + +
    +
    + +
    + +
    +

    Overview ▾

    +

    +Package atom provides integer codes (also known as atoms) for a fixed set of +frequently occurring HTML strings: tag names and attribute keys such as "p" +and "id". +

    +

    +Sharing an atom's name between all elements with the same tag can result in +fewer string allocations when tokenizing and parsing HTML. Integer +comparisons are also generally faster than string comparisons. +

    +

    +The value of an atom's particular code is not guaranteed to stay the same +between versions of this package. Neither is any ordering guaranteed: +whether atom.H1 < atom.H2 may also change. The codes are not guaranteed to +be dense. The only guarantees are that e.g. looking up "div" will yield +atom.Div, calling atom.Div.String will return "div", and atom.Div != 0. +

    + +
    +
    + + +
    + +
    +

    Index ▾

    + + + + + + + +

    Package files

    +

    + + + atom.go + + table.go + + +

    + +
    +
    + + + + + + + + +

    func String

    +
    func String(s []byte) string
    +

    +String returns a string whose contents are equal to s. In that sense, it is +equivalent to string(s) but may be more efficient. +

    + + + + + + + + +

    type Atom

    +
    type Atom uint32
    +

    +Atom is an integer code for a string. The zero value maps to "". +

    + + + +
    const (
    +    A                   Atom = 0x1
    +    Abbr                Atom = 0x4
    +    Accept              Atom = 0x2106
    +    AcceptCharset       Atom = 0x210e
    +    Accesskey           Atom = 0x3309
    +    Action              Atom = 0x1f606
    +    Address             Atom = 0x4f307
    +    Align               Atom = 0x1105
    +    Alt                 Atom = 0x4503
    +    Annotation          Atom = 0x1670a
    +    AnnotationXml       Atom = 0x1670e
    +    Applet              Atom = 0x2b306
    +    Area                Atom = 0x2fa04
    +    Article             Atom = 0x38807
    +    Aside               Atom = 0x8305
    +    Async               Atom = 0x7b05
    +    Audio               Atom = 0xa605
    +    Autocomplete        Atom = 0x1fc0c
    +    Autofocus           Atom = 0xb309
    +    Autoplay            Atom = 0xce08
    +    B                   Atom = 0x101
    +    Base                Atom = 0xd604
    +    Basefont            Atom = 0xd608
    +    Bdi                 Atom = 0x1a03
    +    Bdo                 Atom = 0xe703
    +    Bgsound             Atom = 0x11807
    +    Big                 Atom = 0x12403
    +    Blink               Atom = 0x12705
    +    Blockquote          Atom = 0x12c0a
    +    Body                Atom = 0x2f04
    +    Br                  Atom = 0x202
    +    Button              Atom = 0x13606
    +    Canvas              Atom = 0x7f06
    +    Caption             Atom = 0x1bb07
    +    Center              Atom = 0x5b506
    +    Challenge           Atom = 0x21f09
    +    Charset             Atom = 0x2807
    +    Checked             Atom = 0x32807
    +    Cite                Atom = 0x3c804
    +    Class               Atom = 0x4de05
    +    Code                Atom = 0x14904
    +    Col                 Atom = 0x15003
    +    Colgroup            Atom = 0x15008
    +    Color               Atom = 0x15d05
    +    Cols                Atom = 0x16204
    +    Colspan             Atom = 0x16207
    +    Command             Atom = 0x17507
    +    Content             Atom = 0x42307
    +    Contenteditable     Atom = 0x4230f
    +    Contextmenu         Atom = 0x3310b
    +    Controls            Atom = 0x18808
    +    Coords              Atom = 0x19406
    +    Crossorigin         Atom = 0x19f0b
    +    Data                Atom = 0x44a04
    +    Datalist            Atom = 0x44a08
    +    Datetime            Atom = 0x23c08
    +    Dd                  Atom = 0x26702
    +    Default             Atom = 0x8607
    +    Defer               Atom = 0x14b05
    +    Del                 Atom = 0x3ef03
    +    Desc                Atom = 0x4db04
    +    Details             Atom = 0x4807
    +    Dfn                 Atom = 0x6103
    +    Dialog              Atom = 0x1b06
    +    Dir                 Atom = 0x6903
    +    Dirname             Atom = 0x6907
    +    Disabled            Atom = 0x10c08
    +    Div                 Atom = 0x11303
    +    Dl                  Atom = 0x11e02
    +    Download            Atom = 0x40008
    +    Draggable           Atom = 0x17b09
    +    Dropzone            Atom = 0x39108
    +    Dt                  Atom = 0x50902
    +    Em                  Atom = 0x6502
    +    Embed               Atom = 0x6505
    +    Enctype             Atom = 0x21107
    +    Face                Atom = 0x5b304
    +    Fieldset            Atom = 0x1b008
    +    Figcaption          Atom = 0x1b80a
    +    Figure              Atom = 0x1cc06
    +    Font                Atom = 0xda04
    +    Footer              Atom = 0x8d06
    +    For                 Atom = 0x1d803
    +    ForeignObject       Atom = 0x1d80d
    +    Foreignobject       Atom = 0x1e50d
    +    Form                Atom = 0x1f204
    +    Formaction          Atom = 0x1f20a
    +    Formenctype         Atom = 0x20d0b
    +    Formmethod          Atom = 0x2280a
    +    Formnovalidate      Atom = 0x2320e
    +    Formtarget          Atom = 0x2470a
    +    Frame               Atom = 0x9a05
    +    Frameset            Atom = 0x9a08
    +    H1                  Atom = 0x26e02
    +    H2                  Atom = 0x29402
    +    H3                  Atom = 0x2a702
    +    H4                  Atom = 0x2e902
    +    H5                  Atom = 0x2f302
    +    H6                  Atom = 0x50b02
    +    Head                Atom = 0x2d504
    +    Header              Atom = 0x2d506
    +    Headers             Atom = 0x2d507
    +    Height              Atom = 0x25106
    +    Hgroup              Atom = 0x25906
    +    Hidden              Atom = 0x26506
    +    High                Atom = 0x26b04
    +    Hr                  Atom = 0x27002
    +    Href                Atom = 0x27004
    +    Hreflang            Atom = 0x27008
    +    Html                Atom = 0x25504
    +    HttpEquiv           Atom = 0x2780a
    +    I                   Atom = 0x601
    +    Icon                Atom = 0x42204
    +    Id                  Atom = 0x8502
    +    Iframe              Atom = 0x29606
    +    Image               Atom = 0x29c05
    +    Img                 Atom = 0x2a103
    +    Input               Atom = 0x3e805
    +    Inputmode           Atom = 0x3e809
    +    Ins                 Atom = 0x1a803
    +    Isindex             Atom = 0x2a907
    +    Ismap               Atom = 0x2b005
    +    Itemid              Atom = 0x33c06
    +    Itemprop            Atom = 0x3c908
    +    Itemref             Atom = 0x5ad07
    +    Itemscope           Atom = 0x2b909
    +    Itemtype            Atom = 0x2c308
    +    Kbd                 Atom = 0x1903
    +    Keygen              Atom = 0x3906
    +    Keytype             Atom = 0x53707
    +    Kind                Atom = 0x10904
    +    Label               Atom = 0xf005
    +    Lang                Atom = 0x27404
    +    Legend              Atom = 0x18206
    +    Li                  Atom = 0x1202
    +    Link                Atom = 0x12804
    +    List                Atom = 0x44e04
    +    Listing             Atom = 0x44e07
    +    Loop                Atom = 0xf404
    +    Low                 Atom = 0x11f03
    +    Malignmark          Atom = 0x100a
    +    Manifest            Atom = 0x5f108
    +    Map                 Atom = 0x2b203
    +    Mark                Atom = 0x1604
    +    Marquee             Atom = 0x2cb07
    +    Math                Atom = 0x2d204
    +    Max                 Atom = 0x2e103
    +    Maxlength           Atom = 0x2e109
    +    Media               Atom = 0x6e05
    +    Mediagroup          Atom = 0x6e0a
    +    Menu                Atom = 0x33804
    +    Menuitem            Atom = 0x33808
    +    Meta                Atom = 0x45d04
    +    Meter               Atom = 0x24205
    +    Method              Atom = 0x22c06
    +    Mglyph              Atom = 0x2a206
    +    Mi                  Atom = 0x2eb02
    +    Min                 Atom = 0x2eb03
    +    Minlength           Atom = 0x2eb09
    +    Mn                  Atom = 0x23502
    +    Mo                  Atom = 0x3ed02
    +    Ms                  Atom = 0x2bc02
    +    Mtext               Atom = 0x2f505
    +    Multiple            Atom = 0x30308
    +    Muted               Atom = 0x30b05
    +    Name                Atom = 0x6c04
    +    Nav                 Atom = 0x3e03
    +    Nobr                Atom = 0x5704
    +    Noembed             Atom = 0x6307
    +    Noframes            Atom = 0x9808
    +    Noscript            Atom = 0x3d208
    +    Novalidate          Atom = 0x2360a
    +    Object              Atom = 0x1ec06
    +    Ol                  Atom = 0xc902
    +    Onabort             Atom = 0x13a07
    +    Onafterprint        Atom = 0x1c00c
    +    Onautocomplete      Atom = 0x1fa0e
    +    Onautocompleteerror Atom = 0x1fa13
    +    Onbeforeprint       Atom = 0x6040d
    +    Onbeforeunload      Atom = 0x4e70e
    +    Onblur              Atom = 0xaa06
    +    Oncancel            Atom = 0xe908
    +    Oncanplay           Atom = 0x28509
    +    Oncanplaythrough    Atom = 0x28510
    +    Onchange            Atom = 0x3a708
    +    Onclick             Atom = 0x31007
    +    Onclose             Atom = 0x31707
    +    Oncontextmenu       Atom = 0x32f0d
    +    Oncuechange         Atom = 0x3420b
    +    Ondblclick          Atom = 0x34d0a
    +    Ondrag              Atom = 0x35706
    +    Ondragend           Atom = 0x35709
    +    Ondragenter         Atom = 0x3600b
    +    Ondragleave         Atom = 0x36b0b
    +    Ondragover          Atom = 0x3760a
    +    Ondragstart         Atom = 0x3800b
    +    Ondrop              Atom = 0x38f06
    +    Ondurationchange    Atom = 0x39f10
    +    Onemptied           Atom = 0x39609
    +    Onended             Atom = 0x3af07
    +    Onerror             Atom = 0x3b607
    +    Onfocus             Atom = 0x3bd07
    +    Onhashchange        Atom = 0x3da0c
    +    Oninput             Atom = 0x3e607
    +    Oninvalid           Atom = 0x3f209
    +    Onkeydown           Atom = 0x3fb09
    +    Onkeypress          Atom = 0x4080a
    +    Onkeyup             Atom = 0x41807
    +    Onlanguagechange    Atom = 0x43210
    +    Onload              Atom = 0x44206
    +    Onloadeddata        Atom = 0x4420c
    +    Onloadedmetadata    Atom = 0x45510
    +    Onloadstart         Atom = 0x46b0b
    +    Onmessage           Atom = 0x47609
    +    Onmousedown         Atom = 0x47f0b
    +    Onmousemove         Atom = 0x48a0b
    +    Onmouseout          Atom = 0x4950a
    +    Onmouseover         Atom = 0x4a20b
    +    Onmouseup           Atom = 0x4ad09
    +    Onmousewheel        Atom = 0x4b60c
    +    Onoffline           Atom = 0x4c209
    +    Ononline            Atom = 0x4cb08
    +    Onpagehide          Atom = 0x4d30a
    +    Onpageshow          Atom = 0x4fe0a
    +    Onpause             Atom = 0x50d07
    +    Onplay              Atom = 0x51706
    +    Onplaying           Atom = 0x51709
    +    Onpopstate          Atom = 0x5200a
    +    Onprogress          Atom = 0x52a0a
    +    Onratechange        Atom = 0x53e0c
    +    Onreset             Atom = 0x54a07
    +    Onresize            Atom = 0x55108
    +    Onscroll            Atom = 0x55f08
    +    Onseeked            Atom = 0x56708
    +    Onseeking           Atom = 0x56f09
    +    Onselect            Atom = 0x57808
    +    Onshow              Atom = 0x58206
    +    Onsort              Atom = 0x58b06
    +    Onstalled           Atom = 0x59509
    +    Onstorage           Atom = 0x59e09
    +    Onsubmit            Atom = 0x5a708
    +    Onsuspend           Atom = 0x5bb09
    +    Ontimeupdate        Atom = 0xdb0c
    +    Ontoggle            Atom = 0x5c408
    +    Onunload            Atom = 0x5cc08
    +    Onvolumechange      Atom = 0x5d40e
    +    Onwaiting           Atom = 0x5e209
    +    Open                Atom = 0x3cf04
    +    Optgroup            Atom = 0xf608
    +    Optimum             Atom = 0x5eb07
    +    Option              Atom = 0x60006
    +    Output              Atom = 0x49c06
    +    P                   Atom = 0xc01
    +    Param               Atom = 0xc05
    +    Pattern             Atom = 0x5107
    +    Ping                Atom = 0x7704
    +    Placeholder         Atom = 0xc30b
    +    Plaintext           Atom = 0xfd09
    +    Poster              Atom = 0x15706
    +    Pre                 Atom = 0x25e03
    +    Preload             Atom = 0x25e07
    +    Progress            Atom = 0x52c08
    +    Prompt              Atom = 0x5fa06
    +    Public              Atom = 0x41e06
    +    Q                   Atom = 0x13101
    +    Radiogroup          Atom = 0x30a
    +    Readonly            Atom = 0x2fb08
    +    Rel                 Atom = 0x25f03
    +    Required            Atom = 0x1d008
    +    Reversed            Atom = 0x5a08
    +    Rows                Atom = 0x9204
    +    Rowspan             Atom = 0x9207
    +    Rp                  Atom = 0x1c602
    +    Rt                  Atom = 0x13f02
    +    Ruby                Atom = 0xaf04
    +    S                   Atom = 0x2c01
    +    Samp                Atom = 0x4e04
    +    Sandbox             Atom = 0xbb07
    +    Scope               Atom = 0x2bd05
    +    Scoped              Atom = 0x2bd06
    +    Script              Atom = 0x3d406
    +    Seamless            Atom = 0x31c08
    +    Section             Atom = 0x4e207
    +    Select              Atom = 0x57a06
    +    Selected            Atom = 0x57a08
    +    Shape               Atom = 0x4f905
    +    Size                Atom = 0x55504
    +    Sizes               Atom = 0x55505
    +    Small               Atom = 0x18f05
    +    Sortable            Atom = 0x58d08
    +    Sorted              Atom = 0x19906
    +    Source              Atom = 0x1aa06
    +    Spacer              Atom = 0x2db06
    +    Span                Atom = 0x9504
    +    Spellcheck          Atom = 0x3230a
    +    Src                 Atom = 0x3c303
    +    Srcdoc              Atom = 0x3c306
    +    Srclang             Atom = 0x41107
    +    Start               Atom = 0x38605
    +    Step                Atom = 0x5f704
    +    Strike              Atom = 0x53306
    +    Strong              Atom = 0x55906
    +    Style               Atom = 0x61105
    +    Sub                 Atom = 0x5a903
    +    Summary             Atom = 0x61607
    +    Sup                 Atom = 0x61d03
    +    Svg                 Atom = 0x62003
    +    System              Atom = 0x62306
    +    Tabindex            Atom = 0x46308
    +    Table               Atom = 0x42d05
    +    Target              Atom = 0x24b06
    +    Tbody               Atom = 0x2e05
    +    Td                  Atom = 0x4702
    +    Template            Atom = 0x62608
    +    Textarea            Atom = 0x2f608
    +    Tfoot               Atom = 0x8c05
    +    Th                  Atom = 0x22e02
    +    Thead               Atom = 0x2d405
    +    Time                Atom = 0xdd04
    +    Title               Atom = 0xa105
    +    Tr                  Atom = 0x10502
    +    Track               Atom = 0x10505
    +    Translate           Atom = 0x14009
    +    Tt                  Atom = 0x5302
    +    Type                Atom = 0x21404
    +    Typemustmatch       Atom = 0x2140d
    +    U                   Atom = 0xb01
    +    Ul                  Atom = 0x8a02
    +    Usemap              Atom = 0x51106
    +    Value               Atom = 0x4005
    +    Var                 Atom = 0x11503
    +    Video               Atom = 0x28105
    +    Wbr                 Atom = 0x12103
    +    Width               Atom = 0x50705
    +    Wrap                Atom = 0x58704
    +    Xmp                 Atom = 0xc103
    +)
    + + + + + + + + + + + +

    func Lookup

    +
    func Lookup(s []byte) Atom
    +

    +Lookup returns the atom whose name is s. It returns zero if there is no +such atom. The lookup is case sensitive. +

    + + + + + + + +

    func (Atom) String

    +
    func (a Atom) String() string
    +

    +String returns the atom's name. +

    + + + + + + + + + + + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/golang.org/x/net/html/charset/index.html b/pkg/golang.org/x/net/html/charset/index.html new file mode 100644 index 0000000..4c733db --- /dev/null +++ b/pkg/golang.org/x/net/html/charset/index.html @@ -0,0 +1,281 @@ + + + + + + + + charset - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Package charset

    + + + + + + + + + + + + + + +
    +
    +
    import "golang.org/x/net/html/charset"
    +
    +
    +
    Overview
    +
    Index
    + + +
    +
    + +
    + +
    +

    Overview ▾

    +

    +Package charset provides common text encodings for HTML documents. +

    +

    +The mapping from encoding labels to encodings is defined at +https://encoding.spec.whatwg.org/. +

    + +
    +
    + + + + + + + + + + + +

    func DetermineEncoding

    +
    func DetermineEncoding(content []byte, contentType string) (e encoding.Encoding, name string, certain bool)
    +

    +DetermineEncoding determines the encoding of an HTML document by examining +up to the first 1024 bytes of content and the declared Content-Type. +

    +

    +See http://www.whatwg.org/specs/web-apps/current-work/multipage/parsing.html#determining-the-character-encoding +

    + + + + + + + +

    func Lookup

    +
    func Lookup(label string) (e encoding.Encoding, name string)
    +

    +Lookup returns the encoding with the specified label, and its canonical +name. It returns nil and the empty string if label is not one of the +standard encodings for HTML. Matching is case-insensitive and ignores +leading and trailing whitespace. Encoders will use HTML escape sequences for +runes that are not supported by the character set. +

    + + + + + + + +

    func NewReader

    +
    func NewReader(r io.Reader, contentType string) (io.Reader, error)
    +

    +NewReader returns an io.Reader that converts the content of r to UTF-8. +It calls DetermineEncoding to find out what r's encoding is. +

    + + + + + + + +

    func NewReaderLabel

    +
    func NewReaderLabel(label string, input io.Reader) (io.Reader, error)
    +

    +NewReaderLabel returns a reader that converts from the specified charset to +UTF-8. It uses Lookup to find the encoding that corresponds to label, and +returns an error if Lookup returns nil. It is suitable for use as +encoding/xml.Decoder's CharsetReader function. +

    + + + + + + + + + + + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/golang.org/x/net/html/index.html b/pkg/golang.org/x/net/html/index.html new file mode 100644 index 0000000..64b75c3 --- /dev/null +++ b/pkg/golang.org/x/net/html/index.html @@ -0,0 +1,1080 @@ + + + + + + + + html - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Package html

    + + + + + + + + + + + + + + +
    +
    +
    import "golang.org/x/net/html"
    +
    +
    +
    Overview
    +
    Index
    + +
    Examples
    + + +
    Subdirectories
    + +
    +
    + +
    + +
    +

    Overview ▾

    +

    +Package html implements an HTML5-compliant tokenizer and parser. +

    +

    +Tokenization is done by creating a Tokenizer for an io.Reader r. It is the +caller's responsibility to ensure that r provides UTF-8 encoded HTML. +

    +
    z := html.NewTokenizer(r)
    +
    +

    +Given a Tokenizer z, the HTML is tokenized by repeatedly calling z.Next(), +which parses the next token and returns its type, or an error: +

    +
    for {
    +	tt := z.Next()
    +	if tt == html.ErrorToken {
    +		// ...
    +		return ...
    +	}
    +	// Process the current token.
    +}
    +
    +

    +There are two APIs for retrieving the current token. The high-level API is to +call Token; the low-level API is to call Text or TagName / TagAttr. Both APIs +allow optionally calling Raw after Next but before Token, Text, TagName, or +TagAttr. In EBNF notation, the valid call sequence per token is: +

    +
    Next {Raw} [ Token | Text | TagName {TagAttr} ]
    +
    +

    +Token returns an independent data structure that completely describes a token. +Entities (such as "&lt;") are unescaped, tag names and attribute keys are +lower-cased, and attributes are collected into a []Attribute. For example: +

    +
    for {
    +	if z.Next() == html.ErrorToken {
    +		// Returning io.EOF indicates success.
    +		return z.Err()
    +	}
    +	emitToken(z.Token())
    +}
    +
    +

    +The low-level API performs fewer allocations and copies, but the contents of +the []byte values returned by Text, TagName and TagAttr may change on the next +call to Next. For example, to extract an HTML page's anchor text: +

    +
    depth := 0
    +for {
    +	tt := z.Next()
    +	switch tt {
    +	case ErrorToken:
    +		return z.Err()
    +	case TextToken:
    +		if depth > 0 {
    +			// emitBytes should copy the []byte it receives,
    +			// if it doesn't process it immediately.
    +			emitBytes(z.Text())
    +		}
    +	case StartTagToken, EndTagToken:
    +		tn, _ := z.TagName()
    +		if len(tn) == 1 && tn[0] == 'a' {
    +			if tt == StartTagToken {
    +				depth++
    +			} else {
    +				depth--
    +			}
    +		}
    +	}
    +}
    +
    +

    +Parsing is done by calling Parse with an io.Reader, which returns the root of +the parse tree (the document element) as a *Node. It is the caller's +responsibility to ensure that the Reader provides UTF-8 encoded HTML. For +example, to process each anchor node in depth-first order: +

    +
    doc, err := html.Parse(r)
    +if err != nil {
    +	// ...
    +}
    +var f func(*html.Node)
    +f = func(n *html.Node) {
    +	if n.Type == html.ElementNode && n.Data == "a" {
    +		// Do something with n...
    +	}
    +	for c := n.FirstChild; c != nil; c = c.NextSibling {
    +		f(c)
    +	}
    +}
    +f(doc)
    +
    +

    +The relevant specifications include: +https://html.spec.whatwg.org/multipage/syntax.html and +https://html.spec.whatwg.org/multipage/syntax.html#tokenization +

    + +
    +
    + + +
    + +
    +

    Index ▾

    + + + + + +
    +

    Examples

    +
    + +
    Parse
    + +
    +
    + + + +

    Package files

    +

    + + + const.go + + doc.go + + doctype.go + + entity.go + + escape.go + + foreign.go + + node.go + + parse.go + + render.go + + token.go + + +

    + +
    +
    + + + + + +

    Variables

    + +
    var ErrBufferExceeded = errors.New("max buffer exceeded")
    +

    +ErrBufferExceeded means that the buffering limit was exceeded. +

    + + + + + + +

    func EscapeString

    +
    func EscapeString(s string) string
    +

    +EscapeString escapes special characters like "<" to become "&lt;". It +escapes only five such characters: <, >, &, ' and ". +UnescapeString(EscapeString(s)) == s always holds, but the converse isn't +always true. +

    + + + + + + + +

    func ParseFragment

    +
    func ParseFragment(r io.Reader, context *Node) ([]*Node, error)
    +

    +ParseFragment parses a fragment of HTML and returns the nodes that were +found. If the fragment is the InnerHTML for an existing element, pass that +element in context. +

    + + + + + + + +

    func Render

    +
    func Render(w io.Writer, n *Node) error
    +

    +Render renders the parse tree n to the given writer. +

    +

    +Rendering is done on a 'best effort' basis: calling Parse on the output of +Render will always result in something similar to the original tree, but it +is not necessarily an exact clone unless the original tree was 'well-formed'. +'Well-formed' is not easily specified; the HTML5 specification is +complicated. +

    +

    +Calling Parse on arbitrary input typically results in a 'well-formed' parse +tree. However, it is possible for Parse to yield a 'badly-formed' parse tree. +For example, in a 'well-formed' parse tree, no <a> element is a child of +another <a> element: parsing "<a><a>" results in two sibling elements. +Similarly, in a 'well-formed' parse tree, no <a> element is a child of a +<table> element: parsing "<p><table><a>" results in a <p> with two sibling +children; the <a> is reparented to the <table>'s parent. However, calling +Parse on "<a><table><a>" does not return an error, but the result has an <a> +element with an <a> child, and is therefore not 'well-formed'. +

    +

    +Programmatically constructed trees are typically also 'well-formed', but it +is possible to construct a tree that looks innocuous but, when rendered and +re-parsed, results in a different tree. A simple example is that a solitary +text node would become a tree containing <html>, <head> and <body> elements. +Another example is that the programmatic equivalent of "a<head>b</head>c" +becomes "<html><head><head/><body>abc</body></html>". +

    + + + + + + + +

    func UnescapeString

    +
    func UnescapeString(s string) string
    +

    +UnescapeString unescapes entities like "&lt;" to become "<". It unescapes a +larger range of entities than EscapeString escapes. For example, "&aacute;" +unescapes to "á", as does "&#225;" and "&xE1;". +UnescapeString(EscapeString(s)) == s always holds, but the converse isn't +always true. +

    + + + + + + + + +

    type Attribute

    +
    type Attribute struct {
    +    Namespace, Key, Val string
    +}
    +

    +An Attribute is an attribute namespace-key-value triple. Namespace is +non-empty for foreign attributes like xlink, Key is alphabetic (and hence +does not contain escapable characters like '&', '<' or '>'), and Val is +unescaped (it looks like "a<b" rather than "a&lt;b"). +

    +

    +Namespace is only used by the parser, not the tokenizer. +

    + + + + + + + + + + + + + + + + +

    type Node

    +
    type Node struct {
    +    Parent, FirstChild, LastChild, PrevSibling, NextSibling *Node
    +
    +    Type      NodeType
    +    DataAtom  atom.Atom
    +    Data      string
    +    Namespace string
    +    Attr      []Attribute
    +}
    +

    +A Node consists of a NodeType and some Data (tag name for element nodes, +content for text) and are part of a tree of Nodes. Element nodes may also +have a Namespace and contain a slice of Attributes. Data is unescaped, so +that it looks like "a<b" rather than "a&lt;b". For element nodes, DataAtom +is the atom for Data, or zero if Data is not a known tag name. +

    +

    +An empty Namespace implies a "http://www.w3.org/1999/xhtml" namespace. +Similarly, "math" is short for "http://www.w3.org/1998/Math/MathML", and +"svg" is short for "http://www.w3.org/2000/svg". +

    + + + + + + + + + + + + +

    func Parse

    +
    func Parse(r io.Reader) (*Node, error)
    +

    +Parse returns the parse tree for the HTML from the given Reader. +The input is assumed to be UTF-8 encoded. +

    + +
    + +
    +

    Example

    + + + +

    Code:

    +
    s := `<p>Links:</p><ul><li><a href="foo">Foo</a><li><a href="/bar/baz">BarBaz</a></ul>`
    +doc, err := html.Parse(strings.NewReader(s))
    +if err != nil {
    +    log.Fatal(err)
    +}
    +var f func(*html.Node)
    +f = func(n *html.Node) {
    +    if n.Type == html.ElementNode && n.Data == "a" {
    +        for _, a := range n.Attr {
    +            if a.Key == "href" {
    +                fmt.Println(a.Val)
    +                break
    +            }
    +        }
    +    }
    +    for c := n.FirstChild; c != nil; c = c.NextSibling {
    +        f(c)
    +    }
    +}
    +f(doc)
    +
    + +

    Output:

    +
    foo
    +/bar/baz
    +
    + + +
    +
    + + + + + + +

    func (*Node) AppendChild

    +
    func (n *Node) AppendChild(c *Node)
    +

    +AppendChild adds a node c as a child of n. +

    +

    +It will panic if c already has a parent or siblings. +

    + + + + + + +

    func (*Node) InsertBefore

    +
    func (n *Node) InsertBefore(newChild, oldChild *Node)
    +

    +InsertBefore inserts newChild as a child of n, immediately before oldChild +in the sequence of n's children. oldChild may be nil, in which case newChild +is appended to the end of n's children. +

    +

    +It will panic if newChild already has a parent or siblings. +

    + + + + + + +

    func (*Node) RemoveChild

    +
    func (n *Node) RemoveChild(c *Node)
    +

    +RemoveChild removes a node c that is a child of n. Afterwards, c will have +no parent and no siblings. +

    +

    +It will panic if c's parent is not n. +

    + + + + + + + + +

    type NodeType

    +
    type NodeType uint32
    +

    +A NodeType is the type of a Node. +

    + + + +
    const (
    +    ErrorNode NodeType = iota
    +    TextNode
    +    DocumentNode
    +    ElementNode
    +    CommentNode
    +    DoctypeNode
    +)
    + + + + + + + + + + + + + + + +

    type Token

    +
    type Token struct {
    +    Type     TokenType
    +    DataAtom atom.Atom
    +    Data     string
    +    Attr     []Attribute
    +}
    +

    +A Token consists of a TokenType and some Data (tag name for start and end +tags, content for text, comments and doctypes). A tag Token may also contain +a slice of Attributes. Data is unescaped for all Tokens (it looks like "a<b" +rather than "a&lt;b"). For tag Tokens, DataAtom is the atom for Data, or +zero if Data is not a known tag name. +

    + + + + + + + + + + + + + + +

    func (Token) String

    +
    func (t Token) String() string
    +

    +String returns a string representation of the Token. +

    + + + + + + + + +

    type TokenType

    +
    type TokenType uint32
    +

    +A TokenType is the type of a Token. +

    + + + +
    const (
    +    // ErrorToken means that an error occurred during tokenization.
    +    ErrorToken TokenType = iota
    +    // TextToken means a text node.
    +    TextToken
    +    // A StartTagToken looks like <a>.
    +    StartTagToken
    +    // An EndTagToken looks like </a>.
    +    EndTagToken
    +    // A SelfClosingTagToken tag looks like <br/>.
    +    SelfClosingTagToken
    +    // A CommentToken looks like <!--x-->.
    +    CommentToken
    +    // A DoctypeToken looks like <!DOCTYPE x>
    +    DoctypeToken
    +)
    + + + + + + + + + + + + + +

    func (TokenType) String

    +
    func (t TokenType) String() string
    +

    +String returns a string representation of the TokenType. +

    + + + + + + + + +

    type Tokenizer

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

    +A Tokenizer returns a stream of HTML Tokens. +

    + + + + + + + + + + + + +

    func NewTokenizer

    +
    func NewTokenizer(r io.Reader) *Tokenizer
    +

    +NewTokenizer returns a new HTML Tokenizer for the given Reader. +The input is assumed to be UTF-8 encoded. +

    + + + + + +

    func NewTokenizerFragment

    +
    func NewTokenizerFragment(r io.Reader, contextTag string) *Tokenizer
    +

    +NewTokenizerFragment returns a new HTML Tokenizer for the given Reader, for +tokenizing an existing element's InnerHTML fragment. contextTag is that +element's tag, such as "div" or "iframe". +

    +

    +For example, how the InnerHTML "a<b" is tokenized depends on whether it is +for a <p> tag or a <script> tag. +

    +

    +The input is assumed to be UTF-8 encoded. +

    + + + + + + + +

    func (*Tokenizer) AllowCDATA

    +
    func (z *Tokenizer) AllowCDATA(allowCDATA bool)
    +

    +AllowCDATA sets whether or not the tokenizer recognizes <![CDATA[foo]]> as +the text "foo". The default value is false, which means to recognize it as +a bogus comment "<!-- [CDATA[foo]] -->" instead. +

    +

    +Strictly speaking, an HTML5 compliant tokenizer should allow CDATA if and +only if tokenizing foreign content, such as MathML and SVG. However, +tracking foreign-contentness is difficult to do purely in the tokenizer, +as opposed to the parser, due to HTML integration points: an <svg> element +can contain a <foreignObject> that is foreign-to-SVG but not foreign-to- +HTML. For strict compliance with the HTML5 tokenization algorithm, it is the +responsibility of the user of a tokenizer to call AllowCDATA as appropriate. +In practice, if using the tokenizer without caring whether MathML or SVG +CDATA is text or comments, such as tokenizing HTML to find all the anchor +text, it is acceptable to ignore this responsibility. +

    + + + + + + +

    func (*Tokenizer) Buffered

    +
    func (z *Tokenizer) Buffered() []byte
    +

    +Buffered returns a slice containing data buffered but not yet tokenized. +

    + + + + + + +

    func (*Tokenizer) Err

    +
    func (z *Tokenizer) Err() error
    +

    +Err returns the error associated with the most recent ErrorToken token. +This is typically io.EOF, meaning the end of tokenization. +

    + + + + + + +

    func (*Tokenizer) Next

    +
    func (z *Tokenizer) Next() TokenType
    +

    +Next scans the next token and returns its type. +

    + + + + + + +

    func (*Tokenizer) NextIsNotRawText

    +
    func (z *Tokenizer) NextIsNotRawText()
    +

    +NextIsNotRawText instructs the tokenizer that the next token should not be +considered as 'raw text'. Some elements, such as script and title elements, +normally require the next token after the opening tag to be 'raw text' that +has no child elements. For example, tokenizing "<title>a<b>c</b>d</title>" +yields a start tag token for "<title>", a text token for "a<b>c</b>d", and +an end tag token for "</title>". There are no distinct start tag or end tag +tokens for the "<b>" and "</b>". +

    +

    +This tokenizer implementation will generally look for raw text at the right +times. Strictly speaking, an HTML5 compliant tokenizer should not look for +raw text if in foreign content: <title> generally needs raw text, but a +<title> inside an <svg> does not. Another example is that a <textarea> +generally needs raw text, but a <textarea> is not allowed as an immediate +child of a <select>; in normal parsing, a <textarea> implies </select>, but +one cannot close the implicit element when parsing a <select>'s InnerHTML. +Similarly to AllowCDATA, tracking the correct moment to override raw-text- +ness is difficult to do purely in the tokenizer, as opposed to the parser. +For strict compliance with the HTML5 tokenization algorithm, it is the +responsibility of the user of a tokenizer to call NextIsNotRawText as +appropriate. In practice, like AllowCDATA, it is acceptable to ignore this +responsibility for basic usage. +

    +

    +Note that this 'raw text' concept is different from the one offered by the +Tokenizer.Raw method. +

    + + + + + + +

    func (*Tokenizer) Raw

    +
    func (z *Tokenizer) Raw() []byte
    +

    +Raw returns the unmodified text of the current token. Calling Next, Token, +Text, TagName or TagAttr may change the contents of the returned slice. +

    + + + + + + +

    func (*Tokenizer) SetMaxBuf

    +
    func (z *Tokenizer) SetMaxBuf(n int)
    +

    +SetMaxBuf sets a limit on the amount of data buffered during tokenization. +A value of 0 means unlimited. +

    + + + + + + +

    func (*Tokenizer) TagAttr

    +
    func (z *Tokenizer) TagAttr() (key, val []byte, moreAttr bool)
    +

    +TagAttr returns the lower-cased key and unescaped value of the next unparsed +attribute for the current tag token and whether there are more attributes. +The contents of the returned slices may change on the next call to Next. +

    + + + + + + +

    func (*Tokenizer) TagName

    +
    func (z *Tokenizer) TagName() (name []byte, hasAttr bool)
    +

    +TagName returns the lower-cased name of a tag token (the `img` out of +`<IMG SRC="foo">`) and whether the tag has attributes. +The contents of the returned slice may change on the next call to Next. +

    + + + + + + +

    func (*Tokenizer) Text

    +
    func (z *Tokenizer) Text() []byte
    +

    +Text returns the unescaped text of a text, comment or doctype token. The +contents of the returned slice may change on the next call to Next. +

    + + + + + + +

    func (*Tokenizer) Token

    +
    func (z *Tokenizer) Token() Token
    +

    +Token returns the next Token. The result's Data and Attr values remain valid +after subsequent Next calls. +

    + + + + + + + + + + + + + + + + +

    Subdirectories

    + + + + +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    NameSynopsis
    ..
    + atom + + Package atom provides integer codes (also known as atoms) for a fixed set of frequently occurring HTML strings: tag names and attribute keys such as "p" and "id". +
    + charset + + Package charset provides common text encodings for HTML documents. +
    +
    + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/golang.org/x/net/index.html b/pkg/golang.org/x/net/index.html new file mode 100644 index 0000000..6e11a19 --- /dev/null +++ b/pkg/golang.org/x/net/index.html @@ -0,0 +1,174 @@ + + + + + + + + /src/golang.org/x/net - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Directory /src/golang.org/x/net

    + + + + + + + + + + + + + + + + + + + +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    NameSynopsis
    ..
    + context + + Package context defines the Context type, which carries deadlines, cancelation signals, and other request-scoped values across API boundaries and between processes. +
    + ctxhttp + + Package ctxhttp provides helper functions for performing context-aware HTTP requests. +
    + html + + Package html implements an HTML5-compliant tokenizer and parser. +
    + atom + + Package atom provides integer codes (also known as atoms) for a fixed set of frequently occurring HTML strings: tag names and attribute keys such as "p" and "id". +
    + charset + + Package charset provides common text encodings for HTML documents. +
    +
    + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/golang.org/x/oauth2/bitbucket/index.html b/pkg/golang.org/x/oauth2/bitbucket/index.html new file mode 100644 index 0000000..cf15b33 --- /dev/null +++ b/pkg/golang.org/x/oauth2/bitbucket/index.html @@ -0,0 +1,219 @@ + + + + + + + + bitbucket - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Package bitbucket

    + + + + + + + + + + + + + + +
    +
    +
    import "golang.org/x/oauth2/bitbucket"
    +
    +
    +
    Overview
    +
    Index
    + + +
    +
    + +
    + +
    +

    Overview ▾

    +

    +Package bitbucket provides constants for using OAuth2 to access Bitbucket. +

    + +
    +
    + + +
    + +
    +

    Index ▾

    + + +
    +
    + + +
    Variables
    + + + + +
    +
    + + + + +

    Package files

    +

    + + + bitbucket.go + + +

    + +
    +
    + + + + + +

    Variables

    + +
    var Endpoint = oauth2.Endpoint{
    +    AuthURL:  "https://bitbucket.org/site/oauth2/authorize",
    +    TokenURL: "https://bitbucket.org/site/oauth2/access_token",
    +}
    +

    +Endpoint is Bitbucket's OAuth 2.0 endpoint. +

    + + + + + + + + + + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/golang.org/x/oauth2/clientcredentials/index.html b/pkg/golang.org/x/oauth2/clientcredentials/index.html new file mode 100644 index 0000000..bb3d1c7 --- /dev/null +++ b/pkg/golang.org/x/oauth2/clientcredentials/index.html @@ -0,0 +1,307 @@ + + + + + + + + clientcredentials - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Package clientcredentials

    + + + + + + + + + + + + + + +
    +
    +
    import "golang.org/x/oauth2/clientcredentials"
    +
    +
    +
    Overview
    +
    Index
    + + +
    +
    + +
    + +
    +

    Overview ▾

    +

    +Package clientcredentials implements the OAuth2.0 "client credentials" token flow, +also known as the "two-legged OAuth 2.0". +

    +

    +This should be used when the client is acting on its own behalf or when the client +is the resource owner. It may also be used when requesting access to protected +resources based on an authorization previously arranged with the authorization +server. +

    +

    +See http://tools.ietf.org/html/draft-ietf-oauth-v2-31#section-4.4 +

    + +
    +
    + + +
    + + +
    + + + + + + + + + +

    type Config

    +
    type Config struct {
    +    // ClientID is the application's ID.
    +    ClientID string
    +
    +    // ClientSecret is the application's secret.
    +    ClientSecret string
    +
    +    // TokenURL is the resource server's token endpoint
    +    // URL. This is a constant specific to each server.
    +    TokenURL string
    +
    +    // Scope specifies optional requested permissions.
    +    Scopes []string
    +}
    +

    +Client Credentials Config describes a 2-legged OAuth2 flow, with both the +client application information and the server's endpoint URLs. +

    + + + + + + + + + + + + + + +

    func (*Config) Client

    +
    func (c *Config) Client(ctx context.Context) *http.Client
    +

    +Client returns an HTTP client using the provided token. +The token will auto-refresh as necessary. The underlying +HTTP transport will be obtained using the provided context. +The returned client and its Transport should not be modified. +

    + + + + + + +

    func (*Config) Token

    +
    func (c *Config) Token(ctx context.Context) (*oauth2.Token, error)
    +

    +Token uses client credentials to retrieve a token. +The HTTP client to use is derived from the context. +If nil, http.DefaultClient is used. +

    + + + + + + +

    func (*Config) TokenSource

    +
    func (c *Config) TokenSource(ctx context.Context) oauth2.TokenSource
    +

    +TokenSource returns a TokenSource that returns t until t expires, +automatically refreshing it as necessary using the provided context and the +client ID and client secret. +

    +

    +Most users will use Config.Client instead. +

    + + + + + + + + + + + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/golang.org/x/oauth2/facebook/index.html b/pkg/golang.org/x/oauth2/facebook/index.html new file mode 100644 index 0000000..be3a9da --- /dev/null +++ b/pkg/golang.org/x/oauth2/facebook/index.html @@ -0,0 +1,219 @@ + + + + + + + + facebook - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Package facebook

    + + + + + + + + + + + + + + +
    +
    +
    import "golang.org/x/oauth2/facebook"
    +
    +
    +
    Overview
    +
    Index
    + + +
    +
    + +
    + +
    +

    Overview ▾

    +

    +Package facebook provides constants for using OAuth2 to access Facebook. +

    + +
    +
    + + +
    + +
    +

    Index ▾

    + + +
    +
    + + +
    Variables
    + + + + +
    +
    + + + + +

    Package files

    +

    + + + facebook.go + + +

    + +
    +
    + + + + + +

    Variables

    + +
    var Endpoint = oauth2.Endpoint{
    +    AuthURL:  "https://www.facebook.com/dialog/oauth",
    +    TokenURL: "https://graph.facebook.com/oauth/access_token",
    +}
    +

    +Endpoint is Facebook's OAuth 2.0 endpoint. +

    + + + + + + + + + + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/golang.org/x/oauth2/fitbit/index.html b/pkg/golang.org/x/oauth2/fitbit/index.html new file mode 100644 index 0000000..4ec1f41 --- /dev/null +++ b/pkg/golang.org/x/oauth2/fitbit/index.html @@ -0,0 +1,219 @@ + + + + + + + + fitbit - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Package fitbit

    + + + + + + + + + + + + + + +
    +
    +
    import "golang.org/x/oauth2/fitbit"
    +
    +
    +
    Overview
    +
    Index
    + + +
    +
    + +
    + +
    +

    Overview ▾

    +

    +Package fitbit provides constants for using OAuth2 to access the Fitbit API. +

    + +
    +
    + + +
    + +
    +

    Index ▾

    + + +
    +
    + + +
    Variables
    + + + + +
    +
    + + + + +

    Package files

    +

    + + + fitbit.go + + +

    + +
    +
    + + + + + +

    Variables

    + +
    var Endpoint = oauth2.Endpoint{
    +    AuthURL:  "https://www.fitbit.com/oauth2/authorize",
    +    TokenURL: "https://api.fitbit.com/oauth2/token",
    +}
    +

    +Endpoint is the Fitbit API's OAuth 2.0 endpoint. +

    + + + + + + + + + + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/golang.org/x/oauth2/github/index.html b/pkg/golang.org/x/oauth2/github/index.html new file mode 100644 index 0000000..d2b57c8 --- /dev/null +++ b/pkg/golang.org/x/oauth2/github/index.html @@ -0,0 +1,219 @@ + + + + + + + + github - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Package github

    + + + + + + + + + + + + + + +
    +
    +
    import "golang.org/x/oauth2/github"
    +
    +
    +
    Overview
    +
    Index
    + + +
    +
    + +
    + +
    +

    Overview ▾

    +

    +Package github provides constants for using OAuth2 to access Github. +

    + +
    +
    + + +
    + +
    +

    Index ▾

    + + +
    +
    + + +
    Variables
    + + + + +
    +
    + + + + +

    Package files

    +

    + + + github.go + + +

    + +
    +
    + + + + + +

    Variables

    + +
    var Endpoint = oauth2.Endpoint{
    +    AuthURL:  "https://github.com/login/oauth/authorize",
    +    TokenURL: "https://github.com/login/oauth/access_token",
    +}
    +

    +Endpoint is Github's OAuth 2.0 endpoint. +

    + + + + + + + + + + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/golang.org/x/oauth2/google/index.html b/pkg/golang.org/x/oauth2/google/index.html new file mode 100644 index 0000000..e144824 --- /dev/null +++ b/pkg/golang.org/x/oauth2/google/index.html @@ -0,0 +1,507 @@ + + + + + + + + google - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Package google

    + + + + + + + + + + + + + + +
    +
    +
    import "golang.org/x/oauth2/google"
    +
    +
    +
    Overview
    +
    Index
    + + +
    +
    + +
    + +
    +

    Overview ▾

    +

    +Package google provides support for making OAuth2 authorized and +authenticated HTTP requests to Google APIs. +It supports the Web server flow, client-side credentials, service accounts, +Google Compute Engine service accounts, and Google App Engine service +accounts. +

    +

    +For more information, please read +https://developers.google.com/accounts/docs/OAuth2 +and +https://developers.google.com/accounts/docs/application-default-credentials. +

    + +
    +
    + + + + + + + +

    Constants

    + +
    const JWTTokenURL = "https://accounts.google.com/o/oauth2/token"
    +

    +JWTTokenURL is Google's OAuth 2.0 token URL to use with the JWT flow. +

    + + + + +

    Variables

    + +
    var Endpoint = oauth2.Endpoint{
    +    AuthURL:  "https://accounts.google.com/o/oauth2/auth",
    +    TokenURL: "https://accounts.google.com/o/oauth2/token",
    +}
    +

    +Endpoint is Google's OAuth 2.0 endpoint. +

    + + + + + + +

    func AppEngineTokenSource

    +
    func AppEngineTokenSource(ctx context.Context, scope ...string) oauth2.TokenSource
    +

    +AppEngineTokenSource returns a token source that fetches tokens +issued to the current App Engine application's service account. +If you are implementing a 3-legged OAuth 2.0 flow on App Engine +that involves user accounts, see oauth2.Config instead. +

    +

    +The provided context must have come from appengine.NewContext. +

    + + + + + + + +

    func ComputeTokenSource

    +
    func ComputeTokenSource(account string) oauth2.TokenSource
    +

    +ComputeTokenSource returns a token source that fetches access tokens +from Google Compute Engine (GCE)'s metadata server. It's only valid to use +this token source if your program is running on a GCE instance. +If no account is specified, "default" is used. +Further information about retrieving access tokens from the GCE metadata +server can be found at https://cloud.google.com/compute/docs/authentication. +

    + + + + + + + +

    func ConfigFromJSON

    +
    func ConfigFromJSON(jsonKey []byte, scope ...string) (*oauth2.Config, error)
    +

    +ConfigFromJSON uses a Google Developers Console client_credentials.json +file to construct a config. +client_credentials.json can be downloaded from +https://console.developers.google.com, under "Credentials". Download the Web +application credentials in the JSON format and provide the contents of the +file as jsonKey. +

    + + + + + + + +

    func DefaultClient

    +
    func DefaultClient(ctx context.Context, scope ...string) (*http.Client, error)
    +

    +DefaultClient returns an HTTP Client that uses the +DefaultTokenSource to obtain authentication credentials. +

    +

    +This client should be used when developing services +that run on Google App Engine or Google Compute Engine +and use "Application Default Credentials." +

    +

    +For more details, see: +https://developers.google.com/accounts/docs/application-default-credentials +

    + + + + + + + +

    func DefaultTokenSource

    +
    func DefaultTokenSource(ctx context.Context, scope ...string) (oauth2.TokenSource, error)
    +

    +DefaultTokenSource is a token source that uses +"Application Default Credentials". +

    +

    +It looks for credentials in the following places, +preferring the first location found: +

    +
    1. A JSON file whose path is specified by the
    +   GOOGLE_APPLICATION_CREDENTIALS environment variable.
    +2. A JSON file in a location known to the gcloud command-line tool.
    +   On Windows, this is %APPDATA%/gcloud/application_default_credentials.json.
    +   On other systems, $HOME/.config/gcloud/application_default_credentials.json.
    +3. On Google App Engine it uses the appengine.AccessToken function.
    +4. On Google Compute Engine and Google App Engine Managed VMs, it fetches
    +   credentials from the metadata server.
    +   (In this final case any provided scopes are ignored.)
    +
    +

    +For more details, see: +https://developers.google.com/accounts/docs/application-default-credentials +

    + + + + + + + +

    func JWTAccessTokenSourceFromJSON

    +
    func JWTAccessTokenSourceFromJSON(jsonKey []byte, audience string) (oauth2.TokenSource, error)
    +

    +JWTAccessTokenSourceFromJSON uses a Google Developers service account JSON +key file to read the credentials that authorize and authenticate the +requests, and returns a TokenSource that does not use any OAuth2 flow but +instead creates a JWT and sends that as the access token. +The audience is typically a URL that specifies the scope of the credentials. +

    +

    +Note that this is not a standard OAuth flow, but rather an +optimization supported by a few Google services. +Unless you know otherwise, you should use JWTConfigFromJSON instead. +

    + + + + + + + +

    func JWTConfigFromJSON

    +
    func JWTConfigFromJSON(jsonKey []byte, scope ...string) (*jwt.Config, error)
    +

    +JWTConfigFromJSON uses a Google Developers service account JSON key file to read +the credentials that authorize and authenticate the requests. +Create a service account on "Credentials" for your project at +https://console.developers.google.com to download a JSON key file. +

    + + + + + + + + +

    type SDKConfig

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

    +An SDKConfig provides access to tokens from an account already +authorized via the Google Cloud SDK. +

    + + + + + + + + + + + + +

    func NewSDKConfig

    +
    func NewSDKConfig(account string) (*SDKConfig, error)
    +

    +NewSDKConfig creates an SDKConfig for the given Google Cloud SDK +account. If account is empty, the account currently active in +Google Cloud SDK properties is used. +Google Cloud SDK credentials must be created by running `gcloud auth` +before using this function. +The Google Cloud SDK is available at https://cloud.google.com/sdk/. +

    + + + + + + + +

    func (*SDKConfig) Client

    +
    func (c *SDKConfig) Client(ctx context.Context) *http.Client
    +

    +Client returns an HTTP client using Google Cloud SDK credentials to +authorize requests. The token will auto-refresh as necessary. The +underlying http.RoundTripper will be obtained using the provided +context. The returned client and its Transport should not be +modified. +

    + + + + + + +

    func (*SDKConfig) Scopes

    +
    func (c *SDKConfig) Scopes() []string
    +

    +Scopes are the OAuth 2.0 scopes the current account is authorized for. +

    + + + + + + +

    func (*SDKConfig) TokenSource

    +
    func (c *SDKConfig) TokenSource(ctx context.Context) oauth2.TokenSource
    +

    +TokenSource returns an oauth2.TokenSource that retrieve tokens from +Google Cloud SDK credentials using the provided context. +It will returns the current access token stored in the credentials, +and refresh it when it expires, but it won't update the credentials +with the new access token. +

    + + + + + + + + + + + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/golang.org/x/oauth2/hipchat/index.html b/pkg/golang.org/x/oauth2/hipchat/index.html new file mode 100644 index 0000000..5fed242 --- /dev/null +++ b/pkg/golang.org/x/oauth2/hipchat/index.html @@ -0,0 +1,255 @@ + + + + + + + + hipchat - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Package hipchat

    + + + + + + + + + + + + + + +
    +
    +
    import "golang.org/x/oauth2/hipchat"
    +
    +
    +
    Overview
    +
    Index
    + + +
    +
    + +
    + +
    +

    Overview ▾

    +

    +Package hipchat provides constants for using OAuth2 to access HipChat. +

    + +
    +
    + + + + + + + + +

    Variables

    + +
    var Endpoint = oauth2.Endpoint{
    +    AuthURL:  "https://www.hipchat.com/users/authorize",
    +    TokenURL: "https://api.hipchat.com/v2/oauth/token",
    +}
    +

    +Endpoint is HipChat's OAuth 2.0 endpoint. +

    + + + + + + +

    func ClientCredentialsConfigFromCaps

    +
    func ClientCredentialsConfigFromCaps(capsJSON []byte, clientID, clientSecret string, scopes ...string) (*clientcredentials.Config, error)
    +

    +ClientCredentialsConfigFromCaps generates a Config from a HipChat API +capabilities descriptor. It does not verify the scopes against the +capabilities document at this time. +

    +

    +For more information see: https://www.hipchat.com/docs/apiv2/method/get_capabilities +

    + + + + + + + +

    func ServerEndpoint

    +
    func ServerEndpoint(host string) oauth2.Endpoint
    +

    +ServerEndpoint returns a new oauth2.Endpoint for a HipChat Server instance +running on the given domain or host. +

    + + + + + + + + + + + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/golang.org/x/oauth2/index.html b/pkg/golang.org/x/oauth2/index.html new file mode 100644 index 0000000..33a0c9f --- /dev/null +++ b/pkg/golang.org/x/oauth2/index.html @@ -0,0 +1,1052 @@ + + + + + + + + oauth2 - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Package oauth2

    + + + + + + + + + + + + + + +
    +
    +
    import "golang.org/x/oauth2"
    +
    +
    +
    Overview
    +
    Index
    + +
    Examples
    + + +
    Subdirectories
    + +
    +
    + +
    + +
    +

    Overview ▾

    +

    +Package oauth2 provides support for making +OAuth2 authorized and authenticated HTTP requests. +It can additionally grant authorization with Bearer JWT. +

    + +
    +
    + + +
    + +
    +

    Index ▾

    + + + + + +
    +

    Examples

    +
    + +
    Config
    + +
    +
    + + + +

    Package files

    +

    + + + oauth2.go + + token.go + + transport.go + + +

    + +
    +
    + + + + + +

    Variables

    + +
    var HTTPClient internal.ContextKey
    +

    +HTTPClient is the context key to use with golang.org/x/net/context's +WithValue function to associate an *http.Client value with a context. +

    + + +
    var NoContext = context.TODO()
    +

    +NoContext is the default context you should supply if not using +your own context.Context (see https://golang.org/x/net/context). +

    + + + + + + +

    func NewClient

    +
    func NewClient(ctx context.Context, src TokenSource) *http.Client
    +

    +NewClient creates an *http.Client from a Context and TokenSource. +The returned client is not valid beyond the lifetime of the context. +

    +

    +As a special case, if src is nil, a non-OAuth2 client is returned +using the provided context. This exists to support related OAuth2 +packages. +

    + + + + + + + +

    func RegisterBrokenAuthHeaderProvider

    +
    func RegisterBrokenAuthHeaderProvider(tokenURL string)
    +

    +RegisterBrokenAuthHeaderProvider registers an OAuth2 server +identified by the tokenURL prefix as an OAuth2 implementation +which doesn't support the HTTP Basic authentication +scheme to authenticate with the authorization server. +Once a server is registered, credentials (client_id and client_secret) +will be passed as query parameters rather than being present +in the Authorization header. +See https://code.google.com/p/goauth2/issues/detail?id=31 for background. +

    + + + + + + + + +

    type AuthCodeOption

    +
    type AuthCodeOption interface {
    +    // contains filtered or unexported methods
    +}
    +

    +An AuthCodeOption is passed to Config.AuthCodeURL. +

    + + + + + +
    var (
    +    // AccessTypeOnline and AccessTypeOffline are options passed
    +    // to the Options.AuthCodeURL method. They modify the
    +    // "access_type" field that gets sent in the URL returned by
    +    // AuthCodeURL.
    +    //
    +    // Online is the default if neither is specified. If your
    +    // application needs to refresh access tokens when the user
    +    // is not present at the browser, then use offline. This will
    +    // result in your application obtaining a refresh token the
    +    // first time your application exchanges an authorization
    +    // code for a user.
    +    AccessTypeOnline  AuthCodeOption = SetAuthURLParam("access_type", "online")
    +    AccessTypeOffline AuthCodeOption = SetAuthURLParam("access_type", "offline")
    +
    +    // ApprovalForce forces the users to view the consent dialog
    +    // and confirm the permissions request at the URL returned
    +    // from AuthCodeURL, even if they've already done so.
    +    ApprovalForce AuthCodeOption = SetAuthURLParam("approval_prompt", "force")
    +)
    + + + + + + + + + +

    func SetAuthURLParam

    +
    func SetAuthURLParam(key, value string) AuthCodeOption
    +

    +SetAuthURLParam builds an AuthCodeOption which passes key/value parameters +to a provider's authorization endpoint. +

    + + + + + + + + + +

    type Config

    +
    type Config struct {
    +    // ClientID is the application's ID.
    +    ClientID string
    +
    +    // ClientSecret is the application's secret.
    +    ClientSecret string
    +
    +    // Endpoint contains the resource server's token endpoint
    +    // URLs. These are constants specific to each server and are
    +    // often available via site-specific packages, such as
    +    // google.Endpoint or github.Endpoint.
    +    Endpoint Endpoint
    +
    +    // RedirectURL is the URL to redirect users going through
    +    // the OAuth flow, after the resource owner's URLs.
    +    RedirectURL string
    +
    +    // Scope specifies optional requested permissions.
    +    Scopes []string
    +}
    +

    +Config describes a typical 3-legged OAuth2 flow, with both the +client application information and the server's endpoint URLs. +

    + + + + + + +
    + +
    +

    Example

    + + + +

    Code:

    +
    +conf := &oauth2.Config{
    +    ClientID:     "YOUR_CLIENT_ID",
    +    ClientSecret: "YOUR_CLIENT_SECRET",
    +    Scopes:       []string{"SCOPE1", "SCOPE2"},
    +    Endpoint: oauth2.Endpoint{
    +        AuthURL:  "https://provider.com/o/oauth2/auth",
    +        TokenURL: "https://provider.com/o/oauth2/token",
    +    },
    +}
    +
    +// Redirect user to consent page to ask for permission
    +// for the scopes specified above.
    +url := conf.AuthCodeURL("state", oauth2.AccessTypeOffline)
    +fmt.Printf("Visit the URL for the auth dialog: %v", url)
    +
    +// Use the authorization code that is pushed to the redirect
    +// URL. Exchange will do the handshake to retrieve the
    +// initial access token. The HTTP Client returned by
    +// conf.Client will refresh the token as necessary.
    +var code string
    +if _, err := fmt.Scan(&code); err != nil {
    +    log.Fatal(err)
    +}
    +tok, err := conf.Exchange(oauth2.NoContext, code)
    +if err != nil {
    +    log.Fatal(err)
    +}
    +
    +client := conf.Client(oauth2.NoContext, tok)
    +client.Get("...")
    +
    + + +
    +
    + + + + + + + + +

    func (*Config) AuthCodeURL

    +
    func (c *Config) AuthCodeURL(state string, opts ...AuthCodeOption) string
    +

    +AuthCodeURL returns a URL to OAuth 2.0 provider's consent page +that asks for permissions for the required scopes explicitly. +

    +

    +State is a token to protect the user from CSRF attacks. You must +always provide a non-zero string and validate that it matches the +the state query parameter on your redirect callback. +See http://tools.ietf.org/html/rfc6749#section-10.12 for more info. +

    +

    +Opts may include AccessTypeOnline or AccessTypeOffline, as well +as ApprovalForce. +

    + + + + + + +

    func (*Config) Client

    +
    func (c *Config) Client(ctx context.Context, t *Token) *http.Client
    +

    +Client returns an HTTP client using the provided token. +The token will auto-refresh as necessary. The underlying +HTTP transport will be obtained using the provided context. +The returned client and its Transport should not be modified. +

    + + + + + + +

    func (*Config) Exchange

    +
    func (c *Config) Exchange(ctx context.Context, code string) (*Token, error)
    +

    +Exchange converts an authorization code into a token. +

    +

    +It is used after a resource provider redirects the user back +to the Redirect URI (the URL obtained from AuthCodeURL). +

    +

    +The HTTP client to use is derived from the context. +If a client is not provided via the context, http.DefaultClient is used. +

    +

    +The code will be in the *http.Request.FormValue("code"). Before +calling Exchange, be sure to validate FormValue("state"). +

    + + + + + + +

    func (*Config) PasswordCredentialsToken

    +
    func (c *Config) PasswordCredentialsToken(ctx context.Context, username, password string) (*Token, error)
    +

    +PasswordCredentialsToken converts a resource owner username and password +pair into a token. +

    +

    +Per the RFC, this grant type should only be used "when there is a high +degree of trust between the resource owner and the client (e.g., the client +is part of the device operating system or a highly privileged application), +and when other authorization grant types are not available." +See https://tools.ietf.org/html/rfc6749#section-4.3 for more info. +

    +

    +The HTTP client to use is derived from the context. +If nil, http.DefaultClient is used. +

    + + + + + + +

    func (*Config) TokenSource

    +
    func (c *Config) TokenSource(ctx context.Context, t *Token) TokenSource
    +

    +TokenSource returns a TokenSource that returns t until t expires, +automatically refreshing it as necessary using the provided context. +

    +

    +Most users will use Config.Client instead. +

    + + + + + + + + +

    type Endpoint

    +
    type Endpoint struct {
    +    AuthURL  string
    +    TokenURL string
    +}
    +

    +Endpoint contains the OAuth 2.0 provider's authorization and token +endpoint URLs. +

    + + + + + + + + + + + + + + + + +

    type Token

    +
    type Token struct {
    +    // AccessToken is the token that authorizes and authenticates
    +    // the requests.
    +    AccessToken string `json:"access_token"`
    +
    +    // TokenType is the type of token.
    +    // The Type method returns either this or "Bearer", the default.
    +    TokenType string `json:"token_type,omitempty"`
    +
    +    // RefreshToken is a token that's used by the application
    +    // (as opposed to the user) to refresh the access token
    +    // if it expires.
    +    RefreshToken string `json:"refresh_token,omitempty"`
    +
    +    // Expiry is the optional expiration time of the access token.
    +    //
    +    // If zero, TokenSource implementations will reuse the same
    +    // token forever and RefreshToken or equivalent
    +    // mechanisms for that TokenSource will not be used.
    +    Expiry time.Time `json:"expiry,omitempty"`
    +    // contains filtered or unexported fields
    +}
    +

    +Token represents the crendentials used to authorize +the requests to access protected resources on the OAuth 2.0 +provider's backend. +

    +

    +Most users of this package should not access fields of Token +directly. They're exported mostly for use by related packages +implementing derivative OAuth2 flows. +

    + + + + + + + + + + + + + + +

    func (*Token) Extra

    +
    func (t *Token) Extra(key string) interface{}
    +

    +Extra returns an extra field. +Extra fields are key-value pairs returned by the server as a +part of the token retrieval response. +

    + + + + + + +

    func (*Token) SetAuthHeader

    +
    func (t *Token) SetAuthHeader(r *http.Request)
    +

    +SetAuthHeader sets the Authorization header to r using the access +token in t. +

    +

    +This method is unnecessary when using Transport or an HTTP Client +returned by this package. +

    + + + + + + +

    func (*Token) Type

    +
    func (t *Token) Type() string
    +

    +Type returns t.TokenType if non-empty, else "Bearer". +

    + + + + + + +

    func (*Token) Valid

    +
    func (t *Token) Valid() bool
    +

    +Valid reports whether t is non-nil, has an AccessToken, and is not expired. +

    + + + + + + +

    func (*Token) WithExtra

    +
    func (t *Token) WithExtra(extra interface{}) *Token
    +

    +WithExtra returns a new Token that's a clone of t, but using the +provided raw extra map. This is only intended for use by packages +implementing derivative OAuth2 flows. +

    + + + + + + + + +

    type TokenSource

    +
    type TokenSource interface {
    +    // Token returns a token or an error.
    +    // Token must be safe for concurrent use by multiple goroutines.
    +    // The returned Token must not be modified.
    +    Token() (*Token, error)
    +}
    +

    +A TokenSource is anything that can return a token. +

    + + + + + + + + + + + + +

    func ReuseTokenSource

    +
    func ReuseTokenSource(t *Token, src TokenSource) TokenSource
    +

    +ReuseTokenSource returns a TokenSource which repeatedly returns the +same token as long as it's valid, starting with t. +When its cached token is invalid, a new token is obtained from src. +

    +

    +ReuseTokenSource is typically used to reuse tokens from a cache +(such as a file on disk) between runs of a program, rather than +obtaining new tokens unnecessarily. +

    +

    +The initial token t may be nil, in which case the TokenSource is +wrapped in a caching version if it isn't one already. This also +means it's always safe to wrap ReuseTokenSource around any other +TokenSource without adverse effects. +

    + + + + + +

    func StaticTokenSource

    +
    func StaticTokenSource(t *Token) TokenSource
    +

    +StaticTokenSource returns a TokenSource that always returns the same token. +Because the provided token t is never refreshed, StaticTokenSource is only +useful for tokens that never expire. +

    + + + + + + + + + +

    type Transport

    +
    type Transport struct {
    +    // Source supplies the token to add to outgoing requests'
    +    // Authorization headers.
    +    Source TokenSource
    +
    +    // Base is the base RoundTripper used to make HTTP requests.
    +    // If nil, http.DefaultTransport is used.
    +    Base http.RoundTripper
    +    // contains filtered or unexported fields
    +}
    +

    +Transport is an http.RoundTripper that makes OAuth 2.0 HTTP requests, +wrapping a base RoundTripper and adding an Authorization header +with a token from the supplied Sources. +

    +

    +Transport is a low-level mechanism. Most code will use the +higher-level Config.Client method instead. +

    + + + + + + + + + + + + + + +

    func (*Transport) CancelRequest

    +
    func (t *Transport) CancelRequest(req *http.Request)
    +

    +CancelRequest cancels an in-flight request by closing its connection. +

    + + + + + + +

    func (*Transport) RoundTrip

    +
    func (t *Transport) RoundTrip(req *http.Request) (*http.Response, error)
    +

    +RoundTrip authorizes and authenticates the request with an +access token. If no token exists or token is expired, +tries to refresh/fetch a new token. +

    + + + + + + + + + + + + + + + + +

    Subdirectories

    + + + + +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    NameSynopsis
    ..
    + bitbucket + + Package bitbucket provides constants for using OAuth2 to access Bitbucket. +
    + clientcredentials + + Package clientcredentials implements the OAuth2.0 "client credentials" token flow, also known as the "two-legged OAuth 2.0". +
    + facebook + + Package facebook provides constants for using OAuth2 to access Facebook. +
    + fitbit + + Package fitbit provides constants for using OAuth2 to access the Fitbit API. +
    + github + + Package github provides constants for using OAuth2 to access Github. +
    + google + + Package google provides support for making OAuth2 authorized and authenticated HTTP requests to Google APIs. +
    + hipchat + + Package hipchat provides constants for using OAuth2 to access HipChat. +
    + jws + + Package jws provides encoding and decoding utilities for signed JWS messages. +
    + jwt + + Package jwt implements the OAuth 2.0 JSON Web Token flow, commonly known as "two-legged OAuth 2.0". +
    + linkedin + + Package linkedin provides constants for using OAuth2 to access LinkedIn. +
    + microsoft + + Package microsoft provides constants for using OAuth2 to access Windows Live ID. +
    + odnoklassniki + + Package odnoklassniki provides constants for using OAuth2 to access Odnoklassniki. +
    + paypal + + Package paypal provides constants for using OAuth2 to access PayPal. +
    + slack + + Package slack provides constants for using OAuth2 to access Slack. +
    + vk + + Package vk provides constants for using OAuth2 to access VK.com. +
    +
    + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/golang.org/x/oauth2/internal/index.html b/pkg/golang.org/x/oauth2/internal/index.html new file mode 100644 index 0000000..d54f29b --- /dev/null +++ b/pkg/golang.org/x/oauth2/internal/index.html @@ -0,0 +1,476 @@ + + + + + + + + internal - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Package internal

    + + + + + + + + + + + + + + +
    +
    +
    import "golang.org/x/oauth2/internal"
    +
    +
    +
    Overview
    +
    Index
    + + +
    +
    + +
    + +
    +

    Overview ▾

    +

    +Package internal contains support packages for oauth2 package. +

    +

    +Package internal contains support packages for oauth2 package. +

    +

    +Package internal contains support packages for oauth2 package. +

    + +
    +
    + + + + + + + + + + + +

    func CondVal

    +
    func CondVal(v string) []string
    + + + + + + + +

    func ContextClient

    +
    func ContextClient(ctx context.Context) (*http.Client, error)
    + + + + + + + +

    func ContextTransport

    +
    func ContextTransport(ctx context.Context) http.RoundTripper
    + + + + + + + +

    func ParseINI

    +
    func ParseINI(ini io.Reader) (map[string]map[string]string, error)
    + + + + + + + +

    func ParseKey

    +
    func ParseKey(key []byte) (*rsa.PrivateKey, error)
    +

    +ParseKey converts the binary contents of a private key file +to an *rsa.PrivateKey. It detects whether the private key is in a +PEM container or not. If so, it extracts the the private key +from PEM container before conversion. It only supports PEM +containers with no passphrase. +

    + + + + + + + +

    func RegisterBrokenAuthHeaderProvider

    +
    func RegisterBrokenAuthHeaderProvider(tokenURL string)
    + + + + + + + +

    func RegisterContextClientFunc

    +
    func RegisterContextClientFunc(fn ContextClientFunc)
    + + + + + + + + +

    type ContextClientFunc

    +
    type ContextClientFunc func(context.Context) (*http.Client, error)
    +

    +ContextClientFunc is a func which tries to return an *http.Client +given a Context value. If it returns an error, the search stops +with that error. If it returns (nil, nil), the search continues +down the list of registered funcs. +

    + + + + + + + + + + + + + + + + +

    type ContextKey

    +
    type ContextKey struct{}
    +

    +ContextKey is just an empty struct. It exists so HTTPClient can be +an immutable public variable with a unique type. It's immutable +because nobody else can create a ContextKey, being unexported. +

    + + + + + +
    var HTTPClient ContextKey
    +

    +HTTPClient is the context key to use with golang.org/x/net/context's +WithValue function to associate an *http.Client value with a context. +

    + + + + + + + + + + + + + +

    type ErrorTransport

    +
    type ErrorTransport struct{ Err error }
    +

    +ErrorTransport returns the specified error on RoundTrip. +This RoundTripper should be used in rare error cases where +error handling can be postponed to response handling time. +

    + + + + + + + + + + + + + + +

    func (ErrorTransport) RoundTrip

    +
    func (t ErrorTransport) RoundTrip(*http.Request) (*http.Response, error)
    + + + + + + + + +

    type Token

    +
    type Token struct {
    +    // AccessToken is the token that authorizes and authenticates
    +    // the requests.
    +    AccessToken string
    +
    +    // TokenType is the type of token.
    +    // The Type method returns either this or "Bearer", the default.
    +    TokenType string
    +
    +    // RefreshToken is a token that's used by the application
    +    // (as opposed to the user) to refresh the access token
    +    // if it expires.
    +    RefreshToken string
    +
    +    // Expiry is the optional expiration time of the access token.
    +    //
    +    // If zero, TokenSource implementations will reuse the same
    +    // token forever and RefreshToken or equivalent
    +    // mechanisms for that TokenSource will not be used.
    +    Expiry time.Time
    +
    +    // Raw optionally contains extra metadata from the server
    +    // when updating a token.
    +    Raw interface{}
    +}
    +

    +Token represents the crendentials used to authorize +the requests to access protected resources on the OAuth 2.0 +provider's backend. +

    +

    +This type is a mirror of oauth2.Token and exists to break +an otherwise-circular dependency. Other internal packages +should convert this Token into an oauth2.Token before use. +

    + + + + + + + + + + + + +

    func RetrieveToken

    +
    func RetrieveToken(ctx context.Context, clientID, clientSecret, tokenURL string, v url.Values) (*Token, error)
    + + + + + + + + + + + + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/golang.org/x/oauth2/jws/index.html b/pkg/golang.org/x/oauth2/jws/index.html new file mode 100644 index 0000000..613c356 --- /dev/null +++ b/pkg/golang.org/x/oauth2/jws/index.html @@ -0,0 +1,373 @@ + + + + + + + + jws - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Package jws

    + + + + + + + + + + + + + + +
    +
    +
    import "golang.org/x/oauth2/jws"
    +
    +
    +
    Overview
    +
    Index
    + + +
    +
    + +
    + +
    +

    Overview ▾

    +

    +Package jws provides encoding and decoding utilities for +signed JWS messages. +

    + +
    +
    + + + + + + + + + + + +

    func Encode

    +
    func Encode(header *Header, c *ClaimSet, key *rsa.PrivateKey) (string, error)
    +

    +Encode encodes a signed JWS with provided header and claim set. +This invokes EncodeWithSigner using crypto/rsa.SignPKCS1v15 with the given RSA private key. +

    + + + + + + + +

    func EncodeWithSigner

    +
    func EncodeWithSigner(header *Header, c *ClaimSet, sg Signer) (string, error)
    +

    +EncodeWithSigner encodes a header and claim set with the provided signer. +

    + + + + + + + +

    func Verify

    +
    func Verify(token string, key *rsa.PublicKey) error
    +

    +Verify tests whether the provided JWT token's signature was produced by the private key +associated with the supplied public key. +

    + + + + + + + + +

    type ClaimSet

    +
    type ClaimSet struct {
    +    Iss   string `json:"iss"`             // email address of the client_id of the application making the access token request
    +    Scope string `json:"scope,omitempty"` // space-delimited list of the permissions the application requests
    +    Aud   string `json:"aud"`             // descriptor of the intended target of the assertion (Optional).
    +    Exp   int64  `json:"exp"`             // the expiration time of the assertion (seconds since Unix epoch)
    +    Iat   int64  `json:"iat"`             // the time the assertion was issued (seconds since Unix epoch)
    +    Typ   string `json:"typ,omitempty"`   // token type (Optional).
    +
    +    // Email for which the application is requesting delegated access (Optional).
    +    Sub string `json:"sub,omitempty"`
    +
    +    // The old name of Sub. Client keeps setting Prn to be
    +    // complaint with legacy OAuth 2.0 providers. (Optional)
    +    Prn string `json:"prn,omitempty"`
    +
    +    // See http://tools.ietf.org/html/draft-jones-json-web-token-10#section-4.3
    +    // This array is marshalled using custom code (see (c *ClaimSet) encode()).
    +    PrivateClaims map[string]interface{} `json:"-"`
    +}
    +

    +ClaimSet contains information about the JWT signature including the +permissions being requested (scopes), the target of the token, the issuer, +the time the token was issued, and the lifetime of the token. +

    + + + + + + + + + + + + +

    func Decode

    +
    func Decode(payload string) (*ClaimSet, error)
    +

    +Decode decodes a claim set from a JWS payload. +

    + + + + + + + + + + +
    type Header struct {
    +    // The algorithm used for signature.
    +    Algorithm string `json:"alg"`
    +
    +    // Represents the token type.
    +    Typ string `json:"typ"`
    +
    +    // The optional hint of which key is being used.
    +    KeyID string `json:"kid,omitempty"`
    +}
    +

    +Header represents the header for the signed JWS payloads. +

    + + + + + + + + + + + + + + + + +

    type Signer

    +
    type Signer func(data []byte) (sig []byte, err error)
    +

    +Signer returns a signature for the given data. +

    + + + + + + + + + + + + + + + + + + + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/golang.org/x/oauth2/jwt/index.html b/pkg/golang.org/x/oauth2/jwt/index.html new file mode 100644 index 0000000..ae6032e --- /dev/null +++ b/pkg/golang.org/x/oauth2/jwt/index.html @@ -0,0 +1,300 @@ + + + + + + + + jwt - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Package jwt

    + + + + + + + + + + + + + + +
    +
    +
    import "golang.org/x/oauth2/jwt"
    +
    +
    +
    Overview
    +
    Index
    + + +
    +
    + +
    + +
    +

    Overview ▾

    +

    +Package jwt implements the OAuth 2.0 JSON Web Token flow, commonly +known as "two-legged OAuth 2.0". +

    +

    +See: https://tools.ietf.org/html/draft-ietf-oauth-jwt-bearer-12 +

    + +
    +
    + + +
    + +
    +

    Index ▾

    + + + + + + + +

    Package files

    +

    + + + jwt.go + + +

    + +
    +
    + + + + + + + + + +

    type Config

    +
    type Config struct {
    +    // Email is the OAuth client identifier used when communicating with
    +    // the configured OAuth provider.
    +    Email string
    +
    +    // PrivateKey contains the contents of an RSA private key or the
    +    // contents of a PEM file that contains a private key. The provided
    +    // private key is used to sign JWT payloads.
    +    // PEM containers with a passphrase are not supported.
    +    // Use the following command to convert a PKCS 12 file into a PEM.
    +    //
    +    //    $ openssl pkcs12 -in key.p12 -out key.pem -nodes
    +    //
    +    PrivateKey []byte
    +
    +    // PrivateKeyID contains an optional hint indicating which key is being
    +    // used.
    +    PrivateKeyID string
    +
    +    // Subject is the optional user to impersonate.
    +    Subject string
    +
    +    // Scopes optionally specifies a list of requested permission scopes.
    +    Scopes []string
    +
    +    // TokenURL is the endpoint required to complete the 2-legged JWT flow.
    +    TokenURL string
    +
    +    // Expires optionally specifies how long the token is valid for.
    +    Expires time.Duration
    +}
    +

    +Config is the configuration for using JWT to fetch tokens, +commonly known as "two-legged OAuth 2.0". +

    + + + + + + + + + + + + + + +

    func (*Config) Client

    +
    func (c *Config) Client(ctx context.Context) *http.Client
    +

    +Client returns an HTTP client wrapping the context's +HTTP transport and adding Authorization headers with tokens +obtained from c. +

    +

    +The returned client and its Transport should not be modified. +

    + + + + + + +

    func (*Config) TokenSource

    +
    func (c *Config) TokenSource(ctx context.Context) oauth2.TokenSource
    +

    +TokenSource returns a JWT TokenSource using the configuration +in c and the HTTP client from the provided context. +

    + + + + + + + + + + + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/golang.org/x/oauth2/linkedin/index.html b/pkg/golang.org/x/oauth2/linkedin/index.html new file mode 100644 index 0000000..ec55843 --- /dev/null +++ b/pkg/golang.org/x/oauth2/linkedin/index.html @@ -0,0 +1,219 @@ + + + + + + + + linkedin - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Package linkedin

    + + + + + + + + + + + + + + +
    +
    +
    import "golang.org/x/oauth2/linkedin"
    +
    +
    +
    Overview
    +
    Index
    + + +
    +
    + +
    + +
    +

    Overview ▾

    +

    +Package linkedin provides constants for using OAuth2 to access LinkedIn. +

    + +
    +
    + + +
    + +
    +

    Index ▾

    + + +
    +
    + + +
    Variables
    + + + + +
    +
    + + + + +

    Package files

    +

    + + + linkedin.go + + +

    + +
    +
    + + + + + +

    Variables

    + +
    var Endpoint = oauth2.Endpoint{
    +    AuthURL:  "https://www.linkedin.com/uas/oauth2/authorization",
    +    TokenURL: "https://www.linkedin.com/uas/oauth2/accessToken",
    +}
    +

    +Endpoint is LinkedIn's OAuth 2.0 endpoint. +

    + + + + + + + + + + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/golang.org/x/oauth2/microsoft/index.html b/pkg/golang.org/x/oauth2/microsoft/index.html new file mode 100644 index 0000000..3e92398 --- /dev/null +++ b/pkg/golang.org/x/oauth2/microsoft/index.html @@ -0,0 +1,219 @@ + + + + + + + + microsoft - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Package microsoft

    + + + + + + + + + + + + + + +
    +
    +
    import "golang.org/x/oauth2/microsoft"
    +
    +
    +
    Overview
    +
    Index
    + + +
    +
    + +
    + +
    +

    Overview ▾

    +

    +Package microsoft provides constants for using OAuth2 to access Windows Live ID. +

    + +
    +
    + + +
    + +
    +

    Index ▾

    + + +
    +
    + + +
    Variables
    + + + + +
    +
    + + + + +

    Package files

    +

    + + + microsoft.go + + +

    + +
    +
    + + + + + +

    Variables

    + +
    var LiveConnectEndpoint = oauth2.Endpoint{
    +    AuthURL:  "https://login.live.com/oauth20_authorize.srf",
    +    TokenURL: "https://login.live.com/oauth20_token.srf",
    +}
    +

    +LiveConnectEndpoint is Windows's Live ID OAuth 2.0 endpoint. +

    + + + + + + + + + + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/golang.org/x/oauth2/odnoklassniki/index.html b/pkg/golang.org/x/oauth2/odnoklassniki/index.html new file mode 100644 index 0000000..83d03c6 --- /dev/null +++ b/pkg/golang.org/x/oauth2/odnoklassniki/index.html @@ -0,0 +1,219 @@ + + + + + + + + odnoklassniki - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Package odnoklassniki

    + + + + + + + + + + + + + + +
    +
    +
    import "golang.org/x/oauth2/odnoklassniki"
    +
    +
    +
    Overview
    +
    Index
    + + +
    +
    + +
    + +
    +

    Overview ▾

    +

    +Package odnoklassniki provides constants for using OAuth2 to access Odnoklassniki. +

    + +
    +
    + + +
    + +
    +

    Index ▾

    + + +
    +
    + + +
    Variables
    + + + + +
    +
    + + + + +

    Package files

    +

    + + + odnoklassniki.go + + +

    + +
    +
    + + + + + +

    Variables

    + +
    var Endpoint = oauth2.Endpoint{
    +    AuthURL:  "https://www.odnoklassniki.ru/oauth/authorize",
    +    TokenURL: "https://api.odnoklassniki.ru/oauth/token.do",
    +}
    +

    +Endpoint is Odnoklassniki's OAuth 2.0 endpoint. +

    + + + + + + + + + + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/golang.org/x/oauth2/paypal/index.html b/pkg/golang.org/x/oauth2/paypal/index.html new file mode 100644 index 0000000..f1434d4 --- /dev/null +++ b/pkg/golang.org/x/oauth2/paypal/index.html @@ -0,0 +1,228 @@ + + + + + + + + paypal - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Package paypal

    + + + + + + + + + + + + + + +
    +
    +
    import "golang.org/x/oauth2/paypal"
    +
    +
    +
    Overview
    +
    Index
    + + +
    +
    + +
    + +
    +

    Overview ▾

    +

    +Package paypal provides constants for using OAuth2 to access PayPal. +

    + +
    +
    + + +
    + +
    +

    Index ▾

    + + +
    +
    + + +
    Variables
    + + + + +
    +
    + + + + +

    Package files

    +

    + + + paypal.go + + +

    + +
    +
    + + + + + +

    Variables

    + +
    var Endpoint = oauth2.Endpoint{
    +    AuthURL:  "https://www.paypal.com/webapps/auth/protocol/openidconnect/v1/authorize",
    +    TokenURL: "https://api.paypal.com/v1/identity/openidconnect/tokenservice",
    +}
    +

    +Endpoint is PayPal's OAuth 2.0 endpoint in live (production) environment. +

    + + +
    var SandboxEndpoint = oauth2.Endpoint{
    +    AuthURL:  "https://www.sandbox.paypal.com/webapps/auth/protocol/openidconnect/v1/authorize",
    +    TokenURL: "https://api.sandbox.paypal.com/v1/identity/openidconnect/tokenservice",
    +}
    +

    +SandboxEndpoint is PayPal's OAuth 2.0 endpoint in sandbox (testing) environment. +

    + + + + + + + + + + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/golang.org/x/oauth2/slack/index.html b/pkg/golang.org/x/oauth2/slack/index.html new file mode 100644 index 0000000..47214cb --- /dev/null +++ b/pkg/golang.org/x/oauth2/slack/index.html @@ -0,0 +1,219 @@ + + + + + + + + slack - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Package slack

    + + + + + + + + + + + + + + +
    +
    +
    import "golang.org/x/oauth2/slack"
    +
    +
    +
    Overview
    +
    Index
    + + +
    +
    + +
    + +
    +

    Overview ▾

    +

    +Package slack provides constants for using OAuth2 to access Slack. +

    + +
    +
    + + +
    + +
    +

    Index ▾

    + + +
    +
    + + +
    Variables
    + + + + +
    +
    + + + + +

    Package files

    +

    + + + slack.go + + +

    + +
    +
    + + + + + +

    Variables

    + +
    var Endpoint = oauth2.Endpoint{
    +    AuthURL:  "https://slack.com/oauth/authorize",
    +    TokenURL: "https://slack.com/api/oauth.access",
    +}
    +

    +Endpoint is Slack's OAuth 2.0 endpoint. +

    + + + + + + + + + + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/golang.org/x/oauth2/vk/index.html b/pkg/golang.org/x/oauth2/vk/index.html new file mode 100644 index 0000000..c034a9e --- /dev/null +++ b/pkg/golang.org/x/oauth2/vk/index.html @@ -0,0 +1,219 @@ + + + + + + + + vk - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Package vk

    + + + + + + + + + + + + + + +
    +
    +
    import "golang.org/x/oauth2/vk"
    +
    +
    +
    Overview
    +
    Index
    + + +
    +
    + +
    + +
    +

    Overview ▾

    +

    +Package vk provides constants for using OAuth2 to access VK.com. +

    + +
    +
    + + +
    + +
    +

    Index ▾

    + + +
    +
    + + +
    Variables
    + + + + +
    +
    + + + + +

    Package files

    +

    + + + vk.go + + +

    + +
    +
    + + + + + +

    Variables

    + +
    var Endpoint = oauth2.Endpoint{
    +    AuthURL:  "https://oauth.vk.com/authorize",
    +    TokenURL: "https://oauth.vk.com/access_token",
    +}
    +

    +Endpoint is VK's OAuth 2.0 endpoint. +

    + + + + + + + + + + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/golang.org/x/text/encoding/charmap/index.html b/pkg/golang.org/x/text/encoding/charmap/index.html new file mode 100644 index 0000000..3d5aed1 --- /dev/null +++ b/pkg/golang.org/x/text/encoding/charmap/index.html @@ -0,0 +1,469 @@ + + + + + + + + charmap - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Package charmap

    + + + + + + + + + + + + + + +
    +
    +
    import "golang.org/x/text/encoding/charmap"
    +
    +
    +
    Overview
    +
    Index
    + + +
    +
    + +
    + +
    +

    Overview ▾

    +

    +Package charmap provides simple character encodings such as IBM Code Page 437 +and Windows 1252. +

    + +
    +
    + + +
    + +
    +

    Index ▾

    + + +
    +
    + + +
    Variables
    + + + + +
    +
    + + + + +

    Package files

    +

    + + + charmap.go + + tables.go + + +

    + +
    +
    + + + + + +

    Variables

    + +
    var (
    +    // ISO8859_6E is the ISO 8859-6E encoding.
    +    ISO8859_6E encoding.Encoding = &iso8859_6E
    +
    +    // ISO8859_6I is the ISO 8859-6I encoding.
    +    ISO8859_6I encoding.Encoding = &iso8859_6I
    +
    +    // ISO8859_8E is the ISO 8859-8E encoding.
    +    ISO8859_8E encoding.Encoding = &iso8859_8E
    +
    +    // ISO8859_8I is the ISO 8859-8I encoding.
    +    ISO8859_8I encoding.Encoding = &iso8859_8I
    +)
    +

    +These encodings vary only in the way clients should interpret them. Their +coded character set is identical and a single implementation can be shared. +

    + + +
    var All = listAll
    +

    +All is a list of all defined encodings in this package. +

    + + +
    var CodePage437 encoding.Encoding = &codePage437
    +

    +CodePage437 is the IBM Code Page 437 encoding. +

    + + +
    var CodePage850 encoding.Encoding = &codePage850
    +

    +CodePage850 is the IBM Code Page 850 encoding. +

    + + +
    var CodePage852 encoding.Encoding = &codePage852
    +

    +CodePage852 is the IBM Code Page 852 encoding. +

    + + +
    var CodePage855 encoding.Encoding = &codePage855
    +

    +CodePage855 is the IBM Code Page 855 encoding. +

    + + +
    var CodePage858 encoding.Encoding = &codePage858
    +

    +CodePage858 is the Windows Code Page 858 encoding. +

    + + +
    var CodePage860 encoding.Encoding = &codePage860
    +

    +CodePage860 is the IBM Code Page 860 encoding. +

    + + +
    var CodePage862 encoding.Encoding = &codePage862
    +

    +CodePage862 is the IBM Code Page 862 encoding. +

    + + +
    var CodePage863 encoding.Encoding = &codePage863
    +

    +CodePage863 is the IBM Code Page 863 encoding. +

    + + +
    var CodePage865 encoding.Encoding = &codePage865
    +

    +CodePage865 is the IBM Code Page 865 encoding. +

    + + +
    var CodePage866 encoding.Encoding = &codePage866
    +

    +CodePage866 is the IBM Code Page 866 encoding. +

    + + +
    var ISO8859_1 encoding.Encoding = &iso8859_1
    +

    +ISO8859_1 is the ISO 8859-1 encoding. +

    + + +
    var ISO8859_10 encoding.Encoding = &iso8859_10
    +

    +ISO8859_10 is the ISO 8859-10 encoding. +

    + + +
    var ISO8859_13 encoding.Encoding = &iso8859_13
    +

    +ISO8859_13 is the ISO 8859-13 encoding. +

    + + +
    var ISO8859_14 encoding.Encoding = &iso8859_14
    +

    +ISO8859_14 is the ISO 8859-14 encoding. +

    + + +
    var ISO8859_15 encoding.Encoding = &iso8859_15
    +

    +ISO8859_15 is the ISO 8859-15 encoding. +

    + + +
    var ISO8859_16 encoding.Encoding = &iso8859_16
    +

    +ISO8859_16 is the ISO 8859-16 encoding. +

    + + +
    var ISO8859_2 encoding.Encoding = &iso8859_2
    +

    +ISO8859_2 is the ISO 8859-2 encoding. +

    + + +
    var ISO8859_3 encoding.Encoding = &iso8859_3
    +

    +ISO8859_3 is the ISO 8859-3 encoding. +

    + + +
    var ISO8859_4 encoding.Encoding = &iso8859_4
    +

    +ISO8859_4 is the ISO 8859-4 encoding. +

    + + +
    var ISO8859_5 encoding.Encoding = &iso8859_5
    +

    +ISO8859_5 is the ISO 8859-5 encoding. +

    + + +
    var ISO8859_6 encoding.Encoding = &iso8859_6
    +

    +ISO8859_6 is the ISO 8859-6 encoding. +

    + + +
    var ISO8859_7 encoding.Encoding = &iso8859_7
    +

    +ISO8859_7 is the ISO 8859-7 encoding. +

    + + +
    var ISO8859_8 encoding.Encoding = &iso8859_8
    +

    +ISO8859_8 is the ISO 8859-8 encoding. +

    + + +
    var KOI8R encoding.Encoding = &koi8R
    +

    +KOI8R is the KOI8-R encoding. +

    + + +
    var KOI8U encoding.Encoding = &koi8U
    +

    +KOI8U is the KOI8-U encoding. +

    + + +
    var Macintosh encoding.Encoding = &macintosh
    +

    +Macintosh is the Macintosh encoding. +

    + + +
    var MacintoshCyrillic encoding.Encoding = &macintoshCyrillic
    +

    +MacintoshCyrillic is the Macintosh Cyrillic encoding. +

    + + +
    var Windows1250 encoding.Encoding = &windows1250
    +

    +Windows1250 is the Windows 1250 encoding. +

    + + +
    var Windows1251 encoding.Encoding = &windows1251
    +

    +Windows1251 is the Windows 1251 encoding. +

    + + +
    var Windows1252 encoding.Encoding = &windows1252
    +

    +Windows1252 is the Windows 1252 encoding. +

    + + +
    var Windows1253 encoding.Encoding = &windows1253
    +

    +Windows1253 is the Windows 1253 encoding. +

    + + +
    var Windows1254 encoding.Encoding = &windows1254
    +

    +Windows1254 is the Windows 1254 encoding. +

    + + +
    var Windows1255 encoding.Encoding = &windows1255
    +

    +Windows1255 is the Windows 1255 encoding. +

    + + +
    var Windows1256 encoding.Encoding = &windows1256
    +

    +Windows1256 is the Windows 1256 encoding. +

    + + +
    var Windows1257 encoding.Encoding = &windows1257
    +

    +Windows1257 is the Windows 1257 encoding. +

    + + +
    var Windows1258 encoding.Encoding = &windows1258
    +

    +Windows1258 is the Windows 1258 encoding. +

    + + +
    var Windows874 encoding.Encoding = &windows874
    +

    +Windows874 is the Windows 874 encoding. +

    + + +
    var XUserDefined encoding.Encoding = &xUserDefined
    +

    +XUserDefined is the X-User-Defined encoding. +

    +

    +It is defined at http://encoding.spec.whatwg.org/#x-user-defined +

    + + + + + + + + + + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/golang.org/x/text/encoding/htmlindex/index.html b/pkg/golang.org/x/text/encoding/htmlindex/index.html new file mode 100644 index 0000000..101745b --- /dev/null +++ b/pkg/golang.org/x/text/encoding/htmlindex/index.html @@ -0,0 +1,259 @@ + + + + + + + + htmlindex - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Package htmlindex

    + + + + + + + + + + + + + + +
    +
    +
    import "golang.org/x/text/encoding/htmlindex"
    +
    +
    +
    Overview
    +
    Index
    + + +
    +
    + +
    + +
    +

    Overview ▾

    +

    +Package htmlindex maps character set encoding names to Encodings as +recommended by the W3C for use in HTML 5. See http://www.w3.org/TR/encoding. +

    + +
    +
    + + +
    + + +
    + + + + + + + + +

    func Get

    +
    func Get(name string) (encoding.Encoding, error)
    +

    +Get returns an Encoding for one of the names listed in +http://www.w3.org/TR/encoding using the Default Index. Matching is case- +insensitive. +

    + + + + + + + +

    func LanguageDefault

    +
    func LanguageDefault(tag language.Tag) string
    +

    +LanguageDefault returns the canonical name of the default encoding for a +given language. +

    + + + + + + + +

    func Name

    +
    func Name(e encoding.Encoding) (string, error)
    +

    +Name reports the canonical name of the given Encoding. It will return +an error if e is not associated with a supported encoding scheme. +

    + + + + + + + + + + + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/golang.org/x/text/encoding/ianaindex/index.html b/pkg/golang.org/x/text/encoding/ianaindex/index.html new file mode 100644 index 0000000..0822590 --- /dev/null +++ b/pkg/golang.org/x/text/encoding/ianaindex/index.html @@ -0,0 +1,315 @@ + + + + + + + + ianaindex - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Package ianaindex

    + + + + + + + + + + + + + + +
    +
    +
    import "golang.org/x/text/encoding/ianaindex"
    +
    +
    +
    Overview
    +
    Index
    + +
    Examples
    + + +
    +
    + +
    + +
    +

    Overview ▾

    +

    +Package ianaindex maps names to Encodings as specified by the IANA registry. +This includes both the MIME and IANA names. +

    +

    +See http://www.iana.org/assignments/character-sets/character-sets.xhtml for +more details. +

    + +
    +
    + + +
    + +
    +

    Index ▾

    + + + + + +
    +

    Examples

    +
    + +
    Index
    + +
    +
    + + + +

    Package files

    +

    + + + ianaindex.go + + +

    + +
    +
    + + + + + + + + + +

    type Index

    +
    type Index struct {
    +}
    +

    +Index maps names registered by IANA to Encodings. +

    + + + + + +
    var (
    +    // MIME is an index to map MIME names. It does not support aliases.
    +    MIME *Index
    +
    +    // IANA is an index that supports all names and aliases using IANA names as
    +    // the canonical identifier.
    +    IANA *Index
    +)
    + + + +
    + +
    +

    Example

    + + + +

    Code:

    +
    +fmt.Println(ianaindex.MIME.Name(charmap.ISO8859_7))
    +
    +fmt.Println(ianaindex.IANA.Name(charmap.ISO8859_7))
    +
    +e, _ := ianaindex.IANA.Get("cp437")
    +fmt.Println(ianaindex.IANA.Name(e))
    +
    +// TODO: Output:
    +// ISO-8859-7
    +// ISO8859_7:1987
    +// IBM437
    +
    + + +
    +
    + + + + + + + + +

    func (*Index) Get

    +
    func (x *Index) Get(name string) (encoding.Encoding, error)
    +

    +Get returns an Encoding for IANA-registered names. Matching is +case-insensitive. +

    + + + + + + +

    func (*Index) Name

    +
    func (x *Index) Name(e encoding.Encoding) (string, error)
    +

    +Name reports the canonical name of the given Encoding. It will return an +error if the e is not associated with a known encoding scheme. +

    + + + + + + + + + + + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/golang.org/x/text/encoding/index.html b/pkg/golang.org/x/text/encoding/index.html new file mode 100644 index 0000000..0d67fb2 --- /dev/null +++ b/pkg/golang.org/x/text/encoding/index.html @@ -0,0 +1,637 @@ + + + + + + + + encoding - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Package encoding

    + + + + + + + + + + + + + + +
    +
    +
    import "golang.org/x/text/encoding"
    +
    +
    +
    Overview
    +
    Index
    + +
    Examples
    + + +
    Subdirectories
    + +
    +
    + +
    + +
    +

    Overview ▾

    +

    +Package encoding defines an interface for character encodings, such as Shift +JIS and Windows 1252, that can convert to and from UTF-8. +

    +

    +Encoding implementations are provided in other packages, such as +golang.org/x/text/encoding/charmap and +golang.org/x/text/encoding/japanese. +

    + +
    +
    + + + + + + + +

    Constants

    + +
    const ASCIISub = '\x1a'
    +

    +ASCIISub is the ASCII substitute character, as recommended by +http://unicode.org/reports/tr36/#Text_Comparison +

    + + + + +

    Variables

    + +
    var ErrInvalidUTF8 = errors.New("encoding: invalid UTF-8")
    +

    +ErrInvalidUTF8 means that a transformer encountered invalid UTF-8. +

    + + +
    var UTF8Validator transform.Transformer = utf8Validator{}
    +

    +UTF8Validator is a transformer that returns ErrInvalidUTF8 on the first +input byte that is not valid UTF-8. +

    + + + + + + + +

    type Decoder

    +
    type Decoder struct {
    +    transform.Transformer
    +    // contains filtered or unexported fields
    +}
    +

    +A Decoder converts bytes to UTF-8. It implements transform.Transformer. +

    +

    +Transforming source bytes that are not of that encoding will not result in an +error per se. Each byte that cannot be transcoded will be represented in the +output by the UTF-8 encoding of '\uFFFD', the replacement rune. +

    + + + + + + + + + + + + + + +

    func (*Decoder) Bytes

    +
    func (d *Decoder) Bytes(b []byte) ([]byte, error)
    +

    +Bytes converts the given encoded bytes to UTF-8. It returns the converted +bytes or nil, err if any error occurred. +

    + + + + + + +

    func (*Decoder) Reader

    +
    func (d *Decoder) Reader(r io.Reader) io.Reader
    +

    +Reader wraps another Reader to decode its bytes. +

    +

    +The Decoder may not be used for any other operation as long as the returned +Reader is in use. +

    + + + + + + +

    func (*Decoder) String

    +
    func (d *Decoder) String(s string) (string, error)
    +

    +String converts the given encoded string to UTF-8. It returns the converted +string or "", err if any error occurred. +

    + + + + + + + + +

    type Encoder

    +
    type Encoder struct {
    +    transform.Transformer
    +    // contains filtered or unexported fields
    +}
    +

    +An Encoder converts bytes from UTF-8. It implements transform.Transformer. +

    +

    +Each rune that cannot be transcoded will result in an error. In this case, +the transform will consume all source byte up to, not including the offending +rune. Transforming source bytes that are not valid UTF-8 will be replaced by +`\uFFFD`. To return early with an error instead, use transform.Chain to +preprocess the data with a UTF8Validator. +

    + + + + + + + + + + + + +

    func HTMLEscapeUnsupported

    +
    func HTMLEscapeUnsupported(e *Encoder) *Encoder
    +

    +HTMLEscapeUnsupported wraps encoders to replace source runes outside the +repertoire of the destination encoding with HTML escape sequences. +

    +

    +This wrapper exists to comply to URL and HTML forms requiring a +non-terminating legacy encoder. The produced sequences may lead to data +loss as they are indistinguishable from legitimate input. To avoid this +issue, use UTF-8 encodings whenever possible. +

    + + + + + +

    func ReplaceUnsupported

    +
    func ReplaceUnsupported(e *Encoder) *Encoder
    +

    +ReplaceUnsupported wraps encoders to replace source runes outside the +repertoire of the destination encoding with an encoding-specific +replacement. +

    +

    +This wrapper is only provided for backwards compatibility and legacy +handling. Its use is strongly discouraged. Use UTF-8 whenever possible. +

    + + + + + + + +

    func (*Encoder) Bytes

    +
    func (e *Encoder) Bytes(b []byte) ([]byte, error)
    +

    +Bytes converts bytes from UTF-8. It returns the converted bytes or nil, err if +any error occurred. +

    + + + + + + +

    func (*Encoder) String

    +
    func (e *Encoder) String(s string) (string, error)
    +

    +String converts a string from UTF-8. It returns the converted string or +"", err if any error occurred. +

    + + + + + + +

    func (*Encoder) Writer

    +
    func (e *Encoder) Writer(w io.Writer) io.Writer
    +

    +Writer wraps another Writer to encode its UTF-8 output. +

    +

    +The Encoder may not be used for any other operation as long as the returned +Writer is in use. +

    + + + + + + + + +

    type Encoding

    +
    type Encoding interface {
    +    // NewDecoder returns a Decoder.
    +    NewDecoder() *Decoder
    +
    +    // NewEncoder returns an Encoder.
    +    NewEncoder() *Encoder
    +}
    +

    +Encoding is a character set encoding that can be transformed to and from +UTF-8. +

    + + + + + +
    var Nop Encoding = nop{}
    +

    +Nop is the nop encoding. Its transformed bytes are the same as the source +bytes; it does not replace invalid UTF-8 sequences. +

    + + +
    var Replacement Encoding = replacement{}
    +

    +Replacement is the replacement encoding. Decoding from the replacement +encoding yields a single '\uFFFD' replacement rune. Encoding from UTF-8 to +the replacement encoding yields the same as the source bytes except that +invalid UTF-8 is converted to '\uFFFD'. +

    +

    +It is defined at http://encoding.spec.whatwg.org/#replacement +

    + + + + + + + + + + + + + + + + + + + + + +

    Subdirectories

    + + + + +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    NameSynopsis
    ..
    + charmap + + Package charmap provides simple character encodings such as IBM Code Page 437 and Windows 1252. +
    + htmlindex + + Package htmlindex maps character set encoding names to Encodings as recommended by the W3C for use in HTML 5. +
    + ianaindex + + Package ianaindex maps names to Encodings as specified by the IANA registry. +
    + japanese + + Package japanese provides Japanese encodings such as EUC-JP and Shift JIS. +
    + korean + + Package korean provides Korean encodings such as EUC-KR. +
    + simplifiedchinese + + Package simplifiedchinese provides Simplified Chinese encodings such as GBK. +
    + traditionalchinese + + Package traditionalchinese provides Traditional Chinese encodings such as Big5. +
    + unicode + + Package unicode provides Unicode encodings such as UTF-16. +
    + utf32 + + Package utf32 provides the UTF-32 Unicode encoding. +
    +
    + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/golang.org/x/text/encoding/japanese/index.html b/pkg/golang.org/x/text/encoding/japanese/index.html new file mode 100644 index 0000000..f1b53e7 --- /dev/null +++ b/pkg/golang.org/x/text/encoding/japanese/index.html @@ -0,0 +1,243 @@ + + + + + + + + japanese - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Package japanese

    + + + + + + + + + + + + + + +
    +
    +
    import "golang.org/x/text/encoding/japanese"
    +
    +
    +
    Overview
    +
    Index
    + + +
    +
    + +
    + +
    +

    Overview ▾

    +

    +Package japanese provides Japanese encodings such as EUC-JP and Shift JIS. +

    + +
    +
    + + +
    + +
    +

    Index ▾

    + + +
    +
    + + +
    Variables
    + + + + +
    +
    + + + + +

    Package files

    +

    + + + all.go + + eucjp.go + + iso2022jp.go + + shiftjis.go + + tables.go + + +

    + +
    +
    + + + + + +

    Variables

    + +
    var All = []encoding.Encoding{EUCJP, ISO2022JP, ShiftJIS}
    +

    +All is a list of all defined encodings in this package. +

    + + +
    var EUCJP encoding.Encoding = &eucJP
    +

    +EUCJP is the EUC-JP encoding. +

    + + +
    var ISO2022JP encoding.Encoding = &iso2022JP
    +

    +ISO2022JP is the ISO-2022-JP encoding. +

    + + +
    var ShiftJIS encoding.Encoding = &shiftJIS
    +

    +ShiftJIS is the Shift JIS encoding, also known as Code Page 932 and +Windows-31J. +

    + + + + + + + + + + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/golang.org/x/text/encoding/korean/index.html b/pkg/golang.org/x/text/encoding/korean/index.html new file mode 100644 index 0000000..1cd45db --- /dev/null +++ b/pkg/golang.org/x/text/encoding/korean/index.html @@ -0,0 +1,224 @@ + + + + + + + + korean - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Package korean

    + + + + + + + + + + + + + + +
    +
    +
    import "golang.org/x/text/encoding/korean"
    +
    +
    +
    Overview
    +
    Index
    + + +
    +
    + +
    + +
    +

    Overview ▾

    +

    +Package korean provides Korean encodings such as EUC-KR. +

    + +
    +
    + + +
    + +
    +

    Index ▾

    + + +
    +
    + + +
    Variables
    + + + + +
    +
    + + + + +

    Package files

    +

    + + + euckr.go + + tables.go + + +

    + +
    +
    + + + + + +

    Variables

    + +
    var All = []encoding.Encoding{EUCKR}
    +

    +All is a list of all defined encodings in this package. +

    + + +
    var EUCKR encoding.Encoding = &eucKR
    +

    +EUCKR is the EUC-KR encoding, also known as Code Page 949. +

    + + + + + + + + + + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/golang.org/x/text/encoding/simplifiedchinese/index.html b/pkg/golang.org/x/text/encoding/simplifiedchinese/index.html new file mode 100644 index 0000000..7acc65f --- /dev/null +++ b/pkg/golang.org/x/text/encoding/simplifiedchinese/index.html @@ -0,0 +1,237 @@ + + + + + + + + simplifiedchinese - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Package simplifiedchinese

    + + + + + + + + + + + + + + +
    +
    +
    import "golang.org/x/text/encoding/simplifiedchinese"
    +
    +
    +
    Overview
    +
    Index
    + + +
    +
    + +
    + +
    +

    Overview ▾

    +

    +Package simplifiedchinese provides Simplified Chinese encodings such as GBK. +

    + +
    +
    + + +
    + +
    +

    Index ▾

    + + +
    +
    + + +
    Variables
    + + + + +
    +
    + + + + +

    Package files

    +

    + + + all.go + + gbk.go + + hzgb2312.go + + tables.go + + +

    + +
    +
    + + + + + +

    Variables

    + +
    var (
    +    // GB18030 is the GB18030 encoding.
    +    GB18030 encoding.Encoding = &gbk18030
    +    // GBK is the GBK encoding. It encodes an extension of the GB2312 character set
    +    // and is also known as Code Page 936.
    +    GBK encoding.Encoding = &gbk
    +)
    + + +
    var All = []encoding.Encoding{GB18030, GBK, HZGB2312}
    +

    +All is a list of all defined encodings in this package. +

    + + +
    var HZGB2312 encoding.Encoding = &hzGB2312
    +

    +HZGB2312 is the HZ-GB2312 encoding. +

    + + + + + + + + + + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/golang.org/x/text/encoding/traditionalchinese/index.html b/pkg/golang.org/x/text/encoding/traditionalchinese/index.html new file mode 100644 index 0000000..1eac604 --- /dev/null +++ b/pkg/golang.org/x/text/encoding/traditionalchinese/index.html @@ -0,0 +1,224 @@ + + + + + + + + traditionalchinese - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Package traditionalchinese

    + + + + + + + + + + + + + + +
    +
    +
    import "golang.org/x/text/encoding/traditionalchinese"
    +
    +
    +
    Overview
    +
    Index
    + + +
    +
    + +
    + +
    +

    Overview ▾

    +

    +Package traditionalchinese provides Traditional Chinese encodings such as Big5. +

    + +
    +
    + + +
    + +
    +

    Index ▾

    + + +
    +
    + + +
    Variables
    + + + + +
    +
    + + + + +

    Package files

    +

    + + + big5.go + + tables.go + + +

    + +
    +
    + + + + + +

    Variables

    + +
    var All = []encoding.Encoding{Big5}
    +

    +All is a list of all defined encodings in this package. +

    + + +
    var Big5 encoding.Encoding = &big5
    +

    +Big5 is the Big5 encoding, also known as Code Page 950. +

    + + + + + + + + + + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/golang.org/x/text/encoding/unicode/index.html b/pkg/golang.org/x/text/encoding/unicode/index.html new file mode 100644 index 0000000..b4259a9 --- /dev/null +++ b/pkg/golang.org/x/text/encoding/unicode/index.html @@ -0,0 +1,429 @@ + + + + + + + + unicode - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Package unicode

    + + + + + + + + + + + + + + +
    +
    +
    import "golang.org/x/text/encoding/unicode"
    +
    +
    +
    Overview
    +
    Index
    + + +
    Subdirectories
    + +
    +
    + +
    + +
    +

    Overview ▾

    +

    +Package unicode provides Unicode encodings such as UTF-16. +

    + +
    +
    + + +
    + +
    +

    Index ▾

    + + + + + + + +

    Package files

    +

    + + + override.go + + unicode.go + + +

    + +
    +
    + + + + + +

    Variables

    + +
    var All = []encoding.Encoding{
    +    UTF8,
    +    UTF16(BigEndian, UseBOM),
    +    UTF16(BigEndian, IgnoreBOM),
    +    UTF16(LittleEndian, IgnoreBOM),
    +}
    +

    +All lists a configuration for each IANA-defined UTF-16 variant. +

    + + +
    var ErrMissingBOM = errors.New("encoding: missing byte order mark")
    +

    +ErrMissingBOM means that decoding UTF-16 input with ExpectBOM did not find a +starting byte order mark. +

    + + +
    var UTF8 encoding.Encoding = utf8enc
    +

    +UTF8 is the UTF-8 encoding. +

    + + + + + + +

    func BOMOverride

    +
    func BOMOverride(fallback transform.Transformer) transform.Transformer
    +

    +BOMOverride returns a new decoder transformer that is identical to fallback, +except that the presence of a Byte Order Mark at the start of the input +causes it to switch to the corresponding Unicode decoding. It will only +consider BOMs for UTF-8, UTF-16BE, and UTF-16LE. +

    +

    +This differs from using ExpectBOM by allowing a BOM to switch to UTF-8, not +just UTF-16 variants, and allowing falling back to any encoding scheme. +

    +

    +This technique is recommended by the W3C for use in HTML 5: "For +compatibility with deployed content, the byte order mark (also known as BOM) +is considered more authoritative than anything else." +http://www.w3.org/TR/encoding/#specification-hooks +

    +

    +Using BOMOverride is mostly intended for use cases where the first characters +of a fallback encoding are known to not be a BOM, for example, for valid HTML +and most encodings. +

    + + + + + + + +

    func UTF16

    +
    func UTF16(e Endianness, b BOMPolicy) encoding.Encoding
    +

    +UTF16 returns a UTF-16 Encoding for the given default endianness and byte +order mark (BOM) policy. +

    +

    +When decoding from UTF-16 to UTF-8, if the BOMPolicy is IgnoreBOM then +neither BOMs U+FEFF nor noncharacters U+FFFE in the input stream will affect +the endianness used for decoding, and will instead be output as their +standard UTF-8 encodings: "\xef\xbb\xbf" and "\xef\xbf\xbe". If the BOMPolicy +is UseBOM or ExpectBOM a staring BOM is not written to the UTF-8 output. +Instead, it overrides the default endianness e for the remainder of the +transformation. Any subsequent BOMs U+FEFF or noncharacters U+FFFE will not +affect the endianness used, and will instead be output as their standard +UTF-8 encodings. For UseBOM, if there is no starting BOM, it will proceed +with the default Endianness. For ExpectBOM, in that case, the transformation +will return early with an ErrMissingBOM error. +

    +

    +When encoding from UTF-8 to UTF-16, a BOM will be inserted at the start of +the output if the BOMPolicy is UseBOM or ExpectBOM. Otherwise, a BOM will not +be inserted. The UTF-8 input does not need to contain a BOM. +

    +

    +There is no concept of a 'native' endianness. If the UTF-16 data is produced +and consumed in a greater context that implies a certain endianness, use +IgnoreBOM. Otherwise, use ExpectBOM and always produce and consume a BOM. +

    +

    +In the language of http://www.unicode.org/faq/utf_bom.html#bom10, IgnoreBOM +corresponds to "Where the precise type of the data stream is known... the +BOM should not be used" and ExpectBOM corresponds to "A particular +protocol... may require use of the BOM". +

    + + + + + + + + +

    type BOMPolicy

    +
    type BOMPolicy uint8
    +

    +BOMPolicy is a UTF-16 encoding's byte order mark policy. +

    + + + +
    const (
    +
    +    // IgnoreBOM means to ignore any byte order marks.
    +    IgnoreBOM BOMPolicy = 0
    +
    +    // UseBOM means that the UTF-16 form may start with a byte order mark, which
    +    // will be used to override the default encoding.
    +    UseBOM BOMPolicy = writeBOM | acceptBOM
    +
    +    // ExpectBOM means that the UTF-16 form must start with a byte order mark,
    +    // which will be used to override the default encoding.
    +    ExpectBOM BOMPolicy = writeBOM | acceptBOM | requireBOM
    +)
    + + + + + + + + + + + + + + + +

    type Endianness

    +
    type Endianness bool
    +

    +Endianness is a UTF-16 encoding's default endianness. +

    + + + +
    const (
    +    // BigEndian is UTF-16BE.
    +    BigEndian Endianness = false
    +    // LittleEndian is UTF-16LE.
    +    LittleEndian Endianness = true
    +)
    + + + + + + + + + + + + + + + + + + + + + + + +

    Subdirectories

    + + + + +
    + + + + + + + + + + + + + + + + + + + + +
    NameSynopsis
    ..
    + utf32 + + Package utf32 provides the UTF-32 Unicode encoding. +
    +
    + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/golang.org/x/text/encoding/unicode/utf32/index.html b/pkg/golang.org/x/text/encoding/unicode/utf32/index.html new file mode 100644 index 0000000..73c6419 --- /dev/null +++ b/pkg/golang.org/x/text/encoding/unicode/utf32/index.html @@ -0,0 +1,359 @@ + + + + + + + + utf32 - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Package utf32

    + + + + + + + + + + + + + + +
    +
    +
    import "golang.org/x/text/encoding/unicode/utf32"
    +
    +
    +
    Overview
    +
    Index
    + + +
    +
    + +
    + +
    +

    Overview ▾

    +

    +Package utf32 provides the UTF-32 Unicode encoding. +

    +

    +Please note that support for UTF-32 is discouraged as it is a rare and +inefficient encoding, unfit for use as an interchange format. For use +on the web, the W3C strongly discourages its use +(https://www.w3.org/TR/html5/document-metadata.html#charset) +while WHATWG directly prohibits supporting it +(https://html.spec.whatwg.org/multipage/syntax.html#character-encodings). +

    + +
    +
    + + +
    + +
    +

    Index ▾

    + + + + + + + +

    Package files

    +

    + + + utf32.go + + +

    + +
    +
    + + + + + +

    Variables

    + +
    var All = []encoding.Encoding{
    +    UTF32(BigEndian, UseBOM),
    +    UTF32(BigEndian, IgnoreBOM),
    +    UTF32(LittleEndian, IgnoreBOM),
    +}
    +

    +All lists a configuration for each IANA-defined UTF-32 variant. +

    + + +
    var ErrMissingBOM = errors.New("encoding: missing byte order mark")
    +

    +ErrMissingBOM means that decoding UTF-32 input with ExpectBOM did not +find a starting byte order mark. +

    + + + + + + +

    func UTF32

    +
    func UTF32(e Endianness, b BOMPolicy) encoding.Encoding
    +

    +UTF32 returns a UTF-32 Encoding for the given default endianness and +byte order mark (BOM) policy. +

    +

    +When decoding from UTF-32 to UTF-8, if the BOMPolicy is IgnoreBOM then +neither BOMs U+FEFF nor ill-formed code units 0xFFFE0000 in the input +stream will affect the endianness used for decoding. Instead BOMs will +be output as their standard UTF-8 encoding "\xef\xbb\xbf" while +0xFFFE0000 code units will be output as "\xef\xbf\xbd", the standard +UTF-8 encoding for the Unicode replacement character. If the BOMPolicy +is UseBOM or ExpectBOM a starting BOM is not written to the UTF-8 +output. Instead, it overrides the default endianness e for the remainder +of the transformation. Any subsequent BOMs U+FEFF or ill-formed code +units 0xFFFE0000 will not affect the endianness used, and will instead +be output as their standard UTF-8 (replacement) encodings. For UseBOM, +if there is no starting BOM, it will proceed with the default +Endianness. For ExpectBOM, in that case, the transformation will return +early with an ErrMissingBOM error. +

    +

    +When encoding from UTF-8 to UTF-32, a BOM will be inserted at the start +of the output if the BOMPolicy is UseBOM or ExpectBOM. Otherwise, a BOM +will not be inserted. The UTF-8 input does not need to contain a BOM. +

    +

    +There is no concept of a 'native' endianness. If the UTF-32 data is +produced and consumed in a greater context that implies a certain +endianness, use IgnoreBOM. Otherwise, use ExpectBOM and always produce +and consume a BOM. +

    +

    +In the language of http://www.unicode.org/faq/utf_bom.html#bom10, +IgnoreBOM corresponds to "Where the precise type of the data stream is +known... the BOM should not be used" and ExpectBOM corresponds to "A +particular protocol... may require use of the BOM". +

    + + + + + + + + +

    type BOMPolicy

    +
    type BOMPolicy uint8
    +

    +BOMPolicy is a UTF-32 encodings's byte order mark policy. +

    + + + +
    const (
    +
    +    // IgnoreBOM means to ignore any byte order marks.
    +    IgnoreBOM BOMPolicy = 0
    +
    +    // UseBOM means that the UTF-32 form may start with a byte order mark,
    +    // which will be used to override the default encoding.
    +    UseBOM BOMPolicy = writeBOM | acceptBOM
    +
    +    // ExpectBOM means that the UTF-32 form must start with a byte order mark,
    +    // which will be used to override the default encoding.
    +    ExpectBOM BOMPolicy = writeBOM | acceptBOM | requireBOM
    +)
    + + + + + + + + + + + + + + + +

    type Endianness

    +
    type Endianness bool
    +

    +Endianness is a UTF-32 encoding's default endianness. +

    + + + +
    const (
    +    // BigEndian is UTF-32BE.
    +    BigEndian Endianness = false
    +    // LittleEndian is UTF-32LE.
    +    LittleEndian Endianness = true
    +)
    + + + + + + + + + + + + + + + + + + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/golang.org/x/text/index.html b/pkg/golang.org/x/text/index.html new file mode 100644 index 0000000..8b25dcc --- /dev/null +++ b/pkg/golang.org/x/text/index.html @@ -0,0 +1,273 @@ + + + + + + + + /src/golang.org/x/text - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Directory /src/golang.org/x/text

    + + + + + + + + + + + + + + + + + + + +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    NameSynopsis
    ..
    + encoding + + Package encoding defines an interface for character encodings, such as Shift JIS and Windows 1252, that can convert to and from UTF-8. +
    + charmap + + Package charmap provides simple character encodings such as IBM Code Page 437 and Windows 1252. +
    + htmlindex + + Package htmlindex maps character set encoding names to Encodings as recommended by the W3C for use in HTML 5. +
    + ianaindex + + Package ianaindex maps names to Encodings as specified by the IANA registry. +
    + japanese + + Package japanese provides Japanese encodings such as EUC-JP and Shift JIS. +
    + korean + + Package korean provides Korean encodings such as EUC-KR. +
    + simplifiedchinese + + Package simplifiedchinese provides Simplified Chinese encodings such as GBK. +
    + traditionalchinese + + Package traditionalchinese provides Traditional Chinese encodings such as Big5. +
    + unicode + + Package unicode provides Unicode encodings such as UTF-16. +
    + utf32 + + Package utf32 provides the UTF-32 Unicode encoding. +
    + language + + Package language implements BCP 47 language tags and related functionality. +
    + display + + Package display provides display names for languages, scripts and regions in a requested language. +
    + runes + + Package runes provide transforms for UTF-8 encoded text. +
    + transform + + Package transform provides reader and writer wrappers that transform the bytes passing through as well as various transformations. +
    +
    + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/golang.org/x/text/language/display/index.html b/pkg/golang.org/x/text/language/display/index.html new file mode 100644 index 0000000..5a5ca7c --- /dev/null +++ b/pkg/golang.org/x/text/language/display/index.html @@ -0,0 +1,729 @@ + + + + + + + + display - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Package display

    + + + + + + + + + + + + + + +
    +
    +
    import "golang.org/x/text/language/display"
    +
    +
    +
    Overview
    +
    Index
    + +
    Examples
    + + +
    +
    + +
    + +
    +

    Overview ▾

    +

    +Package display provides display names for languages, scripts and regions in +a requested language. +

    +

    +The data is based on CLDR's localeDisplayNames. It includes the names of the +draft level "contributed" or "approved". The resulting tables are quite +large. The display package is designed so that users can reduce the linked-in +table sizes by cherry picking the languages one wishes to support. There is a +Dictionary defined for a selected set of common languages for this purpose. +

    + +
    +
    + + +
    + +
    +

    Index ▾

    + + + + + +
    +

    Examples

    +
    + +
    Dictionary
    + +
    Namer
    + +
    Tags
    + +
    +
    + + + +

    Package files

    +

    + + + dict.go + + display.go + + lookup.go + + tables.go + + +

    + +
    +
    + + + + +

    Constants

    + +
    const CLDRVersion = "29"
    +

    +CLDRVersion is the CLDR version from which the tables in this package are derived. +

    + + +
    const Version = "29"
    +

    +Version is deprecated. Use CLDRVersion. +

    + + + + +

    Variables

    + +
    var (
    +    // Supported lists the languages for which names are defined.
    +    Supported language.Coverage
    +
    +    // The set of all possible values for which names are defined. Note that not
    +    // all Namer implementations will cover all the values of a given type.
    +    // A Namer will return the empty string for unsupported values.
    +    Values language.Coverage
    +)
    + + + + + + + +

    type Dictionary

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

    +A Dictionary holds a collection of Namers for a single language. One can +reduce the amount of data linked in to a binary by only referencing +Dictionaries for the languages one needs to support instead of using the +generic Namer factories. +

    + + + + + +
    var (
    +    Afrikaans            *Dictionary = &af        // af
    +    Amharic              *Dictionary = &am        // am
    +    Arabic               *Dictionary = &ar        // ar
    +    ModernStandardArabic *Dictionary = Arabic     // ar-001
    +    Azerbaijani          *Dictionary = &az        // az
    +    Bulgarian            *Dictionary = &bg        // bg
    +    Bengali              *Dictionary = &bn        // bn
    +    Catalan              *Dictionary = &ca        // ca
    +    Czech                *Dictionary = &cs        // cs
    +    Danish               *Dictionary = &da        // da
    +    German               *Dictionary = &de        // de
    +    Greek                *Dictionary = &el        // el
    +    English              *Dictionary = &en        // en
    +    AmericanEnglish      *Dictionary = English    // en-US
    +    BritishEnglish       *Dictionary = English    // en-GB
    +    Spanish              *Dictionary = &es        // es
    +    EuropeanSpanish      *Dictionary = Spanish    // es-ES
    +    LatinAmericanSpanish *Dictionary = Spanish    // es-419
    +    Estonian             *Dictionary = &et        // et
    +    Persian              *Dictionary = &fa        // fa
    +    Finnish              *Dictionary = &fi        // fi
    +    Filipino             *Dictionary = &fil       // fil
    +    French               *Dictionary = &fr        // fr
    +    Gujarati             *Dictionary = &gu        // gu
    +    Hebrew               *Dictionary = &he        // he
    +    Hindi                *Dictionary = &hi        // hi
    +    Croatian             *Dictionary = &hr        // hr
    +    Hungarian            *Dictionary = &hu        // hu
    +    Armenian             *Dictionary = &hy        // hy
    +    Indonesian           *Dictionary = &id        // id
    +    Icelandic            *Dictionary = &is        // is
    +    Italian              *Dictionary = &it        // it
    +    Japanese             *Dictionary = &ja        // ja
    +    Georgian             *Dictionary = &ka        // ka
    +    Kazakh               *Dictionary = &kk        // kk
    +    Khmer                *Dictionary = &km        // km
    +    Kannada              *Dictionary = &kn        // kn
    +    Korean               *Dictionary = &ko        // ko
    +    Kirghiz              *Dictionary = &ky        // ky
    +    Lao                  *Dictionary = &lo        // lo
    +    Lithuanian           *Dictionary = &lt        // lt
    +    Latvian              *Dictionary = &lv        // lv
    +    Macedonian           *Dictionary = &mk        // mk
    +    Malayalam            *Dictionary = &ml        // ml
    +    Mongolian            *Dictionary = &mn        // mn
    +    Marathi              *Dictionary = &mr        // mr
    +    Malay                *Dictionary = &ms        // ms
    +    Burmese              *Dictionary = &my        // my
    +    Nepali               *Dictionary = &ne        // ne
    +    Dutch                *Dictionary = &nl        // nl
    +    Norwegian            *Dictionary = &no        // no
    +    Punjabi              *Dictionary = &pa        // pa
    +    Polish               *Dictionary = &pl        // pl
    +    Portuguese           *Dictionary = &pt        // pt
    +    BrazilianPortuguese  *Dictionary = Portuguese // pt-BR
    +    EuropeanPortuguese   *Dictionary = &ptPT      // pt-PT
    +    Romanian             *Dictionary = &ro        // ro
    +    Russian              *Dictionary = &ru        // ru
    +    Sinhala              *Dictionary = &si        // si
    +    Slovak               *Dictionary = &sk        // sk
    +    Slovenian            *Dictionary = &sl        // sl
    +    Albanian             *Dictionary = &sq        // sq
    +    Serbian              *Dictionary = &sr        // sr
    +    SerbianLatin         *Dictionary = &srLatn    // sr
    +    Swedish              *Dictionary = &sv        // sv
    +    Swahili              *Dictionary = &sw        // sw
    +    Tamil                *Dictionary = &ta        // ta
    +    Telugu               *Dictionary = &te        // te
    +    Thai                 *Dictionary = &th        // th
    +    Turkish              *Dictionary = &tr        // tr
    +    Ukrainian            *Dictionary = &uk        // uk
    +    Urdu                 *Dictionary = &ur        // ur
    +    Uzbek                *Dictionary = &uz        // uz
    +    Vietnamese           *Dictionary = &vi        // vi
    +    Chinese              *Dictionary = &zh        // zh
    +    SimplifiedChinese    *Dictionary = Chinese    // zh-Hans
    +    TraditionalChinese   *Dictionary = &zhHant    // zh-Hant
    +    Zulu                 *Dictionary = &zu        // zu
    +)
    + + + +
    + +
    +

    Example

    +

    ExampleDictionary shows how to reduce the amount of data linked into your +binary by only using the predefined Dictionary variables of the languages you +wish to support. +

    + + +

    Code:

    +
    tags := []language.Tag{
    +    language.English,
    +    language.German,
    +    language.Japanese,
    +    language.Russian,
    +}
    +dicts := []*display.Dictionary{
    +    display.English,
    +    display.German,
    +    display.Japanese,
    +    display.Russian,
    +}
    +
    +m := language.NewMatcher(tags)
    +
    +getDict := func(t language.Tag) *display.Dictionary {
    +    _, i, confidence := m.Match(t)
    +    // Skip this check if you want to support a fall-back language, which
    +    // will be the first one passed to NewMatcher.
    +    if confidence == language.No {
    +        return nil
    +    }
    +    return dicts[i]
    +}
    +
    +// The matcher will match Swiss German to German.
    +n := getDict(language.Make("gsw")).Languages()
    +fmt.Println(n.Name(language.German))
    +fmt.Println(n.Name(language.Make("de-CH")))
    +fmt.Println(n.Name(language.Make("gsw")))
    +
    +
    + +

    Output:

    +
    Deutsch
    +Schweizer Hochdeutsch
    +Schweizerdeutsch
    +
    + + +
    +
    + + + + + + + + +

    func (*Dictionary) Languages

    +
    func (d *Dictionary) Languages() Namer
    +

    +Languages returns a Namer for naming languages. It returns nil if there is no +data for the given tag. The type passed to Name must be either language.Base +or language.Tag. Note that the result may differ between passing a tag or its +base language. For example, for English, passing "nl-BE" would return Flemish +whereas passing "nl" returns "Dutch". +

    + + + + + + +

    func (*Dictionary) Regions

    +
    func (d *Dictionary) Regions() Namer
    +

    +Regions returns a Namer for naming regions. It returns nil if there is no +data for the given tag. The type passed to Name must be either a +language.Region or a language.Tag. It will not attempt to infer a region for +tags with an unspecified region. +

    + + + + + + +

    func (*Dictionary) Scripts

    +
    func (d *Dictionary) Scripts() Namer
    +

    +Scripts returns a Namer for naming scripts. It returns nil if there is no +data for the given tag. The type passed to Name must be either a +language.Script or a language.Tag. It will not attempt to infer a script for +tags with an unspecified script. +

    + + + + + + +

    func (*Dictionary) Tags

    +
    func (d *Dictionary) Tags() Namer
    +

    +Tags returns a Namer for giving a full description of a tag. The names of +scripts and regions that are not already implied by the language name will +in appended within parentheses. It returns nil if there is not data for the +given tag. The type passed to Name must be a tag. +

    + + + + + + + + +

    type Namer

    +
    type Namer interface {
    +    // Name returns a display string for the given value. A Namer returns an
    +    // empty string for values it does not support. A Namer may support naming
    +    // an unspecified value. For example, when getting the name for a region for
    +    // a tag that does not have a defined Region, it may return the name for an
    +    // unknown region. It is up to the user to filter calls to Name for values
    +    // for which one does not want to have a name string.
    +    Name(x interface{}) string
    +}
    +

    +A Namer is used to get the name for a given value, such as a Tag, Language, +Script or Region. +

    + + + + + + +
    + +
    +

    Example

    + + + +

    Code:

    +
    supported := []string{
    +    "en-US", "en-GB", "ja", "zh", "zh-Hans", "zh-Hant", "pt", "pt-PT", "ko", "ar", "el", "ru", "uk", "pa",
    +}
    +
    +en := display.English.Languages()
    +
    +for _, s := range supported {
    +    t := language.MustParse(s)
    +    fmt.Printf("%-20s (%s)\n", en.Name(t), display.Self.Name(t))
    +}
    +
    +
    + +

    Output:

    +
    American English     (American English)
    +British English      (British English)
    +Japanese             (日本語)
    +Chinese              (中文)
    +Simplified Chinese   (简体中文)
    +Traditional Chinese  (繁體中文)
    +Portuguese           (português)
    +European Portuguese  (português europeu)
    +Korean               (한국어)
    +Arabic               (العربية)
    +Greek                (Ελληνικά)
    +Russian              (русский)
    +Ukrainian            (українська)
    +Punjabi              (ਪੰਜਾਬੀ)
    +
    + + +
    +
    + + + + + + +

    func Languages

    +
    func Languages(t language.Tag) Namer
    +

    +Languages returns a Namer for naming languages. It returns nil if there is no +data for the given tag. The type passed to Name must be either language.Base +or language.Tag. Note that the result may differ between passing a tag or its +base language. For example, for English, passing "nl-BE" would return Flemish +whereas passing "nl" returns "Dutch". +

    + + + + + +

    func Regions

    +
    func Regions(t language.Tag) Namer
    +

    +Regions returns a Namer for naming regions. It returns nil if there is no +data for the given tag. The type passed to Name must be either a +language.Region or a language.Tag. It will not attempt to infer a region for +tags with an unspecified region. +

    + + + + + +

    func Scripts

    +
    func Scripts(t language.Tag) Namer
    +

    +Scripts returns a Namer for naming scripts. It returns nil if there is no +data for the given tag. The type passed to Name must be either a +language.Script or a language.Tag. It will not attempt to infer a script for +tags with an unspecified script. +

    + + + + + +

    func Tags

    +
    func Tags(t language.Tag) Namer
    +

    +Tags returns a Namer for giving a full description of a tag. The names of +scripts and regions that are not already implied by the language name will +in appended within parentheses. It returns nil if there is not data for the +given tag. The type passed to Name must be a tag. +

    + +
    + +
    +

    Example

    + + + +

    Code:

    +
    n := display.Tags(language.English)
    +fmt.Println(n.Name(language.Make("nl")))
    +fmt.Println(n.Name(language.Make("nl-BE")))
    +fmt.Println(n.Name(language.Make("nl-CW")))
    +fmt.Println(n.Name(language.Make("nl-Arab")))
    +fmt.Println(n.Name(language.Make("nl-Cyrl-RU")))
    +
    +
    + +

    Output:

    +
    Dutch
    +Flemish
    +Dutch (Curaçao)
    +Dutch (Arabic)
    +Dutch (Cyrillic, Russia)
    +
    + + +
    +
    + + + + + + + + +

    type SelfNamer

    +
    type SelfNamer struct {
    +    // Supported defines the values supported by this Namer.
    +    Supported language.Coverage
    +}
    +

    +A SelfNamer implements a Namer that returns the name of language in this same +language. It provides a very compact mechanism to provide a comprehensive +list of languages to users in their native language. +

    + + + + + +
    var (
    +    // Self is a shared instance of a SelfNamer.
    +    Self *SelfNamer = &self
    +)
    + + + + + + + + + + + +

    func (SelfNamer) Name

    +
    func (n SelfNamer) Name(x interface{}) string
    +

    +Name returns the name of a given language tag in the language identified by +this tag. It supports both the language.Base and language.Tag types. +

    + + + + + + + + + + + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/golang.org/x/text/language/index.html b/pkg/golang.org/x/text/language/index.html new file mode 100644 index 0000000..334cd7c --- /dev/null +++ b/pkg/golang.org/x/text/language/index.html @@ -0,0 +1,2342 @@ + + + + + + + + language - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Package language

    + + + + + + + + + + + + + + +
    +
    +
    import "golang.org/x/text/language"
    +
    +
    +
    Overview
    +
    Index
    + +
    Examples
    + + +
    Subdirectories
    + +
    +
    + +
    + +
    +

    Overview ▾

    +

    +Package language implements BCP 47 language tags and related functionality. +

    +

    +The Tag type, which is used to represent languages, is agnostic to the +meaning of its subtags. Tags are not fully canonicalized to preserve +information that may be valuable in certain contexts. As a consequence, two +different tags may represent identical languages. +

    +

    +Initializing language- or locale-specific components usually consists of +two steps. The first step is to select a display language based on the +preferred languages of the user and the languages supported by an application. +The second step is to create the language-specific services based on +this selection. Each is discussed in more details below. +

    +

    Matching preferred against supported languages

    +

    +An application may support various languages. This list is typically limited +by the languages for which there exists translations of the user interface. +Similarly, a user may provide a list of preferred languages which is limited +by the languages understood by this user. +An application should use a Matcher to find the best supported language based +on the user's preferred list. +Matchers are aware of the intricacies of equivalence between languages. +The default Matcher implementation takes into account things such as +deprecated subtags, legacy tags, and mutual intelligibility between scripts +and languages. +

    +

    +A Matcher for English, Australian English, Danish, and standard Mandarin can +be defined as follows: +

    +
    var matcher = language.NewMatcher([]language.Tag{
    +	language.English,   // The first language is used as fallback.
    +	language.MustParse("en-AU"),
    +	language.Danish,
    +	language.Chinese,
    +})
    +
    +

    +The following code selects the best match for someone speaking Spanish and +Norwegian: +

    +
    preferred := []language.Tag{ language.Spanish, language.Norwegian }
    +tag, _, _ := matcher.Match(preferred...)
    +
    +

    +In this case, the best match is Danish, as Danish is sufficiently a match to +Norwegian to not have to fall back to the default. +See ParseAcceptLanguage on how to handle the Accept-Language HTTP header. +

    +

    Selecting language-specific services

    +

    +One should always use the Tag returned by the Matcher to create an instance +of any of the language-specific services provided by the text repository. +This prevents the mixing of languages, such as having a different language for +messages and display names, as well as improper casing or sorting order for +the selected language. +Using the returned Tag also allows user-defined settings, such as collation +order or numbering system to be transparently passed as options. +

    +

    +If you have language-specific data in your application, however, it will in +most cases suffice to use the index returned by the matcher to identify +the user language. +The following loop provides an alternative in case this is not sufficient: +

    +
    supported := map[language.Tag]data{
    +	language.English:            enData,
    +	language.MustParse("en-AU"): enAUData,
    +	language.Danish:             daData,
    +	language.Chinese:            zhData,
    +}
    +tag, _, _ := matcher.Match(preferred...)
    +for ; tag != language.Und; tag = tag.Parent() {
    +	if v, ok := supported[tag]; ok {
    +		return v
    +	}
    +}
    +return enData // should not reach here
    +
    +

    +Repeatedly taking the Parent of the tag returned by Match will eventually +match one of the tags used to initialize the Matcher. +

    +

    Canonicalization

    +

    +By default, only legacy and deprecated tags are converted into their +canonical equivalent. All other information is preserved. This approach makes +the confidence scores more accurate and allows matchers to distinguish +between variants that are otherwise lost. +

    +

    +As a consequence, two tags that should be treated as identical according to +BCP 47 or CLDR, like "en-Latn" and "en", will be represented differently. The +Matchers will handle such distinctions, though, and are aware of the +equivalence relations. The CanonType type can be used to alter the +canonicalization form. +

    +

    References

    +

    +BCP 47 - Tags for Identifying Languages +http://tools.ietf.org/html/bcp47 +

    + +
    +
    + + +
    + +
    +

    Index ▾

    + + +
    +
    + +
    Constants
    + + +
    Variables
    + + + +
    func CompactIndex(t Tag) (index int, ok bool)
    + + +
    func ParseAcceptLanguage(s string) (tag []Tag, q []float32, err error)
    + + + +
    type Base
    + + +
        func MustParseBase(s string) Base
    + + +
        func ParseBase(s string) (Base, error)
    + + + +
        func (b Base) ISO3() string
    + + +
        func (b Base) IsPrivateUse() bool
    + + +
        func (b Base) String() string
    + + + +
    type CanonType
    + + + +
        func (c CanonType) Canonicalize(t Tag) (Tag, error)
    + + +
        func (c CanonType) Compose(part ...interface{}) (t Tag, err error)
    + + +
        func (c CanonType) Make(s string) Tag
    + + +
        func (c CanonType) MustParse(s string) Tag
    + + +
        func (c CanonType) Parse(s string) (t Tag, err error)
    + + + +
    type Confidence
    + + +
        func Comprehends(speaker, alternative Tag) Confidence
    + + + +
        func (c Confidence) String() string
    + + + +
    type Coverage
    + + +
        func NewCoverage(list ...interface{}) Coverage
    + + + + +
    type Extension
    + + +
        func ParseExtension(s string) (e Extension, err error)
    + + + +
        func (e Extension) String() string
    + + +
        func (e Extension) Tokens() []string
    + + +
        func (e Extension) Type() byte
    + + + +
    type Matcher
    + + +
        func NewMatcher(t []Tag) Matcher
    + + + + +
    type Region
    + + +
        func EncodeM49(r int) (Region, error)
    + + +
        func MustParseRegion(s string) Region
    + + +
        func ParseRegion(s string) (Region, error)
    + + + +
        func (r Region) Canonicalize() Region
    + + +
        func (r Region) Contains(c Region) bool
    + + +
        func (r Region) ISO3() string
    + + +
        func (r Region) IsCountry() bool
    + + +
        func (r Region) IsGroup() bool
    + + +
        func (r Region) IsPrivateUse() bool
    + + +
        func (r Region) M49() int
    + + +
        func (r Region) String() string
    + + +
        func (r Region) TLD() (Region, error)
    + + + +
    type Script
    + + +
        func MustParseScript(s string) Script
    + + +
        func ParseScript(s string) (Script, error)
    + + + +
        func (s Script) IsPrivateUse() bool
    + + +
        func (s Script) String() string
    + + + +
    type Tag
    + + +
        func Compose(part ...interface{}) (t Tag, err error)
    + + +
        func Make(s string) Tag
    + + +
        func MustParse(s string) Tag
    + + +
        func Parse(s string) (t Tag, err error)
    + + + +
        func (t Tag) Base() (Base, Confidence)
    + + +
        func (t Tag) Extension(x byte) (ext Extension, ok bool)
    + + +
        func (t Tag) Extensions() []Extension
    + + +
        func (t Tag) IsRoot() bool
    + + +
        func (t Tag) Parent() Tag
    + + +
        func (t Tag) Raw() (b Base, s Script, r Region)
    + + +
        func (t Tag) Region() (Region, Confidence)
    + + +
        func (t Tag) Script() (Script, Confidence)
    + + +
        func (t Tag) SetTypeForKey(key, value string) (Tag, error)
    + + +
        func (t Tag) String() string
    + + +
        func (t Tag) TypeForKey(key string) string
    + + +
        func (t Tag) Variants() []Variant
    + + + +
    type ValueError
    + + + +
        func (e ValueError) Error() string
    + + +
        func (e ValueError) Subtag() string
    + + + +
    type Variant
    + + +
        func ParseVariant(s string) (Variant, error)
    + + + +
        func (v Variant) String() string
    + + + +
    +
    + + + + + + +

    Package files

    +

    + + + common.go + + coverage.go + + go1_2.go + + index.go + + language.go + + lookup.go + + match.go + + parse.go + + tables.go + + tags.go + + +

    + +
    +
    + + + + +

    Constants

    + +
    const CLDRVersion = "29"
    +

    +CLDRVersion is the CLDR version from which the tables in this package are derived. +

    + + +
    const NumCompactTags = 747
    +

    +NumCompactTags is the number of common tags. The maximum tag is +NumCompactTags-1. +

    + + + + +

    Variables

    + +
    var ErrMissingLikelyTagsData = errors.New("missing likely tags data")
    +

    +ErrMissingLikelyTagsData indicates no information was available +to compute likely values of missing tags. +

    + + + + + + +

    func CompactIndex

    +
    func CompactIndex(t Tag) (index int, ok bool)
    +

    +CompactIndex returns an index, where 0 <= index < NumCompactTags, for tags +for which data exists in the text repository. The index will change over time +and should not be stored in persistent storage. Extensions, except for the +'va' type of the 'u' extension, are ignored. It will return 0, false if no +compact tag exists, where 0 is the index for the root language (Und). +

    + + + + + + + +

    func ParseAcceptLanguage

    +
    func ParseAcceptLanguage(s string) (tag []Tag, q []float32, err error)
    +

    +ParseAcceptLanguage parses the contents of a Accept-Language header as +defined in http://www.ietf.org/rfc/rfc2616.txt and returns a list of Tags and +a list of corresponding quality weights. It is more permissive than RFC 2616 +and may return non-nil slices even if the input is not valid. +The Tags will be sorted by highest weight first and then by first occurrence. +Tags with a weight of zero will be dropped. An error will be returned if the +input could not be parsed. +

    + +
    + +
    +

    Example

    + + + +

    Code:

    +
    package language_test
    +
    +import (
    +    "fmt"
    +    "net/http"
    +    "strings"
    +
    +    "golang.org/x/text/language"
    +)
    +
    +// matcher is a language.Matcher configured for all supported languages.
    +var matcher = language.NewMatcher([]language.Tag{
    +    language.BritishEnglish,
    +    language.Norwegian,
    +    language.German,
    +})
    +
    +// handler is a http.HandlerFunc.
    +func handler(w http.ResponseWriter, r *http.Request) {
    +    t, q, err := language.ParseAcceptLanguage(r.Header.Get("Accept-Language"))
    +    // We ignore the error: the default language will be selected for t == nil.
    +    tag, _, _ := matcher.Match(t...)
    +    fmt.Printf("%5v (t: %6v; q: %3v; err: %v)\n", tag, t, q, err)
    +}
    +
    +func ExampleParseAcceptLanguage() {
    +    for _, al := range []string{
    +        "nn;q=0.3, en-us;q=0.8, en,",
    +        "gsw, en;q=0.7, en-US;q=0.8",
    +        "gsw, nl, da",
    +        "invalid",
    +    } {
    +        // Create dummy request with Accept-Language set and pass it to handler.
    +        r, _ := http.NewRequest("GET", "example.com", strings.NewReader("Hello"))
    +        r.Header.Set("Accept-Language", al)
    +        handler(nil, r)
    +    }
    +
    +    // Output:
    +    // en-GB (t: [    en  en-US     nn]; q: [  1 0.8 0.3]; err: <nil>)
    +    // en-GB (t: [   gsw  en-US     en]; q: [  1 0.8 0.7]; err: <nil>)
    +    //    de (t: [   gsw     nl     da]; q: [  1   1   1]; err: <nil>)
    +    // en-GB (t: []; q: []; err: language: tag is not well-formed)
    +}
    +
    + + +
    +
    + + + + + + + +

    type Base

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

    +Base is an ISO 639 language code, used for encoding the base language +of a language tag. +

    + + + + + + + + + + + + +

    func MustParseBase

    +
    func MustParseBase(s string) Base
    +

    +MustParseBase is like ParseBase, but panics if the given base cannot be parsed. +It simplifies safe initialization of Base values. +

    + + + + + +

    func ParseBase

    +
    func ParseBase(s string) (Base, error)
    +

    +ParseBase parses a 2- or 3-letter ISO 639 code. +It returns a ValueError if s is a well-formed but unknown language identifier +or another error if another error occurred. +

    + + + + + + + +

    func (Base) ISO3

    +
    func (b Base) ISO3() string
    +

    +ISO3 returns the ISO 639-3 language code. +

    + + + + + + +

    func (Base) IsPrivateUse

    +
    func (b Base) IsPrivateUse() bool
    +

    +IsPrivateUse reports whether this language code is reserved for private use. +

    + + + + + + +

    func (Base) String

    +
    func (b Base) String() string
    +

    +String returns the BCP 47 representation of the langID. +Use b as variable name, instead of id, to ensure the variable +used is consistent with that of Base in which this type is embedded. +

    + + + + + + + + +

    type CanonType

    +
    type CanonType int
    +

    +CanonType can be used to enable or disable various types of canonicalization. +

    + + + +
    const (
    +    // Replace deprecated base languages with their preferred replacements.
    +    DeprecatedBase CanonType = 1 << iota
    +    // Replace deprecated scripts with their preferred replacements.
    +    DeprecatedScript
    +    // Replace deprecated regions with their preferred replacements.
    +    DeprecatedRegion
    +    // Remove redundant scripts.
    +    SuppressScript
    +    // Normalize legacy encodings. This includes legacy languages defined in
    +    // CLDR as well as bibliographic codes defined in ISO-639.
    +    Legacy
    +    // Map the dominant language of a macro language group to the macro language
    +    // subtag. For example cmn -> zh.
    +    Macro
    +    // The CLDR flag should be used if full compatibility with CLDR is required.
    +    // There are a few cases where language.Tag may differ from CLDR. To follow all
    +    // of CLDR's suggestions, use All|CLDR.
    +    CLDR
    +
    +    // Raw can be used to Compose or Parse without Canonicalization.
    +    Raw CanonType = 0
    +
    +    // Replace all deprecated tags with their preferred replacements.
    +    Deprecated = DeprecatedBase | DeprecatedScript | DeprecatedRegion
    +
    +    // All canonicalizations recommended by BCP 47.
    +    BCP47 = Deprecated | SuppressScript
    +
    +    // All canonicalizations.
    +    All = BCP47 | Legacy | Macro
    +
    +    // Default is the canonicalization used by Parse, Make and Compose. To
    +    // preserve as much information as possible, canonicalizations that remove
    +    // potentially valuable information are not included. The Matcher is
    +    // designed to recognize similar tags that would be the same if
    +    // they were canonicalized using All.
    +    Default = Deprecated | Legacy
    +)
    + + + + + +
    + +
    +

    Example

    + + + +

    Code:

    +
    p := func(id string) {
    +    fmt.Printf("Default(%s) -> %s\n", id, language.Make(id))
    +    fmt.Printf("BCP47(%s) -> %s\n", id, language.BCP47.Make(id))
    +    fmt.Printf("Macro(%s) -> %s\n", id, language.Macro.Make(id))
    +    fmt.Printf("All(%s) -> %s\n", id, language.All.Make(id))
    +}
    +p("en-Latn")
    +p("sh")
    +p("zh-cmn")
    +p("bjd")
    +p("iw-Latn-fonipa-u-cu-usd")
    +
    + +

    Output:

    +
    Default(en-Latn) -> en-Latn
    +BCP47(en-Latn) -> en
    +Macro(en-Latn) -> en-Latn
    +All(en-Latn) -> en
    +Default(sh) -> sr-Latn
    +BCP47(sh) -> sh
    +Macro(sh) -> sh
    +All(sh) -> sr-Latn
    +Default(zh-cmn) -> cmn
    +BCP47(zh-cmn) -> cmn
    +Macro(zh-cmn) -> zh
    +All(zh-cmn) -> zh
    +Default(bjd) -> drl
    +BCP47(bjd) -> drl
    +Macro(bjd) -> bjd
    +All(bjd) -> drl
    +Default(iw-Latn-fonipa-u-cu-usd) -> he-Latn-fonipa-u-cu-usd
    +BCP47(iw-Latn-fonipa-u-cu-usd) -> he-Latn-fonipa-u-cu-usd
    +Macro(iw-Latn-fonipa-u-cu-usd) -> iw-Latn-fonipa-u-cu-usd
    +All(iw-Latn-fonipa-u-cu-usd) -> he-Latn-fonipa-u-cu-usd
    +
    + + +
    +
    + + + + + + + + +

    func (CanonType) Canonicalize

    +
    func (c CanonType) Canonicalize(t Tag) (Tag, error)
    +

    +Canonicalize returns the canonicalized equivalent of the tag. +

    + + + + + + +

    func (CanonType) Compose

    +
    func (c CanonType) Compose(part ...interface{}) (t Tag, err error)
    +

    +Compose creates a Tag from individual parts, which may be of type Tag, Base, +Script, Region, Variant, []Variant, Extension, []Extension or error. If a +Base, Script or Region or slice of type Variant or Extension is passed more +than once, the latter will overwrite the former. Variants and Extensions are +accumulated, but if two extensions of the same type are passed, the latter +will replace the former. A Tag overwrites all former values and typically +only makes sense as the first argument. The resulting tag is returned after +canonicalizing using CanonType c. If one or more errors are encountered, +one of the errors is returned. +

    + + + + + + +

    func (CanonType) Make

    +
    func (c CanonType) Make(s string) Tag
    +

    +Make is a convenience wrapper for c.Parse that omits the error. +In case of an error, a sensible default is returned. +

    + + + + + + +

    func (CanonType) MustParse

    +
    func (c CanonType) MustParse(s string) Tag
    +

    +MustParse is like Parse, but panics if the given BCP 47 tag cannot be parsed. +It simplifies safe initialization of Tag values. +

    + + + + + + +

    func (CanonType) Parse

    +
    func (c CanonType) Parse(s string) (t Tag, err error)
    +

    +Parse parses the given BCP 47 string and returns a valid Tag. If parsing +failed it returns an error and any part of the tag that could be parsed. +If parsing succeeded but an unknown value was found, it returns +ValueError. The Tag returned in this case is just stripped of the unknown +value. All other values are preserved. It accepts tags in the BCP 47 format +and extensions to this standard defined in +http://www.unicode.org/reports/tr35/#Unicode_Language_and_Locale_Identifiers. +The resulting tag is canonicalized using the the canonicalization type c. +

    + + + + + + + + +

    type Confidence

    +
    type Confidence int
    +

    +Confidence indicates the level of certainty for a given return value. +For example, Serbian may be written in Cyrillic or Latin script. +The confidence level indicates whether a value was explicitly specified, +whether it is typically the only possible value, or whether there is +an ambiguity. +

    + + + +
    const (
    +    No    Confidence = iota // full confidence that there was no match
    +    Low                     // most likely value picked out of a set of alternatives
    +    High                    // value is generally assumed to be the correct match
    +    Exact                   // exact match or explicitly specified value
    +)
    + + + + + + + + + + + +

    func Comprehends

    +
    func Comprehends(speaker, alternative Tag) Confidence
    +

    +Comprehends reports the confidence score for a speaker of a given language +to being able to comprehend the written form of an alternative language. +

    + +
    + +
    +

    Example

    + + + +

    Code:

    +
    // Various levels of comprehensibility.
    +fmt.Println(language.Comprehends(language.English, language.English))
    +fmt.Println(language.Comprehends(language.AmericanEnglish, language.BritishEnglish))
    +
    +// An explicit Und results in no match.
    +fmt.Println(language.Comprehends(language.English, language.Und))
    +
    +fmt.Println("----")
    +
    +// There is usually no mutual comprehensibility between different scripts.
    +fmt.Println(language.Comprehends(language.Make("en-Dsrt"), language.English))
    +
    +// One exception is for Traditional versus Simplified Chinese, albeit with
    +// a low confidence.
    +fmt.Println(language.Comprehends(language.TraditionalChinese, language.SimplifiedChinese))
    +
    +fmt.Println("----")
    +
    +// A Swiss German speaker will often understand High German.
    +fmt.Println(language.Comprehends(language.Make("gsw"), language.Make("de")))
    +
    +// The converse is not generally the case.
    +fmt.Println(language.Comprehends(language.Make("de"), language.Make("gsw")))
    +
    +
    + +

    Output:

    +
    Exact
    +High
    +No
    +----
    +No
    +Low
    +----
    +High
    +No
    +
    + + +
    +
    + + + + + + +

    func (Confidence) String

    +
    func (c Confidence) String() string
    + + + + + + + + +

    type Coverage

    +
    type Coverage interface {
    +    // Tags returns the list of supported tags.
    +    Tags() []Tag
    +
    +    // BaseLanguages returns the list of supported base languages.
    +    BaseLanguages() []Base
    +
    +    // Scripts returns the list of supported scripts.
    +    Scripts() []Script
    +
    +    // Regions returns the list of supported regions.
    +    Regions() []Region
    +}
    +

    +The Coverage interface is used to define the level of coverage of an +internationalization service. Note that not all types are supported by all +services. As lists may be generated on the fly, it is recommended that users +of a Coverage cache the results. +

    + + + + + +
    var (
    +    // Supported defines a Coverage that lists all supported subtags. Tags
    +    // always returns nil.
    +    Supported Coverage = allSubtags{}
    +)
    + + + + + + + + + +

    func NewCoverage

    +
    func NewCoverage(list ...interface{}) Coverage
    +

    +NewCoverage returns a Coverage for the given lists. It is typically used by +packages providing internationalization services to define their level of +coverage. A list may be of type []T or func() []T, where T is either Tag, +Base, Script or Region. The returned Coverage derives the value for Bases +from Tags if no func or slice for []Base is specified. For other unspecified +types the returned Coverage will return nil for the respective methods. +

    + + + + + + + + + +

    type Extension

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

    +Extension is a single BCP 47 extension. +

    + + + + + + + + + + + + +

    func ParseExtension

    +
    func ParseExtension(s string) (e Extension, err error)
    +

    +ParseExtension parses s as an extension and returns it on success. +

    + + + + + + + +

    func (Extension) String

    +
    func (e Extension) String() string
    +

    +String returns the string representation of the extension, including the +type tag. +

    + + + + + + +

    func (Extension) Tokens

    +
    func (e Extension) Tokens() []string
    +

    +Tokens returns the list of tokens of e. +

    + + + + + + +

    func (Extension) Type

    +
    func (e Extension) Type() byte
    +

    +Type returns the one-byte extension type of e. It returns 0 for the zero +exception. +

    + + + + + + + + +

    type Matcher

    +
    type Matcher interface {
    +    Match(t ...Tag) (tag Tag, index int, c Confidence)
    +}
    +

    +Matcher is the interface that wraps the Match method. +

    +

    +Match returns the best match for any of the given tags, along with +a unique index associated with the returned tag and a confidence +score. +

    + + + + + + +
    + +
    +

    Example

    +

    ExampleMatcher_bestMatch gives some examples of getting the best match of +a set of tags to any of the tags of given set. +

    + + +

    Code:

    +
    // This is the set of tags from which we want to pick the best match. These
    +// can be, for example, the supported languages for some package.
    +tags := []language.Tag{
    +    language.English,
    +    language.BritishEnglish,
    +    language.French,
    +    language.Afrikaans,
    +    language.BrazilianPortuguese,
    +    language.EuropeanPortuguese,
    +    language.Croatian,
    +    language.SimplifiedChinese,
    +    language.Raw.Make("iw-IL"),
    +    language.Raw.Make("iw"),
    +    language.Raw.Make("he"),
    +}
    +m := language.NewMatcher(tags)
    +
    +// A simple match.
    +fmt.Println(m.Match(language.Make("fr")))
    +
    +// Australian English is closer to British than American English.
    +fmt.Println(m.Match(language.Make("en-AU")))
    +
    +// Default to the first tag passed to the Matcher if there is no match.
    +fmt.Println(m.Match(language.Make("ar")))
    +
    +// Get the default tag.
    +fmt.Println(m.Match())
    +
    +fmt.Println("----")
    +
    +// Croatian speakers will likely understand Serbian written in Latin script.
    +fmt.Println(m.Match(language.Make("sr-Latn")))
    +
    +// We match SimplifiedChinese, but with Low confidence.
    +fmt.Println(m.Match(language.TraditionalChinese))
    +
    +// Serbian in Latin script is a closer match to Croatian than Traditional
    +// Chinese to Simplified Chinese.
    +fmt.Println(m.Match(language.TraditionalChinese, language.Make("sr-Latn")))
    +
    +fmt.Println("----")
    +
    +// In case a multiple variants of a language are available, the most spoken
    +// variant is typically returned.
    +fmt.Println(m.Match(language.Portuguese))
    +
    +// Pick the first value passed to Match in case of a tie.
    +fmt.Println(m.Match(language.Dutch, language.Make("fr-BE"), language.Make("af-NA")))
    +fmt.Println(m.Match(language.Dutch, language.Make("af-NA"), language.Make("fr-BE")))
    +
    +fmt.Println("----")
    +
    +// If a Matcher is initialized with a language and it's deprecated version,
    +// it will distinguish between them.
    +fmt.Println(m.Match(language.Raw.Make("iw")))
    +
    +// However, for non-exact matches, it will treat deprecated versions as
    +// equivalent and consider other factors first.
    +fmt.Println(m.Match(language.Raw.Make("he-IL")))
    +
    +fmt.Println("----")
    +
    +// User settings passed to the Unicode extension are ignored for matching
    +// and preserved in the returned tag.
    +fmt.Println(m.Match(language.Make("de-u-co-phonebk"), language.Make("fr-u-cu-frf")))
    +
    +// Even if the matching language is different.
    +fmt.Println(m.Match(language.Make("de-u-co-phonebk"), language.Make("br-u-cu-frf")))
    +
    +// If there is no matching language, the options of the first preferred tag are used.
    +fmt.Println(m.Match(language.Make("de-u-co-phonebk")))
    +
    +
    + +

    Output:

    +
    fr 2 Exact
    +en-GB 1 High
    +en 0 No
    +en 0 No
    +----
    +hr 6 High
    +zh-Hans 7 Low
    +hr 6 High
    +----
    +pt-BR 4 High
    +fr 2 High
    +af 3 High
    +----
    +iw 9 Exact
    +iw-IL 8 Exact
    +----
    +fr-u-cu-frf 2 Exact
    +fr-u-cu-frf 2 High
    +en-u-co-phonebk 0 No
    +
    + + +
    +
    + + + + + + +

    func NewMatcher

    +
    func NewMatcher(t []Tag) Matcher
    +

    +NewMatcher returns a Matcher that matches an ordered list of preferred tags +against a list of supported tags based on written intelligibility, closeness +of dialect, equivalence of subtags and various other rules. It is initialized +with the list of supported tags. The first element is used as the default +value in case no match is found. +

    +

    +Its Match method matches the first of the given Tags to reach a certain +confidence threshold. The tags passed to Match should therefore be specified +in order of preference. Extensions are ignored for matching. +

    +

    +The index returned by the Match method corresponds to the index of the +matched tag in t, but is augmented with the Unicode extension ('u')of the +corresponding preferred tag. This allows user locale options to be passed +transparently. +

    + + + + + + + + + +

    type Region

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

    +Region is an ISO 3166-1 or UN M.49 code for representing countries and regions. +

    + + + + + + + + + + + + +

    func EncodeM49

    +
    func EncodeM49(r int) (Region, error)
    +

    +EncodeM49 returns the Region for the given UN M.49 code. +It returns an error if r is not a valid code. +

    + + + + + +

    func MustParseRegion

    +
    func MustParseRegion(s string) Region
    +

    +MustParseRegion is like ParseRegion, but panics if the given region cannot be +parsed. It simplifies safe initialization of Region values. +

    + + + + + +

    func ParseRegion

    +
    func ParseRegion(s string) (Region, error)
    +

    +ParseRegion parses a 2- or 3-letter ISO 3166-1 or a UN M.49 code. +It returns a ValueError if s is a well-formed but unknown region identifier +or another error if another error occurred. +

    + + + + + + + +

    func (Region) Canonicalize

    +
    func (r Region) Canonicalize() Region
    +

    +Canonicalize returns the region or a possible replacement if the region is +deprecated. It will not return a replacement for deprecated regions that +are split into multiple regions. +

    + + + + + + +

    func (Region) Contains

    +
    func (r Region) Contains(c Region) bool
    +

    +Contains returns whether Region c is contained by Region r. It returns true +if c == r. +

    + + + + + + +

    func (Region) ISO3

    +
    func (r Region) ISO3() string
    +

    +ISO3 returns the 3-letter ISO code of r. +Note that not all regions have a 3-letter ISO code. +In such cases this method returns "ZZZ". +

    + + + + + + +

    func (Region) IsCountry

    +
    func (r Region) IsCountry() bool
    +

    +IsCountry returns whether this region is a country or autonomous area. This +includes non-standard definitions from CLDR. +

    + + + + + + +

    func (Region) IsGroup

    +
    func (r Region) IsGroup() bool
    +

    +IsGroup returns whether this region defines a collection of regions. This +includes non-standard definitions from CLDR. +

    + + + + + + +

    func (Region) IsPrivateUse

    +
    func (r Region) IsPrivateUse() bool
    +

    +IsPrivateUse reports whether r has the ISO 3166 User-assigned status. This +may include private-use tags that are assigned by CLDR and used in this +implementation. So IsPrivateUse and IsCountry can be simultaneously true. +

    + + + + + + +

    func (Region) M49

    +
    func (r Region) M49() int
    +

    +M49 returns the UN M.49 encoding of r, or 0 if this encoding +is not defined for r. +

    + + + + + + +

    func (Region) String

    +
    func (r Region) String() string
    +

    +String returns the BCP 47 representation for the region. +It returns "ZZ" for an unspecified region. +

    + + + + + + +

    func (Region) TLD

    +
    func (r Region) TLD() (Region, error)
    +

    +TLD returns the country code top-level domain (ccTLD). UK is returned for GB. +In all other cases it returns either the region itself or an error. +

    +

    +This method may return an error for a region for which there exists a +canonical form with a ccTLD. To get that ccTLD canonicalize r first. The +region will already be canonicalized it was obtained from a Tag that was +obtained using any of the default methods. +

    + + +
    + +
    +

    Example

    + + + +

    Code:

    +
    us := language.MustParseRegion("US")
    +gb := language.MustParseRegion("GB")
    +uk := language.MustParseRegion("UK")
    +bu := language.MustParseRegion("BU")
    +
    +fmt.Println(us.TLD())
    +fmt.Println(gb.TLD())
    +fmt.Println(uk.TLD())
    +fmt.Println(bu.TLD())
    +
    +fmt.Println(us.Canonicalize().TLD())
    +fmt.Println(gb.Canonicalize().TLD())
    +fmt.Println(uk.Canonicalize().TLD())
    +fmt.Println(bu.Canonicalize().TLD())
    +
    + +

    Output:

    +
    US <nil>
    +UK <nil>
    +UK <nil>
    +ZZ language: region is not a valid ccTLD
    +US <nil>
    +UK <nil>
    +UK <nil>
    +MM <nil>
    +
    + + +
    +
    + + + + + + +

    type Script

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

    +Script is a 4-letter ISO 15924 code for representing scripts. +It is idiomatically represented in title case. +

    + + + + + + + + + + + + +

    func MustParseScript

    +
    func MustParseScript(s string) Script
    +

    +MustParseScript is like ParseScript, but panics if the given script cannot be +parsed. It simplifies safe initialization of Script values. +

    + + + + + +

    func ParseScript

    +
    func ParseScript(s string) (Script, error)
    +

    +ParseScript parses a 4-letter ISO 15924 code. +It returns a ValueError if s is a well-formed but unknown script identifier +or another error if another error occurred. +

    + + + + + + + +

    func (Script) IsPrivateUse

    +
    func (s Script) IsPrivateUse() bool
    +

    +IsPrivateUse reports whether this script code is reserved for private use. +

    + + + + + + +

    func (Script) String

    +
    func (s Script) String() string
    +

    +String returns the script code in title case. +It returns "Zzzz" for an unspecified script. +

    + + + + + + + + +

    type Tag

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

    +Tag represents a BCP 47 language tag. It is used to specify an instance of a +specific language or locale. All language tag values are guaranteed to be +well-formed. +

    + + + + + +
    var (
    +    Und Tag = Tag{}
    +
    +    Afrikaans            Tag = Tag{lang: _af}                //  af
    +    Amharic              Tag = Tag{lang: _am}                //  am
    +    Arabic               Tag = Tag{lang: _ar}                //  ar
    +    ModernStandardArabic Tag = Tag{lang: _ar, region: _001}  //  ar-001
    +    Azerbaijani          Tag = Tag{lang: _az}                //  az
    +    Bulgarian            Tag = Tag{lang: _bg}                //  bg
    +    Bengali              Tag = Tag{lang: _bn}                //  bn
    +    Catalan              Tag = Tag{lang: _ca}                //  ca
    +    Czech                Tag = Tag{lang: _cs}                //  cs
    +    Danish               Tag = Tag{lang: _da}                //  da
    +    German               Tag = Tag{lang: _de}                //  de
    +    Greek                Tag = Tag{lang: _el}                //  el
    +    English              Tag = Tag{lang: _en}                //  en
    +    AmericanEnglish      Tag = Tag{lang: _en, region: _US}   //  en-US
    +    BritishEnglish       Tag = Tag{lang: _en, region: _GB}   //  en-GB
    +    Spanish              Tag = Tag{lang: _es}                //  es
    +    EuropeanSpanish      Tag = Tag{lang: _es, region: _ES}   //  es-ES
    +    LatinAmericanSpanish Tag = Tag{lang: _es, region: _419}  //  es-419
    +    Estonian             Tag = Tag{lang: _et}                //  et
    +    Persian              Tag = Tag{lang: _fa}                //  fa
    +    Finnish              Tag = Tag{lang: _fi}                //  fi
    +    Filipino             Tag = Tag{lang: _fil}               //  fil
    +    French               Tag = Tag{lang: _fr}                //  fr
    +    CanadianFrench       Tag = Tag{lang: _fr, region: _CA}   //  fr-CA
    +    Gujarati             Tag = Tag{lang: _gu}                //  gu
    +    Hebrew               Tag = Tag{lang: _he}                //  he
    +    Hindi                Tag = Tag{lang: _hi}                //  hi
    +    Croatian             Tag = Tag{lang: _hr}                //  hr
    +    Hungarian            Tag = Tag{lang: _hu}                //  hu
    +    Armenian             Tag = Tag{lang: _hy}                //  hy
    +    Indonesian           Tag = Tag{lang: _id}                //  id
    +    Icelandic            Tag = Tag{lang: _is}                //  is
    +    Italian              Tag = Tag{lang: _it}                //  it
    +    Japanese             Tag = Tag{lang: _ja}                //  ja
    +    Georgian             Tag = Tag{lang: _ka}                //  ka
    +    Kazakh               Tag = Tag{lang: _kk}                //  kk
    +    Khmer                Tag = Tag{lang: _km}                //  km
    +    Kannada              Tag = Tag{lang: _kn}                //  kn
    +    Korean               Tag = Tag{lang: _ko}                //  ko
    +    Kirghiz              Tag = Tag{lang: _ky}                //  ky
    +    Lao                  Tag = Tag{lang: _lo}                //  lo
    +    Lithuanian           Tag = Tag{lang: _lt}                //  lt
    +    Latvian              Tag = Tag{lang: _lv}                //  lv
    +    Macedonian           Tag = Tag{lang: _mk}                //  mk
    +    Malayalam            Tag = Tag{lang: _ml}                //  ml
    +    Mongolian            Tag = Tag{lang: _mn}                //  mn
    +    Marathi              Tag = Tag{lang: _mr}                //  mr
    +    Malay                Tag = Tag{lang: _ms}                //  ms
    +    Burmese              Tag = Tag{lang: _my}                //  my
    +    Nepali               Tag = Tag{lang: _ne}                //  ne
    +    Dutch                Tag = Tag{lang: _nl}                //  nl
    +    Norwegian            Tag = Tag{lang: _no}                //  no
    +    Punjabi              Tag = Tag{lang: _pa}                //  pa
    +    Polish               Tag = Tag{lang: _pl}                //  pl
    +    Portuguese           Tag = Tag{lang: _pt}                //  pt
    +    BrazilianPortuguese  Tag = Tag{lang: _pt, region: _BR}   //  pt-BR
    +    EuropeanPortuguese   Tag = Tag{lang: _pt, region: _PT}   //  pt-PT
    +    Romanian             Tag = Tag{lang: _ro}                //  ro
    +    Russian              Tag = Tag{lang: _ru}                //  ru
    +    Sinhala              Tag = Tag{lang: _si}                //  si
    +    Slovak               Tag = Tag{lang: _sk}                //  sk
    +    Slovenian            Tag = Tag{lang: _sl}                //  sl
    +    Albanian             Tag = Tag{lang: _sq}                //  sq
    +    Serbian              Tag = Tag{lang: _sr}                //  sr
    +    SerbianLatin         Tag = Tag{lang: _sr, script: _Latn} //  sr-Latn
    +    Swedish              Tag = Tag{lang: _sv}                //  sv
    +    Swahili              Tag = Tag{lang: _sw}                //  sw
    +    Tamil                Tag = Tag{lang: _ta}                //  ta
    +    Telugu               Tag = Tag{lang: _te}                //  te
    +    Thai                 Tag = Tag{lang: _th}                //  th
    +    Turkish              Tag = Tag{lang: _tr}                //  tr
    +    Ukrainian            Tag = Tag{lang: _uk}                //  uk
    +    Urdu                 Tag = Tag{lang: _ur}                //  ur
    +    Uzbek                Tag = Tag{lang: _uz}                //  uz
    +    Vietnamese           Tag = Tag{lang: _vi}                //  vi
    +    Chinese              Tag = Tag{lang: _zh}                //  zh
    +    SimplifiedChinese    Tag = Tag{lang: _zh, script: _Hans} //  zh-Hans
    +    TraditionalChinese   Tag = Tag{lang: _zh, script: _Hant} //  zh-Hant
    +    Zulu                 Tag = Tag{lang: _zu}                //  zu
    +)
    + + + +
    + +
    +

    Example (Values)

    + + + +

    Code:

    +
    us := language.MustParseRegion("US")
    +en := language.MustParseBase("en")
    +
    +lang, _, region := language.AmericanEnglish.Raw()
    +fmt.Println(lang == en, region == us)
    +
    +lang, _, region = language.BritishEnglish.Raw()
    +fmt.Println(lang == en, region == us)
    +
    +// Tags can be compared for exact equivalence using '=='.
    +en_us, _ := language.Compose(en, us)
    +fmt.Println(en_us == language.AmericanEnglish)
    +
    +
    + +

    Output:

    +
    true true
    +true false
    +true
    +
    + + +
    +
    + + + + + + +

    func Compose

    +
    func Compose(part ...interface{}) (t Tag, err error)
    +

    +Compose creates a Tag from individual parts, which may be of type Tag, Base, +Script, Region, Variant, []Variant, Extension, []Extension or error. If a +Base, Script or Region or slice of type Variant or Extension is passed more +than once, the latter will overwrite the former. Variants and Extensions are +accumulated, but if two extensions of the same type are passed, the latter +will replace the former. A Tag overwrites all former values and typically +only makes sense as the first argument. The resulting tag is returned after +canonicalizing using the Default CanonType. If one or more errors are +encountered, one of the errors is returned. +

    + +
    + +
    +

    Example

    + + + +

    Code:

    +
    nl, _ := language.ParseBase("nl")
    +us, _ := language.ParseRegion("US")
    +de := language.Make("de-1901-u-co-phonebk")
    +jp := language.Make("ja-JP")
    +fi := language.Make("fi-x-ing")
    +
    +u, _ := language.ParseExtension("u-nu-arabic")
    +x, _ := language.ParseExtension("x-piglatin")
    +
    +// Combine a base language and region.
    +fmt.Println(language.Compose(nl, us))
    +// Combine a base language and extension.
    +fmt.Println(language.Compose(nl, x))
    +// Replace the region.
    +fmt.Println(language.Compose(jp, us))
    +// Combine several tags.
    +fmt.Println(language.Compose(us, nl, u))
    +
    +// Replace the base language of a tag.
    +fmt.Println(language.Compose(de, nl))
    +fmt.Println(language.Compose(de, nl, u))
    +// Remove the base language.
    +fmt.Println(language.Compose(de, language.Base{}))
    +// Remove all variants.
    +fmt.Println(language.Compose(de, []language.Variant{}))
    +// Remove all extensions.
    +fmt.Println(language.Compose(de, []language.Extension{}))
    +fmt.Println(language.Compose(fi, []language.Extension{}))
    +// Remove all variants and extensions.
    +fmt.Println(language.Compose(de.Raw()))
    +
    +// An error is gobbled or returned if non-nil.
    +fmt.Println(language.Compose(language.ParseRegion("ZA")))
    +fmt.Println(language.Compose(language.ParseRegion("HH")))
    +
    +// Compose uses the same Default canonicalization as Make.
    +fmt.Println(language.Compose(language.Raw.Parse("en-Latn-UK")))
    +
    +// Call compose on a different CanonType for different results.
    +fmt.Println(language.All.Compose(language.Raw.Parse("en-Latn-UK")))
    +
    +
    + +

    Output:

    +
    nl-US <nil>
    +nl-x-piglatin <nil>
    +ja-US <nil>
    +nl-US-u-nu-arabic <nil>
    +nl-1901-u-co-phonebk <nil>
    +nl-1901-u-nu-arabic <nil>
    +und-1901-u-co-phonebk <nil>
    +de-u-co-phonebk <nil>
    +de-1901 <nil>
    +fi <nil>
    +de <nil>
    +und-ZA <nil>
    +und language: subtag "HH" is well-formed but unknown
    +en-Latn-GB <nil>
    +en-GB <nil>
    +
    + + +
    +
    + + + + +

    func Make

    +
    func Make(s string) Tag
    +

    +Make is a convenience wrapper for Parse that omits the error. +In case of an error, a sensible default is returned. +

    + + + + + +

    func MustParse

    +
    func MustParse(s string) Tag
    +

    +MustParse is like Parse, but panics if the given BCP 47 tag cannot be parsed. +It simplifies safe initialization of Tag values. +

    + + + + + +

    func Parse

    +
    func Parse(s string) (t Tag, err error)
    +

    +Parse parses the given BCP 47 string and returns a valid Tag. If parsing +failed it returns an error and any part of the tag that could be parsed. +If parsing succeeded but an unknown value was found, it returns +ValueError. The Tag returned in this case is just stripped of the unknown +value. All other values are preserved. It accepts tags in the BCP 47 format +and extensions to this standard defined in +http://www.unicode.org/reports/tr35/#Unicode_Language_and_Locale_Identifiers. +The resulting tag is canonicalized using the default canonicalization type. +

    + +
    + +
    +

    Example (Errors)

    + + + +

    Code:

    +
    for _, s := range []string{"Foo", "Bar", "Foobar"} {
    +    _, err := language.Parse(s)
    +    if err != nil {
    +        if inv, ok := err.(language.ValueError); ok {
    +            fmt.Println(inv.Subtag())
    +        } else {
    +            fmt.Println(s)
    +        }
    +    }
    +}
    +for _, s := range []string{"en", "aa-Uuuu", "AC", "ac-u"} {
    +    _, err := language.Parse(s)
    +    switch e := err.(type) {
    +    case language.ValueError:
    +        fmt.Printf("%s: culprit %q\n", s, e.Subtag())
    +    case nil:
    +        // No error.
    +    default:
    +        // A syntax error.
    +        fmt.Printf("%s: ill-formed\n", s)
    +    }
    +}
    +
    + +

    Output:

    +
    foo
    +Foobar
    +aa-Uuuu: culprit "Uuuu"
    +AC: culprit "ac"
    +ac-u: ill-formed
    +
    + + +
    +
    + + + + + + +

    func (Tag) Base

    +
    func (t Tag) Base() (Base, Confidence)
    +

    +Base returns the base language of the language tag. If the base language is +unspecified, an attempt will be made to infer it from the context. +It uses a variant of CLDR's Add Likely Subtags algorithm. This is subject to change. +

    + + +
    + +
    +

    Example

    + + + +

    Code:

    +
    fmt.Println(language.Make("und").Base())
    +fmt.Println(language.Make("und-US").Base())
    +fmt.Println(language.Make("und-NL").Base())
    +fmt.Println(language.Make("und-419").Base()) // Latin America
    +fmt.Println(language.Make("und-ZZ").Base())
    +
    + +

    Output:

    +
    en Low
    +en High
    +nl High
    +es Low
    +en Low
    +
    + + +
    +
    + + + + +

    func (Tag) Extension

    +
    func (t Tag) Extension(x byte) (ext Extension, ok bool)
    +

    +Extension returns the extension of type x for tag t. It will return +false for ok if t does not have the requested extension. The returned +extension will be invalid in this case. +

    + + + + + + +

    func (Tag) Extensions

    +
    func (t Tag) Extensions() []Extension
    +

    +Extensions returns all extensions of t. +

    + + + + + + +

    func (Tag) IsRoot

    +
    func (t Tag) IsRoot() bool
    +

    +IsRoot returns true if t is equal to language "und". +

    + + + + + + +

    func (Tag) Parent

    +
    func (t Tag) Parent() Tag
    +

    +Parent returns the CLDR parent of t. In CLDR, missing fields in data for a +specific language are substituted with fields from the parent language. +The parent for a language may change for newer versions of CLDR. +

    + + + + + + +

    func (Tag) Raw

    +
    func (t Tag) Raw() (b Base, s Script, r Region)
    +

    +Raw returns the raw base language, script and region, without making an +attempt to infer their values. +

    + + + + + + +

    func (Tag) Region

    +
    func (t Tag) Region() (Region, Confidence)
    +

    +Region returns the region for the language tag. If it was not explicitly given, it will +infer a most likely candidate from the context. +It uses a variant of CLDR's Add Likely Subtags algorithm. This is subject to change. +

    + + +
    + +
    +

    Example

    + + + +

    Code:

    +
    ru := language.Make("ru")
    +en := language.Make("en")
    +fmt.Println(ru.Region())
    +fmt.Println(en.Region())
    +
    + +

    Output:

    +
    RU Low
    +US Low
    +
    + + +
    +
    + + + + +

    func (Tag) Script

    +
    func (t Tag) Script() (Script, Confidence)
    +

    +Script infers the script for the language tag. If it was not explicitly given, it will infer +a most likely candidate. +If more than one script is commonly used for a language, the most likely one +is returned with a low confidence indication. For example, it returns (Cyrl, Low) +for Serbian. +If a script cannot be inferred (Zzzz, No) is returned. We do not use Zyyy (undetermined) +as one would suspect from the IANA registry for BCP 47. In a Unicode context Zyyy marks +common characters (like 1, 2, 3, '.', etc.) and is therefore more like multiple scripts. +See http://www.unicode.org/reports/tr24/#Values for more details. Zzzz is also used for +unknown value in CLDR. (Zzzz, Exact) is returned if Zzzz was explicitly specified. +Note that an inferred script is never guaranteed to be the correct one. Latin is +almost exclusively used for Afrikaans, but Arabic has been used for some texts +in the past. Also, the script that is commonly used may change over time. +It uses a variant of CLDR's Add Likely Subtags algorithm. This is subject to change. +

    + + +
    + +
    +

    Example

    + + + +

    Code:

    +
    en := language.Make("en")
    +sr := language.Make("sr")
    +sr_Latn := language.Make("sr_Latn")
    +fmt.Println(en.Script())
    +fmt.Println(sr.Script())
    +// Was a script explicitly specified?
    +_, c := sr.Script()
    +fmt.Println(c == language.Exact)
    +_, c = sr_Latn.Script()
    +fmt.Println(c == language.Exact)
    +
    + +

    Output:

    +
    Latn High
    +Cyrl Low
    +false
    +true
    +
    + + +
    +
    + + + + +

    func (Tag) SetTypeForKey

    +
    func (t Tag) SetTypeForKey(key, value string) (Tag, error)
    +

    +SetTypeForKey returns a new Tag with the key set to type, where key and type +are of the allowed values defined for the Unicode locale extension ('u') in +http://www.unicode.org/reports/tr35/#Unicode_Language_and_Locale_Identifiers. +An empty value removes an existing pair with the same key. +

    + + + + + + +

    func (Tag) String

    +
    func (t Tag) String() string
    +

    +String returns the canonical string representation of the language tag. +

    + + + + + + +

    func (Tag) TypeForKey

    +
    func (t Tag) TypeForKey(key string) string
    +

    +TypeForKey returns the type associated with the given key, where key and type +are of the allowed values defined for the Unicode locale extension ('u') in +http://www.unicode.org/reports/tr35/#Unicode_Language_and_Locale_Identifiers. +TypeForKey will traverse the inheritance chain to get the correct value. +

    + + + + + + +

    func (Tag) Variants

    +
    func (t Tag) Variants() []Variant
    +

    +Variant returns the variants specified explicitly for this language tag. +or nil if no variant was specified. +

    + + + + + + + + +

    type ValueError

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

    +ValueError is returned by any of the parsing functions when the +input is well-formed but the respective subtag is not recognized +as a valid value. +

    + + + + + + + + + + + + + + +

    func (ValueError) Error

    +
    func (e ValueError) Error() string
    +

    +Error implements the error interface. +

    + + + + + + +

    func (ValueError) Subtag

    +
    func (e ValueError) Subtag() string
    +

    +Subtag returns the subtag for which the error occurred. +

    + + + + + + + + +

    type Variant

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

    +Variant represents a registered variant of a language as defined by BCP 47. +

    + + + + + + + + + + + + +

    func ParseVariant

    +
    func ParseVariant(s string) (Variant, error)
    +

    +ParseVariant parses and returns a Variant. An error is returned if s is not +a valid variant. +

    + + + + + + + +

    func (Variant) String

    +
    func (v Variant) String() string
    +

    +String returns the string representation of the variant. +

    + + + + + + + + + + + + + + + + +

    Subdirectories

    + + + + +
    + + + + + + + + + + + + + + + + + + + + +
    NameSynopsis
    ..
    + display + + Package display provides display names for languages, scripts and regions in a requested language. +
    +
    + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/golang.org/x/text/runes/index.html b/pkg/golang.org/x/text/runes/index.html new file mode 100644 index 0000000..0955bc7 --- /dev/null +++ b/pkg/golang.org/x/text/runes/index.html @@ -0,0 +1,549 @@ + + + + + + + + runes - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Package runes

    + + + + + + + + + + + + + + +
    +
    +
    import "golang.org/x/text/runes"
    +
    +
    +
    Overview
    +
    Index
    + +
    Examples
    + + +
    +
    + +
    + +
    +

    Overview ▾

    +

    +Package runes provide transforms for UTF-8 encoded text. +

    + +
    +
    + + + + + + + + + + + + +

    type Set

    +
    type Set interface {
    +    // Contains returns true if r is contained in the set.
    +    Contains(r rune) bool
    +}
    +

    +A Set is a collection of runes. +

    + + + + + + + + + + + + +

    func In

    +
    func In(rt *unicode.RangeTable) Set
    +

    +In creates a Set with a Contains method that returns true for all runes in +the given RangeTable. +

    + +
    + +
    +

    Example

    + + + +

    Code:

    +
    // Convert Latin characters to their canonical form, while keeping other
    +// width distinctions.
    +t := runes.If(runes.In(unicode.Latin), width.Fold, nil)
    +s, _, _ := transform.String(t, "アルアノリウ tech / アルアノリウ tech")
    +fmt.Println(s)
    +
    +
    + +

    Output:

    +
    アルアノリウ tech / アルアノリウ tech
    +
    + + +
    +
    + + + + +

    func NotIn

    +
    func NotIn(rt *unicode.RangeTable) Set
    +

    +In creates a Set with a Contains method that returns true for all runes not +in the given RangeTable. +

    + + + + + +

    func Predicate

    +
    func Predicate(f func(rune) bool) Set
    +

    +Predicate creates a Set with a Contains method that returns f(r). +

    + + + + + + + + + +

    type Transformer

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

    +Transformer implements the transform.Transformer interface. +

    + + + + + + + + + + + + +

    func If

    +
    func If(s Set, tIn, tNotIn transform.Transformer) Transformer
    +

    +If returns a transformer that applies tIn to consecutive runes for which +s.Contains(r) and tNotIn to consecutive runes for which !s.Contains(r). Reset +is called on tIn and tNotIn at the start of each run. A Nop transformer will +substitute a nil value passed to tIn or tNotIn. Invalid UTF-8 is translated +to RuneError to determine which transformer to apply, but is passed as is to +the respective transformer. +

    + +
    + +
    +

    Example

    + + + +

    Code:

    +
    // Widen everything but ASCII.
    +isASCII := func(r rune) bool { return r <= unicode.MaxASCII }
    +t := runes.If(runes.Predicate(isASCII), nil, width.Widen)
    +s, _, _ := transform.String(t, "アルアノリウ tech / 中國 / 5₩")
    +fmt.Println(s)
    +
    +
    + +

    Output:

    +
    アルアノリウ tech / 中國 / 5₩
    +
    + + +
    +
    + + + + +

    func Map

    +
    func Map(mapping func(rune) rune) Transformer
    +

    +Map returns a Transformer that maps the runes in the input using the given +mapping. Illegal bytes in the input are converted to utf8.RuneError before +being passed to the mapping func. +

    + +
    + +
    +

    Example

    + + + +

    Code:

    +
    replaceHyphens := runes.Map(func(r rune) rune {
    +    if unicode.Is(unicode.Hyphen, r) {
    +        return '|'
    +    }
    +    return r
    +})
    +s, _, _ := transform.String(replaceHyphens, "a-b‐c⸗d﹣e")
    +fmt.Println(s)
    +
    +
    + +

    Output:

    +
    a|b|c|d|e
    +
    + + +
    +
    + + + + +

    func Remove

    +
    func Remove(s Set) Transformer
    +

    +Remove returns a Transformer that removes runes r for which s.Contains(r). +Illegal input bytes are replaced by RuneError before being passed to f. +

    + +
    + +
    +

    Example

    + + + +

    Code:

    +
    t := transform.Chain(norm.NFD, runes.Remove(runes.In(unicode.Mn)), norm.NFC)
    +s, _, _ := transform.String(t, "résumé")
    +fmt.Println(s)
    +
    +
    + +

    Output:

    +
    resume
    +
    + + +
    +
    + + + + +

    func ReplaceIllFormed

    +
    func ReplaceIllFormed() Transformer
    +

    +ReplaceIllFormed returns a transformer that replaces all input bytes that are +not part of a well-formed UTF-8 code sequence with utf8.RuneError. +

    + + + + + + + +

    func (Transformer) Bytes

    +
    func (t Transformer) Bytes(b []byte) []byte
    +

    +Bytes returns a new byte slice with the result of converting b using t. It +calls Reset on t. It returns nil if any error was found. This can only happen +if an error-producing Transformer is passed to If. +

    + + + + + + +

    func (Transformer) Reset

    +
    func (t Transformer) Reset()
    + + + + + + +

    func (Transformer) Span

    +
    func (t Transformer) Span(b []byte, atEOF bool) (n int, err error)
    + + + + + + +

    func (Transformer) String

    +
    func (t Transformer) String(s string) string
    +

    +String returns a string with the result of converting s using t. It calls +Reset on t. It returns the empty string if any error was found. This can only +happen if an error-producing Transformer is passed to If. +

    + + + + + + +

    func (Transformer) Transform

    +
    func (t Transformer) Transform(dst, src []byte, atEOF bool) (nDst, nSrc int, err error)
    + + + + + + + + + + + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/golang.org/x/text/transform/index.html b/pkg/golang.org/x/text/transform/index.html new file mode 100644 index 0000000..2ebf90e --- /dev/null +++ b/pkg/golang.org/x/text/transform/index.html @@ -0,0 +1,640 @@ + + + + + + + + transform - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Package transform

    + + + + + + + + + + + + + + +
    +
    +
    import "golang.org/x/text/transform"
    +
    +
    +
    Overview
    +
    Index
    + +
    Examples
    + + +
    +
    + +
    + +
    +

    Overview ▾

    +

    +Package transform provides reader and writer wrappers that transform the +bytes passing through as well as various transformations. Example +transformations provided by other packages include normalization and +conversion between character sets. +

    + +
    +
    + + + + + + + + +

    Variables

    + +
    var (
    +    // ErrShortDst means that the destination buffer was too short to
    +    // receive all of the transformed bytes.
    +    ErrShortDst = errors.New("transform: short destination buffer")
    +
    +    // ErrShortSrc means that the source buffer has insufficient data to
    +    // complete the transformation.
    +    ErrShortSrc = errors.New("transform: short source buffer")
    +
    +    // ErrEndOfSpan means that the input and output (the transformed input)
    +    // are not identical.
    +    ErrEndOfSpan = errors.New("transform: input and output are not identical")
    +)
    + + +
    var (
    +    // Discard is a Transformer for which all Transform calls succeed
    +    // by consuming all bytes and writing nothing.
    +    Discard Transformer = discard{}
    +
    +    // Nop is a SpanningTransformer that copies src to dst.
    +    Nop SpanningTransformer = nop{}
    +)
    + + + + + + +

    func Append

    +
    func Append(t Transformer, dst, src []byte) (result []byte, n int, err error)
    +

    +Append appends the result of converting src[:n] using t to dst, where +n <= len(src), If err == nil, n will be len(src). It calls Reset on t. +

    + + + + + + + +

    func Bytes

    +
    func Bytes(t Transformer, b []byte) (result []byte, n int, err error)
    +

    +Bytes returns a new byte slice with the result of converting b[:n] using t, +where n <= len(b). If err == nil, n will be len(b). It calls Reset on t. +

    + + + + + + + +

    func String

    +
    func String(t Transformer, s string) (result string, n int, err error)
    +

    +String returns a string with the result of converting s[:n] using t, where +n <= len(s). If err == nil, n will be len(s). It calls Reset on t. +

    + + + + + + + + +

    type NopResetter

    +
    type NopResetter struct{}
    +

    +NopResetter can be embedded by implementations of Transformer to add a nop +Reset method. +

    + + + + + + + + + + + + + + +

    func (NopResetter) Reset

    +
    func (NopResetter) Reset()
    +

    +Reset implements the Reset method of the Transformer interface. +

    + + + + + + + + +

    type Reader

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

    +Reader wraps another io.Reader by transforming the bytes read. +

    + + + + + + + + + + + + +

    func NewReader

    +
    func NewReader(r io.Reader, t Transformer) *Reader
    +

    +NewReader returns a new Reader that wraps r by transforming the bytes read +via t. It calls Reset on t. +

    + + + + + + + +

    func (*Reader) Read

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

    +Read implements the io.Reader interface. +

    + + + + + + + + +

    type SpanningTransformer

    +
    type SpanningTransformer interface {
    +    Transformer
    +
    +    // Span returns a position in src such that transforming src[:n] results in
    +    // identical output src[:n] for these bytes. It does not necessarily return
    +    // the largest such n. The atEOF argument tells whether src represents the
    +    // last bytes of the input.
    +    //
    +    // Callers should always account for the n bytes consumed before
    +    // considering the error err.
    +    //
    +    // A nil error means that all input bytes are known to be identical to the
    +    // output produced by the Transformer. A nil error can be be returned
    +    // regardless of whether atEOF is true. If err is nil, then then n must
    +    // equal len(src); the converse is not necessarily true.
    +    //
    +    // ErrEndOfSpan means that the Transformer output may differ from the
    +    // input after n bytes. Note that n may be len(src), meaning that the output
    +    // would contain additional bytes after otherwise identical output.
    +    // ErrShortSrc means that src had insufficient data to determine whether the
    +    // remaining bytes would change. Other than the error conditions listed
    +    // here, implementations are free to report other errors that arise.
    +    //
    +    // Calling Span can modify the Transformer state as a side effect. In
    +    // effect, it does the transformation just as calling Transform would, only
    +    // without copying to a destination buffer and only up to a point it can
    +    // determine the input and output bytes are the same. This is obviously more
    +    // limited than calling Transform, but can be more efficient in terms of
    +    // copying and allocating buffers. Calls to Span and Transform may be
    +    // interleaved.
    +    Span(src []byte, atEOF bool) (n int, err error)
    +}
    +

    +SpanningTransformer extends the Transformer interface with a Span method +that determines how much of the input already conforms to the Transformer. +

    + + + + + + + + + + + + + + + + +

    type Transformer

    +
    type Transformer interface {
    +    // Transform writes to dst the transformed bytes read from src, and
    +    // returns the number of dst bytes written and src bytes read. The
    +    // atEOF argument tells whether src represents the last bytes of the
    +    // input.
    +    //
    +    // Callers should always process the nDst bytes produced and account
    +    // for the nSrc bytes consumed before considering the error err.
    +    //
    +    // A nil error means that all of the transformed bytes (whether freshly
    +    // transformed from src or left over from previous Transform calls)
    +    // were written to dst. A nil error can be returned regardless of
    +    // whether atEOF is true. If err is nil then nSrc must equal len(src);
    +    // the converse is not necessarily true.
    +    //
    +    // ErrShortDst means that dst was too short to receive all of the
    +    // transformed bytes. ErrShortSrc means that src had insufficient data
    +    // to complete the transformation. If both conditions apply, then
    +    // either error may be returned. Other than the error conditions listed
    +    // here, implementations are free to report other errors that arise.
    +    Transform(dst, src []byte, atEOF bool) (nDst, nSrc int, err error)
    +
    +    // Reset resets the state and allows a Transformer to be reused.
    +    Reset()
    +}
    +

    +Transformer transforms bytes. +

    + + + + + + + + + + + + +

    func Chain

    +
    func Chain(t ...Transformer) Transformer
    +

    +Chain returns a Transformer that applies t in sequence. +

    + + + + + +

    func RemoveFunc

    +
    func RemoveFunc(f func(r rune) bool) Transformer
    +

    +Deprecated: use runes.Remove instead. +

    + +
    + +
    +

    Example

    + + + +

    Code:

    +
    input := []byte(`tschüß; до свидания`)
    +
    +b := make([]byte, len(input))
    +
    +t := transform.RemoveFunc(unicode.IsSpace)
    +n, _, _ := t.Transform(b, input, true)
    +fmt.Println(string(b[:n]))
    +
    +t = transform.RemoveFunc(func(r rune) bool {
    +    return !unicode.Is(unicode.Latin, r)
    +})
    +n, _, _ = t.Transform(b, input, true)
    +fmt.Println(string(b[:n]))
    +
    +n, _, _ = t.Transform(b, norm.NFD.Bytes(input), true)
    +fmt.Println(string(b[:n]))
    +
    +
    + +

    Output:

    +
    tschüß;досвидания
    +tschüß
    +tschuß
    +
    + + +
    +
    + + + + + + + + +

    type Writer

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

    +Writer wraps another io.Writer by transforming the bytes read. +The user needs to call Close to flush unwritten bytes that may +be buffered. +

    + + + + + + + + + + + + +

    func NewWriter

    +
    func NewWriter(w io.Writer, t Transformer) *Writer
    +

    +NewWriter returns a new Writer that wraps w by transforming the bytes written +via t. It calls Reset on t. +

    + + + + + + + +

    func (*Writer) Close

    +
    func (w *Writer) Close() error
    +

    +Close implements the io.Closer interface. +

    + + + + + + +

    func (*Writer) Write

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

    +Write implements the io.Writer interface. If there are not enough +bytes available to complete a Transform, the bytes will be buffered +for the next write. Call Close to convert the remaining bytes. +

    + + + + + + + + + + + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/hash/adler32/index.html b/pkg/hash/adler32/index.html new file mode 100644 index 0000000..cfc4880 --- /dev/null +++ b/pkg/hash/adler32/index.html @@ -0,0 +1,256 @@ + + + + + + + + adler32 - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Package adler32

    + + + + + + + + + + + + + + +
    +
    +
    import "hash/adler32"
    +
    +
    +
    Overview
    +
    Index
    + + +
    +
    + +
    + +
    +

    Overview ▾

    +

    +Package adler32 implements the Adler-32 checksum. +

    +

    +It is defined in RFC 1950: +

    +
    Adler-32 is composed of two sums accumulated per byte: s1 is
    +the sum of all bytes, s2 is the sum of all s1 values. Both sums
    +are done modulo 65521. s1 is initialized to 1, s2 to zero.  The
    +Adler-32 checksum is stored as s2*65536 + s1 in most-
    +significant-byte first (network) order.
    +
    + +
    +
    + + +
    + +
    +

    Index ▾

    + + + + + + + +

    Package files

    +

    + + + adler32.go + + +

    + +
    +
    + + + + +

    Constants

    + +
    const Size = 4
    +

    +The size of an Adler-32 checksum in bytes. +

    + + + + + + + +

    func Checksum

    +
    func Checksum(data []byte) uint32
    +

    +Checksum returns the Adler-32 checksum of data. +

    + + + + + + + +

    func New

    +
    func New() hash.Hash32
    +

    +New returns a new hash.Hash32 computing the Adler-32 checksum. +Its Sum method will lay the value out in big-endian byte order. +

    + + + + + + + + + + + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/hash/crc32/index.html b/pkg/hash/crc32/index.html new file mode 100644 index 0000000..bfc6ecf --- /dev/null +++ b/pkg/hash/crc32/index.html @@ -0,0 +1,422 @@ + + + + + + + + crc32 - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Package crc32

    + + + + + + + + + + + + + + +
    +
    +
    import "hash/crc32"
    +
    +
    +
    Overview
    +
    Index
    + +
    Examples
    + + +
    +
    + +
    + +
    +

    Overview ▾

    +

    +Package crc32 implements the 32-bit cyclic redundancy check, or CRC-32, +checksum. See http://en.wikipedia.org/wiki/Cyclic_redundancy_check for +information. +

    +

    +Polynomials are represented in LSB-first form also known as reversed representation. +

    +

    +See http://en.wikipedia.org/wiki/Mathematics_of_cyclic_redundancy_checks#Reversed_representations_and_reciprocal_polynomials +for information. +

    + +
    +
    + + +
    + + +
    + + + + +

    Constants

    + +
    const (
    +    // IEEE is by far and away the most common CRC-32 polynomial.
    +    // Used by ethernet (IEEE 802.3), v.42, fddi, gzip, zip, png, ...
    +    IEEE = 0xedb88320
    +
    +    // Castagnoli's polynomial, used in iSCSI.
    +    // Has better error detection characteristics than IEEE.
    +    // http://dx.doi.org/10.1109/26.231911
    +    Castagnoli = 0x82f63b78
    +
    +    // Koopman's polynomial.
    +    // Also has better error detection characteristics than IEEE.
    +    // http://dx.doi.org/10.1109/DSN.2002.1028931
    +    Koopman = 0xeb31d82e
    +)
    +

    +Predefined polynomials. +

    + + +
    const Size = 4
    +

    +The size of a CRC-32 checksum in bytes. +

    + + + + +

    Variables

    + +
    var IEEETable = makeTable(IEEE)
    +

    +IEEETable is the table for the IEEE polynomial. +

    + + + + + + +

    func Checksum

    +
    func Checksum(data []byte, tab *Table) uint32
    +

    +Checksum returns the CRC-32 checksum of data +using the polynomial represented by the Table. +

    + + + + + + + +

    func ChecksumIEEE

    +
    func ChecksumIEEE(data []byte) uint32
    +

    +ChecksumIEEE returns the CRC-32 checksum of data +using the IEEE polynomial. +

    + + + + + + + +

    func New

    +
    func New(tab *Table) hash.Hash32
    +

    +New creates a new hash.Hash32 computing the CRC-32 checksum +using the polynomial represented by the Table. +Its Sum method will lay the value out in big-endian byte order. +

    + + + + + + + +

    func NewIEEE

    +
    func NewIEEE() hash.Hash32
    +

    +NewIEEE creates a new hash.Hash32 computing the CRC-32 checksum +using the IEEE polynomial. +Its Sum method will lay the value out in big-endian byte order. +

    + + + + + + + +

    func Update

    +
    func Update(crc uint32, tab *Table, p []byte) uint32
    +

    +Update returns the result of adding the bytes in p to the crc. +

    + + + + + + + + +

    type Table

    +
    type Table [256]uint32
    +

    +Table is a 256-word table representing the polynomial for efficient processing. +

    + + + + + + + + + + + + +

    func MakeTable

    +
    func MakeTable(poly uint32) *Table
    +

    +MakeTable returns a Table constructed from the specified polynomial. +The contents of this Table must not be modified. +

    + +
    + +
    +

    Example

    + + + +

    Code:

    +
    // In this package, the CRC polynomial is represented in reversed notation,
    +// or LSB-first representation.
    +//
    +// LSB-first representation is a hexadecimal number with n bits, in which the
    +// most significant bit represents the coefficient of x⁰ and the least significant
    +// bit represents the coefficient of xⁿ⁻¹ (the coefficient for xⁿ is implicit).
    +//
    +// For example, CRC32-Q, as defined by the following polynomial,
    +//	x³²+ x³¹+ x²⁴+ x²²+ x¹⁶+ x¹⁴+ x⁸+ x⁷+ x⁵+ x³+ x¹+ x⁰
    +// has the reversed notation 0b11010101100000101000001010000001, so the value
    +// that should be passed to MakeTable is 0xD5828281.
    +crc32q := crc32.MakeTable(0xD5828281)
    +fmt.Printf("%08x\n", crc32.Checksum([]byte("Hello world"), crc32q))
    +
    + +

    Output:

    +
    2964d064
    +
    + + +
    +
    + + + + + + + + + + + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/hash/crc64/index.html b/pkg/hash/crc64/index.html new file mode 100644 index 0000000..3bd7727 --- /dev/null +++ b/pkg/hash/crc64/index.html @@ -0,0 +1,318 @@ + + + + + + + + crc64 - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Package crc64

    + + + + + + + + + + + + + + +
    +
    +
    import "hash/crc64"
    +
    +
    +
    Overview
    +
    Index
    + + +
    +
    + +
    + +
    +

    Overview ▾

    +

    +Package crc64 implements the 64-bit cyclic redundancy check, or CRC-64, +checksum. See http://en.wikipedia.org/wiki/Cyclic_redundancy_check for +information. +

    + +
    +
    + + +
    + +
    +

    Index ▾

    + + + + + + + +

    Package files

    +

    + + + crc64.go + + +

    + +
    +
    + + + + +

    Constants

    + +
    const (
    +    // The ISO polynomial, defined in ISO 3309 and used in HDLC.
    +    ISO = 0xD800000000000000
    +
    +    // The ECMA polynomial, defined in ECMA 182.
    +    ECMA = 0xC96C5795D7870F42
    +)
    +

    +Predefined polynomials. +

    + + +
    const Size = 8
    +

    +The size of a CRC-64 checksum in bytes. +

    + + + + + + + +

    func Checksum

    +
    func Checksum(data []byte, tab *Table) uint64
    +

    +Checksum returns the CRC-64 checksum of data +using the polynomial represented by the Table. +

    + + + + + + + +

    func New

    +
    func New(tab *Table) hash.Hash64
    +

    +New creates a new hash.Hash64 computing the CRC-64 checksum +using the polynomial represented by the Table. +Its Sum method will lay the value out in big-endian byte order. +

    + + + + + + + +

    func Update

    +
    func Update(crc uint64, tab *Table, p []byte) uint64
    +

    +Update returns the result of adding the bytes in p to the crc. +

    + + + + + + + + +

    type Table

    +
    type Table [256]uint64
    +

    +Table is a 256-word table representing the polynomial for efficient processing. +

    + + + + + + + + + + + + +

    func MakeTable

    +
    func MakeTable(poly uint64) *Table
    +

    +MakeTable returns a Table constructed from the specified polynomial. +The contents of this Table must not be modified. +

    + + + + + + + + + + + + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/hash/fnv/index.html b/pkg/hash/fnv/index.html new file mode 100644 index 0000000..4b917ce --- /dev/null +++ b/pkg/hash/fnv/index.html @@ -0,0 +1,272 @@ + + + + + + + + fnv - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Package fnv

    + + + + + + + + + + + + + + +
    +
    +
    import "hash/fnv"
    +
    +
    +
    Overview
    +
    Index
    + + +
    +
    + +
    + +
    +

    Overview ▾

    +

    +Package fnv implements FNV-1 and FNV-1a, non-cryptographic hash functions +created by Glenn Fowler, Landon Curt Noll, and Phong Vo. +See +https://en.wikipedia.org/wiki/Fowler-Noll-Vo_hash_function. +

    + +
    +
    + + +
    + +
    +

    Index ▾

    + + + + + + + +

    Package files

    +

    + + + fnv.go + + +

    + +
    +
    + + + + + + + + +

    func New32

    +
    func New32() hash.Hash32
    +

    +New32 returns a new 32-bit FNV-1 hash.Hash. +Its Sum method will lay the value out in big-endian byte order. +

    + + + + + + + +

    func New32a

    +
    func New32a() hash.Hash32
    +

    +New32a returns a new 32-bit FNV-1a hash.Hash. +Its Sum method will lay the value out in big-endian byte order. +

    + + + + + + + +

    func New64

    +
    func New64() hash.Hash64
    +

    +New64 returns a new 64-bit FNV-1 hash.Hash. +Its Sum method will lay the value out in big-endian byte order. +

    + + + + + + + +

    func New64a

    +
    func New64a() hash.Hash64
    +

    +New64a returns a new 64-bit FNV-1a hash.Hash. +Its Sum method will lay the value out in big-endian byte order. +

    + + + + + + + + + + + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/hash/index.html b/pkg/hash/index.html new file mode 100644 index 0000000..dc1cec7 --- /dev/null +++ b/pkg/hash/index.html @@ -0,0 +1,382 @@ + + + + + + + + hash - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Package hash

    + + + + + + + + + + + + + + +
    +
    +
    import "hash"
    +
    +
    +
    Overview
    +
    Index
    + + +
    Subdirectories
    + +
    +
    + +
    + +
    +

    Overview ▾

    +

    +Package hash provides interfaces for hash functions. +

    + +
    +
    + + +
    + +
    +

    Index ▾

    + + +
    +
    + + + + + +
    type Hash
    + + + + +
    type Hash32
    + + + + +
    type Hash64
    + + + + +
    +
    + + + + +

    Package files

    +

    + + + hash.go + + +

    + +
    +
    + + + + + + + + + +

    type Hash

    +
    type Hash interface {
    +    // Write (via the embedded io.Writer interface) adds more data to the running hash.
    +    // It never returns an error.
    +    io.Writer
    +
    +    // Sum appends the current hash to b and returns the resulting slice.
    +    // It does not change the underlying hash state.
    +    Sum(b []byte) []byte
    +
    +    // Reset resets the Hash to its initial state.
    +    Reset()
    +
    +    // Size returns the number of bytes Sum will return.
    +    Size() int
    +
    +    // BlockSize returns the hash's underlying block size.
    +    // The Write method must be able to accept any amount
    +    // of data, but it may operate more efficiently if all writes
    +    // are a multiple of the block size.
    +    BlockSize() int
    +}
    +

    +Hash is the common interface implemented by all hash functions. +

    + + + + + + + + + + + + + + + + +

    type Hash32

    +
    type Hash32 interface {
    +    Hash
    +    Sum32() uint32
    +}
    +

    +Hash32 is the common interface implemented by all 32-bit hash functions. +

    + + + + + + + + + + + + + + + + +

    type Hash64

    +
    type Hash64 interface {
    +    Hash
    +    Sum64() uint64
    +}
    +

    +Hash64 is the common interface implemented by all 64-bit hash functions. +

    + + + + + + + + + + + + + + + + + + + + + + + + +

    Subdirectories

    + + + + +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    NameSynopsis
    ..
    + adler32 + + Package adler32 implements the Adler-32 checksum. +
    + crc32 + + Package crc32 implements the 32-bit cyclic redundancy check, or CRC-32, checksum. +
    + crc64 + + Package crc64 implements the 64-bit cyclic redundancy check, or CRC-64, checksum. +
    + fnv + + Package fnv implements FNV-1 and FNV-1a, non-cryptographic hash functions created by Glenn Fowler, Landon Curt Noll, and Phong Vo. +
    +
    + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/io/index.html b/pkg/io/index.html new file mode 100644 index 0000000..d21ea29 --- /dev/null +++ b/pkg/io/index.html @@ -0,0 +1,1945 @@ + + + + + + + + io - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Package io

    + + + + + + + + + + + + + + +
    +
    +
    import "io"
    +
    +
    +
    Overview
    +
    Index
    + +
    Examples
    + + +
    Subdirectories
    + +
    +
    + +
    + +
    +

    Overview ▾

    +

    +Package io provides basic interfaces to I/O primitives. +Its primary job is to wrap existing implementations of such primitives, +such as those in package os, into shared public interfaces that +abstract the functionality, plus some other related primitives. +

    +

    +Because these interfaces and primitives wrap lower-level operations with +various implementations, unless otherwise informed clients should not +assume they are safe for parallel execution. +

    + +
    +
    + + +
    + +
    +

    Index ▾

    + + +
    +
    + + +
    Variables
    + + + +
    func Copy(dst Writer, src Reader) (written int64, err error)
    + + +
    func CopyBuffer(dst Writer, src Reader, buf []byte) (written int64, err error)
    + + +
    func CopyN(dst Writer, src Reader, n int64) (written int64, err error)
    + + +
    func ReadAtLeast(r Reader, buf []byte, min int) (n int, err error)
    + + +
    func ReadFull(r Reader, buf []byte) (n int, err error)
    + + +
    func WriteString(w Writer, s string) (n int, err error)
    + + + +
    type ByteReader
    + + + + +
    type ByteScanner
    + + + + +
    type ByteWriter
    + + + + +
    type Closer
    + + + + +
    type LimitedReader
    + + + +
        func (l *LimitedReader) Read(p []byte) (n int, err error)
    + + + +
    type PipeReader
    + + +
        func Pipe() (*PipeReader, *PipeWriter)
    + + + +
        func (r *PipeReader) Close() error
    + + +
        func (r *PipeReader) CloseWithError(err error) error
    + + +
        func (r *PipeReader) Read(data []byte) (n int, err error)
    + + + +
    type PipeWriter
    + + + +
        func (w *PipeWriter) Close() error
    + + +
        func (w *PipeWriter) CloseWithError(err error) error
    + + +
        func (w *PipeWriter) Write(data []byte) (n int, err error)
    + + + +
    type ReadCloser
    + + + + +
    type ReadSeeker
    + + + + +
    type ReadWriteCloser
    + + + + +
    type ReadWriteSeeker
    + + + + +
    type ReadWriter
    + + + + +
    type Reader
    + + +
        func LimitReader(r Reader, n int64) Reader
    + + +
        func MultiReader(readers ...Reader) Reader
    + + +
        func TeeReader(r Reader, w Writer) Reader
    + + + + +
    type ReaderAt
    + + + + +
    type ReaderFrom
    + + + + +
    type RuneReader
    + + + + +
    type RuneScanner
    + + + + +
    type SectionReader
    + + +
        func NewSectionReader(r ReaderAt, off int64, n int64) *SectionReader
    + + + +
        func (s *SectionReader) Read(p []byte) (n int, err error)
    + + +
        func (s *SectionReader) ReadAt(p []byte, off int64) (n int, err error)
    + + +
        func (s *SectionReader) Seek(offset int64, whence int) (int64, error)
    + + +
        func (s *SectionReader) Size() int64
    + + + +
    type Seeker
    + + + + +
    type WriteCloser
    + + + + +
    type WriteSeeker
    + + + + +
    type Writer
    + + +
        func MultiWriter(writers ...Writer) Writer
    + + + + +
    type WriterAt
    + + + + +
    type WriterTo
    + + + + +
    +
    + + + + + + +

    Package files

    +

    + + + io.go + + multi.go + + pipe.go + + +

    + +
    +
    + + + + + +

    Variables

    + +
    var EOF = errors.New("EOF")
    +

    +EOF is the error returned by Read when no more input is available. +Functions should return EOF only to signal a graceful end of input. +If the EOF occurs unexpectedly in a structured data stream, +the appropriate error is either ErrUnexpectedEOF or some other error +giving more detail. +

    + + +
    var ErrClosedPipe = errors.New("io: read/write on closed pipe")
    +

    +ErrClosedPipe is the error used for read or write operations on a closed pipe. +

    + + +
    var ErrNoProgress = errors.New("multiple Read calls return no data or error")
    +

    +ErrNoProgress is returned by some clients of an io.Reader when +many calls to Read have failed to return any data or error, +usually the sign of a broken io.Reader implementation. +

    + + +
    var ErrShortBuffer = errors.New("short buffer")
    +

    +ErrShortBuffer means that a read required a longer buffer than was provided. +

    + + +
    var ErrShortWrite = errors.New("short write")
    +

    +ErrShortWrite means that a write accepted fewer bytes than requested +but failed to return an explicit error. +

    + + +
    var ErrUnexpectedEOF = errors.New("unexpected EOF")
    +

    +ErrUnexpectedEOF means that EOF was encountered in the +middle of reading a fixed-size block or data structure. +

    + + + + + + +

    func Copy

    +
    func Copy(dst Writer, src Reader) (written int64, err error)
    +

    +Copy copies from src to dst until either EOF is reached +on src or an error occurs. It returns the number of bytes +copied and the first error encountered while copying, if any. +

    +

    +A successful Copy returns err == nil, not err == EOF. +Because Copy is defined to read from src until EOF, it does +not treat an EOF from Read as an error to be reported. +

    +

    +If src implements the WriterTo interface, +the copy is implemented by calling src.WriteTo(dst). +Otherwise, if dst implements the ReaderFrom interface, +the copy is implemented by calling dst.ReadFrom(src). +

    + +
    + +
    +

    Example

    + + + +

    Code:

    +
    r := strings.NewReader("some io.Reader stream to be read\n")
    +
    +if _, err := io.Copy(os.Stdout, r); err != nil {
    +    log.Fatal(err)
    +}
    +
    +
    + +

    Output:

    +
    some io.Reader stream to be read
    +
    + + +
    +
    + + + + + + +

    func CopyBuffer

    +
    func CopyBuffer(dst Writer, src Reader, buf []byte) (written int64, err error)
    +

    +CopyBuffer is identical to Copy except that it stages through the +provided buffer (if one is required) rather than allocating a +temporary one. If buf is nil, one is allocated; otherwise if it has +zero length, CopyBuffer panics. +

    + +
    + +
    +

    Example

    + + + +

    Code:

    +
    r1 := strings.NewReader("first reader\n")
    +r2 := strings.NewReader("second reader\n")
    +buf := make([]byte, 8)
    +
    +// buf is used here...
    +if _, err := io.CopyBuffer(os.Stdout, r1, buf); err != nil {
    +    log.Fatal(err)
    +}
    +
    +// ... reused here also. No need to allocate an extra buffer.
    +if _, err := io.CopyBuffer(os.Stdout, r2, buf); err != nil {
    +    log.Fatal(err)
    +}
    +
    +
    + +

    Output:

    +
    first reader
    +second reader
    +
    + + +
    +
    + + + + + + +

    func CopyN

    +
    func CopyN(dst Writer, src Reader, n int64) (written int64, err error)
    +

    +CopyN copies n bytes (or until an error) from src to dst. +It returns the number of bytes copied and the earliest +error encountered while copying. +On return, written == n if and only if err == nil. +

    +

    +If dst implements the ReaderFrom interface, +the copy is implemented using it. +

    + +
    + +
    +

    Example

    + + + +

    Code:

    +
    r := strings.NewReader("some io.Reader stream to be read")
    +
    +if _, err := io.CopyN(os.Stdout, r, 5); err != nil {
    +    log.Fatal(err)
    +}
    +
    +
    + +

    Output:

    +
    some
    +
    + + +
    +
    + + + + + + +

    func ReadAtLeast

    +
    func ReadAtLeast(r Reader, buf []byte, min int) (n int, err error)
    +

    +ReadAtLeast reads from r into buf until it has read at least min bytes. +It returns the number of bytes copied and an error if fewer bytes were read. +The error is EOF only if no bytes were read. +If an EOF happens after reading fewer than min bytes, +ReadAtLeast returns ErrUnexpectedEOF. +If min is greater than the length of buf, ReadAtLeast returns ErrShortBuffer. +On return, n >= min if and only if err == nil. +

    + +
    + +
    +

    Example

    + + + +

    Code:

    +
    r := strings.NewReader("some io.Reader stream to be read\n")
    +
    +buf := make([]byte, 33)
    +if _, err := io.ReadAtLeast(r, buf, 4); err != nil {
    +    log.Fatal(err)
    +}
    +fmt.Printf("%s\n", buf)
    +
    +// buffer smaller than minimal read size.
    +shortBuf := make([]byte, 3)
    +if _, err := io.ReadAtLeast(r, shortBuf, 4); err != nil {
    +    fmt.Println("error:", err)
    +}
    +
    +// minimal read size bigger than io.Reader stream
    +longBuf := make([]byte, 64)
    +if _, err := io.ReadAtLeast(r, longBuf, 64); err != nil {
    +    fmt.Println("error:", err)
    +}
    +
    +
    + +

    Output:

    +
    some io.Reader stream to be read
    +
    +error: short buffer
    +error: EOF
    +
    + + +
    +
    + + + + + + +

    func ReadFull

    +
    func ReadFull(r Reader, buf []byte) (n int, err error)
    +

    +ReadFull reads exactly len(buf) bytes from r into buf. +It returns the number of bytes copied and an error if fewer bytes were read. +The error is EOF only if no bytes were read. +If an EOF happens after reading some but not all the bytes, +ReadFull returns ErrUnexpectedEOF. +On return, n == len(buf) if and only if err == nil. +

    + +
    + +
    +

    Example

    + + + +

    Code:

    +
    r := strings.NewReader("some io.Reader stream to be read\n")
    +
    +buf := make([]byte, 4)
    +if _, err := io.ReadFull(r, buf); err != nil {
    +    log.Fatal(err)
    +}
    +fmt.Printf("%s\n", buf)
    +
    +// minimal read size bigger than io.Reader stream
    +longBuf := make([]byte, 64)
    +if _, err := io.ReadFull(r, longBuf); err != nil {
    +    fmt.Println("error:", err)
    +}
    +
    +
    + +

    Output:

    +
    some
    +error: unexpected EOF
    +
    + + +
    +
    + + + + + + +

    func WriteString

    +
    func WriteString(w Writer, s string) (n int, err error)
    +

    +WriteString writes the contents of the string s to w, which accepts a slice of bytes. +If w implements a WriteString method, it is invoked directly. +

    + +
    + +
    +

    Example

    + + + +

    Code:

    +
    io.WriteString(os.Stdout, "Hello World")
    +
    +
    + +

    Output:

    +
    Hello World
    +
    + + +
    +
    + + + + + + + +

    type ByteReader

    +
    type ByteReader interface {
    +    ReadByte() (c byte, err error)
    +}
    +

    +ByteReader is the interface that wraps the ReadByte method. +

    +

    +ReadByte reads and returns the next byte from the input. +

    + + + + + + + + + + + + + + + + +

    type ByteScanner

    +
    type ByteScanner interface {
    +    ByteReader
    +    UnreadByte() error
    +}
    +

    +ByteScanner is the interface that adds the UnreadByte method to the +basic ReadByte method. +

    +

    +UnreadByte causes the next call to ReadByte to return the same byte +as the previous call to ReadByte. +It may be an error to call UnreadByte twice without an intervening +call to ReadByte. +

    + + + + + + + + + + + + + + + + +

    type ByteWriter

    +
    type ByteWriter interface {
    +    WriteByte(c byte) error
    +}
    +

    +ByteWriter is the interface that wraps the WriteByte method. +

    + + + + + + + + + + + + + + + + +

    type Closer

    +
    type Closer interface {
    +    Close() error
    +}
    +

    +Closer is the interface that wraps the basic Close method. +

    +

    +The behavior of Close after the first call is undefined. +Specific implementations may document their own behavior. +

    + + + + + + + + + + + + + + + + +

    type LimitedReader

    +
    type LimitedReader struct {
    +    R Reader // underlying reader
    +    N int64  // max bytes remaining
    +}
    +

    +A LimitedReader reads from R but limits the amount of +data returned to just N bytes. Each call to Read +updates N to reflect the new amount remaining. +

    + + + + + + + + + + + + + + +

    func (*LimitedReader) Read

    +
    func (l *LimitedReader) Read(p []byte) (n int, err error)
    + + + + + + + + +

    type PipeReader

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

    +A PipeReader is the read half of a pipe. +

    + + + + + + + + + + + + +

    func Pipe

    +
    func Pipe() (*PipeReader, *PipeWriter)
    +

    +Pipe creates a synchronous in-memory pipe. +It can be used to connect code expecting an io.Reader +with code expecting an io.Writer. +Reads on one end are matched with writes on the other, +copying data directly between the two; there is no internal buffering. +It is safe to call Read and Write in parallel with each other or with +Close. Close will complete once pending I/O is done. Parallel calls to +Read, and parallel calls to Write, are also safe: +the individual calls will be gated sequentially. +

    + + + + + + + +

    func (*PipeReader) Close

    +
    func (r *PipeReader) Close() error
    +

    +Close closes the reader; subsequent writes to the +write half of the pipe will return the error ErrClosedPipe. +

    + + + + + + +

    func (*PipeReader) CloseWithError

    +
    func (r *PipeReader) CloseWithError(err error) error
    +

    +CloseWithError closes the reader; subsequent writes +to the write half of the pipe will return the error err. +

    + + + + + + +

    func (*PipeReader) Read

    +
    func (r *PipeReader) Read(data []byte) (n int, err error)
    +

    +Read implements the standard Read interface: +it reads data from the pipe, blocking until a writer +arrives or the write end is closed. +If the write end is closed with an error, that error is +returned as err; otherwise err is EOF. +

    + + + + + + + + +

    type PipeWriter

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

    +A PipeWriter is the write half of a pipe. +

    + + + + + + + + + + + + + + +

    func (*PipeWriter) Close

    +
    func (w *PipeWriter) Close() error
    +

    +Close closes the writer; subsequent reads from the +read half of the pipe will return no bytes and EOF. +

    + + + + + + +

    func (*PipeWriter) CloseWithError

    +
    func (w *PipeWriter) CloseWithError(err error) error
    +

    +CloseWithError closes the writer; subsequent reads from the +read half of the pipe will return no bytes and the error err, +or EOF if err is nil. +

    +

    +CloseWithError always returns nil. +

    + + + + + + +

    func (*PipeWriter) Write

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

    +Write implements the standard Write interface: +it writes data to the pipe, blocking until readers +have consumed all the data or the read end is closed. +If the read end is closed with an error, that err is +returned as err; otherwise err is ErrClosedPipe. +

    + + + + + + + + +

    type ReadCloser

    +
    type ReadCloser interface {
    +    Reader
    +    Closer
    +}
    +

    +ReadCloser is the interface that groups the basic Read and Close methods. +

    + + + + + + + + + + + + + + + + +

    type ReadSeeker

    +
    type ReadSeeker interface {
    +    Reader
    +    Seeker
    +}
    +

    +ReadSeeker is the interface that groups the basic Read and Seek methods. +

    + + + + + + + + + + + + + + + + +

    type ReadWriteCloser

    +
    type ReadWriteCloser interface {
    +    Reader
    +    Writer
    +    Closer
    +}
    +

    +ReadWriteCloser is the interface that groups the basic Read, Write and Close methods. +

    + + + + + + + + + + + + + + + + +

    type ReadWriteSeeker

    +
    type ReadWriteSeeker interface {
    +    Reader
    +    Writer
    +    Seeker
    +}
    +

    +ReadWriteSeeker is the interface that groups the basic Read, Write and Seek methods. +

    + + + + + + + + + + + + + + + + +

    type ReadWriter

    +
    type ReadWriter interface {
    +    Reader
    +    Writer
    +}
    +

    +ReadWriter is the interface that groups the basic Read and Write methods. +

    + + + + + + + + + + + + + + + + +

    type Reader

    +
    type Reader interface {
    +    Read(p []byte) (n int, err error)
    +}
    +

    +Reader is the interface that wraps the basic Read method. +

    +

    +Read reads up to len(p) bytes into p. It returns the number of bytes +read (0 <= n <= len(p)) and any error encountered. Even if Read +returns n < len(p), it may use all of p as scratch space during the call. +If some data is available but not len(p) bytes, Read conventionally +returns what is available instead of waiting for more. +

    +

    +When Read encounters an error or end-of-file condition after +successfully reading n > 0 bytes, it returns the number of +bytes read. It may return the (non-nil) error from the same call +or return the error (and n == 0) from a subsequent call. +An instance of this general case is that a Reader returning +a non-zero number of bytes at the end of the input stream may +return either err == EOF or err == nil. The next Read should +return 0, EOF. +

    +

    +Callers should always process the n > 0 bytes returned before +considering the error err. Doing so correctly handles I/O errors +that happen after reading some bytes and also both of the +allowed EOF behaviors. +

    +

    +Implementations of Read are discouraged from returning a +zero byte count with a nil error, except when len(p) == 0. +Callers should treat a return of 0 and nil as indicating that +nothing happened; in particular it does not indicate EOF. +

    +

    +Implementations must not retain p. +

    + + + + + + + + + + + + +

    func LimitReader

    +
    func LimitReader(r Reader, n int64) Reader
    +

    +LimitReader returns a Reader that reads from r +but stops with EOF after n bytes. +The underlying implementation is a *LimitedReader. +

    + +
    + +
    +

    Example

    + + + +

    Code:

    +
    r := strings.NewReader("some io.Reader stream to be read\n")
    +lr := io.LimitReader(r, 4)
    +
    +if _, err := io.Copy(os.Stdout, lr); err != nil {
    +    log.Fatal(err)
    +}
    +
    +
    + +

    Output:

    +
    some
    +
    + + +
    +
    + + + + +

    func MultiReader

    +
    func MultiReader(readers ...Reader) Reader
    +

    +MultiReader returns a Reader that's the logical concatenation of +the provided input readers. They're read sequentially. Once all +inputs have returned EOF, Read will return EOF. If any of the readers +return a non-nil, non-EOF error, Read will return that error. +

    + +
    + +
    +

    Example

    + + + +

    Code:

    +
    r1 := strings.NewReader("first reader ")
    +r2 := strings.NewReader("second reader ")
    +r3 := strings.NewReader("third reader\n")
    +r := io.MultiReader(r1, r2, r3)
    +
    +if _, err := io.Copy(os.Stdout, r); err != nil {
    +    log.Fatal(err)
    +}
    +
    +
    + +

    Output:

    +
    first reader second reader third reader
    +
    + + +
    +
    + + + + +

    func TeeReader

    +
    func TeeReader(r Reader, w Writer) Reader
    +

    +TeeReader returns a Reader that writes to w what it reads from r. +All reads from r performed through it are matched with +corresponding writes to w. There is no internal buffering - +the write must complete before the read completes. +Any error encountered while writing is reported as a read error. +

    + +
    + +
    +

    Example

    + + + +

    Code:

    +
    r := strings.NewReader("some io.Reader stream to be read\n")
    +var buf bytes.Buffer
    +tee := io.TeeReader(r, &buf)
    +
    +printall := func(r io.Reader) {
    +    b, err := ioutil.ReadAll(r)
    +    if err != nil {
    +        log.Fatal(err)
    +    }
    +
    +    fmt.Printf("%s", b)
    +}
    +
    +printall(tee)
    +printall(&buf)
    +
    +
    + +

    Output:

    +
    some io.Reader stream to be read
    +some io.Reader stream to be read
    +
    + + +
    +
    + + + + + + + + +

    type ReaderAt

    +
    type ReaderAt interface {
    +    ReadAt(p []byte, off int64) (n int, err error)
    +}
    +

    +ReaderAt is the interface that wraps the basic ReadAt method. +

    +

    +ReadAt reads len(p) bytes into p starting at offset off in the +underlying input source. It returns the number of bytes +read (0 <= n <= len(p)) and any error encountered. +

    +

    +When ReadAt returns n < len(p), it returns a non-nil error +explaining why more bytes were not returned. In this respect, +ReadAt is stricter than Read. +

    +

    +Even if ReadAt returns n < len(p), it may use all of p as scratch +space during the call. If some data is available but not len(p) bytes, +ReadAt blocks until either all the data is available or an error occurs. +In this respect ReadAt is different from Read. +

    +

    +If the n = len(p) bytes returned by ReadAt are at the end of the +input source, ReadAt may return either err == EOF or err == nil. +

    +

    +If ReadAt is reading from an input source with a seek offset, +ReadAt should not affect nor be affected by the underlying +seek offset. +

    +

    +Clients of ReadAt can execute parallel ReadAt calls on the +same input source. +

    +

    +Implementations must not retain p. +

    + + + + + + + + + + + + + + + + +

    type ReaderFrom

    +
    type ReaderFrom interface {
    +    ReadFrom(r Reader) (n int64, err error)
    +}
    +

    +ReaderFrom is the interface that wraps the ReadFrom method. +

    +

    +ReadFrom reads data from r until EOF or error. +The return value n is the number of bytes read. +Any error except io.EOF encountered during the read is also returned. +

    +

    +The Copy function uses ReaderFrom if available. +

    + + + + + + + + + + + + + + + + +

    type RuneReader

    +
    type RuneReader interface {
    +    ReadRune() (r rune, size int, err error)
    +}
    +

    +RuneReader is the interface that wraps the ReadRune method. +

    +

    +ReadRune reads a single UTF-8 encoded Unicode character +and returns the rune and its size in bytes. If no character is +available, err will be set. +

    + + + + + + + + + + + + + + + + +

    type RuneScanner

    +
    type RuneScanner interface {
    +    RuneReader
    +    UnreadRune() error
    +}
    +

    +RuneScanner is the interface that adds the UnreadRune method to the +basic ReadRune method. +

    +

    +UnreadRune causes the next call to ReadRune to return the same rune +as the previous call to ReadRune. +It may be an error to call UnreadRune twice without an intervening +call to ReadRune. +

    + + + + + + + + + + + + + + + + +

    type SectionReader

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

    +SectionReader implements Read, Seek, and ReadAt on a section +of an underlying ReaderAt. +

    + + + + + + +
    + +
    +

    Example

    + + + +

    Code:

    +
    r := strings.NewReader("some io.Reader stream to be read\n")
    +s := io.NewSectionReader(r, 5, 17)
    +
    +if _, err := io.Copy(os.Stdout, s); err != nil {
    +    log.Fatal(err)
    +}
    +
    +
    + +

    Output:

    +
    io.Reader stream
    +
    + + +
    +
    + + + + + + +

    func NewSectionReader

    +
    func NewSectionReader(r ReaderAt, off int64, n int64) *SectionReader
    +

    +NewSectionReader returns a SectionReader that reads from r +starting at offset off and stops with EOF after n bytes. +

    + + + + + + + +

    func (*SectionReader) Read

    +
    func (s *SectionReader) Read(p []byte) (n int, err error)
    + + + + + + +

    func (*SectionReader) ReadAt

    +
    func (s *SectionReader) ReadAt(p []byte, off int64) (n int, err error)
    + + +
    + +
    +

    Example

    + + + +

    Code:

    +
    r := strings.NewReader("some io.Reader stream to be read\n")
    +s := io.NewSectionReader(r, 5, 16)
    +
    +buf := make([]byte, 6)
    +if _, err := s.ReadAt(buf, 10); err != nil {
    +    log.Fatal(err)
    +}
    +
    +fmt.Printf("%s\n", buf)
    +
    +
    + +

    Output:

    +
    stream
    +
    + + +
    +
    + + + + +

    func (*SectionReader) Seek

    +
    func (s *SectionReader) Seek(offset int64, whence int) (int64, error)
    + + +
    + +
    +

    Example

    + + + +

    Code:

    +
    r := strings.NewReader("some io.Reader stream to be read\n")
    +s := io.NewSectionReader(r, 5, 16)
    +
    +if _, err := s.Seek(10, 0); err != nil {
    +    log.Fatal(err)
    +}
    +
    +buf := make([]byte, 6)
    +if _, err := s.Read(buf); err != nil {
    +    log.Fatal(err)
    +}
    +
    +fmt.Printf("%s\n", buf)
    +
    +
    + +

    Output:

    +
    stream
    +
    + + +
    +
    + + + + +

    func (*SectionReader) Size

    +
    func (s *SectionReader) Size() int64
    +

    +Size returns the size of the section in bytes. +

    + + + + + + + + +

    type Seeker

    +
    type Seeker interface {
    +    Seek(offset int64, whence int) (int64, error)
    +}
    +

    +Seeker is the interface that wraps the basic Seek method. +

    +

    +Seek sets the offset for the next Read or Write to offset, +interpreted according to whence: 0 means relative to the start of +the file, 1 means relative to the current offset, and 2 means +relative to the end. Seek returns the new offset relative to the +start of the file and an error, if any. +

    +

    +Seeking to an offset before the start of the file is an error. +Seeking to any positive offset is legal, but the behavior of subsequent +I/O operations on the underlying object is implementation-dependent. +

    + + + + + + + + + + + + + + + + +

    type WriteCloser

    +
    type WriteCloser interface {
    +    Writer
    +    Closer
    +}
    +

    +WriteCloser is the interface that groups the basic Write and Close methods. +

    + + + + + + + + + + + + + + + + +

    type WriteSeeker

    +
    type WriteSeeker interface {
    +    Writer
    +    Seeker
    +}
    +

    +WriteSeeker is the interface that groups the basic Write and Seek methods. +

    + + + + + + + + + + + + + + + + +

    type Writer

    +
    type Writer interface {
    +    Write(p []byte) (n int, err error)
    +}
    +

    +Writer is the interface that wraps the basic Write method. +

    +

    +Write writes len(p) bytes from p to the underlying data stream. +It returns the number of bytes written from p (0 <= n <= len(p)) +and any error encountered that caused the write to stop early. +Write must return a non-nil error if it returns n < len(p). +Write must not modify the slice data, even temporarily. +

    +

    +Implementations must not retain p. +

    + + + + + + + + + + + + +

    func MultiWriter

    +
    func MultiWriter(writers ...Writer) Writer
    +

    +MultiWriter creates a writer that duplicates its writes to all the +provided writers, similar to the Unix tee(1) command. +

    + +
    + +
    +

    Example

    + + + +

    Code:

    +
    r := strings.NewReader("some io.Reader stream to be read\n")
    +
    +var buf1, buf2 bytes.Buffer
    +w := io.MultiWriter(&buf1, &buf2)
    +
    +if _, err := io.Copy(w, r); err != nil {
    +    log.Fatal(err)
    +}
    +
    +fmt.Print(buf1.String())
    +fmt.Print(buf2.String())
    +
    +
    + +

    Output:

    +
    some io.Reader stream to be read
    +some io.Reader stream to be read
    +
    + + +
    +
    + + + + + + + + +

    type WriterAt

    +
    type WriterAt interface {
    +    WriteAt(p []byte, off int64) (n int, err error)
    +}
    +

    +WriterAt is the interface that wraps the basic WriteAt method. +

    +

    +WriteAt writes len(p) bytes from p to the underlying data stream +at offset off. It returns the number of bytes written from p (0 <= n <= len(p)) +and any error encountered that caused the write to stop early. +WriteAt must return a non-nil error if it returns n < len(p). +

    +

    +If WriteAt is writing to a destination with a seek offset, +WriteAt should not affect nor be affected by the underlying +seek offset. +

    +

    +Clients of WriteAt can execute parallel WriteAt calls on the same +destination if the ranges do not overlap. +

    +

    +Implementations must not retain p. +

    + + + + + + + + + + + + + + + + +

    type WriterTo

    +
    type WriterTo interface {
    +    WriteTo(w Writer) (n int64, err error)
    +}
    +

    +WriterTo is the interface that wraps the WriteTo method. +

    +

    +WriteTo writes data to w until there's no more data to write or +when an error occurs. The return value n is the number of bytes +written. Any error encountered during the write is also returned. +

    +

    +The Copy function uses WriterTo if available. +

    + + + + + + + + + + + + + + + + + + + + + + + + +

    Subdirectories

    + + + + +
    + + + + + + + + + + + + + + + + + + + + +
    NameSynopsis
    ..
    + ioutil + + Package ioutil implements some I/O utility functions. +
    +
    + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/io/ioutil/index.html b/pkg/io/ioutil/index.html new file mode 100644 index 0000000..abaa124 --- /dev/null +++ b/pkg/io/ioutil/index.html @@ -0,0 +1,475 @@ + + + + + + + + ioutil - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Package ioutil

    + + + + + + + + + + + + + + +
    +
    +
    import "io/ioutil"
    +
    +
    +
    Overview
    +
    Index
    + +
    Examples
    + + +
    +
    + +
    + +
    +

    Overview ▾

    +

    +Package ioutil implements some I/O utility functions. +

    + +
    +
    + + + + + + + + +

    Variables

    + +
    var Discard io.Writer = devNull(0)
    +

    +Discard is an io.Writer on which all Write calls succeed +without doing anything. +

    + + + + + + +

    func NopCloser

    +
    func NopCloser(r io.Reader) io.ReadCloser
    +

    +NopCloser returns a ReadCloser with a no-op Close method wrapping +the provided Reader r. +

    + + + + + + + +

    func ReadAll

    +
    func ReadAll(r io.Reader) ([]byte, error)
    +

    +ReadAll reads from r until an error or EOF and returns the data it read. +A successful call returns err == nil, not err == EOF. Because ReadAll is +defined to read from src until EOF, it does not treat an EOF from Read +as an error to be reported. +

    + +
    + +
    +

    Example

    + + + +

    Code:

    +
    r := strings.NewReader("Go is a general-purpose language designed with systems programming in mind.")
    +
    +b, err := ioutil.ReadAll(r)
    +if err != nil {
    +    log.Fatal(err)
    +}
    +
    +fmt.Printf("%s", b)
    +
    +
    + +

    Output:

    +
    Go is a general-purpose language designed with systems programming in mind.
    +
    + + +
    +
    + + + + + + +

    func ReadDir

    +
    func ReadDir(dirname string) ([]os.FileInfo, error)
    +

    +ReadDir reads the directory named by dirname and returns +a list of directory entries sorted by filename. +

    + +
    + +
    +

    Example

    + + + +

    Code:

    +
    +files, err := ioutil.ReadDir(".")
    +if err != nil {
    +    log.Fatal(err)
    +}
    +
    +for _, file := range files {
    +    fmt.Println(file.Name())
    +}
    +
    + + +
    +
    + + + + + + +

    func ReadFile

    +
    func ReadFile(filename string) ([]byte, error)
    +

    +ReadFile reads the file named by filename and returns the contents. +A successful call returns err == nil, not err == EOF. Because ReadFile +reads the whole file, it does not treat an EOF from Read as an error +to be reported. +

    + + + + + + + +

    func TempDir

    +
    func TempDir(dir, prefix string) (name string, err error)
    +

    +TempDir creates a new temporary directory in the directory dir +with a name beginning with prefix and returns the path of the +new directory. If dir is the empty string, TempDir uses the +default directory for temporary files (see os.TempDir). +Multiple programs calling TempDir simultaneously +will not choose the same directory. It is the caller's responsibility +to remove the directory when no longer needed. +

    + +
    + +
    +

    Example

    + + + +

    Code:

    +
    +content := []byte("temporary file's content")
    +dir, err := ioutil.TempDir("", "example")
    +if err != nil {
    +    log.Fatal(err)
    +}
    +
    +defer os.RemoveAll(dir) // clean up
    +
    +tmpfn := filepath.Join(dir, "tmpfile")
    +if err := ioutil.WriteFile(tmpfn, content, 0666); err != nil {
    +    log.Fatal(err)
    +}
    +
    + + +
    +
    + + + + + + +

    func TempFile

    +
    func TempFile(dir, prefix string) (f *os.File, err error)
    +

    +TempFile creates a new temporary file in the directory dir +with a name beginning with prefix, opens the file for reading +and writing, and returns the resulting *os.File. +If dir is the empty string, TempFile uses the default directory +for temporary files (see os.TempDir). +Multiple programs calling TempFile simultaneously +will not choose the same file. The caller can use f.Name() +to find the pathname of the file. It is the caller's responsibility +to remove the file when no longer needed. +

    + +
    + +
    +

    Example

    + + + +

    Code:

    +
    +content := []byte("temporary file's content")
    +tmpfile, err := ioutil.TempFile("", "example")
    +if err != nil {
    +    log.Fatal(err)
    +}
    +
    +defer os.Remove(tmpfile.Name()) // clean up
    +
    +if _, err := tmpfile.Write(content); err != nil {
    +    log.Fatal(err)
    +}
    +if err := tmpfile.Close(); err != nil {
    +    log.Fatal(err)
    +}
    +
    + + +
    +
    + + + + + + +

    func WriteFile

    +
    func WriteFile(filename string, data []byte, perm os.FileMode) error
    +

    +WriteFile writes data to a file named by filename. +If the file does not exist, WriteFile creates it with permissions perm; +otherwise WriteFile truncates it before writing. +

    + + + + + + + + + + + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/log/index.html b/pkg/log/index.html new file mode 100644 index 0000000..e701044 --- /dev/null +++ b/pkg/log/index.html @@ -0,0 +1,814 @@ + + + + + + + + log - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Package log

    + + + + + + + + + + + + + + +
    +
    +
    import "log"
    +
    +
    +
    Overview
    +
    Index
    + +
    Examples
    + + +
    Subdirectories
    + +
    +
    + +
    + +
    +

    Overview ▾

    +

    +Package log implements a simple logging package. It defines a type, Logger, +with methods for formatting output. It also has a predefined 'standard' +Logger accessible through helper functions Print[f|ln], Fatal[f|ln], and +Panic[f|ln], which are easier to use than creating a Logger manually. +That logger writes to standard error and prints the date and time +of each logged message. +The Fatal functions call os.Exit(1) after writing the log message. +The Panic functions call panic after writing the log message. +

    + +
    +
    + + +
    + +
    +

    Index ▾

    + + +
    +
    + +
    Constants
    + + + + +
    func Fatal(v ...interface{})
    + + +
    func Fatalf(format string, v ...interface{})
    + + +
    func Fatalln(v ...interface{})
    + + +
    func Flags() int
    + + +
    func Output(calldepth int, s string) error
    + + +
    func Panic(v ...interface{})
    + + +
    func Panicf(format string, v ...interface{})
    + + +
    func Panicln(v ...interface{})
    + + +
    func Prefix() string
    + + +
    func Print(v ...interface{})
    + + +
    func Printf(format string, v ...interface{})
    + + +
    func Println(v ...interface{})
    + + +
    func SetFlags(flag int)
    + + +
    func SetOutput(w io.Writer)
    + + +
    func SetPrefix(prefix string)
    + + + +
    type Logger
    + + +
        func New(out io.Writer, prefix string, flag int) *Logger
    + + + +
        func (l *Logger) Fatal(v ...interface{})
    + + +
        func (l *Logger) Fatalf(format string, v ...interface{})
    + + +
        func (l *Logger) Fatalln(v ...interface{})
    + + +
        func (l *Logger) Flags() int
    + + +
        func (l *Logger) Output(calldepth int, s string) error
    + + +
        func (l *Logger) Panic(v ...interface{})
    + + +
        func (l *Logger) Panicf(format string, v ...interface{})
    + + +
        func (l *Logger) Panicln(v ...interface{})
    + + +
        func (l *Logger) Prefix() string
    + + +
        func (l *Logger) Print(v ...interface{})
    + + +
        func (l *Logger) Printf(format string, v ...interface{})
    + + +
        func (l *Logger) Println(v ...interface{})
    + + +
        func (l *Logger) SetFlags(flag int)
    + + +
        func (l *Logger) SetOutput(w io.Writer)
    + + +
        func (l *Logger) SetPrefix(prefix string)
    + + + +
    +
    + + +
    +

    Examples

    +
    + +
    Logger
    + +
    +
    + + + +

    Package files

    +

    + + + log.go + + +

    + +
    +
    + + + + +

    Constants

    + +
    const (
    +    // Bits or'ed together to control what's printed.
    +    // There is no control over the order they appear (the order listed
    +    // here) or the format they present (as described in the comments).
    +    // The prefix is followed by a colon only when Llongfile or Lshortfile
    +    // is specified.
    +    // For example, flags Ldate | Ltime (or LstdFlags) produce,
    +    //	2009/01/23 01:23:23 message
    +    // while flags Ldate | Ltime | Lmicroseconds | Llongfile produce,
    +    //	2009/01/23 01:23:23.123123 /a/b/c/d.go:23: message
    +    Ldate         = 1 << iota     // the date in the local time zone: 2009/01/23
    +    Ltime                         // the time in the local time zone: 01:23:23
    +    Lmicroseconds                 // microsecond resolution: 01:23:23.123123.  assumes Ltime.
    +    Llongfile                     // full file name and line number: /a/b/c/d.go:23
    +    Lshortfile                    // final file name element and line number: d.go:23. overrides Llongfile
    +    LUTC                          // if Ldate or Ltime is set, use UTC rather than the local time zone
    +    LstdFlags     = Ldate | Ltime // initial values for the standard logger
    +)
    +

    +These flags define which text to prefix to each log entry generated by the Logger. +

    + + + + + + + +

    func Fatal

    +
    func Fatal(v ...interface{})
    +

    +Fatal is equivalent to Print() followed by a call to os.Exit(1). +

    + + + + + + + +

    func Fatalf

    +
    func Fatalf(format string, v ...interface{})
    +

    +Fatalf is equivalent to Printf() followed by a call to os.Exit(1). +

    + + + + + + + +

    func Fatalln

    +
    func Fatalln(v ...interface{})
    +

    +Fatalln is equivalent to Println() followed by a call to os.Exit(1). +

    + + + + + + + +

    func Flags

    +
    func Flags() int
    +

    +Flags returns the output flags for the standard logger. +

    + + + + + + + +

    func Output

    +
    func Output(calldepth int, s string) error
    +

    +Output writes the output for a logging event. The string s contains +the text to print after the prefix specified by the flags of the +Logger. A newline is appended if the last character of s is not +already a newline. Calldepth is the count of the number of +frames to skip when computing the file name and line number +if Llongfile or Lshortfile is set; a value of 1 will print the details +for the caller of Output. +

    + + + + + + + +

    func Panic

    +
    func Panic(v ...interface{})
    +

    +Panic is equivalent to Print() followed by a call to panic(). +

    + + + + + + + +

    func Panicf

    +
    func Panicf(format string, v ...interface{})
    +

    +Panicf is equivalent to Printf() followed by a call to panic(). +

    + + + + + + + +

    func Panicln

    +
    func Panicln(v ...interface{})
    +

    +Panicln is equivalent to Println() followed by a call to panic(). +

    + + + + + + + +

    func Prefix

    +
    func Prefix() string
    +

    +Prefix returns the output prefix for the standard logger. +

    + + + + + + + +

    func Print

    +
    func Print(v ...interface{})
    +

    +Print calls Output to print to the standard logger. +Arguments are handled in the manner of fmt.Print. +

    + + + + + + + +

    func Printf

    +
    func Printf(format string, v ...interface{})
    +

    +Printf calls Output to print to the standard logger. +Arguments are handled in the manner of fmt.Printf. +

    + + + + + + + +

    func Println

    +
    func Println(v ...interface{})
    +

    +Println calls Output to print to the standard logger. +Arguments are handled in the manner of fmt.Println. +

    + + + + + + + +

    func SetFlags

    +
    func SetFlags(flag int)
    +

    +SetFlags sets the output flags for the standard logger. +

    + + + + + + + +

    func SetOutput

    +
    func SetOutput(w io.Writer)
    +

    +SetOutput sets the output destination for the standard logger. +

    + + + + + + + +

    func SetPrefix

    +
    func SetPrefix(prefix string)
    +

    +SetPrefix sets the output prefix for the standard logger. +

    + + + + + + + + +

    type Logger

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

    +A Logger represents an active logging object that generates lines of +output to an io.Writer. Each logging operation makes a single call to +the Writer's Write method. A Logger can be used simultaneously from +multiple goroutines; it guarantees to serialize access to the Writer. +

    + + + + + + +
    + +
    +

    Example

    + + + +

    Code:

    +
    var buf bytes.Buffer
    +logger := log.New(&buf, "logger: ", log.Lshortfile)
    +logger.Print("Hello, log file!")
    +
    +fmt.Print(&buf)
    +
    + +

    Output:

    +
    logger: example_test.go:16: Hello, log file!
    +
    + + +
    +
    + + + + + + +

    func New

    +
    func New(out io.Writer, prefix string, flag int) *Logger
    +

    +New creates a new Logger. The out variable sets the +destination to which log data will be written. +The prefix appears at the beginning of each generated log line. +The flag argument defines the logging properties. +

    + + + + + + + +

    func (*Logger) Fatal

    +
    func (l *Logger) Fatal(v ...interface{})
    +

    +Fatal is equivalent to l.Print() followed by a call to os.Exit(1). +

    + + + + + + +

    func (*Logger) Fatalf

    +
    func (l *Logger) Fatalf(format string, v ...interface{})
    +

    +Fatalf is equivalent to l.Printf() followed by a call to os.Exit(1). +

    + + + + + + +

    func (*Logger) Fatalln

    +
    func (l *Logger) Fatalln(v ...interface{})
    +

    +Fatalln is equivalent to l.Println() followed by a call to os.Exit(1). +

    + + + + + + +

    func (*Logger) Flags

    +
    func (l *Logger) Flags() int
    +

    +Flags returns the output flags for the logger. +

    + + + + + + +

    func (*Logger) Output

    +
    func (l *Logger) Output(calldepth int, s string) error
    +

    +Output writes the output for a logging event. The string s contains +the text to print after the prefix specified by the flags of the +Logger. A newline is appended if the last character of s is not +already a newline. Calldepth is used to recover the PC and is +provided for generality, although at the moment on all pre-defined +paths it will be 2. +

    + + + + + + +

    func (*Logger) Panic

    +
    func (l *Logger) Panic(v ...interface{})
    +

    +Panic is equivalent to l.Print() followed by a call to panic(). +

    + + + + + + +

    func (*Logger) Panicf

    +
    func (l *Logger) Panicf(format string, v ...interface{})
    +

    +Panicf is equivalent to l.Printf() followed by a call to panic(). +

    + + + + + + +

    func (*Logger) Panicln

    +
    func (l *Logger) Panicln(v ...interface{})
    +

    +Panicln is equivalent to l.Println() followed by a call to panic(). +

    + + + + + + +

    func (*Logger) Prefix

    +
    func (l *Logger) Prefix() string
    +

    +Prefix returns the output prefix for the logger. +

    + + + + + + +

    func (*Logger) Print

    +
    func (l *Logger) Print(v ...interface{})
    +

    +Print calls l.Output to print to the logger. +Arguments are handled in the manner of fmt.Print. +

    + + + + + + +

    func (*Logger) Printf

    +
    func (l *Logger) Printf(format string, v ...interface{})
    +

    +Printf calls l.Output to print to the logger. +Arguments are handled in the manner of fmt.Printf. +

    + + + + + + +

    func (*Logger) Println

    +
    func (l *Logger) Println(v ...interface{})
    +

    +Println calls l.Output to print to the logger. +Arguments are handled in the manner of fmt.Println. +

    + + + + + + +

    func (*Logger) SetFlags

    +
    func (l *Logger) SetFlags(flag int)
    +

    +SetFlags sets the output flags for the logger. +

    + + + + + + +

    func (*Logger) SetOutput

    +
    func (l *Logger) SetOutput(w io.Writer)
    +

    +SetOutput sets the output destination for the logger. +

    + + + + + + +

    func (*Logger) SetPrefix

    +
    func (l *Logger) SetPrefix(prefix string)
    +

    +SetPrefix sets the output prefix for the logger. +

    + + + + + + + + + + + + + + + + +

    Subdirectories

    + + + + +
    + + + + + + + + + + + + + + + + + + + + +
    NameSynopsis
    ..
    + syslog + + Package syslog provides a simple interface to the system log service. +
    +
    + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/log/syslog/index.html b/pkg/log/syslog/index.html new file mode 100644 index 0000000..6e9a366 --- /dev/null +++ b/pkg/log/syslog/index.html @@ -0,0 +1,543 @@ + + + + + + + + syslog - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Package syslog

    + + + + + + + + + + + + + + +
    +
    +
    import "log/syslog"
    +
    +
    +
    Overview
    +
    Index
    + + +
    +
    + +
    + +
    +

    Overview ▾

    +

    +Package syslog provides a simple interface to the system log +service. It can send messages to the syslog daemon using UNIX +domain sockets, UDP or TCP. +

    +

    +Only one call to Dial is necessary. On write failures, +the syslog client will attempt to reconnect to the server +and write again. +

    +

    +The syslog package is frozen and not accepting new features. +Some external packages provide more functionality. See: +

    +
    https://godoc.org/?q=syslog
    +
    + +
    +
    + + + + + + + + + + + +

    func NewLogger

    +
    func NewLogger(p Priority, logFlag int) (*log.Logger, error)
    +

    +NewLogger creates a log.Logger whose output is written to +the system log service with the specified priority. The logFlag +argument is the flag set passed through to log.New to create +the Logger. +

    + + + + + + + + +

    type Priority

    +
    type Priority int
    +

    +The Priority is a combination of the syslog facility and +severity. For example, LOG_ALERT | LOG_FTP sends an alert severity +message from the FTP facility. The default severity is LOG_EMERG; +the default facility is LOG_KERN. +

    + + + +
    const (
    +
    +    // From /usr/include/sys/syslog.h.
    +    // These are the same on Linux, BSD, and OS X.
    +    LOG_EMERG Priority = iota
    +    LOG_ALERT
    +    LOG_CRIT
    +    LOG_ERR
    +    LOG_WARNING
    +    LOG_NOTICE
    +    LOG_INFO
    +    LOG_DEBUG
    +)
    + + +
    const (
    +
    +    // From /usr/include/sys/syslog.h.
    +    // These are the same up to LOG_FTP on Linux, BSD, and OS X.
    +    LOG_KERN Priority = iota << 3
    +    LOG_USER
    +    LOG_MAIL
    +    LOG_DAEMON
    +    LOG_AUTH
    +    LOG_SYSLOG
    +    LOG_LPR
    +    LOG_NEWS
    +    LOG_UUCP
    +    LOG_CRON
    +    LOG_AUTHPRIV
    +    LOG_FTP
    +
    +    LOG_LOCAL0
    +    LOG_LOCAL1
    +    LOG_LOCAL2
    +    LOG_LOCAL3
    +    LOG_LOCAL4
    +    LOG_LOCAL5
    +    LOG_LOCAL6
    +    LOG_LOCAL7
    +)
    + + + + + + + + + + + + + + + +

    type Writer

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

    +A Writer is a connection to a syslog server. +

    + + + + + + + + + + + + +

    func Dial

    +
    func Dial(network, raddr string, priority Priority, tag string) (*Writer, error)
    +

    +Dial establishes a connection to a log daemon by connecting to +address raddr on the specified network. Each write to the returned +writer sends a log message with the given facility, severity and +tag. +If network is empty, Dial will connect to the local syslog server. +

    + + + + + +

    func New

    +
    func New(priority Priority, tag string) (w *Writer, err error)
    +

    +New establishes a new connection to the system log daemon. Each +write to the returned writer sends a log message with the given +priority and prefix. +

    + + + + + + + +

    func (*Writer) Alert

    +
    func (w *Writer) Alert(m string) (err error)
    +

    +Alert logs a message with severity LOG_ALERT, ignoring the severity +passed to New. +

    + + + + + + +

    func (*Writer) Close

    +
    func (w *Writer) Close() error
    +

    +Close closes a connection to the syslog daemon. +

    + + + + + + +

    func (*Writer) Crit

    +
    func (w *Writer) Crit(m string) (err error)
    +

    +Crit logs a message with severity LOG_CRIT, ignoring the severity +passed to New. +

    + + + + + + +

    func (*Writer) Debug

    +
    func (w *Writer) Debug(m string) (err error)
    +

    +Debug logs a message with severity LOG_DEBUG, ignoring the severity +passed to New. +

    + + + + + + +

    func (*Writer) Emerg

    +
    func (w *Writer) Emerg(m string) (err error)
    +

    +Emerg logs a message with severity LOG_EMERG, ignoring the severity +passed to New. +

    + + + + + + +

    func (*Writer) Err

    +
    func (w *Writer) Err(m string) (err error)
    +

    +Err logs a message with severity LOG_ERR, ignoring the severity +passed to New. +

    + + + + + + +

    func (*Writer) Info

    +
    func (w *Writer) Info(m string) (err error)
    +

    +Info logs a message with severity LOG_INFO, ignoring the severity +passed to New. +

    + + + + + + +

    func (*Writer) Notice

    +
    func (w *Writer) Notice(m string) (err error)
    +

    +Notice logs a message with severity LOG_NOTICE, ignoring the +severity passed to New. +

    + + + + + + +

    func (*Writer) Warning

    +
    func (w *Writer) Warning(m string) (err error)
    +

    +Warning logs a message with severity LOG_WARNING, ignoring the +severity passed to New. +

    + + + + + + +

    func (*Writer) Write

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

    +Write sends a log message to the syslog daemon. +

    + + + + + + + + + + +

    Bugs

    +
      + +
    • This package is not implemented on Windows. As the +syslog package is frozen, Windows users are encouraged to +use a package outside of the standard library. For background, +see https://golang.org/issue/1108. +
    • + +
    • This package is not implemented on Plan 9. +
    • + +
    • This package is not implemented on NaCl (Native Client). +
    • + +
    + + + + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/math/big/index.html b/pkg/math/big/index.html new file mode 100644 index 0000000..7e3e4dc --- /dev/null +++ b/pkg/math/big/index.html @@ -0,0 +1,3238 @@ + + + + + + + + big - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Package big

    + + + + + + + + + + + + + + +
    +
    +
    import "math/big"
    +
    +
    +
    Overview
    +
    Index
    + +
    Examples
    + + +
    +
    + +
    + +
    +

    Overview ▾

    +

    +Package big implements arbitrary-precision arithmetic (big numbers). +The following numeric types are supported: +

    +
    Int    signed integers
    +Rat    rational numbers
    +Float  floating-point numbers
    +
    +

    +The zero value for an Int, Rat, or Float correspond to 0. Thus, new +values can be declared in the usual ways and denote 0 without further +initialization: +

    +
    var x Int        // &x is an *Int of value 0
    +var r = &Rat{}   // r is a *Rat of value 0
    +y := new(Float)  // y is a *Float of value 0
    +
    +

    +Alternatively, new values can be allocated and initialized with factory +functions of the form: +

    +
    func NewT(v V) *T
    +
    +

    +For instance, NewInt(x) returns an *Int set to the value of the int64 +argument x, NewRat(a, b) returns a *Rat set to the fraction a/b where +a and b are int64 values, and NewFloat(f) returns a *Float initialized +to the float64 argument f. More flexibility is provided with explicit +setters, for instance: +

    +
    var z1 Int
    +z1.SetUint64(123)                 // z1 := 123
    +z2 := new(Rat).SetFloat64(1.2)    // z2 := 6/5
    +z3 := new(Float).SetInt(z1)       // z3 := 123.0
    +
    +

    +Setters, numeric operations and predicates are represented as methods of +the form: +

    +
    func (z *T) SetV(v V) *T          // z = v
    +func (z *T) Unary(x *T) *T        // z = unary x
    +func (z *T) Binary(x, y *T) *T    // z = x binary y
    +func (x *T) Pred() P              // p = pred(x)
    +
    +

    +with T one of Int, Rat, or Float. For unary and binary operations, the +result is the receiver (usually named z in that case; see below); if it +is one of the operands x or y it may be safely overwritten (and its memory +reused). +

    +

    +Arithmetic expressions are typically written as a sequence of individual +method calls, with each call corresponding to an operation. The receiver +denotes the result and the method arguments are the operation's operands. +For instance, given three *Int values a, b and c, the invocation +

    +
    c.Add(a, b)
    +
    +

    +computes the sum a + b and stores the result in c, overwriting whatever +value was held in c before. Unless specified otherwise, operations permit +aliasing of parameters, so it is perfectly ok to write +

    +
    sum.Add(sum, x)
    +
    +

    +to accumulate values x in a sum. +

    +

    +(By always passing in a result value via the receiver, memory use can be +much better controlled. Instead of having to allocate new memory for each +result, an operation can reuse the space allocated for the result value, +and overwrite that value with the new result in the process.) +

    +

    +Notational convention: Incoming method parameters (including the receiver) +are named consistently in the API to clarify their use. Incoming operands +are usually named x, y, a, b, and so on, but never z. A parameter specifying +the result is named z (typically the receiver). +

    +

    +For instance, the arguments for (*Int).Add are named x and y, and because +the receiver specifies the result destination, it is called z: +

    +
    func (z *Int) Add(x, y *Int) *Int
    +
    +

    +Methods of this form typically return the incoming receiver as well, to +enable simple call chaining. +

    +

    +Methods which don't require a result value to be passed in (for instance, +Int.Sign), simply return the result. In this case, the receiver is typically +the first operand, named x: +

    +
    func (x *Int) Sign() int
    +
    +

    +Various methods support conversions between strings and corresponding +numeric values, and vice versa: *Int, *Rat, and *Float values implement +the Stringer interface for a (default) string representation of the value, +but also provide SetString methods to initialize a value from a string in +a variety of supported formats (see the respective SetString documentation). +

    +

    +Finally, *Int, *Rat, and *Float satisfy the fmt package's Scanner interface +for scanning and (except for *Rat) the Formatter interface for formatted +printing. +

    + +
    +
    +
    + +
    +

    Example (EConvergents)

    +

    This example demonstrates how to use big.Rat to compute the +first 15 terms in the sequence of rational convergents for +the constant e (base of natural logarithm). +

    + + +

    Code:

    +
    package big_test
    +
    +import (
    +    "fmt"
    +    "math/big"
    +)
    +
    +// Use the classic continued fraction for e
    +//     e = [1; 0, 1, 1, 2, 1, 1, ... 2n, 1, 1, ...]
    +// i.e., for the nth term, use
    +//     1          if   n mod 3 != 1
    +//  (n-1)/3 * 2   if   n mod 3 == 1
    +func recur(n, lim int64) *big.Rat {
    +    term := new(big.Rat)
    +    if n%3 != 1 {
    +        term.SetInt64(1)
    +    } else {
    +        term.SetInt64((n - 1) / 3 * 2)
    +    }
    +
    +    if n > lim {
    +        return term
    +    }
    +
    +    // Directly initialize frac as the fractional
    +    // inverse of the result of recur.
    +    frac := new(big.Rat).Inv(recur(n+1, lim))
    +
    +    return term.Add(term, frac)
    +}
    +
    +// This example demonstrates how to use big.Rat to compute the
    +// first 15 terms in the sequence of rational convergents for
    +// the constant e (base of natural logarithm).
    +func Example_eConvergents() {
    +    for i := 1; i <= 15; i++ {
    +        r := recur(0, int64(i))
    +
    +        // Print r both as a fraction and as a floating-point number.
    +        // Since big.Rat implements fmt.Formatter, we can use %-13s to
    +        // get a left-aligned string representation of the fraction.
    +        fmt.Printf("%-13s = %s\n", r, r.FloatString(8))
    +    }
    +
    +    // Output:
    +    // 2/1           = 2.00000000
    +    // 3/1           = 3.00000000
    +    // 8/3           = 2.66666667
    +    // 11/4          = 2.75000000
    +    // 19/7          = 2.71428571
    +    // 87/32         = 2.71875000
    +    // 106/39        = 2.71794872
    +    // 193/71        = 2.71830986
    +    // 1264/465      = 2.71827957
    +    // 1457/536      = 2.71828358
    +    // 2721/1001     = 2.71828172
    +    // 23225/8544    = 2.71828184
    +    // 25946/9545    = 2.71828182
    +    // 49171/18089   = 2.71828183
    +    // 517656/190435 = 2.71828183
    +}
    +
    + + +
    +
    +
    + +
    +

    Example (Fibonacci)

    +

    This example demonstrates how to use big.Int to compute the smallest +Fibonacci number with 100 decimal digits and to test whether it is prime. +

    + + +

    Code:

    +
    // Initialize two big ints with the first two numbers in the sequence.
    +a := big.NewInt(0)
    +b := big.NewInt(1)
    +
    +// Initialize limit as 10^99, the smallest integer with 100 digits.
    +var limit big.Int
    +limit.Exp(big.NewInt(10), big.NewInt(99), nil)
    +
    +// Loop while a is smaller than 1e100.
    +for a.Cmp(&limit) < 0 {
    +    // Compute the next Fibonacci number, storing it in a.
    +    a.Add(a, b)
    +    // Swap a and b so that b is the next number in the sequence.
    +    a, b = b, a
    +}
    +fmt.Println(a) // 100-digit Fibonacci number
    +
    +// Test a for primality.
    +// (ProbablyPrimes' argument sets the number of Miller-Rabin
    +// rounds to be performed. 20 is a good value.)
    +fmt.Println(a.ProbablyPrime(20))
    +
    +
    + +

    Output:

    +
    1344719667586153181419716641724567886890850696275767987106294472017884974410332069524504824747437757
    +false
    +
    + + +
    +
    +
    + +
    +

    Example (Sqrt2)

    +

    This example shows how to use big.Float to compute the square root of 2 with +a precision of 200 bits, and how to print the result as a decimal number. +

    + + +

    Code:

    +
    // We'll do computations with 200 bits of precision in the mantissa.
    +const prec = 200
    +
    +// Compute the square root of 2 using Newton's Method. We start with
    +// an initial estimate for sqrt(2), and then iterate:
    +//     x_{n+1} = 1/2 * ( x_n + (2.0 / x_n) )
    +
    +// Since Newton's Method doubles the number of correct digits at each
    +// iteration, we need at least log_2(prec) steps.
    +steps := int(math.Log2(prec))
    +
    +// Initialize values we need for the computation.
    +two := new(big.Float).SetPrec(prec).SetInt64(2)
    +half := new(big.Float).SetPrec(prec).SetFloat64(0.5)
    +
    +// Use 1 as the initial estimate.
    +x := new(big.Float).SetPrec(prec).SetInt64(1)
    +
    +// We use t as a temporary variable. There's no need to set its precision
    +// since big.Float values with unset (== 0) precision automatically assume
    +// the largest precision of the arguments when used as the result (receiver)
    +// of a big.Float operation.
    +t := new(big.Float)
    +
    +// Iterate.
    +for i := 0; i <= steps; i++ {
    +    t.Quo(two, x)  // t = 2.0 / x_n
    +    t.Add(x, t)    // t = x_n + (2.0 / x_n)
    +    x.Mul(half, t) // x_{n+1} = 0.5 * t
    +}
    +
    +// We can use the usual fmt.Printf verbs since big.Float implements fmt.Formatter
    +fmt.Printf("sqrt(2) = %.50f\n", x)
    +
    +// Print the error between 2 and x*x.
    +t.Mul(x, x) // t = x*x
    +fmt.Printf("error = %e\n", t.Sub(two, t))
    +
    +
    + +

    Output:

    +
    sqrt(2) = 1.41421356237309504880168872420969807856967187537695
    +error = 0.000000e+00
    +
    + + +
    +
    + + +
    + +
    +

    Index ▾

    + + +
    +
    + +
    Constants
    + + + + +
    func Jacobi(x, y *Int) int
    + + + +
    type Accuracy
    + + + +
        func (i Accuracy) String() string
    + + + +
    type ErrNaN
    + + + +
        func (err ErrNaN) Error() string
    + + + +
    type Float
    + + +
        func NewFloat(x float64) *Float
    + + +
        func ParseFloat(s string, base int, prec uint, mode RoundingMode) (f *Float, b int, err error)
    + + + +
        func (z *Float) Abs(x *Float) *Float
    + + +
        func (x *Float) Acc() Accuracy
    + + +
        func (z *Float) Add(x, y *Float) *Float
    + + +
        func (x *Float) Append(buf []byte, fmt byte, prec int) []byte
    + + +
        func (x *Float) Cmp(y *Float) int
    + + +
        func (z *Float) Copy(x *Float) *Float
    + + +
        func (x *Float) Float32() (float32, Accuracy)
    + + +
        func (x *Float) Float64() (float64, Accuracy)
    + + +
        func (x *Float) Format(s fmt.State, format rune)
    + + +
        func (x *Float) Int(z *Int) (*Int, Accuracy)
    + + +
        func (x *Float) Int64() (int64, Accuracy)
    + + +
        func (x *Float) IsInf() bool
    + + +
        func (x *Float) IsInt() bool
    + + +
        func (x *Float) MantExp(mant *Float) (exp int)
    + + +
        func (x *Float) MarshalText() (text []byte, err error)
    + + +
        func (x *Float) MinPrec() uint
    + + +
        func (x *Float) Mode() RoundingMode
    + + +
        func (z *Float) Mul(x, y *Float) *Float
    + + +
        func (z *Float) Neg(x *Float) *Float
    + + +
        func (z *Float) Parse(s string, base int) (f *Float, b int, err error)
    + + +
        func (x *Float) Prec() uint
    + + +
        func (z *Float) Quo(x, y *Float) *Float
    + + +
        func (x *Float) Rat(z *Rat) (*Rat, Accuracy)
    + + +
        func (z *Float) Set(x *Float) *Float
    + + +
        func (z *Float) SetFloat64(x float64) *Float
    + + +
        func (z *Float) SetInf(signbit bool) *Float
    + + +
        func (z *Float) SetInt(x *Int) *Float
    + + +
        func (z *Float) SetInt64(x int64) *Float
    + + +
        func (z *Float) SetMantExp(mant *Float, exp int) *Float
    + + +
        func (z *Float) SetMode(mode RoundingMode) *Float
    + + +
        func (z *Float) SetPrec(prec uint) *Float
    + + +
        func (z *Float) SetRat(x *Rat) *Float
    + + +
        func (z *Float) SetString(s string) (*Float, bool)
    + + +
        func (z *Float) SetUint64(x uint64) *Float
    + + +
        func (x *Float) Sign() int
    + + +
        func (x *Float) Signbit() bool
    + + +
        func (x *Float) String() string
    + + +
        func (z *Float) Sub(x, y *Float) *Float
    + + +
        func (x *Float) Text(format byte, prec int) string
    + + +
        func (x *Float) Uint64() (uint64, Accuracy)
    + + +
        func (z *Float) UnmarshalText(text []byte) error
    + + + +
    type Int
    + + +
        func NewInt(x int64) *Int
    + + + +
        func (z *Int) Abs(x *Int) *Int
    + + +
        func (z *Int) Add(x, y *Int) *Int
    + + +
        func (z *Int) And(x, y *Int) *Int
    + + +
        func (z *Int) AndNot(x, y *Int) *Int
    + + +
        func (x *Int) Append(buf []byte, base int) []byte
    + + +
        func (z *Int) Binomial(n, k int64) *Int
    + + +
        func (x *Int) Bit(i int) uint
    + + +
        func (x *Int) BitLen() int
    + + +
        func (x *Int) Bits() []Word
    + + +
        func (x *Int) Bytes() []byte
    + + +
        func (x *Int) Cmp(y *Int) (r int)
    + + +
        func (z *Int) Div(x, y *Int) *Int
    + + +
        func (z *Int) DivMod(x, y, m *Int) (*Int, *Int)
    + + +
        func (z *Int) Exp(x, y, m *Int) *Int
    + + +
        func (x *Int) Format(s fmt.State, ch rune)
    + + +
        func (z *Int) GCD(x, y, a, b *Int) *Int
    + + +
        func (z *Int) GobDecode(buf []byte) error
    + + +
        func (x *Int) GobEncode() ([]byte, error)
    + + +
        func (x *Int) Int64() int64
    + + +
        func (z *Int) Lsh(x *Int, n uint) *Int
    + + +
        func (x *Int) MarshalJSON() ([]byte, error)
    + + +
        func (x *Int) MarshalText() (text []byte, err error)
    + + +
        func (z *Int) Mod(x, y *Int) *Int
    + + +
        func (z *Int) ModInverse(g, n *Int) *Int
    + + +
        func (z *Int) ModSqrt(x, p *Int) *Int
    + + +
        func (z *Int) Mul(x, y *Int) *Int
    + + +
        func (z *Int) MulRange(a, b int64) *Int
    + + +
        func (z *Int) Neg(x *Int) *Int
    + + +
        func (z *Int) Not(x *Int) *Int
    + + +
        func (z *Int) Or(x, y *Int) *Int
    + + +
        func (x *Int) ProbablyPrime(n int) bool
    + + +
        func (z *Int) Quo(x, y *Int) *Int
    + + +
        func (z *Int) QuoRem(x, y, r *Int) (*Int, *Int)
    + + +
        func (z *Int) Rand(rnd *rand.Rand, n *Int) *Int
    + + +
        func (z *Int) Rem(x, y *Int) *Int
    + + +
        func (z *Int) Rsh(x *Int, n uint) *Int
    + + +
        func (z *Int) Scan(s fmt.ScanState, ch rune) error
    + + +
        func (z *Int) Set(x *Int) *Int
    + + +
        func (z *Int) SetBit(x *Int, i int, b uint) *Int
    + + +
        func (z *Int) SetBits(abs []Word) *Int
    + + +
        func (z *Int) SetBytes(buf []byte) *Int
    + + +
        func (z *Int) SetInt64(x int64) *Int
    + + +
        func (z *Int) SetString(s string, base int) (*Int, bool)
    + + +
        func (z *Int) SetUint64(x uint64) *Int
    + + +
        func (x *Int) Sign() int
    + + +
        func (x *Int) String() string
    + + +
        func (z *Int) Sub(x, y *Int) *Int
    + + +
        func (x *Int) Text(base int) string
    + + +
        func (x *Int) Uint64() uint64
    + + +
        func (z *Int) UnmarshalJSON(text []byte) error
    + + +
        func (z *Int) UnmarshalText(text []byte) error
    + + +
        func (z *Int) Xor(x, y *Int) *Int
    + + + +
    type Rat
    + + +
        func NewRat(a, b int64) *Rat
    + + + +
        func (z *Rat) Abs(x *Rat) *Rat
    + + +
        func (z *Rat) Add(x, y *Rat) *Rat
    + + +
        func (x *Rat) Cmp(y *Rat) int
    + + +
        func (x *Rat) Denom() *Int
    + + +
        func (x *Rat) Float32() (f float32, exact bool)
    + + +
        func (x *Rat) Float64() (f float64, exact bool)
    + + +
        func (x *Rat) FloatString(prec int) string
    + + +
        func (z *Rat) GobDecode(buf []byte) error
    + + +
        func (x *Rat) GobEncode() ([]byte, error)
    + + +
        func (z *Rat) Inv(x *Rat) *Rat
    + + +
        func (x *Rat) IsInt() bool
    + + +
        func (x *Rat) MarshalText() (text []byte, err error)
    + + +
        func (z *Rat) Mul(x, y *Rat) *Rat
    + + +
        func (z *Rat) Neg(x *Rat) *Rat
    + + +
        func (x *Rat) Num() *Int
    + + +
        func (z *Rat) Quo(x, y *Rat) *Rat
    + + +
        func (x *Rat) RatString() string
    + + +
        func (z *Rat) Scan(s fmt.ScanState, ch rune) error
    + + +
        func (z *Rat) Set(x *Rat) *Rat
    + + +
        func (z *Rat) SetFloat64(f float64) *Rat
    + + +
        func (z *Rat) SetFrac(a, b *Int) *Rat
    + + +
        func (z *Rat) SetFrac64(a, b int64) *Rat
    + + +
        func (z *Rat) SetInt(x *Int) *Rat
    + + +
        func (z *Rat) SetInt64(x int64) *Rat
    + + +
        func (z *Rat) SetString(s string) (*Rat, bool)
    + + +
        func (x *Rat) Sign() int
    + + +
        func (x *Rat) String() string
    + + +
        func (z *Rat) Sub(x, y *Rat) *Rat
    + + +
        func (z *Rat) UnmarshalText(text []byte) error
    + + + +
    type RoundingMode
    + + + +
        func (i RoundingMode) String() string
    + + + +
    type Word
    + + + + + +
    Bugs
    + + +
    +
    + + + + + + +

    Package files

    +

    + + + accuracy_string.go + + arith.go + + arith_decl.go + + decimal.go + + doc.go + + float.go + + floatconv.go + + floatmarsh.go + + ftoa.go + + int.go + + intconv.go + + intmarsh.go + + nat.go + + natconv.go + + rat.go + + ratconv.go + + ratmarsh.go + + roundingmode_string.go + + +

    + +
    +
    + + + + +

    Constants

    + +
    const (
    +    MaxExp  = math.MaxInt32  // largest supported exponent
    +    MinExp  = math.MinInt32  // smallest supported exponent
    +    MaxPrec = math.MaxUint32 // largest (theoretically) supported precision; likely memory-limited
    +)
    +

    +Exponent and precision limits. +

    + + +
    const MaxBase = 'z' - 'a' + 10 + 1
    +

    +MaxBase is the largest number base accepted for string conversions. +

    + + + + + + + +

    func Jacobi

    +
    func Jacobi(x, y *Int) int
    +

    +Jacobi returns the Jacobi symbol (x/y), either +1, -1, or 0. +The y argument must be an odd integer. +

    + + + + + + + + +

    type Accuracy

    +
    type Accuracy int8
    +

    +Accuracy describes the rounding error produced by the most recent +operation that generated a Float value, relative to the exact value. +

    + + + +
    const (
    +    Below Accuracy = -1
    +    Exact Accuracy = 0
    +    Above Accuracy = +1
    +)
    +

    +Constants describing the Accuracy of a Float. +

    + + + + + + + + + + + + + +

    func (Accuracy) String

    +
    func (i Accuracy) String() string
    + + + + + + + + +

    type ErrNaN

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

    +An ErrNaN panic is raised by a Float operation that would lead to +a NaN under IEEE-754 rules. An ErrNaN implements the error interface. +

    + + + + + + + + + + + + + + +

    func (ErrNaN) Error

    +
    func (err ErrNaN) Error() string
    + + + + + + + + +

    type Float

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

    +A nonzero finite Float represents a multi-precision floating point number +

    +
    sign × mantissa × 2**exponent
    +
    +

    +with 0.5 <= mantissa < 1.0, and MinExp <= exponent <= MaxExp. +A Float may also be zero (+0, -0) or infinite (+Inf, -Inf). +All Floats are ordered, and the ordering of two Floats x and y +is defined by x.Cmp(y). +

    +

    +Each Float value also has a precision, rounding mode, and accuracy. +The precision is the maximum number of mantissa bits available to +represent the value. The rounding mode specifies how a result should +be rounded to fit into the mantissa bits, and accuracy describes the +rounding error with respect to the exact result. +

    +

    +Unless specified otherwise, all operations (including setters) that +specify a *Float variable for the result (usually via the receiver +with the exception of MantExp), round the numeric result according +to the precision and rounding mode of the result variable. +

    +

    +If the provided result precision is 0 (see below), it is set to the +precision of the argument with the largest precision value before any +rounding takes place, and the rounding mode remains unchanged. Thus, +uninitialized Floats provided as result arguments will have their +precision set to a reasonable value determined by the operands and +their mode is the zero value for RoundingMode (ToNearestEven). +

    +

    +By setting the desired precision to 24 or 53 and using matching rounding +mode (typically ToNearestEven), Float operations produce the same results +as the corresponding float32 or float64 IEEE-754 arithmetic for operands +that correspond to normal (i.e., not denormal) float32 or float64 numbers. +Exponent underflow and overflow lead to a 0 or an Infinity for different +values than IEEE-754 because Float exponents have a much larger range. +

    +

    +The zero (uninitialized) value for a Float is ready to use and represents +the number +0.0 exactly, with precision 0 and rounding mode ToNearestEven. +

    + + + + + + + + + + + + +

    func NewFloat

    +
    func NewFloat(x float64) *Float
    +

    +NewFloat allocates and returns a new Float set to x, +with precision 53 and rounding mode ToNearestEven. +NewFloat panics with ErrNaN if x is a NaN. +

    + + + + + +

    func ParseFloat

    +
    func ParseFloat(s string, base int, prec uint, mode RoundingMode) (f *Float, b int, err error)
    +

    +ParseFloat is like f.Parse(s, base) with f set to the given precision +and rounding mode. +

    + + + + + + + +

    func (*Float) Abs

    +
    func (z *Float) Abs(x *Float) *Float
    +

    +Abs sets z to the (possibly rounded) value |x| (the absolute value of x) +and returns z. +

    + + + + + + +

    func (*Float) Acc

    +
    func (x *Float) Acc() Accuracy
    +

    +Acc returns the accuracy of x produced by the most recent operation. +

    + + + + + + +

    func (*Float) Add

    +
    func (z *Float) Add(x, y *Float) *Float
    +

    +Add sets z to the rounded sum x+y and returns z. If z's precision is 0, +it is changed to the larger of x's or y's precision before the operation. +Rounding is performed according to z's precision and rounding mode; and +z's accuracy reports the result error relative to the exact (not rounded) +result. Add panics with ErrNaN if x and y are infinities with opposite +signs. The value of z is undefined in that case. +

    +

    +BUG(gri) When rounding ToNegativeInf, the sign of Float values rounded to 0 is incorrect. +

    + + +
    + +
    +

    Example

    + + + +

    Code:

    +
    // Operating on numbers of different precision.
    +var x, y, z big.Float
    +x.SetInt64(1000)          // x is automatically set to 64bit precision
    +y.SetFloat64(2.718281828) // y is automatically set to 53bit precision
    +z.SetPrec(32)
    +z.Add(&x, &y)
    +fmt.Printf("x = %.10g (%s, prec = %d, acc = %s)\n", &x, x.Text('p', 0), x.Prec(), x.Acc())
    +fmt.Printf("y = %.10g (%s, prec = %d, acc = %s)\n", &y, y.Text('p', 0), y.Prec(), y.Acc())
    +fmt.Printf("z = %.10g (%s, prec = %d, acc = %s)\n", &z, z.Text('p', 0), z.Prec(), z.Acc())
    +
    + +

    Output:

    +
    x = 1000 (0x.fap+10, prec = 64, acc = Exact)
    +y = 2.718281828 (0x.adf85458248cd8p+2, prec = 53, acc = Exact)
    +z = 1002.718282 (0x.faadf854p+10, prec = 32, acc = Below)
    +
    + + +
    +
    + + + + +

    func (*Float) Append

    +
    func (x *Float) Append(buf []byte, fmt byte, prec int) []byte
    +

    +Append appends to buf the string form of the floating-point number x, +as generated by x.Text, and returns the extended buffer. +

    + + + + + + +

    func (*Float) Cmp

    +
    func (x *Float) Cmp(y *Float) int
    +

    +Cmp compares x and y and returns: +

    +
    -1 if x <  y
    + 0 if x == y (incl. -0 == 0, -Inf == -Inf, and +Inf == +Inf)
    ++1 if x >  y
    +
    + + +
    + +
    +

    Example

    + + + +

    Code:

    +
    inf := math.Inf(1)
    +zero := 0.0
    +
    +operands := []float64{-inf, -1.2, -zero, 0, +1.2, +inf}
    +
    +fmt.Println("   x     y  cmp")
    +fmt.Println("---------------")
    +for _, x64 := range operands {
    +    x := big.NewFloat(x64)
    +    for _, y64 := range operands {
    +        y := big.NewFloat(y64)
    +        fmt.Printf("%4g  %4g  %3d\n", x, y, x.Cmp(y))
    +    }
    +    fmt.Println()
    +}
    +
    +
    + +

    Output:

    +
       x     y  cmp
    +---------------
    +-Inf  -Inf    0
    +-Inf  -1.2   -1
    +-Inf    -0   -1
    +-Inf     0   -1
    +-Inf   1.2   -1
    +-Inf  +Inf   -1
    +
    +-1.2  -Inf    1
    +-1.2  -1.2    0
    +-1.2    -0   -1
    +-1.2     0   -1
    +-1.2   1.2   -1
    +-1.2  +Inf   -1
    +
    +  -0  -Inf    1
    +  -0  -1.2    1
    +  -0    -0    0
    +  -0     0    0
    +  -0   1.2   -1
    +  -0  +Inf   -1
    +
    +   0  -Inf    1
    +   0  -1.2    1
    +   0    -0    0
    +   0     0    0
    +   0   1.2   -1
    +   0  +Inf   -1
    +
    + 1.2  -Inf    1
    + 1.2  -1.2    1
    + 1.2    -0    1
    + 1.2     0    1
    + 1.2   1.2    0
    + 1.2  +Inf   -1
    +
    ++Inf  -Inf    1
    ++Inf  -1.2    1
    ++Inf    -0    1
    ++Inf     0    1
    ++Inf   1.2    1
    ++Inf  +Inf    0
    +
    + + +
    +
    + + + + +

    func (*Float) Copy

    +
    func (z *Float) Copy(x *Float) *Float
    +

    +Copy sets z to x, with the same precision, rounding mode, and +accuracy as x, and returns z. x is not changed even if z and +x are the same. +

    + + + + + + +

    func (*Float) Float32

    +
    func (x *Float) Float32() (float32, Accuracy)
    +

    +Float32 returns the float32 value nearest to x. If x is too small to be +represented by a float32 (|x| < math.SmallestNonzeroFloat32), the result +is (0, Below) or (-0, Above), respectively, depending on the sign of x. +If x is too large to be represented by a float32 (|x| > math.MaxFloat32), +the result is (+Inf, Above) or (-Inf, Below), depending on the sign of x. +

    + + + + + + +

    func (*Float) Float64

    +
    func (x *Float) Float64() (float64, Accuracy)
    +

    +Float64 returns the float64 value nearest to x. If x is too small to be +represented by a float64 (|x| < math.SmallestNonzeroFloat64), the result +is (0, Below) or (-0, Above), respectively, depending on the sign of x. +If x is too large to be represented by a float64 (|x| > math.MaxFloat64), +the result is (+Inf, Above) or (-Inf, Below), depending on the sign of x. +

    + + + + + + +

    func (*Float) Format

    +
    func (x *Float) Format(s fmt.State, format rune)
    +

    +Format implements fmt.Formatter. It accepts all the regular +formats for floating-point numbers ('e', 'E', 'f', 'F', 'g', +'G') as well as 'b', 'p', and 'v'. See (*Float).Text for the +interpretation of 'b' and 'p'. The 'v' format is handled like +'g'. +Format also supports specification of the minimum precision +in digits, the output field width, as well as the format verbs +'+' and ' ' for sign control, '0' for space or zero padding, +and '-' for left or right justification. See the fmt package +for details. +

    + + + + + + +

    func (*Float) Int

    +
    func (x *Float) Int(z *Int) (*Int, Accuracy)
    +

    +Int returns the result of truncating x towards zero; +or nil if x is an infinity. +The result is Exact if x.IsInt(); otherwise it is Below +for x > 0, and Above for x < 0. +If a non-nil *Int argument z is provided, Int stores +the result in z instead of allocating a new Int. +

    + + + + + + +

    func (*Float) Int64

    +
    func (x *Float) Int64() (int64, Accuracy)
    +

    +Int64 returns the integer resulting from truncating x towards zero. +If math.MinInt64 <= x <= math.MaxInt64, the result is Exact if x is +an integer, and Above (x < 0) or Below (x > 0) otherwise. +The result is (math.MinInt64, Above) for x < math.MinInt64, +and (math.MaxInt64, Below) for x > math.MaxInt64. +

    + + + + + + +

    func (*Float) IsInf

    +
    func (x *Float) IsInf() bool
    +

    +IsInf reports whether x is +Inf or -Inf. +

    + + + + + + +

    func (*Float) IsInt

    +
    func (x *Float) IsInt() bool
    +

    +IsInt reports whether x is an integer. +±Inf values are not integers. +

    + + + + + + +

    func (*Float) MantExp

    +
    func (x *Float) MantExp(mant *Float) (exp int)
    +

    +MantExp breaks x into its mantissa and exponent components +and returns the exponent. If a non-nil mant argument is +provided its value is set to the mantissa of x, with the +same precision and rounding mode as x. The components +satisfy x == mant × 2**exp, with 0.5 <= |mant| < 1.0. +Calling MantExp with a nil argument is an efficient way to +get the exponent of the receiver. +

    +

    +Special cases are: +

    +
    (  ±0).MantExp(mant) = 0, with mant set to   ±0
    +(±Inf).MantExp(mant) = 0, with mant set to ±Inf
    +
    +

    +x and mant may be the same in which case x is set to its +mantissa value. +

    + + + + + + +

    func (*Float) MarshalText

    +
    func (x *Float) MarshalText() (text []byte, err error)
    +

    +MarshalText implements the encoding.TextMarshaler interface. +Only the Float value is marshaled (in full precision), other +attributes such as precision or accuracy are ignored. +

    + + + + + + +

    func (*Float) MinPrec

    +
    func (x *Float) MinPrec() uint
    +

    +MinPrec returns the minimum precision required to represent x exactly +(i.e., the smallest prec before x.SetPrec(prec) would start rounding x). +The result is 0 for |x| == 0 and |x| == Inf. +

    + + + + + + +

    func (*Float) Mode

    +
    func (x *Float) Mode() RoundingMode
    +

    +Mode returns the rounding mode of x. +

    + + + + + + +

    func (*Float) Mul

    +
    func (z *Float) Mul(x, y *Float) *Float
    +

    +Mul sets z to the rounded product x*y and returns z. +Precision, rounding, and accuracy reporting are as for Add. +Mul panics with ErrNaN if one operand is zero and the other +operand an infinity. The value of z is undefined in that case. +

    + + + + + + +

    func (*Float) Neg

    +
    func (z *Float) Neg(x *Float) *Float
    +

    +Neg sets z to the (possibly rounded) value of x with its sign negated, +and returns z. +

    + + + + + + +

    func (*Float) Parse

    +
    func (z *Float) Parse(s string, base int) (f *Float, b int, err error)
    +

    +Parse parses s which must contain a text representation of a floating- +point number with a mantissa in the given conversion base (the exponent +is always a decimal number), or a string representing an infinite value. +

    +

    +It sets z to the (possibly rounded) value of the corresponding floating- +point value, and returns z, the actual base b, and an error err, if any. +If z's precision is 0, it is changed to 64 before rounding takes effect. +The number must be of the form: +

    +
    	number   = [ sign ] [ prefix ] mantissa [ exponent ] | infinity .
    +	sign     = "+" | "-" .
    +     prefix   = "0" ( "x" | "X" | "b" | "B" ) .
    +	mantissa = digits | digits "." [ digits ] | "." digits .
    +	exponent = ( "E" | "e" | "p" ) [ sign ] digits .
    +	digits   = digit { digit } .
    +	digit    = "0" ... "9" | "a" ... "z" | "A" ... "Z" .
    +     infinity = [ sign ] ( "inf" | "Inf" ) .
    +
    +

    +The base argument must be 0, 2, 10, or 16. Providing an invalid base +argument will lead to a run-time panic. +

    +

    +For base 0, the number prefix determines the actual base: A prefix of +"0x" or "0X" selects base 16, and a "0b" or "0B" prefix selects +base 2; otherwise, the actual base is 10 and no prefix is accepted. +The octal prefix "0" is not supported (a leading "0" is simply +considered a "0"). +

    +

    +A "p" exponent indicates a binary (rather then decimal) exponent; +for instance "0x1.fffffffffffffp1023" (using base 0) represents the +maximum float64 value. For hexadecimal mantissae, the exponent must +be binary, if present (an "e" or "E" exponent indicator cannot be +distinguished from a mantissa digit). +

    +

    +The returned *Float f is nil and the value of z is valid but not +defined if an error is reported. +

    + + + + + + +

    func (*Float) Prec

    +
    func (x *Float) Prec() uint
    +

    +Prec returns the mantissa precision of x in bits. +The result may be 0 for |x| == 0 and |x| == Inf. +

    + + + + + + +

    func (*Float) Quo

    +
    func (z *Float) Quo(x, y *Float) *Float
    +

    +Quo sets z to the rounded quotient x/y and returns z. +Precision, rounding, and accuracy reporting are as for Add. +Quo panics with ErrNaN if both operands are zero or infinities. +The value of z is undefined in that case. +

    + + + + + + +

    func (*Float) Rat

    +
    func (x *Float) Rat(z *Rat) (*Rat, Accuracy)
    +

    +Rat returns the rational number corresponding to x; +or nil if x is an infinity. +The result is Exact if x is not an Inf. +If a non-nil *Rat argument z is provided, Rat stores +the result in z instead of allocating a new Rat. +

    + + + + + + +

    func (*Float) Set

    +
    func (z *Float) Set(x *Float) *Float
    +

    +Set sets z to the (possibly rounded) value of x and returns z. +If z's precision is 0, it is changed to the precision of x +before setting z (and rounding will have no effect). +Rounding is performed according to z's precision and rounding +mode; and z's accuracy reports the result error relative to the +exact (not rounded) result. +

    + + + + + + +

    func (*Float) SetFloat64

    +
    func (z *Float) SetFloat64(x float64) *Float
    +

    +SetFloat64 sets z to the (possibly rounded) value of x and returns z. +If z's precision is 0, it is changed to 53 (and rounding will have +no effect). SetFloat64 panics with ErrNaN if x is a NaN. +

    + + + + + + +

    func (*Float) SetInf

    +
    func (z *Float) SetInf(signbit bool) *Float
    +

    +SetInf sets z to the infinite Float -Inf if signbit is +set, or +Inf if signbit is not set, and returns z. The +precision of z is unchanged and the result is always +Exact. +

    + + + + + + +

    func (*Float) SetInt

    +
    func (z *Float) SetInt(x *Int) *Float
    +

    +SetInt sets z to the (possibly rounded) value of x and returns z. +If z's precision is 0, it is changed to the larger of x.BitLen() +or 64 (and rounding will have no effect). +

    + + + + + + +

    func (*Float) SetInt64

    +
    func (z *Float) SetInt64(x int64) *Float
    +

    +SetInt64 sets z to the (possibly rounded) value of x and returns z. +If z's precision is 0, it is changed to 64 (and rounding will have +no effect). +

    + + + + + + +

    func (*Float) SetMantExp

    +
    func (z *Float) SetMantExp(mant *Float, exp int) *Float
    +

    +SetMantExp sets z to mant × 2**exp and and returns z. +The result z has the same precision and rounding mode +as mant. SetMantExp is an inverse of MantExp but does +not require 0.5 <= |mant| < 1.0. Specifically: +

    +
    mant := new(Float)
    +new(Float).SetMantExp(mant, x.MantExp(mant)).Cmp(x) == 0
    +
    +

    +Special cases are: +

    +
    z.SetMantExp(  ±0, exp) =   ±0
    +z.SetMantExp(±Inf, exp) = ±Inf
    +
    +

    +z and mant may be the same in which case z's exponent +is set to exp. +

    + + + + + + +

    func (*Float) SetMode

    +
    func (z *Float) SetMode(mode RoundingMode) *Float
    +

    +SetMode sets z's rounding mode to mode and returns an exact z. +z remains unchanged otherwise. +z.SetMode(z.Mode()) is a cheap way to set z's accuracy to Exact. +

    + + + + + + +

    func (*Float) SetPrec

    +
    func (z *Float) SetPrec(prec uint) *Float
    +

    +SetPrec sets z's precision to prec and returns the (possibly) rounded +value of z. Rounding occurs according to z's rounding mode if the mantissa +cannot be represented in prec bits without loss of precision. +SetPrec(0) maps all finite values to ±0; infinite values remain unchanged. +If prec > MaxPrec, it is set to MaxPrec. +

    + + + + + + +

    func (*Float) SetRat

    +
    func (z *Float) SetRat(x *Rat) *Float
    +

    +SetRat sets z to the (possibly rounded) value of x and returns z. +If z's precision is 0, it is changed to the largest of a.BitLen(), +b.BitLen(), or 64; with x = a/b. +

    + + + + + + +

    func (*Float) SetString

    +
    func (z *Float) SetString(s string) (*Float, bool)
    +

    +SetString sets z to the value of s and returns z and a boolean indicating +success. s must be a floating-point number of the same format as accepted +by Parse, with base argument 0. +

    + + + + + + +

    func (*Float) SetUint64

    +
    func (z *Float) SetUint64(x uint64) *Float
    +

    +SetUint64 sets z to the (possibly rounded) value of x and returns z. +If z's precision is 0, it is changed to 64 (and rounding will have +no effect). +

    + + + + + + +

    func (*Float) Sign

    +
    func (x *Float) Sign() int
    +

    +Sign returns: +

    +
    -1 if x <   0
    + 0 if x is ±0
    ++1 if x >   0
    +
    + + + + + + +

    func (*Float) Signbit

    +
    func (x *Float) Signbit() bool
    +

    +Signbit returns true if x is negative or negative zero. +

    + + + + + + +

    func (*Float) String

    +
    func (x *Float) String() string
    +

    +String formats x like x.Text('g', 10). +(String must be called explicitly, Float.Format does not support %s verb.) +

    + + + + + + +

    func (*Float) Sub

    +
    func (z *Float) Sub(x, y *Float) *Float
    +

    +Sub sets z to the rounded difference x-y and returns z. +Precision, rounding, and accuracy reporting are as for Add. +Sub panics with ErrNaN if x and y are infinities with equal +signs. The value of z is undefined in that case. +

    + + + + + + +

    func (*Float) Text

    +
    func (x *Float) Text(format byte, prec int) string
    +

    +Text converts the floating-point number x to a string according +to the given format and precision prec. The format is one of: +

    +
    'e'	-d.dddde±dd, decimal exponent, at least two (possibly 0) exponent digits
    +'E'	-d.ddddE±dd, decimal exponent, at least two (possibly 0) exponent digits
    +'f'	-ddddd.dddd, no exponent
    +'g'	like 'e' for large exponents, like 'f' otherwise
    +'G'	like 'E' for large exponents, like 'f' otherwise
    +'b'	-ddddddp±dd, binary exponent
    +'p'	-0x.dddp±dd, binary exponent, hexadecimal mantissa
    +
    +

    +For the binary exponent formats, the mantissa is printed in normalized form: +

    +
    'b'	decimal integer mantissa using x.Prec() bits, or -0
    +'p'	hexadecimal fraction with 0.5 <= 0.mantissa < 1.0, or -0
    +
    +

    +If format is a different character, Text returns a "%" followed by the +unrecognized format character. +

    +

    +The precision prec controls the number of digits (excluding the exponent) +printed by the 'e', 'E', 'f', 'g', and 'G' formats. For 'e', 'E', and 'f' +it is the number of digits after the decimal point. For 'g' and 'G' it is +the total number of digits. A negative precision selects the smallest +number of decimal digits necessary to identify the value x uniquely using +x.Prec() mantissa bits. +The prec value is ignored for the 'b' or 'p' format. +

    + + + + + + +

    func (*Float) Uint64

    +
    func (x *Float) Uint64() (uint64, Accuracy)
    +

    +Uint64 returns the unsigned integer resulting from truncating x +towards zero. If 0 <= x <= math.MaxUint64, the result is Exact +if x is an integer and Below otherwise. +The result is (0, Above) for x < 0, and (math.MaxUint64, Below) +for x > math.MaxUint64. +

    + + + + + + +

    func (*Float) UnmarshalText

    +
    func (z *Float) UnmarshalText(text []byte) error
    +

    +UnmarshalText implements the encoding.TextUnmarshaler interface. +The result is rounded per the precision and rounding mode of z. +If z's precision is 0, it is changed to 64 before rounding takes +effect. +

    + + + + + + + + +

    type Int

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

    +An Int represents a signed multi-precision integer. +The zero value for an Int represents the value 0. +

    + + + + + + + + + + + + +

    func NewInt

    +
    func NewInt(x int64) *Int
    +

    +NewInt allocates and returns a new Int set to x. +

    + + + + + + + +

    func (*Int) Abs

    +
    func (z *Int) Abs(x *Int) *Int
    +

    +Abs sets z to |x| (the absolute value of x) and returns z. +

    + + + + + + +

    func (*Int) Add

    +
    func (z *Int) Add(x, y *Int) *Int
    +

    +Add sets z to the sum x+y and returns z. +

    + + + + + + +

    func (*Int) And

    +
    func (z *Int) And(x, y *Int) *Int
    +

    +And sets z = x & y and returns z. +

    + + + + + + +

    func (*Int) AndNot

    +
    func (z *Int) AndNot(x, y *Int) *Int
    +

    +AndNot sets z = x &^ y and returns z. +

    + + + + + + +

    func (*Int) Append

    +
    func (x *Int) Append(buf []byte, base int) []byte
    +

    +Append appends the string representation of x, as generated by +x.Text(base), to buf and returns the extended buffer. +

    + + + + + + +

    func (*Int) Binomial

    +
    func (z *Int) Binomial(n, k int64) *Int
    +

    +Binomial sets z to the binomial coefficient of (n, k) and returns z. +

    + + + + + + +

    func (*Int) Bit

    +
    func (x *Int) Bit(i int) uint
    +

    +Bit returns the value of the i'th bit of x. That is, it +returns (x>>i)&1. The bit index i must be >= 0. +

    + + + + + + +

    func (*Int) BitLen

    +
    func (x *Int) BitLen() int
    +

    +BitLen returns the length of the absolute value of x in bits. +The bit length of 0 is 0. +

    + + + + + + +

    func (*Int) Bits

    +
    func (x *Int) Bits() []Word
    +

    +Bits provides raw (unchecked but fast) access to x by returning its +absolute value as a little-endian Word slice. The result and x share +the same underlying array. +Bits is intended to support implementation of missing low-level Int +functionality outside this package; it should be avoided otherwise. +

    + + + + + + +

    func (*Int) Bytes

    +
    func (x *Int) Bytes() []byte
    +

    +Bytes returns the absolute value of x as a big-endian byte slice. +

    + + + + + + +

    func (*Int) Cmp

    +
    func (x *Int) Cmp(y *Int) (r int)
    +

    +Cmp compares x and y and returns: +

    +
    -1 if x <  y
    + 0 if x == y
    ++1 if x >  y
    +
    + + + + + + +

    func (*Int) Div

    +
    func (z *Int) Div(x, y *Int) *Int
    +

    +Div sets z to the quotient x/y for y != 0 and returns z. +If y == 0, a division-by-zero run-time panic occurs. +Div implements Euclidean division (unlike Go); see DivMod for more details. +

    + + + + + + +

    func (*Int) DivMod

    +
    func (z *Int) DivMod(x, y, m *Int) (*Int, *Int)
    +

    +DivMod sets z to the quotient x div y and m to the modulus x mod y +and returns the pair (z, m) for y != 0. +If y == 0, a division-by-zero run-time panic occurs. +

    +

    +DivMod implements Euclidean division and modulus (unlike Go): +

    +
    q = x div y  such that
    +m = x - y*q  with 0 <= m < |y|
    +
    +

    +(See Raymond T. Boute, “The Euclidean definition of the functions +div and mod”. ACM Transactions on Programming Languages and +Systems (TOPLAS), 14(2):127-144, New York, NY, USA, 4/1992. +ACM press.) +See QuoRem for T-division and modulus (like Go). +

    + + + + + + +

    func (*Int) Exp

    +
    func (z *Int) Exp(x, y, m *Int) *Int
    +

    +Exp sets z = x**y mod |m| (i.e. the sign of m is ignored), and returns z. +If y <= 0, the result is 1 mod |m|; if m == nil or m == 0, z = x**y. +See Knuth, volume 2, section 4.6.3. +

    + + + + + + +

    func (*Int) Format

    +
    func (x *Int) Format(s fmt.State, ch rune)
    +

    +Format is a support routine for fmt.Formatter. It accepts +the formats 'b' (binary), 'o' (octal), 'd' (decimal), 'x' +(lowercase hexadecimal), and 'X' (uppercase hexadecimal). +Also supported are the full suite of package fmt's format +verbs for integral types, including '+', '-', and ' ' +for sign control, '#' for leading zero in octal and for +hexadecimal, a leading "0x" or "0X" for "%#x" and "%#X" +respectively, specification of minimum digits precision, +output field width, space or zero padding, and left or +right justification. +

    + + + + + + +

    func (*Int) GCD

    +
    func (z *Int) GCD(x, y, a, b *Int) *Int
    +

    +GCD sets z to the greatest common divisor of a and b, which both must +be > 0, and returns z. +If x and y are not nil, GCD sets x and y such that z = a*x + b*y. +If either a or b is <= 0, GCD sets z = x = y = 0. +

    + + + + + + +

    func (*Int) GobDecode

    +
    func (z *Int) GobDecode(buf []byte) error
    +

    +GobDecode implements the gob.GobDecoder interface. +

    + + + + + + +

    func (*Int) GobEncode

    +
    func (x *Int) GobEncode() ([]byte, error)
    +

    +GobEncode implements the gob.GobEncoder interface. +

    + + + + + + +

    func (*Int) Int64

    +
    func (x *Int) Int64() int64
    +

    +Int64 returns the int64 representation of x. +If x cannot be represented in an int64, the result is undefined. +

    + + + + + + +

    func (*Int) Lsh

    +
    func (z *Int) Lsh(x *Int, n uint) *Int
    +

    +Lsh sets z = x << n and returns z. +

    + + + + + + +

    func (*Int) MarshalJSON

    +
    func (x *Int) MarshalJSON() ([]byte, error)
    +

    +MarshalJSON implements the json.Marshaler interface. +

    + + + + + + +

    func (*Int) MarshalText

    +
    func (x *Int) MarshalText() (text []byte, err error)
    +

    +MarshalText implements the encoding.TextMarshaler interface. +

    + + + + + + +

    func (*Int) Mod

    +
    func (z *Int) Mod(x, y *Int) *Int
    +

    +Mod sets z to the modulus x%y for y != 0 and returns z. +If y == 0, a division-by-zero run-time panic occurs. +Mod implements Euclidean modulus (unlike Go); see DivMod for more details. +

    + + + + + + +

    func (*Int) ModInverse

    +
    func (z *Int) ModInverse(g, n *Int) *Int
    +

    +ModInverse sets z to the multiplicative inverse of g in the ring ℤ/nℤ +and returns z. If g and n are not relatively prime, the result is undefined. +

    + + + + + + +

    func (*Int) ModSqrt

    +
    func (z *Int) ModSqrt(x, p *Int) *Int
    +

    +ModSqrt sets z to a square root of x mod p if such a square root exists, and +returns z. The modulus p must be an odd prime. If x is not a square mod p, +ModSqrt leaves z unchanged and returns nil. This function panics if p is +not an odd integer. +

    + + + + + + +

    func (*Int) Mul

    +
    func (z *Int) Mul(x, y *Int) *Int
    +

    +Mul sets z to the product x*y and returns z. +

    + + + + + + +

    func (*Int) MulRange

    +
    func (z *Int) MulRange(a, b int64) *Int
    +

    +MulRange sets z to the product of all integers +in the range [a, b] inclusively and returns z. +If a > b (empty range), the result is 1. +

    + + + + + + +

    func (*Int) Neg

    +
    func (z *Int) Neg(x *Int) *Int
    +

    +Neg sets z to -x and returns z. +

    + + + + + + +

    func (*Int) Not

    +
    func (z *Int) Not(x *Int) *Int
    +

    +Not sets z = ^x and returns z. +

    + + + + + + +

    func (*Int) Or

    +
    func (z *Int) Or(x, y *Int) *Int
    +

    +Or sets z = x | y and returns z. +

    + + + + + + +

    func (*Int) ProbablyPrime

    +
    func (x *Int) ProbablyPrime(n int) bool
    +

    +ProbablyPrime performs n Miller-Rabin tests to check whether x is prime. +If x is prime, it returns true. +If x is not prime, it returns false with probability at least 1 - ¼ⁿ. +

    +

    +It is not suitable for judging primes that an adversary may have crafted +to fool this test. +

    + + + + + + +

    func (*Int) Quo

    +
    func (z *Int) Quo(x, y *Int) *Int
    +

    +Quo sets z to the quotient x/y for y != 0 and returns z. +If y == 0, a division-by-zero run-time panic occurs. +Quo implements truncated division (like Go); see QuoRem for more details. +

    + + + + + + +

    func (*Int) QuoRem

    +
    func (z *Int) QuoRem(x, y, r *Int) (*Int, *Int)
    +

    +QuoRem sets z to the quotient x/y and r to the remainder x%y +and returns the pair (z, r) for y != 0. +If y == 0, a division-by-zero run-time panic occurs. +

    +

    +QuoRem implements T-division and modulus (like Go): +

    +
    q = x/y      with the result truncated to zero
    +r = x - y*q
    +
    +

    +(See Daan Leijen, “Division and Modulus for Computer Scientists”.) +See DivMod for Euclidean division and modulus (unlike Go). +

    + + + + + + +

    func (*Int) Rand

    +
    func (z *Int) Rand(rnd *rand.Rand, n *Int) *Int
    +

    +Rand sets z to a pseudo-random number in [0, n) and returns z. +

    + + + + + + +

    func (*Int) Rem

    +
    func (z *Int) Rem(x, y *Int) *Int
    +

    +Rem sets z to the remainder x%y for y != 0 and returns z. +If y == 0, a division-by-zero run-time panic occurs. +Rem implements truncated modulus (like Go); see QuoRem for more details. +

    + + + + + + +

    func (*Int) Rsh

    +
    func (z *Int) Rsh(x *Int, n uint) *Int
    +

    +Rsh sets z = x >> n and returns z. +

    + + + + + + +

    func (*Int) Scan

    +
    func (z *Int) Scan(s fmt.ScanState, ch rune) error
    +

    +Scan is a support routine for fmt.Scanner; it sets z to the value of +the scanned number. It accepts the formats 'b' (binary), 'o' (octal), +'d' (decimal), 'x' (lowercase hexadecimal), and 'X' (uppercase hexadecimal). +

    + + +
    + +
    +

    Example

    + + + +

    Code:

    +
    // The Scan function is rarely used directly;
    +// the fmt package recognizes it as an implementation of fmt.Scanner.
    +i := new(big.Int)
    +_, err := fmt.Sscan("18446744073709551617", i)
    +if err != nil {
    +    log.Println("error scanning value:", err)
    +} else {
    +    fmt.Println(i)
    +}
    +
    + +

    Output:

    +
    18446744073709551617
    +
    + + +
    +
    + + + + +

    func (*Int) Set

    +
    func (z *Int) Set(x *Int) *Int
    +

    +Set sets z to x and returns z. +

    + + + + + + +

    func (*Int) SetBit

    +
    func (z *Int) SetBit(x *Int, i int, b uint) *Int
    +

    +SetBit sets z to x, with x's i'th bit set to b (0 or 1). +That is, if b is 1 SetBit sets z = x | (1 << i); +if b is 0 SetBit sets z = x &^ (1 << i). If b is not 0 or 1, +SetBit will panic. +

    + + + + + + +

    func (*Int) SetBits

    +
    func (z *Int) SetBits(abs []Word) *Int
    +

    +SetBits provides raw (unchecked but fast) access to z by setting its +value to abs, interpreted as a little-endian Word slice, and returning +z. The result and abs share the same underlying array. +SetBits is intended to support implementation of missing low-level Int +functionality outside this package; it should be avoided otherwise. +

    + + + + + + +

    func (*Int) SetBytes

    +
    func (z *Int) SetBytes(buf []byte) *Int
    +

    +SetBytes interprets buf as the bytes of a big-endian unsigned +integer, sets z to that value, and returns z. +

    + + + + + + +

    func (*Int) SetInt64

    +
    func (z *Int) SetInt64(x int64) *Int
    +

    +SetInt64 sets z to x and returns z. +

    + + + + + + +

    func (*Int) SetString

    +
    func (z *Int) SetString(s string, base int) (*Int, bool)
    +

    +SetString sets z to the value of s, interpreted in the given base, +and returns z and a boolean indicating success. If SetString fails, +the value of z is undefined but the returned value is nil. +

    +

    +The base argument must be 0 or a value between 2 and MaxBase. If the base +is 0, the string prefix determines the actual conversion base. A prefix of +“0x” or “0X” selects base 16; the “0” prefix selects base 8, and a +“0b” or “0B” prefix selects base 2. Otherwise the selected base is 10. +

    + + +
    + +
    +

    Example

    + + + +

    Code:

    +
    i := new(big.Int)
    +i.SetString("644", 8) // octal
    +fmt.Println(i)
    +
    + +

    Output:

    +
    420
    +
    + + +
    +
    + + + + +

    func (*Int) SetUint64

    +
    func (z *Int) SetUint64(x uint64) *Int
    +

    +SetUint64 sets z to x and returns z. +

    + + + + + + +

    func (*Int) Sign

    +
    func (x *Int) Sign() int
    +

    +Sign returns: +

    +
    -1 if x <  0
    + 0 if x == 0
    ++1 if x >  0
    +
    + + + + + + +

    func (*Int) String

    +
    func (x *Int) String() string
    + + + + + + +

    func (*Int) Sub

    +
    func (z *Int) Sub(x, y *Int) *Int
    +

    +Sub sets z to the difference x-y and returns z. +

    + + + + + + +

    func (*Int) Text

    +
    func (x *Int) Text(base int) string
    +

    +Text returns the string representation of x in the given base. +Base must be between 2 and 36, inclusive. The result uses the +lower-case letters 'a' to 'z' for digit values >= 10. No base +prefix (such as "0x") is added to the string. +

    + + + + + + +

    func (*Int) Uint64

    +
    func (x *Int) Uint64() uint64
    +

    +Uint64 returns the uint64 representation of x. +If x cannot be represented in a uint64, the result is undefined. +

    + + + + + + +

    func (*Int) UnmarshalJSON

    +
    func (z *Int) UnmarshalJSON(text []byte) error
    +

    +UnmarshalJSON implements the json.Unmarshaler interface. +

    + + + + + + +

    func (*Int) UnmarshalText

    +
    func (z *Int) UnmarshalText(text []byte) error
    +

    +UnmarshalText implements the encoding.TextUnmarshaler interface. +

    + + + + + + +

    func (*Int) Xor

    +
    func (z *Int) Xor(x, y *Int) *Int
    +

    +Xor sets z = x ^ y and returns z. +

    + + + + + + + + +

    type Rat

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

    +A Rat represents a quotient a/b of arbitrary precision. +The zero value for a Rat represents the value 0. +

    + + + + + + + + + + + + +

    func NewRat

    +
    func NewRat(a, b int64) *Rat
    +

    +NewRat creates a new Rat with numerator a and denominator b. +

    + + + + + + + +

    func (*Rat) Abs

    +
    func (z *Rat) Abs(x *Rat) *Rat
    +

    +Abs sets z to |x| (the absolute value of x) and returns z. +

    + + + + + + +

    func (*Rat) Add

    +
    func (z *Rat) Add(x, y *Rat) *Rat
    +

    +Add sets z to the sum x+y and returns z. +

    + + + + + + +

    func (*Rat) Cmp

    +
    func (x *Rat) Cmp(y *Rat) int
    +

    +Cmp compares x and y and returns: +

    +
    -1 if x <  y
    + 0 if x == y
    ++1 if x >  y
    +
    + + + + + + +

    func (*Rat) Denom

    +
    func (x *Rat) Denom() *Int
    +

    +Denom returns the denominator of x; it is always > 0. +The result is a reference to x's denominator; it +may change if a new value is assigned to x, and vice versa. +

    + + + + + + +

    func (*Rat) Float32

    +
    func (x *Rat) Float32() (f float32, exact bool)
    +

    +Float32 returns the nearest float32 value for x and a bool indicating +whether f represents x exactly. If the magnitude of x is too large to +be represented by a float32, f is an infinity and exact is false. +The sign of f always matches the sign of x, even if f == 0. +

    + + + + + + +

    func (*Rat) Float64

    +
    func (x *Rat) Float64() (f float64, exact bool)
    +

    +Float64 returns the nearest float64 value for x and a bool indicating +whether f represents x exactly. If the magnitude of x is too large to +be represented by a float64, f is an infinity and exact is false. +The sign of f always matches the sign of x, even if f == 0. +

    + + + + + + +

    func (*Rat) FloatString

    +
    func (x *Rat) FloatString(prec int) string
    +

    +FloatString returns a string representation of x in decimal form with prec +digits of precision after the decimal point. The last digit is rounded to +nearest, with halves rounded away from zero. +

    + + + + + + +

    func (*Rat) GobDecode

    +
    func (z *Rat) GobDecode(buf []byte) error
    +

    +GobDecode implements the gob.GobDecoder interface. +

    + + + + + + +

    func (*Rat) GobEncode

    +
    func (x *Rat) GobEncode() ([]byte, error)
    +

    +GobEncode implements the gob.GobEncoder interface. +

    + + + + + + +

    func (*Rat) Inv

    +
    func (z *Rat) Inv(x *Rat) *Rat
    +

    +Inv sets z to 1/x and returns z. +

    + + + + + + +

    func (*Rat) IsInt

    +
    func (x *Rat) IsInt() bool
    +

    +IsInt reports whether the denominator of x is 1. +

    + + + + + + +

    func (*Rat) MarshalText

    +
    func (x *Rat) MarshalText() (text []byte, err error)
    +

    +MarshalText implements the encoding.TextMarshaler interface. +

    + + + + + + +

    func (*Rat) Mul

    +
    func (z *Rat) Mul(x, y *Rat) *Rat
    +

    +Mul sets z to the product x*y and returns z. +

    + + + + + + +

    func (*Rat) Neg

    +
    func (z *Rat) Neg(x *Rat) *Rat
    +

    +Neg sets z to -x and returns z. +

    + + + + + + +

    func (*Rat) Num

    +
    func (x *Rat) Num() *Int
    +

    +Num returns the numerator of x; it may be <= 0. +The result is a reference to x's numerator; it +may change if a new value is assigned to x, and vice versa. +The sign of the numerator corresponds to the sign of x. +

    + + + + + + +

    func (*Rat) Quo

    +
    func (z *Rat) Quo(x, y *Rat) *Rat
    +

    +Quo sets z to the quotient x/y and returns z. +If y == 0, a division-by-zero run-time panic occurs. +

    + + + + + + +

    func (*Rat) RatString

    +
    func (x *Rat) RatString() string
    +

    +RatString returns a string representation of x in the form "a/b" if b != 1, +and in the form "a" if b == 1. +

    + + + + + + +

    func (*Rat) Scan

    +
    func (z *Rat) Scan(s fmt.ScanState, ch rune) error
    +

    +Scan is a support routine for fmt.Scanner. It accepts the formats +'e', 'E', 'f', 'F', 'g', 'G', and 'v'. All formats are equivalent. +

    + + +
    + +
    +

    Example

    + + + +

    Code:

    +
    // The Scan function is rarely used directly;
    +// the fmt package recognizes it as an implementation of fmt.Scanner.
    +r := new(big.Rat)
    +_, err := fmt.Sscan("1.5000", r)
    +if err != nil {
    +    log.Println("error scanning value:", err)
    +} else {
    +    fmt.Println(r)
    +}
    +
    + +

    Output:

    +
    3/2
    +
    + + +
    +
    + + + + +

    func (*Rat) Set

    +
    func (z *Rat) Set(x *Rat) *Rat
    +

    +Set sets z to x (by making a copy of x) and returns z. +

    + + + + + + +

    func (*Rat) SetFloat64

    +
    func (z *Rat) SetFloat64(f float64) *Rat
    +

    +SetFloat64 sets z to exactly f and returns z. +If f is not finite, SetFloat returns nil. +

    + + + + + + +

    func (*Rat) SetFrac

    +
    func (z *Rat) SetFrac(a, b *Int) *Rat
    +

    +SetFrac sets z to a/b and returns z. +

    + + + + + + +

    func (*Rat) SetFrac64

    +
    func (z *Rat) SetFrac64(a, b int64) *Rat
    +

    +SetFrac64 sets z to a/b and returns z. +

    + + + + + + +

    func (*Rat) SetInt

    +
    func (z *Rat) SetInt(x *Int) *Rat
    +

    +SetInt sets z to x (by making a copy of x) and returns z. +

    + + + + + + +

    func (*Rat) SetInt64

    +
    func (z *Rat) SetInt64(x int64) *Rat
    +

    +SetInt64 sets z to x and returns z. +

    + + + + + + +

    func (*Rat) SetString

    +
    func (z *Rat) SetString(s string) (*Rat, bool)
    +

    +SetString sets z to the value of s and returns z and a boolean indicating +success. s can be given as a fraction "a/b" or as a floating-point number +optionally followed by an exponent. If the operation failed, the value of +z is undefined but the returned value is nil. +

    + + +
    + +
    +

    Example

    + + + +

    Code:

    +
    r := new(big.Rat)
    +r.SetString("355/113")
    +fmt.Println(r.FloatString(3))
    +
    + +

    Output:

    +
    3.142
    +
    + + +
    +
    + + + + +

    func (*Rat) Sign

    +
    func (x *Rat) Sign() int
    +

    +Sign returns: +

    +
    -1 if x <  0
    + 0 if x == 0
    ++1 if x >  0
    +
    + + + + + + +

    func (*Rat) String

    +
    func (x *Rat) String() string
    +

    +String returns a string representation of x in the form "a/b" (even if b == 1). +

    + + + + + + +

    func (*Rat) Sub

    +
    func (z *Rat) Sub(x, y *Rat) *Rat
    +

    +Sub sets z to the difference x-y and returns z. +

    + + + + + + +

    func (*Rat) UnmarshalText

    +
    func (z *Rat) UnmarshalText(text []byte) error
    +

    +UnmarshalText implements the encoding.TextUnmarshaler interface. +

    + + + + + + + + +

    type RoundingMode

    +
    type RoundingMode byte
    +

    +RoundingMode determines how a Float value is rounded to the +desired precision. Rounding may change the Float value; the +rounding error is described by the Float's Accuracy. +

    + + + +
    const (
    +    ToNearestEven RoundingMode = iota // == IEEE 754-2008 roundTiesToEven
    +    ToNearestAway                     // == IEEE 754-2008 roundTiesToAway
    +    ToZero                            // == IEEE 754-2008 roundTowardZero
    +    AwayFromZero                      // no IEEE 754-2008 equivalent
    +    ToNegativeInf                     // == IEEE 754-2008 roundTowardNegative
    +    ToPositiveInf                     // == IEEE 754-2008 roundTowardPositive
    +)
    +

    +These constants define supported rounding modes. +

    + + + + + +
    + +
    +

    Example

    + + + +

    Code:

    +
    operands := []float64{2.6, 2.5, 2.1, -2.1, -2.5, -2.6}
    +
    +fmt.Print("   x")
    +for mode := big.ToNearestEven; mode <= big.ToPositiveInf; mode++ {
    +    fmt.Printf("  %s", mode)
    +}
    +fmt.Println()
    +
    +for _, f64 := range operands {
    +    fmt.Printf("%4g", f64)
    +    for mode := big.ToNearestEven; mode <= big.ToPositiveInf; mode++ {
    +        // sample operands above require 2 bits to represent mantissa
    +        // set binary precision to 2 to round them to integer values
    +        f := new(big.Float).SetPrec(2).SetMode(mode).SetFloat64(f64)
    +        fmt.Printf("  %*g", len(mode.String()), f)
    +    }
    +    fmt.Println()
    +}
    +
    +
    + +

    Output:

    +
       x  ToNearestEven  ToNearestAway  ToZero  AwayFromZero  ToNegativeInf  ToPositiveInf
    + 2.6              3              3       2             3              2              3
    + 2.5              2              3       2             3              2              3
    + 2.1              2              2       2             3              2              3
    +-2.1             -2             -2      -2            -3             -3             -2
    +-2.5             -2             -3      -2            -3             -3             -2
    +-2.6             -3             -3      -2            -3             -3             -2
    +
    + + +
    +
    + + + + + + + + +

    func (RoundingMode) String

    +
    func (i RoundingMode) String() string
    + + + + + + + + +

    type Word

    +
    type Word uintptr
    +

    +A Word represents a single digit of a multi-precision unsigned integer. +

    + + + + + + + + + + + + + + + + + + +

    Bugs

    +
      + +
    • When rounding ToNegativeInf, the sign of Float values rounded to 0 is incorrect. +
    • + +
    + + + + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/math/cmplx/index.html b/pkg/math/cmplx/index.html new file mode 100644 index 0000000..669f8a7 --- /dev/null +++ b/pkg/math/cmplx/index.html @@ -0,0 +1,646 @@ + + + + + + + + cmplx - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Package cmplx

    + + + + + + + + + + + + + + +
    +
    +
    import "math/cmplx"
    +
    +
    +
    Overview
    +
    Index
    + + +
    +
    + +
    + +
    +

    Overview ▾

    +

    +Package cmplx provides basic constants and mathematical functions for +complex numbers. +

    + +
    +
    + + + + + + + + + + + +

    func Abs

    +
    func Abs(x complex128) float64
    +

    +Abs returns the absolute value (also called the modulus) of x. +

    + + + + + + + +

    func Acos

    +
    func Acos(x complex128) complex128
    +

    +Acos returns the inverse cosine of x. +

    + + + + + + + +

    func Acosh

    +
    func Acosh(x complex128) complex128
    +

    +Acosh returns the inverse hyperbolic cosine of x. +

    + + + + + + + +

    func Asin

    +
    func Asin(x complex128) complex128
    +

    +Asin returns the inverse sine of x. +

    + + + + + + + +

    func Asinh

    +
    func Asinh(x complex128) complex128
    +

    +Asinh returns the inverse hyperbolic sine of x. +

    + + + + + + + +

    func Atan

    +
    func Atan(x complex128) complex128
    +

    +Atan returns the inverse tangent of x. +

    + + + + + + + +

    func Atanh

    +
    func Atanh(x complex128) complex128
    +

    +Atanh returns the inverse hyperbolic tangent of x. +

    + + + + + + + +

    func Conj

    +
    func Conj(x complex128) complex128
    +

    +Conj returns the complex conjugate of x. +

    + + + + + + + +

    func Cos

    +
    func Cos(x complex128) complex128
    +

    +Cos returns the cosine of x. +

    + + + + + + + +

    func Cosh

    +
    func Cosh(x complex128) complex128
    +

    +Cosh returns the hyperbolic cosine of x. +

    + + + + + + + +

    func Cot

    +
    func Cot(x complex128) complex128
    +

    +Cot returns the cotangent of x. +

    + + + + + + + +

    func Exp

    +
    func Exp(x complex128) complex128
    +

    +Exp returns e**x, the base-e exponential of x. +

    + + + + + + + +

    func Inf

    +
    func Inf() complex128
    +

    +Inf returns a complex infinity, complex(+Inf, +Inf). +

    + + + + + + + +

    func IsInf

    +
    func IsInf(x complex128) bool
    +

    +IsInf returns true if either real(x) or imag(x) is an infinity. +

    + + + + + + + +

    func IsNaN

    +
    func IsNaN(x complex128) bool
    +

    +IsNaN returns true if either real(x) or imag(x) is NaN +and neither is an infinity. +

    + + + + + + + +

    func Log

    +
    func Log(x complex128) complex128
    +

    +Log returns the natural logarithm of x. +

    + + + + + + + +

    func Log10

    +
    func Log10(x complex128) complex128
    +

    +Log10 returns the decimal logarithm of x. +

    + + + + + + + +

    func NaN

    +
    func NaN() complex128
    +

    +NaN returns a complex “not-a-number” value. +

    + + + + + + + +

    func Phase

    +
    func Phase(x complex128) float64
    +

    +Phase returns the phase (also called the argument) of x. +The returned value is in the range [-Pi, Pi]. +

    + + + + + + + +

    func Polar

    +
    func Polar(x complex128) (r, θ float64)
    +

    +Polar returns the absolute value r and phase θ of x, +such that x = r * e**θi. +The phase is in the range [-Pi, Pi]. +

    + + + + + + + +

    func Pow

    +
    func Pow(x, y complex128) complex128
    +

    +Pow returns x**y, the base-x exponential of y. +For generalized compatibility with math.Pow: +

    +
    Pow(0, ±0) returns 1+0i
    +Pow(0, c) for real(c)<0 returns Inf+0i if imag(c) is zero, otherwise Inf+Inf i.
    +
    + + + + + + + +

    func Rect

    +
    func Rect(r, θ float64) complex128
    +

    +Rect returns the complex number x with polar coordinates r, θ. +

    + + + + + + + +

    func Sin

    +
    func Sin(x complex128) complex128
    +

    +Sin returns the sine of x. +

    + + + + + + + +

    func Sinh

    +
    func Sinh(x complex128) complex128
    +

    +Sinh returns the hyperbolic sine of x. +

    + + + + + + + +

    func Sqrt

    +
    func Sqrt(x complex128) complex128
    +

    +Sqrt returns the square root of x. +The result r is chosen so that real(r) ≥ 0 and imag(r) has the same sign as imag(x). +

    + + + + + + + +

    func Tan

    +
    func Tan(x complex128) complex128
    +

    +Tan returns the tangent of x. +

    + + + + + + + +

    func Tanh

    +
    func Tanh(x complex128) complex128
    +

    +Tanh returns the hyperbolic tangent of x. +

    + + + + + + + + + + + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/math/index.html b/pkg/math/index.html new file mode 100644 index 0000000..a1cda04 --- /dev/null +++ b/pkg/math/index.html @@ -0,0 +1,1753 @@ + + + + + + + + math - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Package math

    + + + + + + + + + + + + + + +
    +
    +
    import "math"
    +
    +
    +
    Overview
    +
    Index
    + + +
    Subdirectories
    + +
    +
    + +
    + +
    +

    Overview ▾

    +

    +Package math provides basic constants and mathematical functions. +

    + +
    +
    + + +
    + +
    +

    Index ▾

    + + +
    +
    + +
    Constants
    + + + + +
    func Abs(x float64) float64
    + + +
    func Acos(x float64) float64
    + + +
    func Acosh(x float64) float64
    + + +
    func Asin(x float64) float64
    + + +
    func Asinh(x float64) float64
    + + +
    func Atan(x float64) float64
    + + +
    func Atan2(y, x float64) float64
    + + +
    func Atanh(x float64) float64
    + + +
    func Cbrt(x float64) float64
    + + +
    func Ceil(x float64) float64
    + + +
    func Copysign(x, y float64) float64
    + + +
    func Cos(x float64) float64
    + + +
    func Cosh(x float64) float64
    + + +
    func Dim(x, y float64) float64
    + + +
    func Erf(x float64) float64
    + + +
    func Erfc(x float64) float64
    + + +
    func Exp(x float64) float64
    + + +
    func Exp2(x float64) float64
    + + +
    func Expm1(x float64) float64
    + + +
    func Float32bits(f float32) uint32
    + + +
    func Float32frombits(b uint32) float32
    + + +
    func Float64bits(f float64) uint64
    + + +
    func Float64frombits(b uint64) float64
    + + +
    func Floor(x float64) float64
    + + +
    func Frexp(f float64) (frac float64, exp int)
    + + +
    func Gamma(x float64) float64
    + + +
    func Hypot(p, q float64) float64
    + + +
    func Ilogb(x float64) int
    + + +
    func Inf(sign int) float64
    + + +
    func IsInf(f float64, sign int) bool
    + + +
    func IsNaN(f float64) (is bool)
    + + +
    func J0(x float64) float64
    + + +
    func J1(x float64) float64
    + + +
    func Jn(n int, x float64) float64
    + + +
    func Ldexp(frac float64, exp int) float64
    + + +
    func Lgamma(x float64) (lgamma float64, sign int)
    + + +
    func Log(x float64) float64
    + + +
    func Log10(x float64) float64
    + + +
    func Log1p(x float64) float64
    + + +
    func Log2(x float64) float64
    + + +
    func Logb(x float64) float64
    + + +
    func Max(x, y float64) float64
    + + +
    func Min(x, y float64) float64
    + + +
    func Mod(x, y float64) float64
    + + +
    func Modf(f float64) (int float64, frac float64)
    + + +
    func NaN() float64
    + + +
    func Nextafter(x, y float64) (r float64)
    + + +
    func Nextafter32(x, y float32) (r float32)
    + + +
    func Pow(x, y float64) float64
    + + +
    func Pow10(e int) float64
    + + +
    func Remainder(x, y float64) float64
    + + +
    func Signbit(x float64) bool
    + + +
    func Sin(x float64) float64
    + + +
    func Sincos(x float64) (sin, cos float64)
    + + +
    func Sinh(x float64) float64
    + + +
    func Sqrt(x float64) float64
    + + +
    func Tan(x float64) float64
    + + +
    func Tanh(x float64) float64
    + + +
    func Trunc(x float64) float64
    + + +
    func Y0(x float64) float64
    + + +
    func Y1(x float64) float64
    + + +
    func Yn(n int, x float64) float64
    + + + +
    +
    + + + + +

    Package files

    +

    + + + abs.go + + acosh.go + + asin.go + + asinh.go + + atan.go + + atan2.go + + atanh.go + + bits.go + + cbrt.go + + const.go + + copysign.go + + dim.go + + erf.go + + exp.go + + expm1.go + + floor.go + + floor_asm.go + + frexp.go + + gamma.go + + hypot.go + + j0.go + + j1.go + + jn.go + + ldexp.go + + lgamma.go + + log.go + + log10.go + + log1p.go + + logb.go + + mod.go + + modf.go + + nextafter.go + + pow.go + + pow10.go + + remainder.go + + signbit.go + + sin.go + + sincos.go + + sinh.go + + sqrt.go + + tan.go + + tanh.go + + unsafe.go + + +

    + +
    +
    + + + + +

    Constants

    + +
    const (
    +    E   = 2.71828182845904523536028747135266249775724709369995957496696763 // http://oeis.org/A001113
    +    Pi  = 3.14159265358979323846264338327950288419716939937510582097494459 // http://oeis.org/A000796
    +    Phi = 1.61803398874989484820458683436563811772030917980576286213544862 // http://oeis.org/A001622
    +
    +    Sqrt2   = 1.41421356237309504880168872420969807856967187537694807317667974 // http://oeis.org/A002193
    +    SqrtE   = 1.64872127070012814684865078781416357165377610071014801157507931 // http://oeis.org/A019774
    +    SqrtPi  = 1.77245385090551602729816748334114518279754945612238712821380779 // http://oeis.org/A002161
    +    SqrtPhi = 1.27201964951406896425242246173749149171560804184009624861664038 // http://oeis.org/A139339
    +
    +    Ln2    = 0.693147180559945309417232121458176568075500134360255254120680009 // http://oeis.org/A002162
    +    Log2E  = 1 / Ln2
    +    Ln10   = 2.30258509299404568401799145468436420760110148862877297603332790 // http://oeis.org/A002392
    +    Log10E = 1 / Ln10
    +)
    +

    +Mathematical constants. +

    + + +
    const (
    +    MaxFloat32             = 3.40282346638528859811704183484516925440e+38  // 2**127 * (2**24 - 1) / 2**23
    +    SmallestNonzeroFloat32 = 1.401298464324817070923729583289916131280e-45 // 1 / 2**(127 - 1 + 23)
    +
    +    MaxFloat64             = 1.797693134862315708145274237317043567981e+308 // 2**1023 * (2**53 - 1) / 2**52
    +    SmallestNonzeroFloat64 = 4.940656458412465441765687928682213723651e-324 // 1 / 2**(1023 - 1 + 52)
    +)
    +

    +Floating-point limit values. +Max is the largest finite value representable by the type. +SmallestNonzero is the smallest positive, non-zero value representable by the type. +

    + + +
    const (
    +    MaxInt8   = 1<<7 - 1
    +    MinInt8   = -1 << 7
    +    MaxInt16  = 1<<15 - 1
    +    MinInt16  = -1 << 15
    +    MaxInt32  = 1<<31 - 1
    +    MinInt32  = -1 << 31
    +    MaxInt64  = 1<<63 - 1
    +    MinInt64  = -1 << 63
    +    MaxUint8  = 1<<8 - 1
    +    MaxUint16 = 1<<16 - 1
    +    MaxUint32 = 1<<32 - 1
    +    MaxUint64 = 1<<64 - 1
    +)
    +

    +Integer limit values. +

    + + + + + + + +

    func Abs

    +
    func Abs(x float64) float64
    +

    +Abs returns the absolute value of x. +

    +

    +Special cases are: +

    +
    Abs(±Inf) = +Inf
    +Abs(NaN) = NaN
    +
    + + + + + + + +

    func Acos

    +
    func Acos(x float64) float64
    +

    +Acos returns the arccosine, in radians, of x. +

    +

    +Special case is: +

    +
    Acos(x) = NaN if x < -1 or x > 1
    +
    + + + + + + + +

    func Acosh

    +
    func Acosh(x float64) float64
    +

    +Acosh returns the inverse hyperbolic cosine of x. +

    +

    +Special cases are: +

    +
    Acosh(+Inf) = +Inf
    +Acosh(x) = NaN if x < 1
    +Acosh(NaN) = NaN
    +
    + + + + + + + +

    func Asin

    +
    func Asin(x float64) float64
    +

    +Asin returns the arcsine, in radians, of x. +

    +

    +Special cases are: +

    +
    Asin(±0) = ±0
    +Asin(x) = NaN if x < -1 or x > 1
    +
    + + + + + + + +

    func Asinh

    +
    func Asinh(x float64) float64
    +

    +Asinh returns the inverse hyperbolic sine of x. +

    +

    +Special cases are: +

    +
    Asinh(±0) = ±0
    +Asinh(±Inf) = ±Inf
    +Asinh(NaN) = NaN
    +
    + + + + + + + +

    func Atan

    +
    func Atan(x float64) float64
    +

    +Atan returns the arctangent, in radians, of x. +

    +

    +Special cases are: +

    +
    Atan(±0) = ±0
    +Atan(±Inf) = ±Pi/2
    +
    + + + + + + + +

    func Atan2

    +
    func Atan2(y, x float64) float64
    +

    +Atan2 returns the arc tangent of y/x, using +the signs of the two to determine the quadrant +of the return value. +

    +

    +Special cases are (in order): +

    +
    Atan2(y, NaN) = NaN
    +Atan2(NaN, x) = NaN
    +Atan2(+0, x>=0) = +0
    +Atan2(-0, x>=0) = -0
    +Atan2(+0, x<=-0) = +Pi
    +Atan2(-0, x<=-0) = -Pi
    +Atan2(y>0, 0) = +Pi/2
    +Atan2(y<0, 0) = -Pi/2
    +Atan2(+Inf, +Inf) = +Pi/4
    +Atan2(-Inf, +Inf) = -Pi/4
    +Atan2(+Inf, -Inf) = 3Pi/4
    +Atan2(-Inf, -Inf) = -3Pi/4
    +Atan2(y, +Inf) = 0
    +Atan2(y>0, -Inf) = +Pi
    +Atan2(y<0, -Inf) = -Pi
    +Atan2(+Inf, x) = +Pi/2
    +Atan2(-Inf, x) = -Pi/2
    +
    + + + + + + + +

    func Atanh

    +
    func Atanh(x float64) float64
    +

    +Atanh returns the inverse hyperbolic tangent of x. +

    +

    +Special cases are: +

    +
    Atanh(1) = +Inf
    +Atanh(±0) = ±0
    +Atanh(-1) = -Inf
    +Atanh(x) = NaN if x < -1 or x > 1
    +Atanh(NaN) = NaN
    +
    + + + + + + + +

    func Cbrt

    +
    func Cbrt(x float64) float64
    +

    +Cbrt returns the cube root of x. +

    +

    +Special cases are: +

    +
    Cbrt(±0) = ±0
    +Cbrt(±Inf) = ±Inf
    +Cbrt(NaN) = NaN
    +
    + + + + + + + +

    func Ceil

    +
    func Ceil(x float64) float64
    +

    +Ceil returns the least integer value greater than or equal to x. +

    +

    +Special cases are: +

    +
    Ceil(±0) = ±0
    +Ceil(±Inf) = ±Inf
    +Ceil(NaN) = NaN
    +
    + + + + + + + +

    func Copysign

    +
    func Copysign(x, y float64) float64
    +

    +Copysign returns a value with the magnitude +of x and the sign of y. +

    + + + + + + + +

    func Cos

    +
    func Cos(x float64) float64
    +

    +Cos returns the cosine of the radian argument x. +

    +

    +Special cases are: +

    +
    Cos(±Inf) = NaN
    +Cos(NaN) = NaN
    +
    + + + + + + + +

    func Cosh

    +
    func Cosh(x float64) float64
    +

    +Cosh returns the hyperbolic cosine of x. +

    +

    +Special cases are: +

    +
    Cosh(±0) = 1
    +Cosh(±Inf) = +Inf
    +Cosh(NaN) = NaN
    +
    + + + + + + + +

    func Dim

    +
    func Dim(x, y float64) float64
    +

    +Dim returns the maximum of x-y or 0. +

    +

    +Special cases are: +

    +
    Dim(+Inf, +Inf) = NaN
    +Dim(-Inf, -Inf) = NaN
    +Dim(x, NaN) = Dim(NaN, x) = NaN
    +
    + + + + + + + +

    func Erf

    +
    func Erf(x float64) float64
    +

    +Erf returns the error function of x. +

    +

    +Special cases are: +

    +
    Erf(+Inf) = 1
    +Erf(-Inf) = -1
    +Erf(NaN) = NaN
    +
    + + + + + + + +

    func Erfc

    +
    func Erfc(x float64) float64
    +

    +Erfc returns the complementary error function of x. +

    +

    +Special cases are: +

    +
    Erfc(+Inf) = 0
    +Erfc(-Inf) = 2
    +Erfc(NaN) = NaN
    +
    + + + + + + + +

    func Exp

    +
    func Exp(x float64) float64
    +

    +Exp returns e**x, the base-e exponential of x. +

    +

    +Special cases are: +

    +
    Exp(+Inf) = +Inf
    +Exp(NaN) = NaN
    +
    +

    +Very large values overflow to 0 or +Inf. +Very small values underflow to 1. +

    + + + + + + + +

    func Exp2

    +
    func Exp2(x float64) float64
    +

    +Exp2 returns 2**x, the base-2 exponential of x. +

    +

    +Special cases are the same as Exp. +

    + + + + + + + +

    func Expm1

    +
    func Expm1(x float64) float64
    +

    +Expm1 returns e**x - 1, the base-e exponential of x minus 1. +It is more accurate than Exp(x) - 1 when x is near zero. +

    +

    +Special cases are: +

    +
    Expm1(+Inf) = +Inf
    +Expm1(-Inf) = -1
    +Expm1(NaN) = NaN
    +
    +

    +Very large values overflow to -1 or +Inf. +

    + + + + + + + +

    func Float32bits

    +
    func Float32bits(f float32) uint32
    +

    +Float32bits returns the IEEE 754 binary representation of f. +

    + + + + + + + +

    func Float32frombits

    +
    func Float32frombits(b uint32) float32
    +

    +Float32frombits returns the floating point number corresponding +to the IEEE 754 binary representation b. +

    + + + + + + + +

    func Float64bits

    +
    func Float64bits(f float64) uint64
    +

    +Float64bits returns the IEEE 754 binary representation of f. +

    + + + + + + + +

    func Float64frombits

    +
    func Float64frombits(b uint64) float64
    +

    +Float64frombits returns the floating point number corresponding +the IEEE 754 binary representation b. +

    + + + + + + + +

    func Floor

    +
    func Floor(x float64) float64
    +

    +Floor returns the greatest integer value less than or equal to x. +

    +

    +Special cases are: +

    +
    Floor(±0) = ±0
    +Floor(±Inf) = ±Inf
    +Floor(NaN) = NaN
    +
    + + + + + + + +

    func Frexp

    +
    func Frexp(f float64) (frac float64, exp int)
    +

    +Frexp breaks f into a normalized fraction +and an integral power of two. +It returns frac and exp satisfying f == frac × 2**exp, +with the absolute value of frac in the interval [½, 1). +

    +

    +Special cases are: +

    +
    Frexp(±0) = ±0, 0
    +Frexp(±Inf) = ±Inf, 0
    +Frexp(NaN) = NaN, 0
    +
    + + + + + + + +

    func Gamma

    +
    func Gamma(x float64) float64
    +

    +Gamma returns the Gamma function of x. +

    +

    +Special cases are: +

    +
    Gamma(+Inf) = +Inf
    +Gamma(+0) = +Inf
    +Gamma(-0) = -Inf
    +Gamma(x) = NaN for integer x < 0
    +Gamma(-Inf) = NaN
    +Gamma(NaN) = NaN
    +
    + + + + + + + +

    func Hypot

    +
    func Hypot(p, q float64) float64
    +

    +Hypot returns Sqrt(p*p + q*q), taking care to avoid +unnecessary overflow and underflow. +

    +

    +Special cases are: +

    +
    Hypot(±Inf, q) = +Inf
    +Hypot(p, ±Inf) = +Inf
    +Hypot(NaN, q) = NaN
    +Hypot(p, NaN) = NaN
    +
    + + + + + + + +

    func Ilogb

    +
    func Ilogb(x float64) int
    +

    +Ilogb returns the binary exponent of x as an integer. +

    +

    +Special cases are: +

    +
    Ilogb(±Inf) = MaxInt32
    +Ilogb(0) = MinInt32
    +Ilogb(NaN) = MaxInt32
    +
    + + + + + + + +

    func Inf

    +
    func Inf(sign int) float64
    +

    +Inf returns positive infinity if sign >= 0, negative infinity if sign < 0. +

    + + + + + + + +

    func IsInf

    +
    func IsInf(f float64, sign int) bool
    +

    +IsInf reports whether f is an infinity, according to sign. +If sign > 0, IsInf reports whether f is positive infinity. +If sign < 0, IsInf reports whether f is negative infinity. +If sign == 0, IsInf reports whether f is either infinity. +

    + + + + + + + +

    func IsNaN

    +
    func IsNaN(f float64) (is bool)
    +

    +IsNaN reports whether f is an IEEE 754 “not-a-number” value. +

    + + + + + + + +

    func J0

    +
    func J0(x float64) float64
    +

    +J0 returns the order-zero Bessel function of the first kind. +

    +

    +Special cases are: +

    +
    J0(±Inf) = 0
    +J0(0) = 1
    +J0(NaN) = NaN
    +
    + + + + + + + +

    func J1

    +
    func J1(x float64) float64
    +

    +J1 returns the order-one Bessel function of the first kind. +

    +

    +Special cases are: +

    +
    J1(±Inf) = 0
    +J1(NaN) = NaN
    +
    + + + + + + + +

    func Jn

    +
    func Jn(n int, x float64) float64
    +

    +Jn returns the order-n Bessel function of the first kind. +

    +

    +Special cases are: +

    +
    Jn(n, ±Inf) = 0
    +Jn(n, NaN) = NaN
    +
    + + + + + + + +

    func Ldexp

    +
    func Ldexp(frac float64, exp int) float64
    +

    +Ldexp is the inverse of Frexp. +It returns frac × 2**exp. +

    +

    +Special cases are: +

    +
    Ldexp(±0, exp) = ±0
    +Ldexp(±Inf, exp) = ±Inf
    +Ldexp(NaN, exp) = NaN
    +
    + + + + + + + +

    func Lgamma

    +
    func Lgamma(x float64) (lgamma float64, sign int)
    +

    +Lgamma returns the natural logarithm and sign (-1 or +1) of Gamma(x). +

    +

    +Special cases are: +

    +
    Lgamma(+Inf) = +Inf
    +Lgamma(0) = +Inf
    +Lgamma(-integer) = +Inf
    +Lgamma(-Inf) = -Inf
    +Lgamma(NaN) = NaN
    +
    + + + + + + + +

    func Log

    +
    func Log(x float64) float64
    +

    +Log returns the natural logarithm of x. +

    +

    +Special cases are: +

    +
    Log(+Inf) = +Inf
    +Log(0) = -Inf
    +Log(x < 0) = NaN
    +Log(NaN) = NaN
    +
    + + + + + + + +

    func Log10

    +
    func Log10(x float64) float64
    +

    +Log10 returns the decimal logarithm of x. +The special cases are the same as for Log. +

    + + + + + + + +

    func Log1p

    +
    func Log1p(x float64) float64
    +

    +Log1p returns the natural logarithm of 1 plus its argument x. +It is more accurate than Log(1 + x) when x is near zero. +

    +

    +Special cases are: +

    +
    Log1p(+Inf) = +Inf
    +Log1p(±0) = ±0
    +Log1p(-1) = -Inf
    +Log1p(x < -1) = NaN
    +Log1p(NaN) = NaN
    +
    + + + + + + + +

    func Log2

    +
    func Log2(x float64) float64
    +

    +Log2 returns the binary logarithm of x. +The special cases are the same as for Log. +

    + + + + + + + +

    func Logb

    +
    func Logb(x float64) float64
    +

    +Logb returns the binary exponent of x. +

    +

    +Special cases are: +

    +
    Logb(±Inf) = +Inf
    +Logb(0) = -Inf
    +Logb(NaN) = NaN
    +
    + + + + + + + +

    func Max

    +
    func Max(x, y float64) float64
    +

    +Max returns the larger of x or y. +

    +

    +Special cases are: +

    +
    Max(x, +Inf) = Max(+Inf, x) = +Inf
    +Max(x, NaN) = Max(NaN, x) = NaN
    +Max(+0, ±0) = Max(±0, +0) = +0
    +Max(-0, -0) = -0
    +
    + + + + + + + +

    func Min

    +
    func Min(x, y float64) float64
    +

    +Min returns the smaller of x or y. +

    +

    +Special cases are: +

    +
    Min(x, -Inf) = Min(-Inf, x) = -Inf
    +Min(x, NaN) = Min(NaN, x) = NaN
    +Min(-0, ±0) = Min(±0, -0) = -0
    +
    + + + + + + + +

    func Mod

    +
    func Mod(x, y float64) float64
    +

    +Mod returns the floating-point remainder of x/y. +The magnitude of the result is less than y and its +sign agrees with that of x. +

    +

    +Special cases are: +

    +
    Mod(±Inf, y) = NaN
    +Mod(NaN, y) = NaN
    +Mod(x, 0) = NaN
    +Mod(x, ±Inf) = x
    +Mod(x, NaN) = NaN
    +
    + + + + + + + +

    func Modf

    +
    func Modf(f float64) (int float64, frac float64)
    +

    +Modf returns integer and fractional floating-point numbers +that sum to f. Both values have the same sign as f. +

    +

    +Special cases are: +

    +
    Modf(±Inf) = ±Inf, NaN
    +Modf(NaN) = NaN, NaN
    +
    + + + + + + + +

    func NaN

    +
    func NaN() float64
    +

    +NaN returns an IEEE 754 “not-a-number” value. +

    + + + + + + + +

    func Nextafter

    +
    func Nextafter(x, y float64) (r float64)
    +

    +Nextafter returns the next representable float64 value after x towards y. +

    +

    +Special cases are: +

    +
    Nextafter(x, x)   = x
    +Nextafter(NaN, y) = NaN
    +Nextafter(x, NaN) = NaN
    +
    + + + + + + + +

    func Nextafter32

    +
    func Nextafter32(x, y float32) (r float32)
    +

    +Nextafter32 returns the next representable float32 value after x towards y. +

    +

    +Special cases are: +

    +
    Nextafter32(x, x)   = x
    +Nextafter32(NaN, y) = NaN
    +Nextafter32(x, NaN) = NaN
    +
    + + + + + + + +

    func Pow

    +
    func Pow(x, y float64) float64
    +

    +Pow returns x**y, the base-x exponential of y. +

    +

    +Special cases are (in order): +

    +
    Pow(x, ±0) = 1 for any x
    +Pow(1, y) = 1 for any y
    +Pow(x, 1) = x for any x
    +Pow(NaN, y) = NaN
    +Pow(x, NaN) = NaN
    +Pow(±0, y) = ±Inf for y an odd integer < 0
    +Pow(±0, -Inf) = +Inf
    +Pow(±0, +Inf) = +0
    +Pow(±0, y) = +Inf for finite y < 0 and not an odd integer
    +Pow(±0, y) = ±0 for y an odd integer > 0
    +Pow(±0, y) = +0 for finite y > 0 and not an odd integer
    +Pow(-1, ±Inf) = 1
    +Pow(x, +Inf) = +Inf for |x| > 1
    +Pow(x, -Inf) = +0 for |x| > 1
    +Pow(x, +Inf) = +0 for |x| < 1
    +Pow(x, -Inf) = +Inf for |x| < 1
    +Pow(+Inf, y) = +Inf for y > 0
    +Pow(+Inf, y) = +0 for y < 0
    +Pow(-Inf, y) = Pow(-0, -y)
    +Pow(x, y) = NaN for finite x < 0 and finite non-integer y
    +
    + + + + + + + +

    func Pow10

    +
    func Pow10(e int) float64
    +

    +Pow10 returns 10**e, the base-10 exponential of e. +

    +

    +Special cases are: +

    +
    Pow10(e) = +Inf for e > 309
    +Pow10(e) = 0 for e < -324
    +
    + + + + + + + +

    func Remainder

    +
    func Remainder(x, y float64) float64
    +

    +Remainder returns the IEEE 754 floating-point remainder of x/y. +

    +

    +Special cases are: +

    +
    Remainder(±Inf, y) = NaN
    +Remainder(NaN, y) = NaN
    +Remainder(x, 0) = NaN
    +Remainder(x, ±Inf) = x
    +Remainder(x, NaN) = NaN
    +
    + + + + + + + +

    func Signbit

    +
    func Signbit(x float64) bool
    +

    +Signbit returns true if x is negative or negative zero. +

    + + + + + + + +

    func Sin

    +
    func Sin(x float64) float64
    +

    +Sin returns the sine of the radian argument x. +

    +

    +Special cases are: +

    +
    Sin(±0) = ±0
    +Sin(±Inf) = NaN
    +Sin(NaN) = NaN
    +
    + + + + + + + +

    func Sincos

    +
    func Sincos(x float64) (sin, cos float64)
    +

    +Sincos returns Sin(x), Cos(x). +

    +

    +Special cases are: +

    +
    Sincos(±0) = ±0, 1
    +Sincos(±Inf) = NaN, NaN
    +Sincos(NaN) = NaN, NaN
    +
    + + + + + + + +

    func Sinh

    +
    func Sinh(x float64) float64
    +

    +Sinh returns the hyperbolic sine of x. +

    +

    +Special cases are: +

    +
    Sinh(±0) = ±0
    +Sinh(±Inf) = ±Inf
    +Sinh(NaN) = NaN
    +
    + + + + + + + +

    func Sqrt

    +
    func Sqrt(x float64) float64
    +

    +Sqrt returns the square root of x. +

    +

    +Special cases are: +

    +
    Sqrt(+Inf) = +Inf
    +Sqrt(±0) = ±0
    +Sqrt(x < 0) = NaN
    +Sqrt(NaN) = NaN
    +
    + + + + + + + +

    func Tan

    +
    func Tan(x float64) float64
    +

    +Tan returns the tangent of the radian argument x. +

    +

    +Special cases are: +

    +
    Tan(±0) = ±0
    +Tan(±Inf) = NaN
    +Tan(NaN) = NaN
    +
    + + + + + + + +

    func Tanh

    +
    func Tanh(x float64) float64
    +

    +Tanh returns the hyperbolic tangent of x. +

    +

    +Special cases are: +

    +
    Tanh(±0) = ±0
    +Tanh(±Inf) = ±1
    +Tanh(NaN) = NaN
    +
    + + + + + + + +

    func Trunc

    +
    func Trunc(x float64) float64
    +

    +Trunc returns the integer value of x. +

    +

    +Special cases are: +

    +
    Trunc(±0) = ±0
    +Trunc(±Inf) = ±Inf
    +Trunc(NaN) = NaN
    +
    + + + + + + + +

    func Y0

    +
    func Y0(x float64) float64
    +

    +Y0 returns the order-zero Bessel function of the second kind. +

    +

    +Special cases are: +

    +
    Y0(+Inf) = 0
    +Y0(0) = -Inf
    +Y0(x < 0) = NaN
    +Y0(NaN) = NaN
    +
    + + + + + + + +

    func Y1

    +
    func Y1(x float64) float64
    +

    +Y1 returns the order-one Bessel function of the second kind. +

    +

    +Special cases are: +

    +
    Y1(+Inf) = 0
    +Y1(0) = -Inf
    +Y1(x < 0) = NaN
    +Y1(NaN) = NaN
    +
    + + + + + + + +

    func Yn

    +
    func Yn(n int, x float64) float64
    +

    +Yn returns the order-n Bessel function of the second kind. +

    +

    +Special cases are: +

    +
    Yn(n, +Inf) = 0
    +Yn(n > 0, 0) = -Inf
    +Yn(n < 0, 0) = +Inf if n is odd, -Inf if n is even
    +Y1(n, x < 0) = NaN
    +Y1(n, NaN) = NaN
    +
    + + + + + + + + + + + + + + + + +

    Subdirectories

    + + + + +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    NameSynopsis
    ..
    + big + + Package big implements arbitrary-precision arithmetic (big numbers). +
    + cmplx + + Package cmplx provides basic constants and mathematical functions for complex numbers. +
    + rand + + Package rand implements pseudo-random number generators. +
    +
    + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/math/rand/index.html b/pkg/math/rand/index.html new file mode 100644 index 0000000..863c67c --- /dev/null +++ b/pkg/math/rand/index.html @@ -0,0 +1,942 @@ + + + + + + + + rand - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Package rand

    + + + + + + + + + + + + + + +
    +
    +
    import "math/rand"
    +
    +
    +
    Overview
    +
    Index
    + +
    Examples
    + + +
    +
    + +
    + +
    +

    Overview ▾

    +

    +Package rand implements pseudo-random number generators. +

    +

    +Random numbers are generated by a Source. Top-level functions, such as +Float64 and Int, use a default shared Source that produces a deterministic +sequence of values each time a program is run. Use the Seed function to +initialize the default Source if different behavior is required for each run. +The default Source is safe for concurrent use by multiple goroutines. +

    +

    +For random numbers suitable for security-sensitive work, see the crypto/rand +package. +

    + +
    +
    +
    + +
    +

    Example

    + + + +

    Code:

    +
    rand.Seed(42) // Try changing this number!
    +answers := []string{
    +    "It is certain",
    +    "It is decidedly so",
    +    "Without a doubt",
    +    "Yes definitely",
    +    "You may rely on it",
    +    "As I see it yes",
    +    "Most likely",
    +    "Outlook good",
    +    "Yes",
    +    "Signs point to yes",
    +    "Reply hazy try again",
    +    "Ask again later",
    +    "Better not tell you now",
    +    "Cannot predict now",
    +    "Concentrate and ask again",
    +    "Don't count on it",
    +    "My reply is no",
    +    "My sources say no",
    +    "Outlook not so good",
    +    "Very doubtful",
    +}
    +fmt.Println("Magic 8-Ball says:", answers[rand.Intn(len(answers))])
    +
    + +

    Output:

    +
    Magic 8-Ball says: As I see it yes
    +
    + + +
    +
    +
    + +
    +

    Example (Rand)

    +

    This example shows the use of each of the methods on a *Rand. +The use of the global functions is the same, without the receiver. +

    + + +

    Code:

    +
    // Create and seed the generator.
    +// Typically a non-fixed seed should be used, such as time.Now().UnixNano().
    +// Using a fixed seed will produce the same output on every run.
    +r := rand.New(rand.NewSource(99))
    +
    +// The tabwriter here helps us generate aligned output.
    +w := tabwriter.NewWriter(os.Stdout, 1, 1, 1, ' ', 0)
    +defer w.Flush()
    +show := func(name string, v1, v2, v3 interface{}) {
    +    fmt.Fprintf(w, "%s\t%v\t%v\t%v\n", name, v1, v2, v3)
    +}
    +
    +// Float32 and Float64 values are in [0, 1).
    +show("Float32", r.Float32(), r.Float32(), r.Float32())
    +show("Float64", r.Float64(), r.Float64(), r.Float64())
    +
    +// ExpFloat64 values have an average of 1 but decay exponentially.
    +show("ExpFloat64", r.ExpFloat64(), r.ExpFloat64(), r.ExpFloat64())
    +
    +// NormFloat64 values have an average of 0 and a standard deviation of 1.
    +show("NormFloat64", r.NormFloat64(), r.NormFloat64(), r.NormFloat64())
    +
    +// Int31, Int63, and Uint32 generate values of the given width.
    +// The Int method (not shown) is like either Int31 or Int63
    +// depending on the size of 'int'.
    +show("Int31", r.Int31(), r.Int31(), r.Int31())
    +show("Int63", r.Int63(), r.Int63(), r.Int63())
    +show("Uint32", r.Uint32(), r.Uint32(), r.Uint32())
    +
    +// Intn, Int31n, and Int63n limit their output to be < n.
    +// They do so more carefully than using r.Int()%n.
    +show("Intn(10)", r.Intn(10), r.Intn(10), r.Intn(10))
    +show("Int31n(10)", r.Int31n(10), r.Int31n(10), r.Int31n(10))
    +show("Int63n(10)", r.Int63n(10), r.Int63n(10), r.Int63n(10))
    +
    +// Perm generates a random permutation of the numbers [0, n).
    +show("Perm", r.Perm(5), r.Perm(5), r.Perm(5))
    +
    + +

    Output:

    +
    Float32     0.2635776           0.6358173           0.6718283
    +Float64     0.628605430454327   0.4504798828572669  0.9562755949377957
    +ExpFloat64  0.3362240648200941  1.4256072328483647  0.24354758816173044
    +NormFloat64 0.17233959114940064 1.577014951434847   0.04259129641113857
    +Int31       1501292890          1486668269          182840835
    +Int63       3546343826724305832 5724354148158589552 5239846799706671610
    +Uint32      2760229429          296659907           1922395059
    +Intn(10)    1                   2                   5
    +Int31n(10)  4                   7                   8
    +Int63n(10)  7                   6                   3
    +Perm        [1 4 2 3 0]         [4 2 1 3 0]         [1 2 4 0 3]
    +
    + + +
    +
    + + +
    + +
    +

    Index ▾

    + + + + + +
    +

    Examples

    +
    + +
    Package
    + +
    Package (Rand)
    + +
    +
    + + + +

    Package files

    +

    + + + exp.go + + normal.go + + rand.go + + rng.go + + zipf.go + + +

    + +
    +
    + + + + + + + + +

    func ExpFloat64

    +
    func ExpFloat64() float64
    +

    +ExpFloat64 returns an exponentially distributed float64 in the range +(0, +math.MaxFloat64] with an exponential distribution whose rate parameter +(lambda) is 1 and whose mean is 1/lambda (1) from the default Source. +To produce a distribution with a different rate parameter, +callers can adjust the output using: +

    +
    sample = ExpFloat64() / desiredRateParameter
    +
    + + + + + + + +

    func Float32

    +
    func Float32() float32
    +

    +Float32 returns, as a float32, a pseudo-random number in [0.0,1.0) +from the default Source. +

    + + + + + + + +

    func Float64

    +
    func Float64() float64
    +

    +Float64 returns, as a float64, a pseudo-random number in [0.0,1.0) +from the default Source. +

    + + + + + + + +

    func Int

    +
    func Int() int
    +

    +Int returns a non-negative pseudo-random int from the default Source. +

    + + + + + + + +

    func Int31

    +
    func Int31() int32
    +

    +Int31 returns a non-negative pseudo-random 31-bit integer as an int32 +from the default Source. +

    + + + + + + + +

    func Int31n

    +
    func Int31n(n int32) int32
    +

    +Int31n returns, as an int32, a non-negative pseudo-random number in [0,n) +from the default Source. +It panics if n <= 0. +

    + + + + + + + +

    func Int63

    +
    func Int63() int64
    +

    +Int63 returns a non-negative pseudo-random 63-bit integer as an int64 +from the default Source. +

    + + + + + + + +

    func Int63n

    +
    func Int63n(n int64) int64
    +

    +Int63n returns, as an int64, a non-negative pseudo-random number in [0,n) +from the default Source. +It panics if n <= 0. +

    + + + + + + + +

    func Intn

    +
    func Intn(n int) int
    +

    +Intn returns, as an int, a non-negative pseudo-random number in [0,n) +from the default Source. +It panics if n <= 0. +

    + + + + + + + +

    func NormFloat64

    +
    func NormFloat64() float64
    +

    +NormFloat64 returns a normally distributed float64 in the range +[-math.MaxFloat64, +math.MaxFloat64] with +standard normal distribution (mean = 0, stddev = 1) +from the default Source. +To produce a different normal distribution, callers can +adjust the output using: +

    +
    sample = NormFloat64() * desiredStdDev + desiredMean
    +
    + + + + + + + +

    func Perm

    +
    func Perm(n int) []int
    +

    +Perm returns, as a slice of n ints, a pseudo-random permutation of the integers [0,n) +from the default Source. +

    + + + + + + + +

    func Read

    +
    func Read(p []byte) (n int, err error)
    +

    +Read generates len(p) random bytes from the default Source and +writes them into p. It always returns len(p) and a nil error. +

    + + + + + + + +

    func Seed

    +
    func Seed(seed int64)
    +

    +Seed uses the provided seed value to initialize the default Source to a +deterministic state. If Seed is not called, the generator behaves as +if seeded by Seed(1). +

    + + + + + + + +

    func Uint32

    +
    func Uint32() uint32
    +

    +Uint32 returns a pseudo-random 32-bit value as a uint32 +from the default Source. +

    + + + + + + + + +

    type Rand

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

    +A Rand is a source of random numbers. +

    + + + + + + + + + + + + +

    func New

    +
    func New(src Source) *Rand
    +

    +New returns a new Rand that uses random values from src +to generate other random values. +

    + + + + + + + +

    func (*Rand) ExpFloat64

    +
    func (r *Rand) ExpFloat64() float64
    +

    +ExpFloat64 returns an exponentially distributed float64 in the range +(0, +math.MaxFloat64] with an exponential distribution whose rate parameter +(lambda) is 1 and whose mean is 1/lambda (1). +To produce a distribution with a different rate parameter, +callers can adjust the output using: +

    +
    sample = ExpFloat64() / desiredRateParameter
    +
    + + + + + + +

    func (*Rand) Float32

    +
    func (r *Rand) Float32() float32
    +

    +Float32 returns, as a float32, a pseudo-random number in [0.0,1.0). +

    + + + + + + +

    func (*Rand) Float64

    +
    func (r *Rand) Float64() float64
    +

    +Float64 returns, as a float64, a pseudo-random number in [0.0,1.0). +

    + + + + + + +

    func (*Rand) Int

    +
    func (r *Rand) Int() int
    +

    +Int returns a non-negative pseudo-random int. +

    + + + + + + +

    func (*Rand) Int31

    +
    func (r *Rand) Int31() int32
    +

    +Int31 returns a non-negative pseudo-random 31-bit integer as an int32. +

    + + + + + + +

    func (*Rand) Int31n

    +
    func (r *Rand) Int31n(n int32) int32
    +

    +Int31n returns, as an int32, a non-negative pseudo-random number in [0,n). +It panics if n <= 0. +

    + + + + + + +

    func (*Rand) Int63

    +
    func (r *Rand) Int63() int64
    +

    +Int63 returns a non-negative pseudo-random 63-bit integer as an int64. +

    + + + + + + +

    func (*Rand) Int63n

    +
    func (r *Rand) Int63n(n int64) int64
    +

    +Int63n returns, as an int64, a non-negative pseudo-random number in [0,n). +It panics if n <= 0. +

    + + + + + + +

    func (*Rand) Intn

    +
    func (r *Rand) Intn(n int) int
    +

    +Intn returns, as an int, a non-negative pseudo-random number in [0,n). +It panics if n <= 0. +

    + + + + + + +

    func (*Rand) NormFloat64

    +
    func (r *Rand) NormFloat64() float64
    +

    +NormFloat64 returns a normally distributed float64 in the range +[-math.MaxFloat64, +math.MaxFloat64] with +standard normal distribution (mean = 0, stddev = 1). +To produce a different normal distribution, callers can +adjust the output using: +

    +
    sample = NormFloat64() * desiredStdDev + desiredMean
    +
    + + + + + + +

    func (*Rand) Perm

    +
    func (r *Rand) Perm(n int) []int
    +

    +Perm returns, as a slice of n ints, a pseudo-random permutation of the integers [0,n). +

    + + + + + + +

    func (*Rand) Read

    +
    func (r *Rand) Read(p []byte) (n int, err error)
    +

    +Read generates len(p) random bytes and writes them into p. It +always returns len(p) and a nil error. +

    + + + + + + +

    func (*Rand) Seed

    +
    func (r *Rand) Seed(seed int64)
    +

    +Seed uses the provided seed value to initialize the generator to a deterministic state. +

    + + + + + + +

    func (*Rand) Uint32

    +
    func (r *Rand) Uint32() uint32
    +

    +Uint32 returns a pseudo-random 32-bit value as a uint32. +

    + + + + + + + + +

    type Source

    +
    type Source interface {
    +    Int63() int64
    +    Seed(seed int64)
    +}
    +

    +A Source represents a source of uniformly-distributed +pseudo-random int64 values in the range [0, 1<<63). +

    + + + + + + + + + + + + +

    func NewSource

    +
    func NewSource(seed int64) Source
    +

    +NewSource returns a new pseudo-random Source seeded with the given value. +

    + + + + + + + + + +

    type Zipf

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

    +A Zipf generates Zipf distributed variates. +

    + + + + + + + + + + + + +

    func NewZipf

    +
    func NewZipf(r *Rand, s float64, v float64, imax uint64) *Zipf
    +

    +NewZipf returns a Zipf variate generator. +The generator generates values k ∈ [0, imax] +such that P(k) is proportional to (v + k) ** (-s). +Requirements: s > 1 and v >= 1. +

    + + + + + + + +

    func (*Zipf) Uint64

    +
    func (z *Zipf) Uint64() uint64
    +

    +Uint64 returns a value drawn from the Zipf distribution described +by the Zipf object. +

    + + + + + + + + + + + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/mime/index.html b/pkg/mime/index.html new file mode 100644 index 0000000..f39ad7e --- /dev/null +++ b/pkg/mime/index.html @@ -0,0 +1,634 @@ + + + + + + + + mime - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Package mime

    + + + + + + + + + + + + + + +
    +
    +
    import "mime"
    +
    +
    +
    Overview
    +
    Index
    + +
    Examples
    + + +
    Subdirectories
    + +
    +
    + +
    + +
    +

    Overview ▾

    +

    +Package mime implements parts of the MIME spec. +

    + +
    +
    + + + + + + + +

    Constants

    + +
    const (
    +    // BEncoding represents Base64 encoding scheme as defined by RFC 2045.
    +    BEncoding = WordEncoder('b')
    +    // QEncoding represents the Q-encoding scheme as defined by RFC 2047.
    +    QEncoding = WordEncoder('q')
    +)
    + + + + + + + +

    func AddExtensionType

    +
    func AddExtensionType(ext, typ string) error
    +

    +AddExtensionType sets the MIME type associated with +the extension ext to typ. The extension should begin with +a leading dot, as in ".html". +

    + + + + + + + +

    func ExtensionsByType

    +
    func ExtensionsByType(typ string) ([]string, error)
    +

    +ExtensionsByType returns the extensions known to be associated with the MIME +type typ. The returned extensions will each begin with a leading dot, as in +".html". When typ has no associated extensions, ExtensionsByType returns an +nil slice. +

    + + + + + + + +

    func FormatMediaType

    +
    func FormatMediaType(t string, param map[string]string) string
    +

    +FormatMediaType serializes mediatype t and the parameters +param as a media type conforming to RFC 2045 and RFC 2616. +The type and parameter names are written in lower-case. +When any of the arguments result in a standard violation then +FormatMediaType returns the empty string. +

    + + + + + + + +

    func ParseMediaType

    +
    func ParseMediaType(v string) (mediatype string, params map[string]string, err error)
    +

    +ParseMediaType parses a media type value and any optional +parameters, per RFC 1521. Media types are the values in +Content-Type and Content-Disposition headers (RFC 2183). +On success, ParseMediaType returns the media type converted +to lowercase and trimmed of white space and a non-nil map. +The returned map, params, maps from the lowercase +attribute to the attribute value with its case preserved. +

    + + + + + + + +

    func TypeByExtension

    +
    func TypeByExtension(ext string) string
    +

    +TypeByExtension returns the MIME type associated with the file extension ext. +The extension ext should begin with a leading dot, as in ".html". +When ext has no associated type, TypeByExtension returns "". +

    +

    +Extensions are looked up first case-sensitively, then case-insensitively. +

    +

    +The built-in table is small but on unix it is augmented by the local +system's mime.types file(s) if available under one or more of these +names: +

    +
    /etc/mime.types
    +/etc/apache2/mime.types
    +/etc/apache/mime.types
    +
    +

    +On Windows, MIME types are extracted from the registry. +

    +

    +Text types have the charset parameter set to "utf-8" by default. +

    + + + + + + + + +

    type WordDecoder

    +
    type WordDecoder struct {
    +    // CharsetReader, if non-nil, defines a function to generate
    +    // charset-conversion readers, converting from the provided
    +    // charset into UTF-8.
    +    // Charsets are always lower-case. utf-8, iso-8859-1 and us-ascii charsets
    +    // are handled by default.
    +    // One of the the CharsetReader's result values must be non-nil.
    +    CharsetReader func(charset string, input io.Reader) (io.Reader, error)
    +}
    +

    +A WordDecoder decodes MIME headers containing RFC 2047 encoded-words. +

    + + + + + + + + + + + + + + +

    func (*WordDecoder) Decode

    +
    func (d *WordDecoder) Decode(word string) (string, error)
    +

    +Decode decodes an RFC 2047 encoded-word. +

    + + +
    + +
    +

    Example

    + + + +

    Code:

    +
    dec := new(mime.WordDecoder)
    +header, err := dec.Decode("=?utf-8?q?=C2=A1Hola,_se=C3=B1or!?=")
    +if err != nil {
    +    panic(err)
    +}
    +fmt.Println(header)
    +
    +dec.CharsetReader = func(charset string, input io.Reader) (io.Reader, error) {
    +    switch charset {
    +    case "x-case":
    +        // Fake character set for example.
    +        // Real use would integrate with packages such
    +        // as code.google.com/p/go-charset
    +        content, err := ioutil.ReadAll(input)
    +        if err != nil {
    +            return nil, err
    +        }
    +        return bytes.NewReader(bytes.ToUpper(content)), nil
    +    default:
    +        return nil, fmt.Errorf("unhandled charset %q", charset)
    +    }
    +}
    +header, err = dec.Decode("=?x-case?q?hello!?=")
    +if err != nil {
    +    panic(err)
    +}
    +fmt.Println(header)
    +
    + +

    Output:

    +
    ¡Hola, señor!
    +HELLO!
    +
    + + +
    +
    + + + + +

    func (*WordDecoder) DecodeHeader

    +
    func (d *WordDecoder) DecodeHeader(header string) (string, error)
    +

    +DecodeHeader decodes all encoded-words of the given string. It returns an +error if and only if CharsetReader of d returns an error. +

    + + +
    + +
    +

    Example

    + + + +

    Code:

    +
    dec := new(mime.WordDecoder)
    +header, err := dec.DecodeHeader("=?utf-8?q?=C3=89ric?= <eric@example.org>, =?utf-8?q?Ana=C3=AFs?= <anais@example.org>")
    +if err != nil {
    +    panic(err)
    +}
    +fmt.Println(header)
    +
    +header, err = dec.DecodeHeader("=?utf-8?q?=C2=A1Hola,?= =?utf-8?q?_se=C3=B1or!?=")
    +if err != nil {
    +    panic(err)
    +}
    +fmt.Println(header)
    +
    +dec.CharsetReader = func(charset string, input io.Reader) (io.Reader, error) {
    +    switch charset {
    +    case "x-case":
    +        // Fake character set for example.
    +        // Real use would integrate with packages such
    +        // as code.google.com/p/go-charset
    +        content, err := ioutil.ReadAll(input)
    +        if err != nil {
    +            return nil, err
    +        }
    +        return bytes.NewReader(bytes.ToUpper(content)), nil
    +    default:
    +        return nil, fmt.Errorf("unhandled charset %q", charset)
    +    }
    +}
    +header, err = dec.DecodeHeader("=?x-case?q?hello_?= =?x-case?q?world!?=")
    +if err != nil {
    +    panic(err)
    +}
    +fmt.Println(header)
    +
    + +

    Output:

    +
    Éric <eric@example.org>, Anaïs <anais@example.org>
    +¡Hola, señor!
    +HELLO WORLD!
    +
    + + +
    +
    + + + + + + +

    type WordEncoder

    +
    type WordEncoder byte
    +

    +A WordEncoder is a RFC 2047 encoded-word encoder. +

    + + + + + + + + + + + + + + +

    func (WordEncoder) Encode

    +
    func (e WordEncoder) Encode(charset, s string) string
    +

    +Encode returns the encoded-word form of s. If s is ASCII without special +characters, it is returned unchanged. The provided charset is the IANA +charset name of s. It is case insensitive. +

    + + +
    + +
    +

    Example

    + + + +

    Code:

    +
    fmt.Println(mime.QEncoding.Encode("utf-8", "¡Hola, señor!"))
    +fmt.Println(mime.QEncoding.Encode("utf-8", "Hello!"))
    +fmt.Println(mime.BEncoding.Encode("UTF-8", "¡Hola, señor!"))
    +fmt.Println(mime.QEncoding.Encode("ISO-8859-1", "Caf\xE9"))
    +
    + +

    Output:

    +
    =?utf-8?q?=C2=A1Hola,_se=C3=B1or!?=
    +Hello!
    +=?UTF-8?b?wqFIb2xhLCBzZcOxb3Ih?=
    +=?ISO-8859-1?q?Caf=E9?=
    +
    + + +
    +
    + + + + + + + + + + + + + + +

    Subdirectories

    + + + + +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    NameSynopsis
    ..
    + multipart + + Package multipart implements MIME multipart parsing, as defined in RFC 2046. +
    + quotedprintable + + Package quotedprintable implements quoted-printable encoding as specified by RFC 2045. +
    +
    + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/mime/multipart/index.html b/pkg/mime/multipart/index.html new file mode 100644 index 0000000..785e60e --- /dev/null +++ b/pkg/mime/multipart/index.html @@ -0,0 +1,741 @@ + + + + + + + + multipart - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Package multipart

    + + + + + + + + + + + + + + +
    +
    +
    import "mime/multipart"
    +
    +
    +
    Overview
    +
    Index
    + +
    Examples
    + + +
    +
    + +
    + +
    +

    Overview ▾

    +

    +Package multipart implements MIME multipart parsing, as defined in RFC +2046. +

    +

    +The implementation is sufficient for HTTP (RFC 2388) and the multipart +bodies generated by popular browsers. +

    + +
    +
    + + + + + + + + + + + + +

    type File

    +
    type File interface {
    +    io.Reader
    +    io.ReaderAt
    +    io.Seeker
    +    io.Closer
    +}
    +

    +File is an interface to access the file part of a multipart message. +Its contents may be either stored in memory or on disk. +If stored on disk, the File's underlying concrete type will be an *os.File. +

    + + + + + + + + + + + + + + + + +

    type FileHeader

    +
    type FileHeader struct {
    +    Filename string
    +    Header   textproto.MIMEHeader
    +    // contains filtered or unexported fields
    +}
    +

    +A FileHeader describes a file part of a multipart request. +

    + + + + + + + + + + + + + + +

    func (*FileHeader) Open

    +
    func (fh *FileHeader) Open() (File, error)
    +

    +Open opens and returns the FileHeader's associated File. +

    + + + + + + + + +

    type Form

    +
    type Form struct {
    +    Value map[string][]string
    +    File  map[string][]*FileHeader
    +}
    +

    +Form is a parsed multipart form. +Its File parts are stored either in memory or on disk, +and are accessible via the *FileHeader's Open method. +Its Value parts are stored as strings. +Both are keyed by field name. +

    + + + + + + + + + + + + + + +

    func (*Form) RemoveAll

    +
    func (f *Form) RemoveAll() error
    +

    +RemoveAll removes any temporary files associated with a Form. +

    + + + + + + + + +

    type Part

    +
    type Part struct {
    +    // The headers of the body, if any, with the keys canonicalized
    +    // in the same fashion that the Go http.Request headers are.
    +    // For example, "foo-bar" changes case to "Foo-Bar"
    +    //
    +    // As a special case, if the "Content-Transfer-Encoding" header
    +    // has a value of "quoted-printable", that header is instead
    +    // hidden from this map and the body is transparently decoded
    +    // during Read calls.
    +    Header textproto.MIMEHeader
    +    // contains filtered or unexported fields
    +}
    +

    +A Part represents a single part in a multipart body. +

    + + + + + + + + + + + + + + +

    func (*Part) Close

    +
    func (p *Part) Close() error
    + + + + + + +

    func (*Part) FileName

    +
    func (p *Part) FileName() string
    +

    +FileName returns the filename parameter of the Part's +Content-Disposition header. +

    + + + + + + +

    func (*Part) FormName

    +
    func (p *Part) FormName() string
    +

    +FormName returns the name parameter if p has a Content-Disposition +of type "form-data". Otherwise it returns the empty string. +

    + + + + + + +

    func (*Part) Read

    +
    func (p *Part) Read(d []byte) (n int, err error)
    +

    +Read reads the body of a part, after its headers and before the +next part (if any) begins. +

    + + + + + + + + +

    type Reader

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

    +Reader is an iterator over parts in a MIME multipart body. +Reader's underlying parser consumes its input as needed. Seeking +isn't supported. +

    + + + + + + + + + + + + +

    func NewReader

    +
    func NewReader(r io.Reader, boundary string) *Reader
    +

    +NewReader creates a new multipart Reader reading from r using the +given MIME boundary. +

    +

    +The boundary is usually obtained from the "boundary" parameter of +the message's "Content-Type" header. Use mime.ParseMediaType to +parse such headers. +

    + +
    + +
    +

    Example

    + + + +

    Code:

    +
    msg := &mail.Message{
    +    Header: map[string][]string{
    +        "Content-Type": {"multipart/mixed; boundary=foo"},
    +    },
    +    Body: strings.NewReader(
    +        "--foo\r\nFoo: one\r\n\r\nA section\r\n" +
    +            "--foo\r\nFoo: two\r\n\r\nAnd another\r\n" +
    +            "--foo--\r\n"),
    +}
    +mediaType, params, err := mime.ParseMediaType(msg.Header.Get("Content-Type"))
    +if err != nil {
    +    log.Fatal(err)
    +}
    +if strings.HasPrefix(mediaType, "multipart/") {
    +    mr := multipart.NewReader(msg.Body, params["boundary"])
    +    for {
    +        p, err := mr.NextPart()
    +        if err == io.EOF {
    +            return
    +        }
    +        if err != nil {
    +            log.Fatal(err)
    +        }
    +        slurp, err := ioutil.ReadAll(p)
    +        if err != nil {
    +            log.Fatal(err)
    +        }
    +        fmt.Printf("Part %q: %q\n", p.Header.Get("Foo"), slurp)
    +    }
    +}
    +
    +
    + +

    Output:

    +
    Part "one": "A section"
    +Part "two": "And another"
    +
    + + +
    +
    + + + + + + +

    func (*Reader) NextPart

    +
    func (r *Reader) NextPart() (*Part, error)
    +

    +NextPart returns the next part in the multipart or an error. +When there are no more parts, the error io.EOF is returned. +

    + + + + + + +

    func (*Reader) ReadForm

    +
    func (r *Reader) ReadForm(maxMemory int64) (f *Form, err error)
    +

    +ReadForm parses an entire multipart message whose parts have +a Content-Disposition of "form-data". +It stores up to maxMemory bytes of the file parts in memory +and the remainder on disk in temporary files. +

    + + + + + + + + +

    type Writer

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

    +A Writer generates multipart messages. +

    + + + + + + + + + + + + +

    func NewWriter

    +
    func NewWriter(w io.Writer) *Writer
    +

    +NewWriter returns a new multipart Writer with a random boundary, +writing to w. +

    + + + + + + + +

    func (*Writer) Boundary

    +
    func (w *Writer) Boundary() string
    +

    +Boundary returns the Writer's boundary. +

    + + + + + + +

    func (*Writer) Close

    +
    func (w *Writer) Close() error
    +

    +Close finishes the multipart message and writes the trailing +boundary end line to the output. +

    + + + + + + +

    func (*Writer) CreateFormField

    +
    func (w *Writer) CreateFormField(fieldname string) (io.Writer, error)
    +

    +CreateFormField calls CreatePart with a header using the +given field name. +

    + + + + + + +

    func (*Writer) CreateFormFile

    +
    func (w *Writer) CreateFormFile(fieldname, filename string) (io.Writer, error)
    +

    +CreateFormFile is a convenience wrapper around CreatePart. It creates +a new form-data header with the provided field name and file name. +

    + + + + + + +

    func (*Writer) CreatePart

    +
    func (w *Writer) CreatePart(header textproto.MIMEHeader) (io.Writer, error)
    +

    +CreatePart creates a new multipart section with the provided +header. The body of the part should be written to the returned +Writer. After calling CreatePart, any previous part may no longer +be written to. +

    + + + + + + +

    func (*Writer) FormDataContentType

    +
    func (w *Writer) FormDataContentType() string
    +

    +FormDataContentType returns the Content-Type for an HTTP +multipart/form-data with this Writer's Boundary. +

    + + + + + + +

    func (*Writer) SetBoundary

    +
    func (w *Writer) SetBoundary(boundary string) error
    +

    +SetBoundary overrides the Writer's default randomly-generated +boundary separator with an explicit value. +

    +

    +SetBoundary must be called before any parts are created, may only +contain certain ASCII characters, and must be non-empty and +at most 69 bytes long. +

    + + + + + + +

    func (*Writer) WriteField

    +
    func (w *Writer) WriteField(fieldname, value string) error
    +

    +WriteField calls CreateFormField and then writes the given value. +

    + + + + + + + + + + + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/mime/quotedprintable/index.html b/pkg/mime/quotedprintable/index.html new file mode 100644 index 0000000..90e6d51 --- /dev/null +++ b/pkg/mime/quotedprintable/index.html @@ -0,0 +1,338 @@ + + + + + + + + quotedprintable - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Package quotedprintable

    + + + + + + + + + + + + + + +
    +
    +
    import "mime/quotedprintable"
    +
    +
    +
    Overview
    +
    Index
    + + +
    +
    + +
    + +
    +

    Overview ▾

    +

    +Package quotedprintable implements quoted-printable encoding as specified by +RFC 2045. +

    + +
    +
    + + +
    + +
    +

    Index ▾

    + + + + + + + +

    Package files

    +

    + + + reader.go + + writer.go + + +

    + +
    +
    + + + + + + + + + +

    type Reader

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

    +Reader is a quoted-printable decoder. +

    + + + + + + + + + + + + +

    func NewReader

    +
    func NewReader(r io.Reader) *Reader
    +

    +NewReader returns a quoted-printable reader, decoding from r. +

    + + + + + + + +

    func (*Reader) Read

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

    +Read reads and decodes quoted-printable data from the underlying reader. +

    + + + + + + + + +

    type Writer

    +
    type Writer struct {
    +    // Binary mode treats the writer's input as pure binary and processes end of
    +    // line bytes as binary data.
    +    Binary bool
    +    // contains filtered or unexported fields
    +}
    +

    +A Writer is a quoted-printable writer that implements io.WriteCloser. +

    + + + + + + + + + + + + +

    func NewWriter

    +
    func NewWriter(w io.Writer) *Writer
    +

    +NewWriter returns a new Writer that writes to w. +

    + + + + + + + +

    func (*Writer) Close

    +
    func (w *Writer) Close() error
    +

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

    + + + + + + +

    func (*Writer) Write

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

    +Write encodes p using quoted-printable encoding and writes it to the +underlying io.Writer. It limits line length to 76 characters. The encoded +bytes are not necessarily flushed until the Writer is closed. +

    + + + + + + + + + + + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/net/http/cgi/index.html b/pkg/net/http/cgi/index.html new file mode 100644 index 0000000..bf60804 --- /dev/null +++ b/pkg/net/http/cgi/index.html @@ -0,0 +1,327 @@ + + + + + + + + cgi - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Package cgi

    + + + + + + + + + + + + + + +
    +
    +
    import "net/http/cgi"
    +
    +
    +
    Overview
    +
    Index
    + + +
    +
    + +
    + +
    +

    Overview ▾

    +

    +Package cgi implements CGI (Common Gateway Interface) as specified +in RFC 3875. +

    +

    +Note that using CGI means starting a new process to handle each +request, which is typically less efficient than using a +long-running server. This package is intended primarily for +compatibility with existing systems. +

    + +
    +
    + + + + + + + + + + + +

    func Request

    +
    func Request() (*http.Request, error)
    +

    +Request returns the HTTP request as represented in the current +environment. This assumes the current program is being run +by a web server in a CGI environment. +The returned Request's Body is populated, if applicable. +

    + + + + + + + +

    func RequestFromMap

    +
    func RequestFromMap(params map[string]string) (*http.Request, error)
    +

    +RequestFromMap creates an http.Request from CGI variables. +The returned Request's Body field is not populated. +

    + + + + + + + +

    func Serve

    +
    func Serve(handler http.Handler) error
    +

    +Serve executes the provided Handler on the currently active CGI +request, if any. If there's no current CGI environment +an error is returned. The provided handler may be nil to use +http.DefaultServeMux. +

    + + + + + + + + +

    type Handler

    +
    type Handler struct {
    +    Path string // path to the CGI executable
    +    Root string // root URI prefix of handler or empty for "/"
    +
    +    // Dir specifies the CGI executable's working directory.
    +    // If Dir is empty, the base directory of Path is used.
    +    // If Path has no base directory, the current working
    +    // directory is used.
    +    Dir string
    +
    +    Env        []string    // extra environment variables to set, if any, as "key=value"
    +    InheritEnv []string    // environment variables to inherit from host, as "key"
    +    Logger     *log.Logger // optional log for errors or nil to use log.Print
    +    Args       []string    // optional arguments to pass to child process
    +
    +    // PathLocationHandler specifies the root http Handler that
    +    // should handle internal redirects when the CGI process
    +    // returns a Location header value starting with a "/", as
    +    // specified in RFC 3875 § 6.3.2. This will likely be
    +    // http.DefaultServeMux.
    +    //
    +    // If nil, a CGI response with a local URI path is instead sent
    +    // back to the client and not redirected internally.
    +    PathLocationHandler http.Handler
    +}
    +

    +Handler runs an executable in a subprocess with a CGI environment. +

    + + + + + + + + + + + + + + +

    func (*Handler) ServeHTTP

    +
    func (h *Handler) ServeHTTP(rw http.ResponseWriter, req *http.Request)
    + + + + + + + + + + + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/net/http/cookiejar/index.html b/pkg/net/http/cookiejar/index.html new file mode 100644 index 0000000..6eaff38 --- /dev/null +++ b/pkg/net/http/cookiejar/index.html @@ -0,0 +1,372 @@ + + + + + + + + cookiejar - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Package cookiejar

    + + + + + + + + + + + + + + +
    +
    +
    import "net/http/cookiejar"
    +
    +
    +
    Overview
    +
    Index
    + + +
    +
    + +
    + +
    +

    Overview ▾

    +

    +Package cookiejar implements an in-memory RFC 6265-compliant http.CookieJar. +

    + +
    +
    + + +
    + +
    +

    Index ▾

    + + + + + + + +

    Package files

    +

    + + + jar.go + + punycode.go + + +

    + +
    +
    + + + + + + + + + +

    type Jar

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

    +Jar implements the http.CookieJar interface from the net/http package. +

    + + + + + + + + + + + + +

    func New

    +
    func New(o *Options) (*Jar, error)
    +

    +New returns a new cookie jar. A nil *Options is equivalent to a zero +Options. +

    + + + + + + + +

    func (*Jar) Cookies

    +
    func (j *Jar) Cookies(u *url.URL) (cookies []*http.Cookie)
    +

    +Cookies implements the Cookies method of the http.CookieJar interface. +

    +

    +It returns an empty slice if the URL's scheme is not HTTP or HTTPS. +

    + + + + + + +

    func (*Jar) SetCookies

    +
    func (j *Jar) SetCookies(u *url.URL, cookies []*http.Cookie)
    +

    +SetCookies implements the SetCookies method of the http.CookieJar interface. +

    +

    +It does nothing if the URL's scheme is not HTTP or HTTPS. +

    + + + + + + + + +

    type Options

    +
    type Options struct {
    +    // PublicSuffixList is the public suffix list that determines whether
    +    // an HTTP server can set a cookie for a domain.
    +    //
    +    // A nil value is valid and may be useful for testing but it is not
    +    // secure: it means that the HTTP server for foo.co.uk can set a cookie
    +    // for bar.co.uk.
    +    PublicSuffixList PublicSuffixList
    +}
    +

    +Options are the options for creating a new Jar. +

    + + + + + + + + + + + + + + + + +

    type PublicSuffixList

    +
    type PublicSuffixList interface {
    +    // PublicSuffix returns the public suffix of domain.
    +    //
    +    // TODO: specify which of the caller and callee is responsible for IP
    +    // addresses, for leading and trailing dots, for case sensitivity, and
    +    // for IDN/Punycode.
    +    PublicSuffix(domain string) string
    +
    +    // String returns a description of the source of this public suffix
    +    // list. The description will typically contain something like a time
    +    // stamp or version number.
    +    String() string
    +}
    +

    +PublicSuffixList provides the public suffix of a domain. For example: +

    +
    - the public suffix of "example.com" is "com",
    +- the public suffix of "foo1.foo2.foo3.co.uk" is "co.uk", and
    +- the public suffix of "bar.pvt.k12.ma.us" is "pvt.k12.ma.us".
    +
    +

    +Implementations of PublicSuffixList must be safe for concurrent use by +multiple goroutines. +

    +

    +An implementation that always returns "" is valid and may be useful for +testing but it is not secure: it means that the HTTP server for foo.com can +set a cookie for bar.com. +

    +

    +A public suffix list implementation is in the package +golang.org/x/net/publicsuffix. +

    + + + + + + + + + + + + + + + + + + + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/net/http/fcgi/index.html b/pkg/net/http/fcgi/index.html new file mode 100644 index 0000000..2d8cda8 --- /dev/null +++ b/pkg/net/http/fcgi/index.html @@ -0,0 +1,247 @@ + + + + + + + + fcgi - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Package fcgi

    + + + + + + + + + + + + + + +
    +
    +
    import "net/http/fcgi"
    +
    +
    +
    Overview
    +
    Index
    + + +
    +
    + +
    + +
    +

    Overview ▾

    +

    +Package fcgi implements the FastCGI protocol. +Currently only the responder role is supported. +The protocol is defined at http://www.fastcgi.com/drupal/node/6?q=node/22 +

    + +
    +
    + + +
    + +
    +

    Index ▾

    + + + + + + + +

    Package files

    +

    + + + child.go + + fcgi.go + + +

    + +
    +
    + + + + + +

    Variables

    + +
    var ErrConnClosed = errors.New("fcgi: connection to web server closed")
    +

    +ErrConnClosed is returned by Read when a handler attempts to read the body of +a request after the connection to the web server has been closed. +

    + + +
    var ErrRequestAborted = errors.New("fcgi: request aborted by web server")
    +

    +ErrRequestAborted is returned by Read when a handler attempts to read the +body of a request that has been aborted by the web server. +

    + + + + + + +

    func Serve

    +
    func Serve(l net.Listener, handler http.Handler) error
    +

    +Serve accepts incoming FastCGI connections on the listener l, creating a new +goroutine for each. The goroutine reads requests and then calls handler +to reply to them. +If l is nil, Serve accepts connections from os.Stdin. +If handler is nil, http.DefaultServeMux is used. +

    + + + + + + + + + + + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/net/http/httptest/index.html b/pkg/net/http/httptest/index.html new file mode 100644 index 0000000..6af7f3e --- /dev/null +++ b/pkg/net/http/httptest/index.html @@ -0,0 +1,560 @@ + + + + + + + + httptest - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Package httptest

    + + + + + + + + + + + + + + +
    +
    +
    import "net/http/httptest"
    +
    +
    +
    Overview
    +
    Index
    + +
    Examples
    + + +
    +
    + +
    + +
    +

    Overview ▾

    +

    +Package httptest provides utilities for HTTP testing. +

    + +
    +
    + + + + + + + +

    Constants

    + +
    const DefaultRemoteAddr = "1.2.3.4"
    +

    +DefaultRemoteAddr is the default remote address to return in RemoteAddr if +an explicit DefaultRemoteAddr isn't set on ResponseRecorder. +

    + + + + + + + + +

    type ResponseRecorder

    +
    type ResponseRecorder struct {
    +    Code      int           // the HTTP response code from WriteHeader
    +    HeaderMap http.Header   // the HTTP response headers
    +    Body      *bytes.Buffer // if non-nil, the bytes.Buffer to append written data to
    +    Flushed   bool
    +    // contains filtered or unexported fields
    +}
    +

    +ResponseRecorder is an implementation of http.ResponseWriter that +records its mutations for later inspection in tests. +

    + + + + + + +
    + +
    +

    Example

    + + + +

    Code:

    +
    handler := func(w http.ResponseWriter, r *http.Request) {
    +    http.Error(w, "something failed", http.StatusInternalServerError)
    +}
    +
    +req, err := http.NewRequest("GET", "http://example.com/foo", nil)
    +if err != nil {
    +    log.Fatal(err)
    +}
    +
    +w := httptest.NewRecorder()
    +handler(w, req)
    +
    +fmt.Printf("%d - %s", w.Code, w.Body.String())
    +
    + +

    Output:

    +
    500 - something failed
    +
    + + +
    +
    + + + + + + +

    func NewRecorder

    +
    func NewRecorder() *ResponseRecorder
    +

    +NewRecorder returns an initialized ResponseRecorder. +

    + + + + + + + +

    func (*ResponseRecorder) Flush

    +
    func (rw *ResponseRecorder) Flush()
    +

    +Flush sets rw.Flushed to true. +

    + + + + + + +

    func (*ResponseRecorder) Header

    +
    func (rw *ResponseRecorder) Header() http.Header
    +

    +Header returns the response headers. +

    + + + + + + +

    func (*ResponseRecorder) Write

    +
    func (rw *ResponseRecorder) Write(buf []byte) (int, error)
    +

    +Write always succeeds and writes to rw.Body, if not nil. +

    + + + + + + +

    func (*ResponseRecorder) WriteHeader

    +
    func (rw *ResponseRecorder) WriteHeader(code int)
    +

    +WriteHeader sets rw.Code. +

    + + + + + + +

    func (*ResponseRecorder) WriteString

    +
    func (rw *ResponseRecorder) WriteString(str string) (int, error)
    +

    +WriteString always succeeds and writes to rw.Body, if not nil. +

    + + + + + + + + +

    type Server

    +
    type Server struct {
    +    URL      string // base URL of form http://ipaddr:port with no trailing slash
    +    Listener net.Listener
    +
    +    // TLS is the optional TLS configuration, populated with a new config
    +    // after TLS is started. If set on an unstarted server before StartTLS
    +    // is called, existing fields are copied into the new config.
    +    TLS *tls.Config
    +
    +    // Config may be changed after calling NewUnstartedServer and
    +    // before Start or StartTLS.
    +    Config *http.Server
    +    // contains filtered or unexported fields
    +}
    +

    +A Server is an HTTP server listening on a system-chosen port on the +local loopback interface, for use in end-to-end HTTP tests. +

    + + + + + + +
    + +
    +

    Example

    + + + +

    Code:

    +
    ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
    +    fmt.Fprintln(w, "Hello, client")
    +}))
    +defer ts.Close()
    +
    +res, err := http.Get(ts.URL)
    +if err != nil {
    +    log.Fatal(err)
    +}
    +greeting, err := ioutil.ReadAll(res.Body)
    +res.Body.Close()
    +if err != nil {
    +    log.Fatal(err)
    +}
    +
    +fmt.Printf("%s", greeting)
    +
    + +

    Output:

    +
    Hello, client
    +
    + + +
    +
    + + + + + + +

    func NewServer

    +
    func NewServer(handler http.Handler) *Server
    +

    +NewServer starts and returns a new Server. +The caller should call Close when finished, to shut it down. +

    + + + + + +

    func NewTLSServer

    +
    func NewTLSServer(handler http.Handler) *Server
    +

    +NewTLSServer starts and returns a new Server using TLS. +The caller should call Close when finished, to shut it down. +

    + + + + + +

    func NewUnstartedServer

    +
    func NewUnstartedServer(handler http.Handler) *Server
    +

    +NewUnstartedServer returns a new Server but doesn't start it. +

    +

    +After changing its configuration, the caller should call Start or +StartTLS. +

    +

    +The caller should call Close when finished, to shut it down. +

    + + + + + + + +

    func (*Server) Close

    +
    func (s *Server) Close()
    +

    +Close shuts down the server and blocks until all outstanding +requests on this server have completed. +

    + + + + + + +

    func (*Server) CloseClientConnections

    +
    func (s *Server) CloseClientConnections()
    +

    +CloseClientConnections closes any open HTTP connections to the test Server. +

    + + + + + + +

    func (*Server) Start

    +
    func (s *Server) Start()
    +

    +Start starts a server from NewUnstartedServer. +

    + + + + + + +

    func (*Server) StartTLS

    +
    func (s *Server) StartTLS()
    +

    +StartTLS starts TLS on a server from NewUnstartedServer. +

    + + + + + + + + + + + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/net/http/httputil/index.html b/pkg/net/http/httputil/index.html new file mode 100644 index 0000000..6e00ddc --- /dev/null +++ b/pkg/net/http/httputil/index.html @@ -0,0 +1,935 @@ + + + + + + + + httputil - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Package httputil

    + + + + + + + + + + + + + + +
    +
    +
    import "net/http/httputil"
    +
    +
    +
    Overview
    +
    Index
    + +
    Examples
    + + +
    +
    + +
    + +
    +

    Overview ▾

    +

    +Package httputil provides HTTP utility functions, complementing the +more common ones in the net/http package. +

    + +
    +
    + + +
    + +
    +

    Index ▾

    + + +
    +
    + + +
    Variables
    + + + +
    func DumpRequest(req *http.Request, body bool) (dump []byte, err error)
    + + +
    func DumpRequestOut(req *http.Request, body bool) ([]byte, error)
    + + +
    func DumpResponse(resp *http.Response, body bool) (dump []byte, err error)
    + + +
    func NewChunkedReader(r io.Reader) io.Reader
    + + +
    func NewChunkedWriter(w io.Writer) io.WriteCloser
    + + + +
    type BufferPool
    + + + + +
    type ClientConn
    + + +
        func NewClientConn(c net.Conn, r *bufio.Reader) *ClientConn
    + + +
        func NewProxyClientConn(c net.Conn, r *bufio.Reader) *ClientConn
    + + + +
        func (cc *ClientConn) Close() error
    + + +
        func (cc *ClientConn) Do(req *http.Request) (resp *http.Response, err error)
    + + +
        func (cc *ClientConn) Hijack() (c net.Conn, r *bufio.Reader)
    + + +
        func (cc *ClientConn) Pending() int
    + + +
        func (cc *ClientConn) Read(req *http.Request) (resp *http.Response, err error)
    + + +
        func (cc *ClientConn) Write(req *http.Request) (err error)
    + + + +
    type ReverseProxy
    + + +
        func NewSingleHostReverseProxy(target *url.URL) *ReverseProxy
    + + + +
        func (p *ReverseProxy) ServeHTTP(rw http.ResponseWriter, req *http.Request)
    + + + +
    type ServerConn
    + + +
        func NewServerConn(c net.Conn, r *bufio.Reader) *ServerConn
    + + + +
        func (sc *ServerConn) Close() error
    + + +
        func (sc *ServerConn) Hijack() (c net.Conn, r *bufio.Reader)
    + + +
        func (sc *ServerConn) Pending() int
    + + +
        func (sc *ServerConn) Read() (req *http.Request, err error)
    + + +
        func (sc *ServerConn) Write(req *http.Request, resp *http.Response) error
    + + + +
    +
    + + +
    +

    Examples

    +
    + +
    DumpRequest
    + +
    DumpRequestOut
    + +
    DumpResponse
    + +
    ReverseProxy
    + +
    +
    + + + +

    Package files

    +

    + + + dump.go + + httputil.go + + persist.go + + reverseproxy.go + + +

    + +
    +
    + + + + + +

    Variables

    + +
    var (
    +    ErrPersistEOF = &http.ProtocolError{ErrorString: "persistent connection closed"}
    +    ErrClosed     = &http.ProtocolError{ErrorString: "connection closed by user"}
    +    ErrPipeline   = &http.ProtocolError{ErrorString: "pipeline error"}
    +)
    + + +
    var ErrLineTooLong = internal.ErrLineTooLong
    +

    +ErrLineTooLong is returned when reading malformed chunked data +with lines that are too long. +

    + + + + + + +

    func DumpRequest

    +
    func DumpRequest(req *http.Request, body bool) (dump []byte, err error)
    +

    +DumpRequest returns the given request in its HTTP/1.x wire +representation. It should only be used by servers to debug client +requests. The returned representation is an approximation only; +some details of the initial request are lost while parsing it into +an http.Request. In particular, the order and case of header field +names are lost. The order of values in multi-valued headers is kept +intact. HTTP/2 requests are dumped in HTTP/1.x form, not in their +original binary representations. +

    +

    +If body is true, DumpRequest also returns the body. To do so, it +consumes req.Body and then replaces it with a new io.ReadCloser +that yields the same bytes. If DumpRequest returns an error, +the state of req is undefined. +

    +

    +The documentation for http.Request.Write details which fields +of req are included in the dump. +

    + +
    + +
    +

    Example

    + + + +

    Code:

    +
    ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
    +    dump, err := httputil.DumpRequest(r, true)
    +    if err != nil {
    +        http.Error(w, fmt.Sprint(err), http.StatusInternalServerError)
    +        return
    +    }
    +
    +    fmt.Fprintf(w, "%q", dump)
    +}))
    +defer ts.Close()
    +
    +const body = "Go is a general-purpose language designed with systems programming in mind."
    +req, err := http.NewRequest("POST", ts.URL, strings.NewReader(body))
    +if err != nil {
    +    log.Fatal(err)
    +}
    +req.Host = "www.example.org"
    +resp, err := http.DefaultClient.Do(req)
    +if err != nil {
    +    log.Fatal(err)
    +}
    +defer resp.Body.Close()
    +
    +b, err := ioutil.ReadAll(resp.Body)
    +if err != nil {
    +    log.Fatal(err)
    +}
    +
    +fmt.Printf("%s", b)
    +
    +
    + +

    Output:

    +
    "POST / HTTP/1.1\r\nHost: www.example.org\r\nAccept-Encoding: gzip\r\nUser-Agent: Go-http-client/1.1\r\n\r\nGo is a general-purpose language designed with systems programming in mind."
    +
    + + +
    +
    + + + + + + +

    func DumpRequestOut

    +
    func DumpRequestOut(req *http.Request, body bool) ([]byte, error)
    +

    +DumpRequestOut is like DumpRequest but for outgoing client requests. It +includes any headers that the standard http.Transport adds, such as +User-Agent. +

    + +
    + +
    +

    Example

    + + + +

    Code:

    +
    const body = "Go is a general-purpose language designed with systems programming in mind."
    +req, err := http.NewRequest("PUT", "http://www.example.org", strings.NewReader(body))
    +if err != nil {
    +    log.Fatal(err)
    +}
    +
    +dump, err := httputil.DumpRequestOut(req, true)
    +if err != nil {
    +    log.Fatal(err)
    +}
    +
    +fmt.Printf("%q", dump)
    +
    +
    + +

    Output:

    +
    "PUT / HTTP/1.1\r\nHost: www.example.org\r\nUser-Agent: Go-http-client/1.1\r\nContent-Length: 75\r\nAccept-Encoding: gzip\r\n\r\nGo is a general-purpose language designed with systems programming in mind."
    +
    + + +
    +
    + + + + + + +

    func DumpResponse

    +
    func DumpResponse(resp *http.Response, body bool) (dump []byte, err error)
    +

    +DumpResponse is like DumpRequest but dumps a response. +

    + +
    + +
    +

    Example

    + + + +

    Code:

    +
    const body = "Go is a general-purpose language designed with systems programming in mind."
    +ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
    +    w.Header().Set("Date", "Wed, 19 Jul 1972 19:00:00 GMT")
    +    fmt.Fprintln(w, body)
    +}))
    +defer ts.Close()
    +
    +resp, err := http.Get(ts.URL)
    +if err != nil {
    +    log.Fatal(err)
    +}
    +defer resp.Body.Close()
    +
    +dump, err := httputil.DumpResponse(resp, true)
    +if err != nil {
    +    log.Fatal(err)
    +}
    +
    +fmt.Printf("%q", dump)
    +
    +
    + +

    Output:

    +
    "HTTP/1.1 200 OK\r\nContent-Length: 76\r\nContent-Type: text/plain; charset=utf-8\r\nDate: Wed, 19 Jul 1972 19:00:00 GMT\r\n\r\nGo is a general-purpose language designed with systems programming in mind.\n"
    +
    + + +
    +
    + + + + + + +

    func NewChunkedReader

    +
    func NewChunkedReader(r io.Reader) io.Reader
    +

    +NewChunkedReader returns a new chunkedReader that translates the data read from r +out of HTTP "chunked" format before returning it. +The chunkedReader returns io.EOF when the final 0-length chunk is read. +

    +

    +NewChunkedReader is not needed by normal applications. The http package +automatically decodes chunking when reading response bodies. +

    + + + + + + + +

    func NewChunkedWriter

    +
    func NewChunkedWriter(w io.Writer) io.WriteCloser
    +

    +NewChunkedWriter returns a new chunkedWriter that translates writes into HTTP +"chunked" format before writing them to w. Closing the returned chunkedWriter +sends the final 0-length chunk that marks the end of the stream. +

    +

    +NewChunkedWriter is not needed by normal applications. The http +package adds chunking automatically if handlers don't set a +Content-Length header. Using NewChunkedWriter inside a handler +would result in double chunking or chunking with a Content-Length +length, both of which are wrong. +

    + + + + + + + + +

    type BufferPool

    +
    type BufferPool interface {
    +    Get() []byte
    +    Put([]byte)
    +}
    +

    +A BufferPool is an interface for getting and returning temporary +byte slices for use by io.CopyBuffer. +

    + + + + + + + + + + + + + + + + +

    type ClientConn

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

    +A ClientConn sends request and receives headers over an underlying +connection, while respecting the HTTP keepalive logic. ClientConn +supports hijacking the connection calling Hijack to +regain control of the underlying net.Conn and deal with it as desired. +

    +

    +ClientConn is low-level and old. Applications should instead use +Client or Transport in the net/http package. +

    + + + + + + + + + + + + +

    func NewClientConn

    +
    func NewClientConn(c net.Conn, r *bufio.Reader) *ClientConn
    +

    +NewClientConn returns a new ClientConn reading and writing c. If r is not +nil, it is the buffer to use when reading c. +

    +

    +ClientConn is low-level and old. Applications should use Client or +Transport in the net/http package. +

    + + + + + +

    func NewProxyClientConn

    +
    func NewProxyClientConn(c net.Conn, r *bufio.Reader) *ClientConn
    +

    +NewProxyClientConn works like NewClientConn but writes Requests +using Request's WriteProxy method. +

    +

    +New code should not use NewProxyClientConn. See Client or +Transport in the net/http package instead. +

    + + + + + + + +

    func (*ClientConn) Close

    +
    func (cc *ClientConn) Close() error
    +

    +Close calls Hijack and then also closes the underlying connection +

    + + + + + + +

    func (*ClientConn) Do

    +
    func (cc *ClientConn) Do(req *http.Request) (resp *http.Response, err error)
    +

    +Do is convenience method that writes a request and reads a response. +

    + + + + + + +

    func (*ClientConn) Hijack

    +
    func (cc *ClientConn) Hijack() (c net.Conn, r *bufio.Reader)
    +

    +Hijack detaches the ClientConn and returns the underlying connection as well +as the read-side bufio which may have some left over data. Hijack may be +called before the user or Read have signaled the end of the keep-alive +logic. The user should not call Hijack while Read or Write is in progress. +

    + + + + + + +

    func (*ClientConn) Pending

    +
    func (cc *ClientConn) Pending() int
    +

    +Pending returns the number of unanswered requests +that have been sent on the connection. +

    + + + + + + +

    func (*ClientConn) Read

    +
    func (cc *ClientConn) Read(req *http.Request) (resp *http.Response, err error)
    +

    +Read reads the next response from the wire. A valid response might be +returned together with an ErrPersistEOF, which means that the remote +requested that this be the last request serviced. Read can be called +concurrently with Write, but not with another Read. +

    + + + + + + +

    func (*ClientConn) Write

    +
    func (cc *ClientConn) Write(req *http.Request) (err error)
    +

    +Write writes a request. An ErrPersistEOF error is returned if the connection +has been closed in an HTTP keepalive sense. If req.Close equals true, the +keepalive connection is logically closed after this request and the opposing +server is informed. An ErrUnexpectedEOF indicates the remote closed the +underlying TCP connection, which is usually considered as graceful close. +

    + + + + + + + + +

    type ReverseProxy

    +
    type ReverseProxy struct {
    +    // Director must be a function which modifies
    +    // the request into a new request to be sent
    +    // using Transport. Its response is then copied
    +    // back to the original client unmodified.
    +    Director func(*http.Request)
    +
    +    // The transport used to perform proxy requests.
    +    // If nil, http.DefaultTransport is used.
    +    Transport http.RoundTripper
    +
    +    // FlushInterval specifies the flush interval
    +    // to flush to the client while copying the
    +    // response body.
    +    // If zero, no periodic flushing is done.
    +    FlushInterval time.Duration
    +
    +    // ErrorLog specifies an optional logger for errors
    +    // that occur when attempting to proxy the request.
    +    // If nil, logging goes to os.Stderr via the log package's
    +    // standard logger.
    +    ErrorLog *log.Logger
    +
    +    // BufferPool optionally specifies a buffer pool to
    +    // get byte slices for use by io.CopyBuffer when
    +    // copying HTTP response bodies.
    +    BufferPool BufferPool
    +}
    +

    +ReverseProxy is an HTTP Handler that takes an incoming request and +sends it to another server, proxying the response back to the +client. +

    + + + + + + +
    + +
    +

    Example

    + + + +

    Code:

    +
    backendServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
    +    fmt.Fprintln(w, "this call was relayed by the reverse proxy")
    +}))
    +defer backendServer.Close()
    +
    +rpURL, err := url.Parse(backendServer.URL)
    +if err != nil {
    +    log.Fatal(err)
    +}
    +frontendProxy := httptest.NewServer(httputil.NewSingleHostReverseProxy(rpURL))
    +defer frontendProxy.Close()
    +
    +resp, err := http.Get(frontendProxy.URL)
    +if err != nil {
    +    log.Fatal(err)
    +}
    +
    +b, err := ioutil.ReadAll(resp.Body)
    +if err != nil {
    +    log.Fatal(err)
    +}
    +
    +fmt.Printf("%s", b)
    +
    +
    + +

    Output:

    +
    this call was relayed by the reverse proxy
    +
    + + +
    +
    + + + + + + +

    func NewSingleHostReverseProxy

    +
    func NewSingleHostReverseProxy(target *url.URL) *ReverseProxy
    +

    +NewSingleHostReverseProxy returns a new ReverseProxy that routes +URLs to the scheme, host, and base path provided in target. If the +target's path is "/base" and the incoming request was for "/dir", +the target request will be for /base/dir. +NewSingleHostReverseProxy does not rewrite the Host header. +To rewrite Host headers, use ReverseProxy directly with a custom +Director policy. +

    + + + + + + + +

    func (*ReverseProxy) ServeHTTP

    +
    func (p *ReverseProxy) ServeHTTP(rw http.ResponseWriter, req *http.Request)
    + + + + + + + + +

    type ServerConn

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

    +A ServerConn reads requests and sends responses over an underlying +connection, until the HTTP keepalive logic commands an end. ServerConn +also allows hijacking the underlying connection by calling Hijack +to regain control over the connection. ServerConn supports pipe-lining, +i.e. requests can be read out of sync (but in the same order) while the +respective responses are sent. +

    +

    +ServerConn is low-level and old. Applications should instead use Server +in the net/http package. +

    + + + + + + + + + + + + +

    func NewServerConn

    +
    func NewServerConn(c net.Conn, r *bufio.Reader) *ServerConn
    +

    +NewServerConn returns a new ServerConn reading and writing c. If r is not +nil, it is the buffer to use when reading c. +

    +

    +ServerConn is low-level and old. Applications should instead use Server +in the net/http package. +

    + + + + + + + +

    func (*ServerConn) Close

    +
    func (sc *ServerConn) Close() error
    +

    +Close calls Hijack and then also closes the underlying connection +

    + + + + + + +

    func (*ServerConn) Hijack

    +
    func (sc *ServerConn) Hijack() (c net.Conn, r *bufio.Reader)
    +

    +Hijack detaches the ServerConn and returns the underlying connection as well +as the read-side bufio which may have some left over data. Hijack may be +called before Read has signaled the end of the keep-alive logic. The user +should not call Hijack while Read or Write is in progress. +

    + + + + + + +

    func (*ServerConn) Pending

    +
    func (sc *ServerConn) Pending() int
    +

    +Pending returns the number of unanswered requests +that have been received on the connection. +

    + + + + + + +

    func (*ServerConn) Read

    +
    func (sc *ServerConn) Read() (req *http.Request, err error)
    +

    +Read returns the next request on the wire. An ErrPersistEOF is returned if +it is gracefully determined that there are no more requests (e.g. after the +first request on an HTTP/1.0 connection, or after a Connection:close on a +HTTP/1.1 connection). +

    + + + + + + +

    func (*ServerConn) Write

    +
    func (sc *ServerConn) Write(req *http.Request, resp *http.Response) error
    +

    +Write writes resp in response to req. To close the connection gracefully, set the +Response.Close field to true. Write should be considered operational until +it returns an error, regardless of any errors returned on the Read side. +

    + + + + + + + + + + + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/net/http/index.html b/pkg/net/http/index.html new file mode 100644 index 0000000..dbe1e6b --- /dev/null +++ b/pkg/net/http/index.html @@ -0,0 +1,3745 @@ + + + + + + + + http - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Package http

    + + + + + + + + + + + + + + +
    +
    +
    import "net/http"
    +
    +
    +
    Overview
    +
    Index
    + +
    Examples
    + + +
    Subdirectories
    + +
    +
    + +
    + +
    +

    Overview ▾

    +

    +Package http provides HTTP client and server implementations. +

    +

    +Get, Head, Post, and PostForm make HTTP (or HTTPS) requests: +

    +
    resp, err := http.Get("http://example.com/")
    +...
    +resp, err := http.Post("http://example.com/upload", "image/jpeg", &buf)
    +...
    +resp, err := http.PostForm("http://example.com/form",
    +	url.Values{"key": {"Value"}, "id": {"123"}})
    +
    +

    +The client must close the response body when finished with it: +

    +
    resp, err := http.Get("http://example.com/")
    +if err != nil {
    +	// handle error
    +}
    +defer resp.Body.Close()
    +body, err := ioutil.ReadAll(resp.Body)
    +// ...
    +
    +

    +For control over HTTP client headers, redirect policy, and other +settings, create a Client: +

    +
    client := &http.Client{
    +	CheckRedirect: redirectPolicyFunc,
    +}
    +
    +resp, err := client.Get("http://example.com")
    +// ...
    +
    +req, err := http.NewRequest("GET", "http://example.com", nil)
    +// ...
    +req.Header.Add("If-None-Match", `W/"wyzzy"`)
    +resp, err := client.Do(req)
    +// ...
    +
    +

    +For control over proxies, TLS configuration, keep-alives, +compression, and other settings, create a Transport: +

    +
    tr := &http.Transport{
    +	TLSClientConfig:    &tls.Config{RootCAs: pool},
    +	DisableCompression: true,
    +}
    +client := &http.Client{Transport: tr}
    +resp, err := client.Get("https://example.com")
    +
    +

    +Clients and Transports are safe for concurrent use by multiple +goroutines and for efficiency should only be created once and re-used. +

    +

    +ListenAndServe starts an HTTP server with a given address and handler. +The handler is usually nil, which means to use DefaultServeMux. +Handle and HandleFunc add handlers to DefaultServeMux: +

    +
    http.Handle("/foo", fooHandler)
    +
    +http.HandleFunc("/bar", func(w http.ResponseWriter, r *http.Request) {
    +	fmt.Fprintf(w, "Hello, %q", html.EscapeString(r.URL.Path))
    +})
    +
    +log.Fatal(http.ListenAndServe(":8080", nil))
    +
    +

    +More control over the server's behavior is available by creating a +custom Server: +

    +
    s := &http.Server{
    +	Addr:           ":8080",
    +	Handler:        myHandler,
    +	ReadTimeout:    10 * time.Second,
    +	WriteTimeout:   10 * time.Second,
    +	MaxHeaderBytes: 1 << 20,
    +}
    +log.Fatal(s.ListenAndServe())
    +
    +

    +The http package has transparent support for the HTTP/2 protocol when +using HTTPS. Programs that must disable HTTP/2 can do so by setting +Transport.TLSNextProto (for clients) or Server.TLSNextProto (for +servers) to a non-nil, empty map. Alternatively, the following GODEBUG +environment variables are currently supported: +

    +
    GODEBUG=http2client=0  # disable HTTP/2 client support
    +GODEBUG=http2server=0  # disable HTTP/2 server support
    +GODEBUG=http2debug=1   # enable verbose HTTP/2 debug logs
    +GODEBUG=http2debug=2   # ... even more verbose, with frame dumps
    +
    +

    +The GODEBUG variables are not covered by Go's API compatibility promise. +HTTP/2 support was added in Go 1.6. Please report any issues instead of +disabling HTTP/2 support: https://golang.org/s/http2bug +

    + +
    +
    + + +
    + +
    +

    Index ▾

    + + +
    +
    + +
    Constants
    + + +
    Variables
    + + + +
    func CanonicalHeaderKey(s string) string
    + + +
    func DetectContentType(data []byte) string
    + + +
    func Error(w ResponseWriter, error string, code int)
    + + +
    func Handle(pattern string, handler Handler)
    + + +
    func HandleFunc(pattern string, handler func(ResponseWriter, *Request))
    + + +
    func ListenAndServe(addr string, handler Handler) error
    + + +
    func ListenAndServeTLS(addr, certFile, keyFile string, handler Handler) error
    + + +
    func MaxBytesReader(w ResponseWriter, r io.ReadCloser, n int64) io.ReadCloser
    + + +
    func NotFound(w ResponseWriter, r *Request)
    + + +
    func ParseHTTPVersion(vers string) (major, minor int, ok bool)
    + + +
    func ParseTime(text string) (t time.Time, err error)
    + + +
    func ProxyFromEnvironment(req *Request) (*url.URL, error)
    + + +
    func ProxyURL(fixedURL *url.URL) func(*Request) (*url.URL, error)
    + + +
    func Redirect(w ResponseWriter, r *Request, urlStr string, code int)
    + + +
    func Serve(l net.Listener, handler Handler) error
    + + +
    func ServeContent(w ResponseWriter, req *Request, name string, modtime time.Time, content io.ReadSeeker)
    + + +
    func ServeFile(w ResponseWriter, r *Request, name string)
    + + +
    func SetCookie(w ResponseWriter, cookie *Cookie)
    + + +
    func StatusText(code int) string
    + + + +
    type Client
    + + + +
        func (c *Client) Do(req *Request) (resp *Response, err error)
    + + +
        func (c *Client) Get(url string) (resp *Response, err error)
    + + +
        func (c *Client) Head(url string) (resp *Response, err error)
    + + +
        func (c *Client) Post(url string, bodyType string, body io.Reader) (resp *Response, err error)
    + + +
        func (c *Client) PostForm(url string, data url.Values) (resp *Response, err error)
    + + + +
    type CloseNotifier
    + + + + +
    type ConnState
    + + + +
        func (c ConnState) String() string
    + + + +
    type Cookie
    + + + +
        func (c *Cookie) String() string
    + + + +
    type CookieJar
    + + + + +
    type Dir
    + + + +
        func (d Dir) Open(name string) (File, error)
    + + + +
    type File
    + + + + +
    type FileSystem
    + + + + +
    type Flusher
    + + + + +
    type Handler
    + + +
        func FileServer(root FileSystem) Handler
    + + +
        func NotFoundHandler() Handler
    + + +
        func RedirectHandler(url string, code int) Handler
    + + +
        func StripPrefix(prefix string, h Handler) Handler
    + + +
        func TimeoutHandler(h Handler, dt time.Duration, msg string) Handler
    + + + + +
    type HandlerFunc
    + + + +
        func (f HandlerFunc) ServeHTTP(w ResponseWriter, r *Request)
    + + + +
    type Header
    + + + +
        func (h Header) Add(key, value string)
    + + +
        func (h Header) Del(key string)
    + + +
        func (h Header) Get(key string) string
    + + +
        func (h Header) Set(key, value string)
    + + +
        func (h Header) Write(w io.Writer) error
    + + +
        func (h Header) WriteSubset(w io.Writer, exclude map[string]bool) error
    + + + +
    type Hijacker
    + + + + +
    type ProtocolError
    + + + +
        func (err *ProtocolError) Error() string
    + + + +
    type Request
    + + +
        func NewRequest(method, urlStr string, body io.Reader) (*Request, error)
    + + +
        func ReadRequest(b *bufio.Reader) (req *Request, err error)
    + + + +
        func (r *Request) AddCookie(c *Cookie)
    + + +
        func (r *Request) BasicAuth() (username, password string, ok bool)
    + + +
        func (r *Request) Cookie(name string) (*Cookie, error)
    + + +
        func (r *Request) Cookies() []*Cookie
    + + +
        func (r *Request) FormFile(key string) (multipart.File, *multipart.FileHeader, error)
    + + +
        func (r *Request) FormValue(key string) string
    + + +
        func (r *Request) MultipartReader() (*multipart.Reader, error)
    + + +
        func (r *Request) ParseForm() error
    + + +
        func (r *Request) ParseMultipartForm(maxMemory int64) error
    + + +
        func (r *Request) PostFormValue(key string) string
    + + +
        func (r *Request) ProtoAtLeast(major, minor int) bool
    + + +
        func (r *Request) Referer() string
    + + +
        func (r *Request) SetBasicAuth(username, password string)
    + + +
        func (r *Request) UserAgent() string
    + + +
        func (r *Request) Write(w io.Writer) error
    + + +
        func (r *Request) WriteProxy(w io.Writer) error
    + + + +
    type Response
    + + +
        func Get(url string) (resp *Response, err error)
    + + +
        func Head(url string) (resp *Response, err error)
    + + +
        func Post(url string, bodyType string, body io.Reader) (resp *Response, err error)
    + + +
        func PostForm(url string, data url.Values) (resp *Response, err error)
    + + +
        func ReadResponse(r *bufio.Reader, req *Request) (*Response, error)
    + + + +
        func (r *Response) Cookies() []*Cookie
    + + +
        func (r *Response) Location() (*url.URL, error)
    + + +
        func (r *Response) ProtoAtLeast(major, minor int) bool
    + + +
        func (r *Response) Write(w io.Writer) error
    + + + +
    type ResponseWriter
    + + + + +
    type RoundTripper
    + + +
        func NewFileTransport(fs FileSystem) RoundTripper
    + + + + +
    type ServeMux
    + + +
        func NewServeMux() *ServeMux
    + + + +
        func (mux *ServeMux) Handle(pattern string, handler Handler)
    + + +
        func (mux *ServeMux) HandleFunc(pattern string, handler func(ResponseWriter, *Request))
    + + +
        func (mux *ServeMux) Handler(r *Request) (h Handler, pattern string)
    + + +
        func (mux *ServeMux) ServeHTTP(w ResponseWriter, r *Request)
    + + + +
    type Server
    + + + +
        func (srv *Server) ListenAndServe() error
    + + +
        func (srv *Server) ListenAndServeTLS(certFile, keyFile string) error
    + + +
        func (srv *Server) Serve(l net.Listener) error
    + + +
        func (srv *Server) SetKeepAlivesEnabled(v bool)
    + + + +
    type Transport
    + + + +
        func (t *Transport) CancelRequest(req *Request)
    + + +
        func (t *Transport) CloseIdleConnections()
    + + +
        func (t *Transport) RegisterProtocol(scheme string, rt RoundTripper)
    + + +
        func (t *Transport) RoundTrip(req *Request) (*Response, error)
    + + + +
    +
    + + + + + + +

    Package files

    +

    + + + client.go + + cookie.go + + doc.go + + filetransport.go + + fs.go + + h2_bundle.go + + header.go + + jar.go + + lex.go + + method.go + + request.go + + response.go + + server.go + + sniff.go + + status.go + + transfer.go + + transport.go + + +

    + +
    +
    + + + + +

    Constants

    + +
    const (
    +    MethodGet     = "GET"
    +    MethodHead    = "HEAD"
    +    MethodPost    = "POST"
    +    MethodPut     = "PUT"
    +    MethodPatch   = "PATCH" // RFC 5741
    +    MethodDelete  = "DELETE"
    +    MethodConnect = "CONNECT"
    +    MethodOptions = "OPTIONS"
    +    MethodTrace   = "TRACE"
    +)
    +

    +Common HTTP methods. +

    +

    +Unless otherwise noted, these are defined in RFC 7231 section 4.3. +

    + + +
    const (
    +    StatusContinue           = 100
    +    StatusSwitchingProtocols = 101
    +
    +    StatusOK                   = 200
    +    StatusCreated              = 201
    +    StatusAccepted             = 202
    +    StatusNonAuthoritativeInfo = 203
    +    StatusNoContent            = 204
    +    StatusResetContent         = 205
    +    StatusPartialContent       = 206
    +
    +    StatusMultipleChoices   = 300
    +    StatusMovedPermanently  = 301
    +    StatusFound             = 302
    +    StatusSeeOther          = 303
    +    StatusNotModified       = 304
    +    StatusUseProxy          = 305
    +    StatusTemporaryRedirect = 307
    +
    +    StatusBadRequest                   = 400
    +    StatusUnauthorized                 = 401
    +    StatusPaymentRequired              = 402
    +    StatusForbidden                    = 403
    +    StatusNotFound                     = 404
    +    StatusMethodNotAllowed             = 405
    +    StatusNotAcceptable                = 406
    +    StatusProxyAuthRequired            = 407
    +    StatusRequestTimeout               = 408
    +    StatusConflict                     = 409
    +    StatusGone                         = 410
    +    StatusLengthRequired               = 411
    +    StatusPreconditionFailed           = 412
    +    StatusRequestEntityTooLarge        = 413
    +    StatusRequestURITooLong            = 414
    +    StatusUnsupportedMediaType         = 415
    +    StatusRequestedRangeNotSatisfiable = 416
    +    StatusExpectationFailed            = 417
    +    StatusTeapot                       = 418
    +    StatusPreconditionRequired         = 428
    +    StatusTooManyRequests              = 429
    +    StatusRequestHeaderFieldsTooLarge  = 431
    +    StatusUnavailableForLegalReasons   = 451
    +
    +    StatusInternalServerError           = 500
    +    StatusNotImplemented                = 501
    +    StatusBadGateway                    = 502
    +    StatusServiceUnavailable            = 503
    +    StatusGatewayTimeout                = 504
    +    StatusHTTPVersionNotSupported       = 505
    +    StatusNetworkAuthenticationRequired = 511
    +)
    +

    +HTTP status codes, defined in RFC 2616. +

    + + +
    const DefaultMaxHeaderBytes = 1 << 20 // 1 MB
    +
    +

    +DefaultMaxHeaderBytes is the maximum permitted size of the headers +in an HTTP request. +This can be overridden by setting Server.MaxHeaderBytes. +

    + + +
    const DefaultMaxIdleConnsPerHost = 2
    +

    +DefaultMaxIdleConnsPerHost is the default value of Transport's +MaxIdleConnsPerHost. +

    + + +
    const TimeFormat = "Mon, 02 Jan 2006 15:04:05 GMT"
    +

    +TimeFormat is the time format to use when generating times in HTTP +headers. It is like time.RFC1123 but hard-codes GMT as the time +zone. The time being formatted must be in UTC for Format to +generate the correct format. +

    +

    +For parsing this time format, see ParseTime. +

    + + + + +

    Variables

    + +
    var (
    +    ErrHeaderTooLong        = &ProtocolError{"header too long"}
    +    ErrShortBody            = &ProtocolError{"entity body too short"}
    +    ErrNotSupported         = &ProtocolError{"feature not supported"}
    +    ErrUnexpectedTrailer    = &ProtocolError{"trailer header without chunked transfer encoding"}
    +    ErrMissingContentLength = &ProtocolError{"missing ContentLength in HEAD response"}
    +    ErrNotMultipart         = &ProtocolError{"request Content-Type isn't multipart/form-data"}
    +    ErrMissingBoundary      = &ProtocolError{"no multipart boundary param in Content-Type"}
    +)
    + + +
    var (
    +    ErrWriteAfterFlush = errors.New("Conn.Write called after Flush")
    +    ErrBodyNotAllowed  = errors.New("http: request method or response status code does not allow body")
    +    ErrHijacked        = errors.New("Conn has been hijacked")
    +    ErrContentLength   = errors.New("Conn.Write wrote more than the declared Content-Length")
    +)
    +

    +Errors introduced by the HTTP server. +

    + + +
    var DefaultClient = &Client{}
    +

    +DefaultClient is the default Client and is used by Get, Head, and Post. +

    + + +
    var DefaultServeMux = NewServeMux()
    +

    +DefaultServeMux is the default ServeMux used by Serve. +

    + + +
    var ErrBodyReadAfterClose = errors.New("http: invalid Read on closed Body")
    +

    +ErrBodyReadAfterClose is returned when reading a Request or Response +Body after the body has been closed. This typically happens when the body is +read after an HTTP Handler calls WriteHeader or Write on its +ResponseWriter. +

    + + +
    var ErrHandlerTimeout = errors.New("http: Handler timeout")
    +

    +ErrHandlerTimeout is returned on ResponseWriter Write calls +in handlers which have timed out. +

    + + +
    var ErrLineTooLong = internal.ErrLineTooLong
    +

    +ErrLineTooLong is returned when reading request or response bodies +with malformed chunked encoding. +

    + + +
    var ErrMissingFile = errors.New("http: no such file")
    +

    +ErrMissingFile is returned by FormFile when the provided file field name +is either not present in the request or not a file field. +

    + + +
    var ErrNoCookie = errors.New("http: named cookie not present")
    +

    +ErrNoCookie is returned by Request's Cookie method when a cookie is not found. +

    + + +
    var ErrNoLocation = errors.New("http: no Location header in response")
    +

    +ErrNoLocation is returned by Response's Location method +when no Location header is present. +

    + + +
    var ErrSkipAltProtocol = errors.New("net/http: skip alternate protocol")
    +

    +ErrSkipAltProtocol is a sentinel error value defined by Transport.RegisterProtocol. +

    + + + + + + +

    func CanonicalHeaderKey

    +
    func CanonicalHeaderKey(s string) string
    +

    +CanonicalHeaderKey returns the canonical format of the +header key s. The canonicalization converts the first +letter and any letter following a hyphen to upper case; +the rest are converted to lowercase. For example, the +canonical key for "accept-encoding" is "Accept-Encoding". +If s contains a space or invalid header field bytes, it is +returned without modifications. +

    + + + + + + + +

    func DetectContentType

    +
    func DetectContentType(data []byte) string
    +

    +DetectContentType implements the algorithm described +at http://mimesniff.spec.whatwg.org/ to determine the +Content-Type of the given data. It considers at most the +first 512 bytes of data. DetectContentType always returns +a valid MIME type: if it cannot determine a more specific one, it +returns "application/octet-stream". +

    + + + + + + + +

    func Error

    +
    func Error(w ResponseWriter, error string, code int)
    +

    +Error replies to the request with the specified error message and HTTP code. +The error message should be plain text. +

    + + + + + + + +

    func Handle

    +
    func Handle(pattern string, handler Handler)
    +

    +Handle registers the handler for the given pattern +in the DefaultServeMux. +The documentation for ServeMux explains how patterns are matched. +

    + + + + + + + +

    func HandleFunc

    +
    func HandleFunc(pattern string, handler func(ResponseWriter, *Request))
    +

    +HandleFunc registers the handler function for the given pattern +in the DefaultServeMux. +The documentation for ServeMux explains how patterns are matched. +

    + + + + + + + +

    func ListenAndServe

    +
    func ListenAndServe(addr string, handler Handler) error
    +

    +ListenAndServe listens on the TCP network address addr +and then calls Serve with handler to handle requests +on incoming connections. +Accepted connections are configured to enable TCP keep-alives. +Handler is typically nil, in which case the DefaultServeMux is +used. +

    +

    +A trivial example server is: +

    +
    package main
    +
    +import (
    +	"io"
    +	"net/http"
    +	"log"
    +)
    +
    +// hello world, the web server
    +func HelloServer(w http.ResponseWriter, req *http.Request) {
    +	io.WriteString(w, "hello, world!\n")
    +}
    +
    +func main() {
    +	http.HandleFunc("/hello", HelloServer)
    +	log.Fatal(http.ListenAndServe(":12345", nil))
    +}
    +
    +

    +ListenAndServe always returns a non-nil error. +

    + + + + + + + +

    func ListenAndServeTLS

    +
    func ListenAndServeTLS(addr, certFile, keyFile string, handler Handler) error
    +

    +ListenAndServeTLS acts identically to ListenAndServe, except that it +expects HTTPS connections. Additionally, files containing a certificate and +matching private key for the server must be provided. If the certificate +is signed by a certificate authority, the certFile should be the concatenation +of the server's certificate, any intermediates, and the CA's certificate. +

    +

    +A trivial example server is: +

    +
    import (
    +	"log"
    +	"net/http"
    +)
    +
    +func handler(w http.ResponseWriter, req *http.Request) {
    +	w.Header().Set("Content-Type", "text/plain")
    +	w.Write([]byte("This is an example server.\n"))
    +}
    +
    +func main() {
    +	http.HandleFunc("/", handler)
    +	log.Printf("About to listen on 10443. Go to https://127.0.0.1:10443/")
    +	err := http.ListenAndServeTLS(":10443", "cert.pem", "key.pem", nil)
    +	log.Fatal(err)
    +}
    +
    +

    +One can use generate_cert.go in crypto/tls to generate cert.pem and key.pem. +

    +

    +ListenAndServeTLS always returns a non-nil error. +

    + + + + + + + +

    func MaxBytesReader

    +
    func MaxBytesReader(w ResponseWriter, r io.ReadCloser, n int64) io.ReadCloser
    +

    +MaxBytesReader is similar to io.LimitReader but is intended for +limiting the size of incoming request bodies. In contrast to +io.LimitReader, MaxBytesReader's result is a ReadCloser, returns a +non-EOF error for a Read beyond the limit, and closes the +underlying reader when its Close method is called. +

    +

    +MaxBytesReader prevents clients from accidentally or maliciously +sending a large request and wasting server resources. +

    + + + + + + + +

    func NotFound

    +
    func NotFound(w ResponseWriter, r *Request)
    +

    +NotFound replies to the request with an HTTP 404 not found error. +

    + + + + + + + +

    func ParseHTTPVersion

    +
    func ParseHTTPVersion(vers string) (major, minor int, ok bool)
    +

    +ParseHTTPVersion parses a HTTP version string. +"HTTP/1.0" returns (1, 0, true). +

    + + + + + + + +

    func ParseTime

    +
    func ParseTime(text string) (t time.Time, err error)
    +

    +ParseTime parses a time header (such as the Date: header), +trying each of the three formats allowed by HTTP/1.1: +TimeFormat, time.RFC850, and time.ANSIC. +

    + + + + + + + +

    func ProxyFromEnvironment

    +
    func ProxyFromEnvironment(req *Request) (*url.URL, error)
    +

    +ProxyFromEnvironment returns the URL of the proxy to use for a +given request, as indicated by the environment variables +HTTP_PROXY, HTTPS_PROXY and NO_PROXY (or the lowercase versions +thereof). HTTPS_PROXY takes precedence over HTTP_PROXY for https +requests. +

    +

    +The environment values may be either a complete URL or a +"host[:port]", in which case the "http" scheme is assumed. +An error is returned if the value is a different form. +

    +

    +A nil URL and nil error are returned if no proxy is defined in the +environment, or a proxy should not be used for the given request, +as defined by NO_PROXY. +

    +

    +As a special case, if req.URL.Host is "localhost" (with or without +a port number), then a nil URL and nil error will be returned. +

    + + + + + + + +

    func ProxyURL

    +
    func ProxyURL(fixedURL *url.URL) func(*Request) (*url.URL, error)
    +

    +ProxyURL returns a proxy function (for use in a Transport) +that always returns the same URL. +

    + + + + + + + +

    func Redirect

    +
    func Redirect(w ResponseWriter, r *Request, urlStr string, code int)
    +

    +Redirect replies to the request with a redirect to url, +which may be a path relative to the request path. +

    +

    +The provided code should be in the 3xx range and is usually +StatusMovedPermanently, StatusFound or StatusSeeOther. +

    + + + + + + + +

    func Serve

    +
    func Serve(l net.Listener, handler Handler) error
    +

    +Serve accepts incoming HTTP connections on the listener l, +creating a new service goroutine for each. The service goroutines +read requests and then call handler to reply to them. +Handler is typically nil, in which case the DefaultServeMux is used. +

    + + + + + + + +

    func ServeContent

    +
    func ServeContent(w ResponseWriter, req *Request, name string, modtime time.Time, content io.ReadSeeker)
    +

    +ServeContent replies to the request using the content in the +provided ReadSeeker. The main benefit of ServeContent over io.Copy +is that it handles Range requests properly, sets the MIME type, and +handles If-Modified-Since requests. +

    +

    +If the response's Content-Type header is not set, ServeContent +first tries to deduce the type from name's file extension and, +if that fails, falls back to reading the first block of the content +and passing it to DetectContentType. +The name is otherwise unused; in particular it can be empty and is +never sent in the response. +

    +

    +If modtime is not the zero time or Unix epoch, ServeContent +includes it in a Last-Modified header in the response. If the +request includes an If-Modified-Since header, ServeContent uses +modtime to decide whether the content needs to be sent at all. +

    +

    +The content's Seek method must work: ServeContent uses +a seek to the end of the content to determine its size. +

    +

    +If the caller has set w's ETag header, ServeContent uses it to +handle requests using If-Range and If-None-Match. +

    +

    +Note that *os.File implements the io.ReadSeeker interface. +

    + + + + + + + +

    func ServeFile

    +
    func ServeFile(w ResponseWriter, r *Request, name string)
    +

    +ServeFile replies to the request with the contents of the named +file or directory. +

    +

    +If the provided file or direcory name is a relative path, it is +interpreted relative to the current directory and may ascend to parent +directories. If the provided name is constructed from user input, it +should be sanitized before calling ServeFile. As a precaution, ServeFile +will reject requests where r.URL.Path contains a ".." path element. +

    +

    +As a special case, ServeFile redirects any request where r.URL.Path +ends in "/index.html" to the same path, without the final +"index.html". To avoid such redirects either modify the path or +use ServeContent. +

    + + + + + + + +

    func SetCookie

    +
    func SetCookie(w ResponseWriter, cookie *Cookie)
    +

    +SetCookie adds a Set-Cookie header to the provided ResponseWriter's headers. +The provided cookie must have a valid Name. Invalid cookies may be +silently dropped. +

    + + + + + + + +

    func StatusText

    +
    func StatusText(code int) string
    +

    +StatusText returns a text for the HTTP status code. It returns the empty +string if the code is unknown. +

    + + + + + + + + +

    type Client

    +
    type Client struct {
    +    // Transport specifies the mechanism by which individual
    +    // HTTP requests are made.
    +    // If nil, DefaultTransport is used.
    +    Transport RoundTripper
    +
    +    // CheckRedirect specifies the policy for handling redirects.
    +    // If CheckRedirect is not nil, the client calls it before
    +    // following an HTTP redirect. The arguments req and via are
    +    // the upcoming request and the requests made already, oldest
    +    // first. If CheckRedirect returns an error, the Client's Get
    +    // method returns both the previous Response and
    +    // CheckRedirect's error (wrapped in a url.Error) instead of
    +    // issuing the Request req.
    +    //
    +    // If CheckRedirect is nil, the Client uses its default policy,
    +    // which is to stop after 10 consecutive requests.
    +    CheckRedirect func(req *Request, via []*Request) error
    +
    +    // Jar specifies the cookie jar.
    +    // If Jar is nil, cookies are not sent in requests and ignored
    +    // in responses.
    +    Jar CookieJar
    +
    +    // Timeout specifies a time limit for requests made by this
    +    // Client. The timeout includes connection time, any
    +    // redirects, and reading the response body. The timer remains
    +    // running after Get, Head, Post, or Do return and will
    +    // interrupt reading of the Response.Body.
    +    //
    +    // A Timeout of zero means no timeout.
    +    //
    +    // The Client cancels requests to the underlying Transport
    +    // using the Request.Cancel mechanism. Requests passed
    +    // to Client.Do may still set Request.Cancel; both will
    +    // cancel the request.
    +    //
    +    // For compatibility, the Client will also use the deprecated
    +    // CancelRequest method on Transport if found. New
    +    // RoundTripper implementations should use Request.Cancel
    +    // instead of implementing CancelRequest.
    +    Timeout time.Duration
    +}
    +

    +A Client is an HTTP client. Its zero value (DefaultClient) is a +usable client that uses DefaultTransport. +

    +

    +The Client's Transport typically has internal state (cached TCP +connections), so Clients should be reused instead of created as +needed. Clients are safe for concurrent use by multiple goroutines. +

    +

    +A Client is higher-level than a RoundTripper (such as Transport) +and additionally handles HTTP details such as cookies and +redirects. +

    + + + + + + + + + + + + + + +

    func (*Client) Do

    +
    func (c *Client) Do(req *Request) (resp *Response, err error)
    +

    +Do sends an HTTP request and returns an HTTP response, following +policy (e.g. redirects, cookies, auth) as configured on the client. +

    +

    +An error is returned if caused by client policy (such as +CheckRedirect), or if there was an HTTP protocol error. +A non-2xx response doesn't cause an error. +

    +

    +When err is nil, resp always contains a non-nil resp.Body. +

    +

    +Callers should close resp.Body when done reading from it. If +resp.Body is not closed, the Client's underlying RoundTripper +(typically Transport) may not be able to re-use a persistent TCP +connection to the server for a subsequent "keep-alive" request. +

    +

    +The request Body, if non-nil, will be closed by the underlying +Transport, even on errors. +

    +

    +Generally Get, Post, or PostForm will be used instead of Do. +

    + + + + + + +

    func (*Client) Get

    +
    func (c *Client) Get(url string) (resp *Response, err error)
    +

    +Get issues a GET to the specified URL. If the response is one of the +following redirect codes, Get follows the redirect after calling the +Client's CheckRedirect function: +

    +
    301 (Moved Permanently)
    +302 (Found)
    +303 (See Other)
    +307 (Temporary Redirect)
    +
    +

    +An error is returned if the Client's CheckRedirect function fails +or if there was an HTTP protocol error. A non-2xx response doesn't +cause an error. +

    +

    +When err is nil, resp always contains a non-nil resp.Body. +Caller should close resp.Body when done reading from it. +

    +

    +To make a request with custom headers, use NewRequest and Client.Do. +

    + + + + + + +

    func (*Client) Head

    +
    func (c *Client) Head(url string) (resp *Response, err error)
    +

    +Head issues a HEAD to the specified URL. If the response is one of the +following redirect codes, Head follows the redirect after calling the +Client's CheckRedirect function: +

    +
    301 (Moved Permanently)
    +302 (Found)
    +303 (See Other)
    +307 (Temporary Redirect)
    +
    + + + + + + +

    func (*Client) Post

    +
    func (c *Client) Post(url string, bodyType string, body io.Reader) (resp *Response, err error)
    +

    +Post issues a POST to the specified URL. +

    +

    +Caller should close resp.Body when done reading from it. +

    +

    +If the provided body is an io.Closer, it is closed after the +request. +

    +

    +To set custom headers, use NewRequest and Client.Do. +

    + + + + + + +

    func (*Client) PostForm

    +
    func (c *Client) PostForm(url string, data url.Values) (resp *Response, err error)
    +

    +PostForm issues a POST to the specified URL, +with data's keys and values URL-encoded as the request body. +

    +

    +The Content-Type header is set to application/x-www-form-urlencoded. +To set other headers, use NewRequest and DefaultClient.Do. +

    +

    +When err is nil, resp always contains a non-nil resp.Body. +Caller should close resp.Body when done reading from it. +

    + + + + + + + + +

    type CloseNotifier

    +
    type CloseNotifier interface {
    +    // CloseNotify returns a channel that receives at most a
    +    // single value (true) when the client connection has gone
    +    // away.
    +    //
    +    // CloseNotify may wait to notify until Request.Body has been
    +    // fully read.
    +    //
    +    // After the Handler has returned, there is no guarantee
    +    // that the channel receives a value.
    +    //
    +    // If the protocol is HTTP/1.1 and CloseNotify is called while
    +    // processing an idempotent request (such a GET) while
    +    // HTTP/1.1 pipelining is in use, the arrival of a subsequent
    +    // pipelined request may cause a value to be sent on the
    +    // returned channel. In practice HTTP/1.1 pipelining is not
    +    // enabled in browsers and not seen often in the wild. If this
    +    // is a problem, use HTTP/2 or only use CloseNotify on methods
    +    // such as POST.
    +    CloseNotify() <-chan bool
    +}
    +

    +The CloseNotifier interface is implemented by ResponseWriters which +allow detecting when the underlying connection has gone away. +

    +

    +This mechanism can be used to cancel long operations on the server +if the client has disconnected before the response is ready. +

    + + + + + + + + + + + + + + + + +

    type ConnState

    +
    type ConnState int
    +

    +A ConnState represents the state of a client connection to a server. +It's used by the optional Server.ConnState hook. +

    + + + +
    const (
    +    // StateNew represents a new connection that is expected to
    +    // send a request immediately. Connections begin at this
    +    // state and then transition to either StateActive or
    +    // StateClosed.
    +    StateNew ConnState = iota
    +
    +    // StateActive represents a connection that has read 1 or more
    +    // bytes of a request. The Server.ConnState hook for
    +    // StateActive fires before the request has entered a handler
    +    // and doesn't fire again until the request has been
    +    // handled. After the request is handled, the state
    +    // transitions to StateClosed, StateHijacked, or StateIdle.
    +    // For HTTP/2, StateActive fires on the transition from zero
    +    // to one active request, and only transitions away once all
    +    // active requests are complete. That means that ConnState
    +    // can not be used to do per-request work; ConnState only notes
    +    // the overall state of the connection.
    +    StateActive
    +
    +    // StateIdle represents a connection that has finished
    +    // handling a request and is in the keep-alive state, waiting
    +    // for a new request. Connections transition from StateIdle
    +    // to either StateActive or StateClosed.
    +    StateIdle
    +
    +    // StateHijacked represents a hijacked connection.
    +    // This is a terminal state. It does not transition to StateClosed.
    +    StateHijacked
    +
    +    // StateClosed represents a closed connection.
    +    // This is a terminal state. Hijacked connections do not
    +    // transition to StateClosed.
    +    StateClosed
    +)
    + + + + + + + + + + + + + +

    func (ConnState) String

    +
    func (c ConnState) String() string
    + + + + + + + + + +
    type Cookie struct {
    +    Name  string
    +    Value string
    +
    +    Path       string    // optional
    +    Domain     string    // optional
    +    Expires    time.Time // optional
    +    RawExpires string    // for reading cookies only
    +
    +    // MaxAge=0 means no 'Max-Age' attribute specified.
    +    // MaxAge<0 means delete cookie now, equivalently 'Max-Age: 0'
    +    // MaxAge>0 means Max-Age attribute present and given in seconds
    +    MaxAge   int
    +    Secure   bool
    +    HttpOnly bool
    +    Raw      string
    +    Unparsed []string // Raw text of unparsed attribute-value pairs
    +}
    +

    +A Cookie represents an HTTP cookie as sent in the Set-Cookie header of an +HTTP response or the Cookie header of an HTTP request. +

    +

    +See http://tools.ietf.org/html/rfc6265 for details. +

    + + + + + + + + + + + + + + +

    func (*Cookie) String

    +
    func (c *Cookie) String() string
    +

    +String returns the serialization of the cookie for use in a Cookie +header (if only Name and Value are set) or a Set-Cookie response +header (if other fields are set). +If c is nil or c.Name is invalid, the empty string is returned. +

    + + + + + + + + +

    type CookieJar

    +
    type CookieJar interface {
    +    // SetCookies handles the receipt of the cookies in a reply for the
    +    // given URL.  It may or may not choose to save the cookies, depending
    +    // on the jar's policy and implementation.
    +    SetCookies(u *url.URL, cookies []*Cookie)
    +
    +    // Cookies returns the cookies to send in a request for the given URL.
    +    // It is up to the implementation to honor the standard cookie use
    +    // restrictions such as in RFC 6265.
    +    Cookies(u *url.URL) []*Cookie
    +}
    +

    +A CookieJar manages storage and use of cookies in HTTP requests. +

    +

    +Implementations of CookieJar must be safe for concurrent use by multiple +goroutines. +

    +

    +The net/http/cookiejar package provides a CookieJar implementation. +

    + + + + + + + + + + + + + + + + +

    type Dir

    +
    type Dir string
    +

    +A Dir implements FileSystem using the native file system restricted to a +specific directory tree. +

    +

    +While the FileSystem.Open method takes '/'-separated paths, a Dir's string +value is a filename on the native file system, not a URL, so it is separated +by filepath.Separator, which isn't necessarily '/'. +

    +

    +An empty Dir is treated as ".". +

    + + + + + + + + + + + + + + +

    func (Dir) Open

    +
    func (d Dir) Open(name string) (File, error)
    + + + + + + + + +

    type File

    +
    type File interface {
    +    io.Closer
    +    io.Reader
    +    io.Seeker
    +    Readdir(count int) ([]os.FileInfo, error)
    +    Stat() (os.FileInfo, error)
    +}
    +

    +A File is returned by a FileSystem's Open method and can be +served by the FileServer implementation. +

    +

    +The methods should behave the same as those on an *os.File. +

    + + + + + + + + + + + + + + + + +

    type FileSystem

    +
    type FileSystem interface {
    +    Open(name string) (File, error)
    +}
    +

    +A FileSystem implements access to a collection of named files. +The elements in a file path are separated by slash ('/', U+002F) +characters, regardless of host operating system convention. +

    + + + + + + + + + + + + + + + + +

    type Flusher

    +
    type Flusher interface {
    +    // Flush sends any buffered data to the client.
    +    Flush()
    +}
    +

    +The Flusher interface is implemented by ResponseWriters that allow +an HTTP handler to flush buffered data to the client. +

    +

    +Note that even for ResponseWriters that support Flush, +if the client is connected through an HTTP proxy, +the buffered data may not reach the client until the response +completes. +

    + + + + + + + + + + + + + + + + +

    type Handler

    +
    type Handler interface {
    +    ServeHTTP(ResponseWriter, *Request)
    +}
    +

    +A Handler responds to an HTTP request. +

    +

    +ServeHTTP should write reply headers and data to the ResponseWriter +and then return. Returning signals that the request is finished; it +is not valid to use the ResponseWriter or read from the +Request.Body after or concurrently with the completion of the +ServeHTTP call. +

    +

    +Depending on the HTTP client software, HTTP protocol version, and +any intermediaries between the client and the Go server, it may not +be possible to read from the Request.Body after writing to the +ResponseWriter. Cautious handlers should read the Request.Body +first, and then reply. +

    +

    +If ServeHTTP panics, the server (the caller of ServeHTTP) assumes +that the effect of the panic was isolated to the active request. +It recovers the panic, logs a stack trace to the server error log, +and hangs up the connection. +

    + + + + + + + + + + + + +

    func FileServer

    +
    func FileServer(root FileSystem) Handler
    +

    +FileServer returns a handler that serves HTTP requests +with the contents of the file system rooted at root. +

    +

    +To use the operating system's file system implementation, +use http.Dir: +

    +
    http.Handle("/", http.FileServer(http.Dir("/tmp")))
    +
    +

    +As a special case, the returned file server redirects any request +ending in "/index.html" to the same path, without the final +"index.html". +

    + +
    + +
    +

    Example

    + + + +

    Code:

    +
    +// Simple static webserver:
    +log.Fatal(http.ListenAndServe(":8080", http.FileServer(http.Dir("/usr/share/doc"))))
    +
    + + +
    +
    +
    + +
    +

    Example (StripPrefix)

    + + + +

    Code:

    +
    +// To serve a directory on disk (/tmp) under an alternate URL
    +// path (/tmpfiles/), use StripPrefix to modify the request
    +// URL's path before the FileServer sees it:
    +http.Handle("/tmpfiles/", http.StripPrefix("/tmpfiles/", http.FileServer(http.Dir("/tmp"))))
    +
    + + +
    +
    + + + + +

    func NotFoundHandler

    +
    func NotFoundHandler() Handler
    +

    +NotFoundHandler returns a simple request handler +that replies to each request with a “404 page not found” reply. +

    + + + + + +

    func RedirectHandler

    +
    func RedirectHandler(url string, code int) Handler
    +

    +RedirectHandler returns a request handler that redirects +each request it receives to the given url using the given +status code. +

    +

    +The provided code should be in the 3xx range and is usually +StatusMovedPermanently, StatusFound or StatusSeeOther. +

    + + + + + +

    func StripPrefix

    +
    func StripPrefix(prefix string, h Handler) Handler
    +

    +StripPrefix returns a handler that serves HTTP requests +by removing the given prefix from the request URL's Path +and invoking the handler h. StripPrefix handles a +request for a path that doesn't begin with prefix by +replying with an HTTP 404 not found error. +

    + +
    + +
    +

    Example

    + + + +

    Code:

    +
    +// To serve a directory on disk (/tmp) under an alternate URL
    +// path (/tmpfiles/), use StripPrefix to modify the request
    +// URL's path before the FileServer sees it:
    +http.Handle("/tmpfiles/", http.StripPrefix("/tmpfiles/", http.FileServer(http.Dir("/tmp"))))
    +
    + + +
    +
    + + + + +

    func TimeoutHandler

    +
    func TimeoutHandler(h Handler, dt time.Duration, msg string) Handler
    +

    +TimeoutHandler returns a Handler that runs h with the given time limit. +

    +

    +The new Handler calls h.ServeHTTP to handle each request, but if a +call runs for longer than its time limit, the handler responds with +a 503 Service Unavailable error and the given message in its body. +(If msg is empty, a suitable default message will be sent.) +After such a timeout, writes by h to its ResponseWriter will return +ErrHandlerTimeout. +

    +

    +TimeoutHandler buffers all Handler writes to memory and does not +support the Hijacker or Flusher interfaces. +

    + + + + + + + + + +

    type HandlerFunc

    +
    type HandlerFunc func(ResponseWriter, *Request)
    +

    +The HandlerFunc type is an adapter to allow the use of +ordinary functions as HTTP handlers. If f is a function +with the appropriate signature, HandlerFunc(f) is a +Handler that calls f. +

    + + + + + + + + + + + + + + +

    func (HandlerFunc) ServeHTTP

    +
    func (f HandlerFunc) ServeHTTP(w ResponseWriter, r *Request)
    +

    +ServeHTTP calls f(w, r). +

    + + + + + + + + + +
    type Header map[string][]string
    +

    +A Header represents the key-value pairs in an HTTP header. +

    + + + + + + + + + + + + + + +

    func (Header) Add

    +
    func (h Header) Add(key, value string)
    +

    +Add adds the key, value pair to the header. +It appends to any existing values associated with key. +

    + + + + + + +

    func (Header) Del

    +
    func (h Header) Del(key string)
    +

    +Del deletes the values associated with key. +

    + + + + + + +

    func (Header) Get

    +
    func (h Header) Get(key string) string
    +

    +Get gets the first value associated with the given key. +If there are no values associated with the key, Get returns "". +To access multiple values of a key, access the map directly +with CanonicalHeaderKey. +

    + + + + + + +

    func (Header) Set

    +
    func (h Header) Set(key, value string)
    +

    +Set sets the header entries associated with key to +the single element value. It replaces any existing +values associated with key. +

    + + + + + + +

    func (Header) Write

    +
    func (h Header) Write(w io.Writer) error
    +

    +Write writes a header in wire format. +

    + + + + + + +

    func (Header) WriteSubset

    +
    func (h Header) WriteSubset(w io.Writer, exclude map[string]bool) error
    +

    +WriteSubset writes a header in wire format. +If exclude is not nil, keys where exclude[key] == true are not written. +

    + + + + + + + + +

    type Hijacker

    +
    type Hijacker interface {
    +    // Hijack lets the caller take over the connection.
    +    // After a call to Hijack(), the HTTP server library
    +    // will not do anything else with the connection.
    +    //
    +    // It becomes the caller's responsibility to manage
    +    // and close the connection.
    +    //
    +    // The returned net.Conn may have read or write deadlines
    +    // already set, depending on the configuration of the
    +    // Server. It is the caller's responsibility to set
    +    // or clear those deadlines as needed.
    +    Hijack() (net.Conn, *bufio.ReadWriter, error)
    +}
    +

    +The Hijacker interface is implemented by ResponseWriters that allow +an HTTP handler to take over the connection. +

    + + + + + + +
    + +
    +

    Example

    + + + +

    Code:

    +
    +http.HandleFunc("/hijack", func(w http.ResponseWriter, r *http.Request) {
    +    hj, ok := w.(http.Hijacker)
    +    if !ok {
    +        http.Error(w, "webserver doesn't support hijacking", http.StatusInternalServerError)
    +        return
    +    }
    +    conn, bufrw, err := hj.Hijack()
    +    if err != nil {
    +        http.Error(w, err.Error(), http.StatusInternalServerError)
    +        return
    +    }
    +    // Don't forget to close the connection:
    +    defer conn.Close()
    +    bufrw.WriteString("Now we're speaking raw TCP. Say hi: ")
    +    bufrw.Flush()
    +    s, err := bufrw.ReadString('\n')
    +    if err != nil {
    +        log.Printf("error reading string: %v", err)
    +        return
    +    }
    +    fmt.Fprintf(bufrw, "You said: %q\nBye.\n", s)
    +    bufrw.Flush()
    +})
    +
    + + +
    +
    + + + + + + + + + + +

    type ProtocolError

    +
    type ProtocolError struct {
    +    ErrorString string
    +}
    +

    +HTTP request parsing errors. +

    + + + + + + + + + + + + + + +

    func (*ProtocolError) Error

    +
    func (err *ProtocolError) Error() string
    + + + + + + + + +

    type Request

    +
    type Request struct {
    +    // Method specifies the HTTP method (GET, POST, PUT, etc.).
    +    // For client requests an empty string means GET.
    +    Method string
    +
    +    // URL specifies either the URI being requested (for server
    +    // requests) or the URL to access (for client requests).
    +    //
    +    // For server requests the URL is parsed from the URI
    +    // supplied on the Request-Line as stored in RequestURI.  For
    +    // most requests, fields other than Path and RawQuery will be
    +    // empty. (See RFC 2616, Section 5.1.2)
    +    //
    +    // For client requests, the URL's Host specifies the server to
    +    // connect to, while the Request's Host field optionally
    +    // specifies the Host header value to send in the HTTP
    +    // request.
    +    URL *url.URL
    +
    +    // The protocol version for incoming server requests.
    +    //
    +    // For client requests these fields are ignored. The HTTP
    +    // client code always uses either HTTP/1.1 or HTTP/2.
    +    // See the docs on Transport for details.
    +    Proto      string // "HTTP/1.0"
    +    ProtoMajor int    // 1
    +    ProtoMinor int    // 0
    +
    +    // Header contains the request header fields either received
    +    // by the server or to be sent by the client.
    +    //
    +    // If a server received a request with header lines,
    +    //
    +    //	Host: example.com
    +    //	accept-encoding: gzip, deflate
    +    //	Accept-Language: en-us
    +    //	fOO: Bar
    +    //	foo: two
    +    //
    +    // then
    +    //
    +    //	Header = map[string][]string{
    +    //		"Accept-Encoding": {"gzip, deflate"},
    +    //		"Accept-Language": {"en-us"},
    +    //		"Foo": {"Bar", "two"},
    +    //	}
    +    //
    +    // For incoming requests, the Host header is promoted to the
    +    // Request.Host field and removed from the Header map.
    +    //
    +    // HTTP defines that header names are case-insensitive. The
    +    // request parser implements this by using CanonicalHeaderKey,
    +    // making the first character and any characters following a
    +    // hyphen uppercase and the rest lowercase.
    +    //
    +    // For client requests, certain headers such as Content-Length
    +    // and Connection are automatically written when needed and
    +    // values in Header may be ignored. See the documentation
    +    // for the Request.Write method.
    +    Header Header
    +
    +    // Body is the request's body.
    +    //
    +    // For client requests a nil body means the request has no
    +    // body, such as a GET request. The HTTP Client's Transport
    +    // is responsible for calling the Close method.
    +    //
    +    // For server requests the Request Body is always non-nil
    +    // but will return EOF immediately when no body is present.
    +    // The Server will close the request body. The ServeHTTP
    +    // Handler does not need to.
    +    Body io.ReadCloser
    +
    +    // ContentLength records the length of the associated content.
    +    // The value -1 indicates that the length is unknown.
    +    // Values >= 0 indicate that the given number of bytes may
    +    // be read from Body.
    +    // For client requests, a value of 0 means unknown if Body is not nil.
    +    ContentLength int64
    +
    +    // TransferEncoding lists the transfer encodings from outermost to
    +    // innermost. An empty list denotes the "identity" encoding.
    +    // TransferEncoding can usually be ignored; chunked encoding is
    +    // automatically added and removed as necessary when sending and
    +    // receiving requests.
    +    TransferEncoding []string
    +
    +    // Close indicates whether to close the connection after
    +    // replying to this request (for servers) or after sending this
    +    // request and reading its response (for clients).
    +    //
    +    // For server requests, the HTTP server handles this automatically
    +    // and this field is not needed by Handlers.
    +    //
    +    // For client requests, setting this field prevents re-use of
    +    // TCP connections between requests to the same hosts, as if
    +    // Transport.DisableKeepAlives were set.
    +    Close bool
    +
    +    // For server requests Host specifies the host on which the
    +    // URL is sought. Per RFC 2616, this is either the value of
    +    // the "Host" header or the host name given in the URL itself.
    +    // It may be of the form "host:port".
    +    //
    +    // For client requests Host optionally overrides the Host
    +    // header to send. If empty, the Request.Write method uses
    +    // the value of URL.Host.
    +    Host string
    +
    +    // Form contains the parsed form data, including both the URL
    +    // field's query parameters and the POST or PUT form data.
    +    // This field is only available after ParseForm is called.
    +    // The HTTP client ignores Form and uses Body instead.
    +    Form url.Values
    +
    +    // PostForm contains the parsed form data from POST, PATCH,
    +    // or PUT body parameters.
    +    //
    +    // This field is only available after ParseForm is called.
    +    // The HTTP client ignores PostForm and uses Body instead.
    +    PostForm url.Values
    +
    +    // MultipartForm is the parsed multipart form, including file uploads.
    +    // This field is only available after ParseMultipartForm is called.
    +    // The HTTP client ignores MultipartForm and uses Body instead.
    +    MultipartForm *multipart.Form
    +
    +    // Trailer specifies additional headers that are sent after the request
    +    // body.
    +    //
    +    // For server requests the Trailer map initially contains only the
    +    // trailer keys, with nil values. (The client declares which trailers it
    +    // will later send.)  While the handler is reading from Body, it must
    +    // not reference Trailer. After reading from Body returns EOF, Trailer
    +    // can be read again and will contain non-nil values, if they were sent
    +    // by the client.
    +    //
    +    // For client requests Trailer must be initialized to a map containing
    +    // the trailer keys to later send. The values may be nil or their final
    +    // values. The ContentLength must be 0 or -1, to send a chunked request.
    +    // After the HTTP request is sent the map values can be updated while
    +    // the request body is read. Once the body returns EOF, the caller must
    +    // not mutate Trailer.
    +    //
    +    // Few HTTP clients, servers, or proxies support HTTP trailers.
    +    Trailer Header
    +
    +    // RemoteAddr allows HTTP servers and other software to record
    +    // the network address that sent the request, usually for
    +    // logging. This field is not filled in by ReadRequest and
    +    // has no defined format. The HTTP server in this package
    +    // sets RemoteAddr to an "IP:port" address before invoking a
    +    // handler.
    +    // This field is ignored by the HTTP client.
    +    RemoteAddr string
    +
    +    // RequestURI is the unmodified Request-URI of the
    +    // Request-Line (RFC 2616, Section 5.1) as sent by the client
    +    // to a server. Usually the URL field should be used instead.
    +    // It is an error to set this field in an HTTP client request.
    +    RequestURI string
    +
    +    // TLS allows HTTP servers and other software to record
    +    // information about the TLS connection on which the request
    +    // was received. This field is not filled in by ReadRequest.
    +    // The HTTP server in this package sets the field for
    +    // TLS-enabled connections before invoking a handler;
    +    // otherwise it leaves the field nil.
    +    // This field is ignored by the HTTP client.
    +    TLS *tls.ConnectionState
    +
    +    // Cancel is an optional channel whose closure indicates that the client
    +    // request should be regarded as canceled. Not all implementations of
    +    // RoundTripper may support Cancel.
    +    //
    +    // For server requests, this field is not applicable.
    +    Cancel <-chan struct{}
    +}
    +

    +A Request represents an HTTP request received by a server +or to be sent by a client. +

    +

    +The field semantics differ slightly between client and server +usage. In addition to the notes on the fields below, see the +documentation for Request.Write and RoundTripper. +

    + + + + + + + + + + + + +

    func NewRequest

    +
    func NewRequest(method, urlStr string, body io.Reader) (*Request, error)
    +

    +NewRequest returns a new Request given a method, URL, and optional body. +

    +

    +If the provided body is also an io.Closer, the returned +Request.Body is set to body and will be closed by the Client +methods Do, Post, and PostForm, and Transport.RoundTrip. +

    +

    +NewRequest returns a Request suitable for use with Client.Do or +Transport.RoundTrip. +To create a request for use with testing a Server Handler use either +ReadRequest or manually update the Request fields. See the Request +type's documentation for the difference between inbound and outbound +request fields. +

    + + + + + +

    func ReadRequest

    +
    func ReadRequest(b *bufio.Reader) (req *Request, err error)
    +

    +ReadRequest reads and parses an incoming request from b. +

    + + + + + + + +

    func (*Request) AddCookie

    +
    func (r *Request) AddCookie(c *Cookie)
    +

    +AddCookie adds a cookie to the request. Per RFC 6265 section 5.4, +AddCookie does not attach more than one Cookie header field. That +means all cookies, if any, are written into the same line, +separated by semicolon. +

    + + + + + + +

    func (*Request) BasicAuth

    +
    func (r *Request) BasicAuth() (username, password string, ok bool)
    +

    +BasicAuth returns the username and password provided in the request's +Authorization header, if the request uses HTTP Basic Authentication. +See RFC 2617, Section 2. +

    + + + + + + +

    func (*Request) Cookie

    +
    func (r *Request) Cookie(name string) (*Cookie, error)
    +

    +Cookie returns the named cookie provided in the request or +ErrNoCookie if not found. +

    + + + + + + +

    func (*Request) Cookies

    +
    func (r *Request) Cookies() []*Cookie
    +

    +Cookies parses and returns the HTTP cookies sent with the request. +

    + + + + + + +

    func (*Request) FormFile

    +
    func (r *Request) FormFile(key string) (multipart.File, *multipart.FileHeader, error)
    +

    +FormFile returns the first file for the provided form key. +FormFile calls ParseMultipartForm and ParseForm if necessary. +

    + + + + + + +

    func (*Request) FormValue

    +
    func (r *Request) FormValue(key string) string
    +

    +FormValue returns the first value for the named component of the query. +POST and PUT body parameters take precedence over URL query string values. +FormValue calls ParseMultipartForm and ParseForm if necessary and ignores +any errors returned by these functions. +If key is not present, FormValue returns the empty string. +To access multiple values of the same key, call ParseForm and +then inspect Request.Form directly. +

    + + + + + + +

    func (*Request) MultipartReader

    +
    func (r *Request) MultipartReader() (*multipart.Reader, error)
    +

    +MultipartReader returns a MIME multipart reader if this is a +multipart/form-data POST request, else returns nil and an error. +Use this function instead of ParseMultipartForm to +process the request body as a stream. +

    + + + + + + +

    func (*Request) ParseForm

    +
    func (r *Request) ParseForm() error
    +

    +ParseForm parses the raw query from the URL and updates r.Form. +

    +

    +For POST or PUT requests, it also parses the request body as a form and +put the results into both r.PostForm and r.Form. +POST and PUT body parameters take precedence over URL query string values +in r.Form. +

    +

    +If the request Body's size has not already been limited by MaxBytesReader, +the size is capped at 10MB. +

    +

    +ParseMultipartForm calls ParseForm automatically. +It is idempotent. +

    + + + + + + +

    func (*Request) ParseMultipartForm

    +
    func (r *Request) ParseMultipartForm(maxMemory int64) error
    +

    +ParseMultipartForm parses a request body as multipart/form-data. +The whole request body is parsed and up to a total of maxMemory bytes of +its file parts are stored in memory, with the remainder stored on +disk in temporary files. +ParseMultipartForm calls ParseForm if necessary. +After one call to ParseMultipartForm, subsequent calls have no effect. +

    + + + + + + +

    func (*Request) PostFormValue

    +
    func (r *Request) PostFormValue(key string) string
    +

    +PostFormValue returns the first value for the named component of the POST +or PUT request body. URL query parameters are ignored. +PostFormValue calls ParseMultipartForm and ParseForm if necessary and ignores +any errors returned by these functions. +If key is not present, PostFormValue returns the empty string. +

    + + + + + + +

    func (*Request) ProtoAtLeast

    +
    func (r *Request) ProtoAtLeast(major, minor int) bool
    +

    +ProtoAtLeast reports whether the HTTP protocol used +in the request is at least major.minor. +

    + + + + + + +

    func (*Request) Referer

    +
    func (r *Request) Referer() string
    +

    +Referer returns the referring URL, if sent in the request. +

    +

    +Referer is misspelled as in the request itself, a mistake from the +earliest days of HTTP. This value can also be fetched from the +Header map as Header["Referer"]; the benefit of making it available +as a method is that the compiler can diagnose programs that use the +alternate (correct English) spelling req.Referrer() but cannot +diagnose programs that use Header["Referrer"]. +

    + + + + + + +

    func (*Request) SetBasicAuth

    +
    func (r *Request) SetBasicAuth(username, password string)
    +

    +SetBasicAuth sets the request's Authorization header to use HTTP +Basic Authentication with the provided username and password. +

    +

    +With HTTP Basic Authentication the provided username and password +are not encrypted. +

    + + + + + + +

    func (*Request) UserAgent

    +
    func (r *Request) UserAgent() string
    +

    +UserAgent returns the client's User-Agent, if sent in the request. +

    + + + + + + +

    func (*Request) Write

    +
    func (r *Request) Write(w io.Writer) error
    +

    +Write writes an HTTP/1.1 request, which is the header and body, in wire format. +This method consults the following fields of the request: +

    +
    Host
    +URL
    +Method (defaults to "GET")
    +Header
    +ContentLength
    +TransferEncoding
    +Body
    +
    +

    +If Body is present, Content-Length is <= 0 and TransferEncoding +hasn't been set to "identity", Write adds "Transfer-Encoding: +chunked" to the header. Body is closed after it is sent. +

    + + + + + + +

    func (*Request) WriteProxy

    +
    func (r *Request) WriteProxy(w io.Writer) error
    +

    +WriteProxy is like Write but writes the request in the form +expected by an HTTP proxy. In particular, WriteProxy writes the +initial Request-URI line of the request with an absolute URI, per +section 5.1.2 of RFC 2616, including the scheme and host. +In either case, WriteProxy also writes a Host header, using +either r.Host or r.URL.Host. +

    + + + + + + + + +

    type Response

    +
    type Response struct {
    +    Status     string // e.g. "200 OK"
    +    StatusCode int    // e.g. 200
    +    Proto      string // e.g. "HTTP/1.0"
    +    ProtoMajor int    // e.g. 1
    +    ProtoMinor int    // e.g. 0
    +
    +    // Header maps header keys to values.  If the response had multiple
    +    // headers with the same key, they may be concatenated, with comma
    +    // delimiters.  (Section 4.2 of RFC 2616 requires that multiple headers
    +    // be semantically equivalent to a comma-delimited sequence.) Values
    +    // duplicated by other fields in this struct (e.g., ContentLength) are
    +    // omitted from Header.
    +    //
    +    // Keys in the map are canonicalized (see CanonicalHeaderKey).
    +    Header Header
    +
    +    // Body represents the response body.
    +    //
    +    // The http Client and Transport guarantee that Body is always
    +    // non-nil, even on responses without a body or responses with
    +    // a zero-length body. It is the caller's responsibility to
    +    // close Body. The default HTTP client's Transport does not
    +    // attempt to reuse HTTP/1.0 or HTTP/1.1 TCP connections
    +    // ("keep-alive") unless the Body is read to completion and is
    +    // closed.
    +    //
    +    // The Body is automatically dechunked if the server replied
    +    // with a "chunked" Transfer-Encoding.
    +    Body io.ReadCloser
    +
    +    // ContentLength records the length of the associated content.  The
    +    // value -1 indicates that the length is unknown.  Unless Request.Method
    +    // is "HEAD", values >= 0 indicate that the given number of bytes may
    +    // be read from Body.
    +    ContentLength int64
    +
    +    // Contains transfer encodings from outer-most to inner-most. Value is
    +    // nil, means that "identity" encoding is used.
    +    TransferEncoding []string
    +
    +    // Close records whether the header directed that the connection be
    +    // closed after reading Body.  The value is advice for clients: neither
    +    // ReadResponse nor Response.Write ever closes a connection.
    +    Close bool
    +
    +    // Trailer maps trailer keys to values in the same
    +    // format as Header.
    +    //
    +    // The Trailer initially contains only nil values, one for
    +    // each key specified in the server's "Trailer" header
    +    // value. Those values are not added to Header.
    +    //
    +    // Trailer must not be accessed concurrently with Read calls
    +    // on the Body.
    +    //
    +    // After Body.Read has returned io.EOF, Trailer will contain
    +    // any trailer values sent by the server.
    +    Trailer Header
    +
    +    // The Request that was sent to obtain this Response.
    +    // Request's Body is nil (having already been consumed).
    +    // This is only populated for Client requests.
    +    Request *Request
    +
    +    // TLS contains information about the TLS connection on which the
    +    // response was received. It is nil for unencrypted responses.
    +    // The pointer is shared between responses and should not be
    +    // modified.
    +    TLS *tls.ConnectionState
    +}
    +

    +Response represents the response from an HTTP request. +

    + + + + + + + + + + + + +

    func Get

    +
    func Get(url string) (resp *Response, err error)
    +

    +Get issues a GET to the specified URL. If the response is one of +the following redirect codes, Get follows the redirect, up to a +maximum of 10 redirects: +

    +
    301 (Moved Permanently)
    +302 (Found)
    +303 (See Other)
    +307 (Temporary Redirect)
    +
    +

    +An error is returned if there were too many redirects or if there +was an HTTP protocol error. A non-2xx response doesn't cause an +error. +

    +

    +When err is nil, resp always contains a non-nil resp.Body. +Caller should close resp.Body when done reading from it. +

    +

    +Get is a wrapper around DefaultClient.Get. +

    +

    +To make a request with custom headers, use NewRequest and +DefaultClient.Do. +

    + +
    + +
    +

    Example

    + + + +

    Code:

    +
    +res, err := http.Get("http://www.google.com/robots.txt")
    +if err != nil {
    +    log.Fatal(err)
    +}
    +robots, err := ioutil.ReadAll(res.Body)
    +res.Body.Close()
    +if err != nil {
    +    log.Fatal(err)
    +}
    +fmt.Printf("%s", robots)
    +
    + + +
    +
    + + + + + +
    func Head(url string) (resp *Response, err error)
    +

    +Head issues a HEAD to the specified URL. If the response is one of +the following redirect codes, Head follows the redirect, up to a +maximum of 10 redirects: +

    +
    301 (Moved Permanently)
    +302 (Found)
    +303 (See Other)
    +307 (Temporary Redirect)
    +
    +

    +Head is a wrapper around DefaultClient.Head +

    + + + + + +

    func Post

    +
    func Post(url string, bodyType string, body io.Reader) (resp *Response, err error)
    +

    +Post issues a POST to the specified URL. +

    +

    +Caller should close resp.Body when done reading from it. +

    +

    +If the provided body is an io.Closer, it is closed after the +request. +

    +

    +Post is a wrapper around DefaultClient.Post. +

    +

    +To set custom headers, use NewRequest and DefaultClient.Do. +

    + + + + + +

    func PostForm

    +
    func PostForm(url string, data url.Values) (resp *Response, err error)
    +

    +PostForm issues a POST to the specified URL, with data's keys and +values URL-encoded as the request body. +

    +

    +The Content-Type header is set to application/x-www-form-urlencoded. +To set other headers, use NewRequest and DefaultClient.Do. +

    +

    +When err is nil, resp always contains a non-nil resp.Body. +Caller should close resp.Body when done reading from it. +

    +

    +PostForm is a wrapper around DefaultClient.PostForm. +

    + + + + + +

    func ReadResponse

    +
    func ReadResponse(r *bufio.Reader, req *Request) (*Response, error)
    +

    +ReadResponse reads and returns an HTTP response from r. +The req parameter optionally specifies the Request that corresponds +to this Response. If nil, a GET request is assumed. +Clients must call resp.Body.Close when finished reading resp.Body. +After that call, clients can inspect resp.Trailer to find key/value +pairs included in the response trailer. +

    + + + + + + + +

    func (*Response) Cookies

    +
    func (r *Response) Cookies() []*Cookie
    +

    +Cookies parses and returns the cookies set in the Set-Cookie headers. +

    + + + + + + +

    func (*Response) Location

    +
    func (r *Response) Location() (*url.URL, error)
    +

    +Location returns the URL of the response's "Location" header, +if present. Relative redirects are resolved relative to +the Response's Request. ErrNoLocation is returned if no +Location header is present. +

    + + + + + + +

    func (*Response) ProtoAtLeast

    +
    func (r *Response) ProtoAtLeast(major, minor int) bool
    +

    +ProtoAtLeast reports whether the HTTP protocol used +in the response is at least major.minor. +

    + + + + + + +

    func (*Response) Write

    +
    func (r *Response) Write(w io.Writer) error
    +

    +Write writes r to w in the HTTP/1.n server response format, +including the status line, headers, body, and optional trailer. +

    +

    +This method consults the following fields of the response r: +

    +
    StatusCode
    +ProtoMajor
    +ProtoMinor
    +Request.Method
    +TransferEncoding
    +Trailer
    +Body
    +ContentLength
    +Header, values for non-canonical keys will have unpredictable behavior
    +
    +

    +The Response Body is closed after it is sent. +

    + + + + + + + + +

    type ResponseWriter

    +
    type ResponseWriter interface {
    +    // Header returns the header map that will be sent by
    +    // WriteHeader. Changing the header after a call to
    +    // WriteHeader (or Write) has no effect unless the modified
    +    // headers were declared as trailers by setting the
    +    // "Trailer" header before the call to WriteHeader (see example).
    +    // To suppress implicit response headers, set their value to nil.
    +    Header() Header
    +
    +    // Write writes the data to the connection as part of an HTTP reply.
    +    // If WriteHeader has not yet been called, Write calls WriteHeader(http.StatusOK)
    +    // before writing the data.  If the Header does not contain a
    +    // Content-Type line, Write adds a Content-Type set to the result of passing
    +    // the initial 512 bytes of written data to DetectContentType.
    +    Write([]byte) (int, error)
    +
    +    // WriteHeader sends an HTTP response header with status code.
    +    // If WriteHeader is not called explicitly, the first call to Write
    +    // will trigger an implicit WriteHeader(http.StatusOK).
    +    // Thus explicit calls to WriteHeader are mainly used to
    +    // send error codes.
    +    WriteHeader(int)
    +}
    +

    +A ResponseWriter interface is used by an HTTP handler to +construct an HTTP response. +

    +

    +A ResponseWriter may not be used after the Handler.ServeHTTP method +has returned. +

    + + + + + + +
    + +
    +

    Example (Trailers)

    +

    HTTP Trailers are a set of key/value pairs like headers that come +after the HTTP response, instead of before. +

    + + +

    Code:

    +
    +mux := http.NewServeMux()
    +mux.HandleFunc("/sendstrailers", func(w http.ResponseWriter, req *http.Request) {
    +    // Before any call to WriteHeader or Write, declare
    +    // the trailers you will set during the HTTP
    +    // response. These three headers are actually sent in
    +    // the trailer.
    +    w.Header().Set("Trailer", "AtEnd1, AtEnd2")
    +    w.Header().Add("Trailer", "AtEnd3")
    +
    +    w.Header().Set("Content-Type", "text/plain; charset=utf-8") // normal header
    +    w.WriteHeader(http.StatusOK)
    +
    +    w.Header().Set("AtEnd1", "value 1")
    +    io.WriteString(w, "This HTTP response has both headers before this text and trailers at the end.\n")
    +    w.Header().Set("AtEnd2", "value 2")
    +    w.Header().Set("AtEnd3", "value 3") // These will appear as trailers.
    +})
    +
    + + +
    +
    + + + + + + + + + + +

    type RoundTripper

    +
    type RoundTripper interface {
    +    // RoundTrip executes a single HTTP transaction, returning
    +    // a Response for the provided Request.
    +    //
    +    // RoundTrip should not attempt to interpret the response. In
    +    // particular, RoundTrip must return err == nil if it obtained
    +    // a response, regardless of the response's HTTP status code.
    +    // A non-nil err should be reserved for failure to obtain a
    +    // response. Similarly, RoundTrip should not attempt to
    +    // handle higher-level protocol details such as redirects,
    +    // authentication, or cookies.
    +    //
    +    // RoundTrip should not modify the request, except for
    +    // consuming and closing the Request's Body.
    +    //
    +    // RoundTrip must always close the body, including on errors,
    +    // but depending on the implementation may do so in a separate
    +    // goroutine even after RoundTrip returns. This means that
    +    // callers wanting to reuse the body for subsequent requests
    +    // must arrange to wait for the Close call before doing so.
    +    //
    +    // The Request's URL and Header fields must be initialized.
    +    RoundTrip(*Request) (*Response, error)
    +}
    +

    +RoundTripper is an interface representing the ability to execute a +single HTTP transaction, obtaining the Response for a given Request. +

    +

    +A RoundTripper must be safe for concurrent use by multiple +goroutines. +

    + + + + + +
    var DefaultTransport RoundTripper = &Transport{
    +    Proxy: ProxyFromEnvironment,
    +    Dial: (&net.Dialer{
    +        Timeout:   30 * time.Second,
    +        KeepAlive: 30 * time.Second,
    +    }).Dial,
    +    TLSHandshakeTimeout:   10 * time.Second,
    +    ExpectContinueTimeout: 1 * time.Second,
    +}
    +

    +DefaultTransport is the default implementation of Transport and is +used by DefaultClient. It establishes network connections as needed +and caches them for reuse by subsequent calls. It uses HTTP proxies +as directed by the $HTTP_PROXY and $NO_PROXY (or $http_proxy and +$no_proxy) environment variables. +

    + + + + + + + + + +

    func NewFileTransport

    +
    func NewFileTransport(fs FileSystem) RoundTripper
    +

    +NewFileTransport returns a new RoundTripper, serving the provided +FileSystem. The returned RoundTripper ignores the URL host in its +incoming requests, as well as most other properties of the +request. +

    +

    +The typical use case for NewFileTransport is to register the "file" +protocol with a Transport, as in: +

    +
    t := &http.Transport{}
    +t.RegisterProtocol("file", http.NewFileTransport(http.Dir("/")))
    +c := &http.Client{Transport: t}
    +res, err := c.Get("file:///etc/passwd")
    +...
    +
    + + + + + + + + + +

    type ServeMux

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

    +ServeMux is an HTTP request multiplexer. +It matches the URL of each incoming request against a list of registered +patterns and calls the handler for the pattern that +most closely matches the URL. +

    +

    +Patterns name fixed, rooted paths, like "/favicon.ico", +or rooted subtrees, like "/images/" (note the trailing slash). +Longer patterns take precedence over shorter ones, so that +if there are handlers registered for both "/images/" +and "/images/thumbnails/", the latter handler will be +called for paths beginning "/images/thumbnails/" and the +former will receive requests for any other paths in the +"/images/" subtree. +

    +

    +Note that since a pattern ending in a slash names a rooted subtree, +the pattern "/" matches all paths not matched by other registered +patterns, not just the URL with Path == "/". +

    +

    +If a subtree has been registered and a request is received naming the +subtree root without its trailing slash, ServeMux redirects that +request to the subtree root (adding the trailing slash). This behavior can +be overridden with a separate registration for the path without +the trailing slash. For example, registering "/images/" causes ServeMux +to redirect a request for "/images" to "/images/", unless "/images" has +been registered separately. +

    +

    +Patterns may optionally begin with a host name, restricting matches to +URLs on that host only. Host-specific patterns take precedence over +general patterns, so that a handler might register for the two patterns +"/codesearch" and "codesearch.google.com/" without also taking over +requests for "http://www.google.com/". +

    +

    +ServeMux also takes care of sanitizing the URL request path, +redirecting any request containing . or .. elements or repeated slashes +to an equivalent, cleaner URL. +

    + + + + + + + + + + + + +

    func NewServeMux

    +
    func NewServeMux() *ServeMux
    +

    +NewServeMux allocates and returns a new ServeMux. +

    + + + + + + + +

    func (*ServeMux) Handle

    +
    func (mux *ServeMux) Handle(pattern string, handler Handler)
    +

    +Handle registers the handler for the given pattern. +If a handler already exists for pattern, Handle panics. +

    + + +
    + +
    +

    Example

    + + + +

    Code:

    +
    +mux := http.NewServeMux()
    +mux.Handle("/api/", apiHandler{})
    +mux.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) {
    +    // The "/" pattern matches everything, so we need to check
    +    // that we're at the root here.
    +    if req.URL.Path != "/" {
    +        http.NotFound(w, req)
    +        return
    +    }
    +    fmt.Fprintf(w, "Welcome to the home page!")
    +})
    +
    + + +
    +
    + + + + +

    func (*ServeMux) HandleFunc

    +
    func (mux *ServeMux) HandleFunc(pattern string, handler func(ResponseWriter, *Request))
    +

    +HandleFunc registers the handler function for the given pattern. +

    + + + + + + +

    func (*ServeMux) Handler

    +
    func (mux *ServeMux) Handler(r *Request) (h Handler, pattern string)
    +

    +Handler returns the handler to use for the given request, +consulting r.Method, r.Host, and r.URL.Path. It always returns +a non-nil handler. If the path is not in its canonical form, the +handler will be an internally-generated handler that redirects +to the canonical path. +

    +

    +Handler also returns the registered pattern that matches the +request or, in the case of internally-generated redirects, +the pattern that will match after following the redirect. +

    +

    +If there is no registered handler that applies to the request, +Handler returns a “page not found” handler and an empty pattern. +

    + + + + + + +

    func (*ServeMux) ServeHTTP

    +
    func (mux *ServeMux) ServeHTTP(w ResponseWriter, r *Request)
    +

    +ServeHTTP dispatches the request to the handler whose +pattern most closely matches the request URL. +

    + + + + + + + + +

    type Server

    +
    type Server struct {
    +    Addr           string        // TCP address to listen on, ":http" if empty
    +    Handler        Handler       // handler to invoke, http.DefaultServeMux if nil
    +    ReadTimeout    time.Duration // maximum duration before timing out read of the request
    +    WriteTimeout   time.Duration // maximum duration before timing out write of the response
    +    MaxHeaderBytes int           // maximum size of request headers, DefaultMaxHeaderBytes if 0
    +    TLSConfig      *tls.Config   // optional TLS config, used by ListenAndServeTLS
    +
    +    // TLSNextProto optionally specifies a function to take over
    +    // ownership of the provided TLS connection when an NPN
    +    // protocol upgrade has occurred.  The map key is the protocol
    +    // name negotiated. The Handler argument should be used to
    +    // handle HTTP requests and will initialize the Request's TLS
    +    // and RemoteAddr if not already set.  The connection is
    +    // automatically closed when the function returns.
    +    // If TLSNextProto is nil, HTTP/2 support is enabled automatically.
    +    TLSNextProto map[string]func(*Server, *tls.Conn, Handler)
    +
    +    // ConnState specifies an optional callback function that is
    +    // called when a client connection changes state. See the
    +    // ConnState type and associated constants for details.
    +    ConnState func(net.Conn, ConnState)
    +
    +    // ErrorLog specifies an optional logger for errors accepting
    +    // connections and unexpected behavior from handlers.
    +    // If nil, logging goes to os.Stderr via the log package's
    +    // standard logger.
    +    ErrorLog *log.Logger
    +    // contains filtered or unexported fields
    +}
    +

    +A Server defines parameters for running an HTTP server. +The zero value for Server is a valid configuration. +

    + + + + + + + + + + + + + + +

    func (*Server) ListenAndServe

    +
    func (srv *Server) ListenAndServe() error
    +

    +ListenAndServe listens on the TCP network address srv.Addr and then +calls Serve to handle requests on incoming connections. +Accepted connections are configured to enable TCP keep-alives. +If srv.Addr is blank, ":http" is used. +ListenAndServe always returns a non-nil error. +

    + + + + + + +

    func (*Server) ListenAndServeTLS

    +
    func (srv *Server) ListenAndServeTLS(certFile, keyFile string) error
    +

    +ListenAndServeTLS listens on the TCP network address srv.Addr and +then calls Serve to handle requests on incoming TLS connections. +Accepted connections are configured to enable TCP keep-alives. +

    +

    +Filenames containing a certificate and matching private key for the +server must be provided if neither the Server's TLSConfig.Certificates +nor TLSConfig.GetCertificate are populated. If the certificate is +signed by a certificate authority, the certFile should be the +concatenation of the server's certificate, any intermediates, and +the CA's certificate. +

    +

    +If srv.Addr is blank, ":https" is used. +

    +

    +ListenAndServeTLS always returns a non-nil error. +

    + + + + + + +

    func (*Server) Serve

    +
    func (srv *Server) Serve(l net.Listener) error
    +

    +Serve accepts incoming connections on the Listener l, creating a +new service goroutine for each. The service goroutines read requests and +then call srv.Handler to reply to them. +Serve always returns a non-nil error. +

    + + + + + + +

    func (*Server) SetKeepAlivesEnabled

    +
    func (srv *Server) SetKeepAlivesEnabled(v bool)
    +

    +SetKeepAlivesEnabled controls whether HTTP keep-alives are enabled. +By default, keep-alives are always enabled. Only very +resource-constrained environments or servers in the process of +shutting down should disable them. +

    + + + + + + + + +

    type Transport

    +
    type Transport struct {
    +
    +    // Proxy specifies a function to return a proxy for a given
    +    // Request. If the function returns a non-nil error, the
    +    // request is aborted with the provided error.
    +    // If Proxy is nil or returns a nil *URL, no proxy is used.
    +    Proxy func(*Request) (*url.URL, error)
    +
    +    // Dial specifies the dial function for creating unencrypted
    +    // TCP connections.
    +    // If Dial is nil, net.Dial is used.
    +    Dial func(network, addr string) (net.Conn, error)
    +
    +    // DialTLS specifies an optional dial function for creating
    +    // TLS connections for non-proxied HTTPS requests.
    +    //
    +    // If DialTLS is nil, Dial and TLSClientConfig are used.
    +    //
    +    // If DialTLS is set, the Dial hook is not used for HTTPS
    +    // requests and the TLSClientConfig and TLSHandshakeTimeout
    +    // are ignored. The returned net.Conn is assumed to already be
    +    // past the TLS handshake.
    +    DialTLS func(network, addr string) (net.Conn, error)
    +
    +    // TLSClientConfig specifies the TLS configuration to use with
    +    // tls.Client. If nil, the default configuration is used.
    +    TLSClientConfig *tls.Config
    +
    +    // TLSHandshakeTimeout specifies the maximum amount of time waiting to
    +    // wait for a TLS handshake. Zero means no timeout.
    +    TLSHandshakeTimeout time.Duration
    +
    +    // DisableKeepAlives, if true, prevents re-use of TCP connections
    +    // between different HTTP requests.
    +    DisableKeepAlives bool
    +
    +    // DisableCompression, if true, prevents the Transport from
    +    // requesting compression with an "Accept-Encoding: gzip"
    +    // request header when the Request contains no existing
    +    // Accept-Encoding value. If the Transport requests gzip on
    +    // its own and gets a gzipped response, it's transparently
    +    // decoded in the Response.Body. However, if the user
    +    // explicitly requested gzip it is not automatically
    +    // uncompressed.
    +    DisableCompression bool
    +
    +    // MaxIdleConnsPerHost, if non-zero, controls the maximum idle
    +    // (keep-alive) to keep per-host.  If zero,
    +    // DefaultMaxIdleConnsPerHost is used.
    +    MaxIdleConnsPerHost int
    +
    +    // ResponseHeaderTimeout, if non-zero, specifies the amount of
    +    // time to wait for a server's response headers after fully
    +    // writing the request (including its body, if any). This
    +    // time does not include the time to read the response body.
    +    ResponseHeaderTimeout time.Duration
    +
    +    // ExpectContinueTimeout, if non-zero, specifies the amount of
    +    // time to wait for a server's first response headers after fully
    +    // writing the request headers if the request has an
    +    // "Expect: 100-continue" header. Zero means no timeout.
    +    // This time does not include the time to send the request header.
    +    ExpectContinueTimeout time.Duration
    +
    +    // TLSNextProto specifies how the Transport switches to an
    +    // alternate protocol (such as HTTP/2) after a TLS NPN/ALPN
    +    // protocol negotiation.  If Transport dials an TLS connection
    +    // with a non-empty protocol name and TLSNextProto contains a
    +    // map entry for that key (such as "h2"), then the func is
    +    // called with the request's authority (such as "example.com"
    +    // or "example.com:1234") and the TLS connection. The function
    +    // must return a RoundTripper that then handles the request.
    +    // If TLSNextProto is nil, HTTP/2 support is enabled automatically.
    +    TLSNextProto map[string]func(authority string, c *tls.Conn) RoundTripper
    +    // contains filtered or unexported fields
    +}
    +

    +Transport is an implementation of RoundTripper that supports HTTP, +HTTPS, and HTTP proxies (for either HTTP or HTTPS with CONNECT). +

    +

    +By default, Transport caches connections for future re-use. +This may leave many open connections when accessing many hosts. +This behavior can be managed using Transport's CloseIdleConnections method +and the MaxIdleConnsPerHost and DisableKeepAlives fields. +

    +

    +Transports should be reused instead of created as needed. +Transports are safe for concurrent use by multiple goroutines. +

    +

    +A Transport is a low-level primitive for making HTTP and HTTPS requests. +For high-level functionality, such as cookies and redirects, see Client. +

    +

    +Transport uses HTTP/1.1 for HTTP URLs and either HTTP/1.1 or HTTP/2 +for HTTPS URLs, depending on whether the server supports HTTP/2. +See the package docs for more about HTTP/2. +

    + + + + + + + + + + + + + + +

    func (*Transport) CancelRequest

    +
    func (t *Transport) CancelRequest(req *Request)
    +

    +CancelRequest cancels an in-flight request by closing its connection. +CancelRequest should only be called after RoundTrip has returned. +

    +

    +Deprecated: Use Request.Cancel instead. CancelRequest can not cancel +HTTP/2 requests. +

    + + + + + + +

    func (*Transport) CloseIdleConnections

    +
    func (t *Transport) CloseIdleConnections()
    +

    +CloseIdleConnections closes any connections which were previously +connected from previous requests but are now sitting idle in +a "keep-alive" state. It does not interrupt any connections currently +in use. +

    + + + + + + +

    func (*Transport) RegisterProtocol

    +
    func (t *Transport) RegisterProtocol(scheme string, rt RoundTripper)
    +

    +RegisterProtocol registers a new protocol with scheme. +The Transport will pass requests using the given scheme to rt. +It is rt's responsibility to simulate HTTP request semantics. +

    +

    +RegisterProtocol can be used by other packages to provide +implementations of protocol schemes like "ftp" or "file". +

    +

    +If rt.RoundTrip returns ErrSkipAltProtocol, the Transport will +handle the RoundTrip itself for that one request, as if the +protocol were not registered. +

    + + + + + + +

    func (*Transport) RoundTrip

    +
    func (t *Transport) RoundTrip(req *Request) (*Response, error)
    +

    +RoundTrip implements the RoundTripper interface. +

    +

    +For higher-level HTTP client support (such as handling of cookies +and redirects), see Get, Post, and the Client type. +

    + + + + + + + + + + + + + + + + +

    Subdirectories

    + + + + +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    NameSynopsis
    ..
    + cgi + + Package cgi implements CGI (Common Gateway Interface) as specified in RFC 3875. +
    + cookiejar + + Package cookiejar implements an in-memory RFC 6265-compliant http.CookieJar. +
    + fcgi + + Package fcgi implements the FastCGI protocol. +
    + httptest + + Package httptest provides utilities for HTTP testing. +
    + httputil + + Package httputil provides HTTP utility functions, complementing the more common ones in the net/http package. +
    + pprof + + Package pprof serves via its HTTP server runtime profiling data in the format expected by the pprof visualization tool. +
    +
    + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/net/http/internal/index.html b/pkg/net/http/internal/index.html new file mode 100644 index 0000000..1fbbc4a --- /dev/null +++ b/pkg/net/http/internal/index.html @@ -0,0 +1,335 @@ + + + + + + + + internal - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Package internal

    + + + + + + + + + + + + + + +
    +
    +
    import "net/http/internal"
    +
    +
    +
    Overview
    +
    Index
    + + +
    +
    + +
    + +
    +

    Overview ▾

    +

    +Package internal contains HTTP internals shared by net/http and +net/http/httputil. +

    + +
    +
    + + +
    + +
    +

    Index ▾

    + + + + + + + +

    Package files

    +

    + + + chunked.go + + testcert.go + + +

    + +
    +
    + + + + + +

    Variables

    + +
    var ErrLineTooLong = errors.New("header line too long")
    + + +
    var LocalhostCert = []byte(`-----BEGIN CERTIFICATE-----
    +MIICEzCCAXygAwIBAgIQMIMChMLGrR+QvmQvpwAU6zANBgkqhkiG9w0BAQsFADAS
    +MRAwDgYDVQQKEwdBY21lIENvMCAXDTcwMDEwMTAwMDAwMFoYDzIwODQwMTI5MTYw
    +MDAwWjASMRAwDgYDVQQKEwdBY21lIENvMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCB
    +iQKBgQDuLnQAI3mDgey3VBzWnB2L39JUU4txjeVE6myuDqkM/uGlfjb9SjY1bIw4
    +iA5sBBZzHi3z0h1YV8QPuxEbi4nW91IJm2gsvvZhIrCHS3l6afab4pZBl2+XsDul
    +rKBxKKtD1rGxlG4LjncdabFn9gvLZad2bSysqz/qTAUStTvqJQIDAQABo2gwZjAO
    +BgNVHQ8BAf8EBAMCAqQwEwYDVR0lBAwwCgYIKwYBBQUHAwEwDwYDVR0TAQH/BAUw
    +AwEB/zAuBgNVHREEJzAlggtleGFtcGxlLmNvbYcEfwAAAYcQAAAAAAAAAAAAAAAA
    +AAAAATANBgkqhkiG9w0BAQsFAAOBgQCEcetwO59EWk7WiJsG4x8SY+UIAA+flUI9
    +tyC4lNhbcF2Idq9greZwbYCqTTTr2XiRNSMLCOjKyI7ukPoPjo16ocHj+P3vZGfs
    +h1fIw3cSS2OolhloGw/XM6RWPWtPAlGykKLciQrBru5NAPvCMsb/I1DAceTiotQM
    +fblo6RBxUQ==
    +-----END CERTIFICATE-----`)
    +

    +LocalhostCert is a PEM-encoded TLS cert with SAN IPs +"127.0.0.1" and "[::1]", expiring at Jan 29 16:00:00 2084 GMT. +generated from src/crypto/tls: +go run generate_cert.go --rsa-bits 1024 --host 127.0.0.1,::1,example.com --ca --start-date "Jan 1 00:00:00 1970" --duration=1000000h +

    + + +
    var LocalhostKey = []byte(`-----BEGIN RSA PRIVATE KEY-----
    +MIICXgIBAAKBgQDuLnQAI3mDgey3VBzWnB2L39JUU4txjeVE6myuDqkM/uGlfjb9
    +SjY1bIw4iA5sBBZzHi3z0h1YV8QPuxEbi4nW91IJm2gsvvZhIrCHS3l6afab4pZB
    +l2+XsDulrKBxKKtD1rGxlG4LjncdabFn9gvLZad2bSysqz/qTAUStTvqJQIDAQAB
    +AoGAGRzwwir7XvBOAy5tM/uV6e+Zf6anZzus1s1Y1ClbjbE6HXbnWWF/wbZGOpet
    +3Zm4vD6MXc7jpTLryzTQIvVdfQbRc6+MUVeLKwZatTXtdZrhu+Jk7hx0nTPy8Jcb
    +uJqFk541aEw+mMogY/xEcfbWd6IOkp+4xqjlFLBEDytgbIECQQDvH/E6nk+hgN4H
    +qzzVtxxr397vWrjrIgPbJpQvBsafG7b0dA4AFjwVbFLmQcj2PprIMmPcQrooz8vp
    +jy4SHEg1AkEA/v13/5M47K9vCxmb8QeD/asydfsgS5TeuNi8DoUBEmiSJwma7FXY
    +fFUtxuvL7XvjwjN5B30pNEbc6Iuyt7y4MQJBAIt21su4b3sjXNueLKH85Q+phy2U
    +fQtuUE9txblTu14q3N7gHRZB4ZMhFYyDy8CKrN2cPg/Fvyt0Xlp/DoCzjA0CQQDU
    +y2ptGsuSmgUtWj3NM9xuwYPm+Z/F84K6+ARYiZ6PYj013sovGKUFfYAqVXVlxtIX
    +qyUBnu3X9ps8ZfjLZO7BAkEAlT4R5Yl6cGhaJQYZHOde3JEMhNRcVFMO8dJDaFeo
    +f9Oeos0UUothgiDktdQHxdNEwLjQf7lJJBzV+5OtwswCWA==
    +-----END RSA PRIVATE KEY-----`)
    +

    +LocalhostKey is the private key for localhostCert. +

    + + + + + + +

    func NewChunkedReader

    +
    func NewChunkedReader(r io.Reader) io.Reader
    +

    +NewChunkedReader returns a new chunkedReader that translates the data read from r +out of HTTP "chunked" format before returning it. +The chunkedReader returns io.EOF when the final 0-length chunk is read. +

    +

    +NewChunkedReader is not needed by normal applications. The http package +automatically decodes chunking when reading response bodies. +

    + + + + + + + +

    func NewChunkedWriter

    +
    func NewChunkedWriter(w io.Writer) io.WriteCloser
    +

    +NewChunkedWriter returns a new chunkedWriter that translates writes into HTTP +"chunked" format before writing them to w. Closing the returned chunkedWriter +sends the final 0-length chunk that marks the end of the stream. +

    +

    +NewChunkedWriter is not needed by normal applications. The http +package adds chunking automatically if handlers don't set a +Content-Length header. Using newChunkedWriter inside a handler +would result in double chunking or chunking with a Content-Length +length, both of which are wrong. +

    + + + + + + + + +

    type FlushAfterChunkWriter

    +
    type FlushAfterChunkWriter struct {
    +    *bufio.Writer
    +}
    +

    +FlushAfterChunkWriter signals from the caller of NewChunkedWriter +that each chunk should be followed by a flush. It is used by the +http.Transport code to keep the buffering behavior for headers and +trailers, but flush out chunks aggressively in the middle for +request bodies which may be generated slowly. See Issue 6574. +

    + + + + + + + + + + + + + + + + + + + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/net/http/pprof/index.html b/pkg/net/http/pprof/index.html new file mode 100644 index 0000000..bbfa008 --- /dev/null +++ b/pkg/net/http/pprof/index.html @@ -0,0 +1,356 @@ + + + + + + + + pprof - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Package pprof

    + + + + + + + + + + + + + + +
    +
    +
    import "net/http/pprof"
    +
    +
    +
    Overview
    +
    Index
    + + +
    +
    + +
    + +
    +

    Overview ▾

    +

    +Package pprof serves via its HTTP server runtime profiling data +in the format expected by the pprof visualization tool. +For more information about pprof, see +http://code.google.com/p/google-perftools/. +

    +

    +The package is typically only imported for the side effect of +registering its HTTP handlers. +The handled paths all begin with /debug/pprof/. +

    +

    +To use pprof, link this package into your program: +

    +
    import _ "net/http/pprof"
    +
    +

    +If your application is not already running an http server, you +need to start one. Add "net/http" and "log" to your imports and +the following code to your main function: +

    +
    go func() {
    +	log.Println(http.ListenAndServe("localhost:6060", nil))
    +}()
    +
    +

    +Then use the pprof tool to look at the heap profile: +

    +
    go tool pprof http://localhost:6060/debug/pprof/heap
    +
    +

    +Or to look at a 30-second CPU profile: +

    +
    go tool pprof http://localhost:6060/debug/pprof/profile
    +
    +

    +Or to look at the goroutine blocking profile: +

    +
    go tool pprof http://localhost:6060/debug/pprof/block
    +
    +

    +Or to collect a 5-second execution trace: +

    +
    wget http://localhost:6060/debug/pprof/trace?seconds=5
    +
    +

    +To view all available profiles, open http://localhost:6060/debug/pprof/ +in your browser. +

    +

    +For a study of the facility in action, visit +

    +
    https://blog.golang.org/2011/06/profiling-go-programs.html
    +
    + +
    +
    + + + + + + + + + + + +

    func Cmdline

    +
    func Cmdline(w http.ResponseWriter, r *http.Request)
    +

    +Cmdline responds with the running program's +command line, with arguments separated by NUL bytes. +The package initialization registers it as /debug/pprof/cmdline. +

    + + + + + + + +

    func Handler

    +
    func Handler(name string) http.Handler
    +

    +Handler returns an HTTP handler that serves the named profile. +

    + + + + + + + +

    func Index

    +
    func Index(w http.ResponseWriter, r *http.Request)
    +

    +Index responds with the pprof-formatted profile named by the request. +For example, "/debug/pprof/heap" serves the "heap" profile. +Index responds to a request for "/debug/pprof/" with an HTML page +listing the available profiles. +

    + + + + + + + +

    func Profile

    +
    func Profile(w http.ResponseWriter, r *http.Request)
    +

    +Profile responds with the pprof-formatted cpu profile. +The package initialization registers it as /debug/pprof/profile. +

    + + + + + + + +

    func Symbol

    +
    func Symbol(w http.ResponseWriter, r *http.Request)
    +

    +Symbol looks up the program counters listed in the request, +responding with a table mapping program counters to function names. +The package initialization registers it as /debug/pprof/symbol. +

    + + + + + + + +

    func Trace

    +
    func Trace(w http.ResponseWriter, r *http.Request)
    +

    +Trace responds with the execution trace in binary form. +Tracing lasts for duration specified in seconds GET parameter, or for 1 second if not specified. +The package initialization registers it as /debug/pprof/trace. +

    + + + + + + + + + + + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/net/index.html b/pkg/net/index.html new file mode 100644 index 0000000..ee57fec --- /dev/null +++ b/pkg/net/index.html @@ -0,0 +1,4550 @@ + + + + + + + + net - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Package net

    + + + + + + + + + + + + + + +
    +
    +
    import "net"
    +
    +
    +
    Overview
    +
    Index
    + +
    Examples
    + + +
    Subdirectories
    + +
    +
    + +
    + +
    +

    Overview ▾

    +

    +Package net provides a portable interface for network I/O, including +TCP/IP, UDP, domain name resolution, and Unix domain sockets. +

    +

    +Although the package provides access to low-level networking +primitives, most clients will need only the basic interface provided +by the Dial, Listen, and Accept functions and the associated +Conn and Listener interfaces. The crypto/tls package uses +the same interfaces and similar Dial and Listen functions. +

    +

    +The Dial function connects to a server: +

    +
    conn, err := net.Dial("tcp", "google.com:80")
    +if err != nil {
    +	// handle error
    +}
    +fmt.Fprintf(conn, "GET / HTTP/1.0\r\n\r\n")
    +status, err := bufio.NewReader(conn).ReadString('\n')
    +// ...
    +
    +

    +The Listen function creates servers: +

    +
    ln, err := net.Listen("tcp", ":8080")
    +if err != nil {
    +	// handle error
    +}
    +for {
    +	conn, err := ln.Accept()
    +	if err != nil {
    +		// handle error
    +	}
    +	go handleConnection(conn)
    +}
    +
    +

    Name Resolution

    +

    +The method for resolving domain names, whether indirectly with functions like Dial +or directly with functions like LookupHost and LookupAddr, varies by operating system. +

    +

    +On Unix systems, the resolver has two options for resolving names. +It can use a pure Go resolver that sends DNS requests directly to the servers +listed in /etc/resolv.conf, or it can use a cgo-based resolver that calls C +library routines such as getaddrinfo and getnameinfo. +

    +

    +By default the pure Go resolver is used, because a blocked DNS request consumes +only a goroutine, while a blocked C call consumes an operating system thread. +When cgo is available, the cgo-based resolver is used instead under a variety of +conditions: on systems that do not let programs make direct DNS requests (OS X), +when the LOCALDOMAIN environment variable is present (even if empty), +when the RES_OPTIONS or HOSTALIASES environment variable is non-empty, +when the ASR_CONFIG environment variable is non-empty (OpenBSD only), +when /etc/resolv.conf or /etc/nsswitch.conf specify the use of features that the +Go resolver does not implement, and when the name being looked up ends in .local +or is an mDNS name. +

    +

    +The resolver decision can be overridden by setting the netdns value of the +GODEBUG environment variable (see package runtime) to go or cgo, as in: +

    +
    export GODEBUG=netdns=go    # force pure Go resolver
    +export GODEBUG=netdns=cgo   # force cgo resolver
    +
    +

    +The decision can also be forced while building the Go source tree +by setting the netgo or netcgo build tag. +

    +

    +A numeric netdns setting, as in GODEBUG=netdns=1, causes the resolver +to print debugging information about its decisions. +To force a particular resolver while also printing debugging information, +join the two settings by a plus sign, as in GODEBUG=netdns=go+1. +

    +

    +On Plan 9, the resolver always accesses /net/cs and /net/dns. +

    +

    +On Windows, the resolver always uses C library functions, such as GetAddrInfo and DnsQuery. +

    + +
    +
    + + +
    + +
    +

    Index ▾

    + + +
    +
    + +
    Constants
    + + +
    Variables
    + + + +
    func InterfaceAddrs() ([]Addr, error)
    + + +
    func Interfaces() ([]Interface, error)
    + + +
    func JoinHostPort(host, port string) string
    + + +
    func LookupAddr(addr string) (names []string, err error)
    + + +
    func LookupCNAME(name string) (cname string, err error)
    + + +
    func LookupHost(host string) (addrs []string, err error)
    + + +
    func LookupIP(host string) (ips []IP, err error)
    + + +
    func LookupMX(name string) (mxs []*MX, err error)
    + + +
    func LookupNS(name string) (nss []*NS, err error)
    + + +
    func LookupPort(network, service string) (port int, err error)
    + + +
    func LookupSRV(service, proto, name string) (cname string, addrs []*SRV, err error)
    + + +
    func LookupTXT(name string) (txts []string, err error)
    + + +
    func SplitHostPort(hostport string) (host, port string, err error)
    + + + +
    type Addr
    + + + + +
    type AddrError
    + + + +
        func (e *AddrError) Error() string
    + + +
        func (e *AddrError) Temporary() bool
    + + +
        func (e *AddrError) Timeout() bool
    + + + +
    type Conn
    + + +
        func Dial(network, address string) (Conn, error)
    + + +
        func DialTimeout(network, address string, timeout time.Duration) (Conn, error)
    + + +
        func FileConn(f *os.File) (c Conn, err error)
    + + +
        func Pipe() (Conn, Conn)
    + + + + +
    type DNSConfigError
    + + + +
        func (e *DNSConfigError) Error() string
    + + +
        func (e *DNSConfigError) Temporary() bool
    + + +
        func (e *DNSConfigError) Timeout() bool
    + + + +
    type DNSError
    + + + +
        func (e *DNSError) Error() string
    + + +
        func (e *DNSError) Temporary() bool
    + + +
        func (e *DNSError) Timeout() bool
    + + + +
    type Dialer
    + + + +
        func (d *Dialer) Dial(network, address string) (Conn, error)
    + + + +
    type Error
    + + + + +
    type Flags
    + + + +
        func (f Flags) String() string
    + + + +
    type HardwareAddr
    + + +
        func ParseMAC(s string) (hw HardwareAddr, err error)
    + + + +
        func (a HardwareAddr) String() string
    + + + +
    type IP
    + + +
        func IPv4(a, b, c, d byte) IP
    + + +
        func ParseCIDR(s string) (IP, *IPNet, error)
    + + +
        func ParseIP(s string) IP
    + + + +
        func (ip IP) DefaultMask() IPMask
    + + +
        func (ip IP) Equal(x IP) bool
    + + +
        func (ip IP) IsGlobalUnicast() bool
    + + +
        func (ip IP) IsInterfaceLocalMulticast() bool
    + + +
        func (ip IP) IsLinkLocalMulticast() bool
    + + +
        func (ip IP) IsLinkLocalUnicast() bool
    + + +
        func (ip IP) IsLoopback() bool
    + + +
        func (ip IP) IsMulticast() bool
    + + +
        func (ip IP) IsUnspecified() bool
    + + +
        func (ip IP) MarshalText() ([]byte, error)
    + + +
        func (ip IP) Mask(mask IPMask) IP
    + + +
        func (ip IP) String() string
    + + +
        func (ip IP) To16() IP
    + + +
        func (ip IP) To4() IP
    + + +
        func (ip *IP) UnmarshalText(text []byte) error
    + + + +
    type IPAddr
    + + +
        func ResolveIPAddr(net, addr string) (*IPAddr, error)
    + + + +
        func (a *IPAddr) Network() string
    + + +
        func (a *IPAddr) String() string
    + + + +
    type IPConn
    + + +
        func DialIP(netProto string, laddr, raddr *IPAddr) (*IPConn, error)
    + + +
        func ListenIP(netProto string, laddr *IPAddr) (*IPConn, error)
    + + + +
        func (c *IPConn) Close() error
    + + +
        func (c *IPConn) File() (f *os.File, err error)
    + + +
        func (c *IPConn) LocalAddr() Addr
    + + +
        func (c *IPConn) Read(b []byte) (int, error)
    + + +
        func (c *IPConn) ReadFrom(b []byte) (int, Addr, error)
    + + +
        func (c *IPConn) ReadFromIP(b []byte) (int, *IPAddr, error)
    + + +
        func (c *IPConn) ReadMsgIP(b, oob []byte) (n, oobn, flags int, addr *IPAddr, err error)
    + + +
        func (c *IPConn) RemoteAddr() Addr
    + + +
        func (c *IPConn) SetDeadline(t time.Time) error
    + + +
        func (c *IPConn) SetReadBuffer(bytes int) error
    + + +
        func (c *IPConn) SetReadDeadline(t time.Time) error
    + + +
        func (c *IPConn) SetWriteBuffer(bytes int) error
    + + +
        func (c *IPConn) SetWriteDeadline(t time.Time) error
    + + +
        func (c *IPConn) Write(b []byte) (int, error)
    + + +
        func (c *IPConn) WriteMsgIP(b, oob []byte, addr *IPAddr) (n, oobn int, err error)
    + + +
        func (c *IPConn) WriteTo(b []byte, addr Addr) (int, error)
    + + +
        func (c *IPConn) WriteToIP(b []byte, addr *IPAddr) (int, error)
    + + + +
    type IPMask
    + + +
        func CIDRMask(ones, bits int) IPMask
    + + +
        func IPv4Mask(a, b, c, d byte) IPMask
    + + + +
        func (m IPMask) Size() (ones, bits int)
    + + +
        func (m IPMask) String() string
    + + + +
    type IPNet
    + + + +
        func (n *IPNet) Contains(ip IP) bool
    + + +
        func (n *IPNet) Network() string
    + + +
        func (n *IPNet) String() string
    + + + +
    type Interface
    + + +
        func InterfaceByIndex(index int) (*Interface, error)
    + + +
        func InterfaceByName(name string) (*Interface, error)
    + + + +
        func (ifi *Interface) Addrs() ([]Addr, error)
    + + +
        func (ifi *Interface) MulticastAddrs() ([]Addr, error)
    + + + +
    type InvalidAddrError
    + + + +
        func (e InvalidAddrError) Error() string
    + + +
        func (e InvalidAddrError) Temporary() bool
    + + +
        func (e InvalidAddrError) Timeout() bool
    + + + +
    type Listener
    + + +
        func FileListener(f *os.File) (ln Listener, err error)
    + + +
        func Listen(net, laddr string) (Listener, error)
    + + + + +
    type MX
    + + + + +
    type NS
    + + + + +
    type OpError
    + + + +
        func (e *OpError) Error() string
    + + +
        func (e *OpError) Temporary() bool
    + + +
        func (e *OpError) Timeout() bool
    + + + +
    type PacketConn
    + + +
        func FilePacketConn(f *os.File) (c PacketConn, err error)
    + + +
        func ListenPacket(net, laddr string) (PacketConn, error)
    + + + + +
    type ParseError
    + + + +
        func (e *ParseError) Error() string
    + + + +
    type SRV
    + + + + +
    type TCPAddr
    + + +
        func ResolveTCPAddr(net, addr string) (*TCPAddr, error)
    + + + +
        func (a *TCPAddr) Network() string
    + + +
        func (a *TCPAddr) String() string
    + + + +
    type TCPConn
    + + +
        func DialTCP(net string, laddr, raddr *TCPAddr) (*TCPConn, error)
    + + + +
        func (c *TCPConn) Close() error
    + + +
        func (c *TCPConn) CloseRead() error
    + + +
        func (c *TCPConn) CloseWrite() error
    + + +
        func (c *TCPConn) File() (f *os.File, err error)
    + + +
        func (c *TCPConn) LocalAddr() Addr
    + + +
        func (c *TCPConn) Read(b []byte) (int, error)
    + + +
        func (c *TCPConn) ReadFrom(r io.Reader) (int64, error)
    + + +
        func (c *TCPConn) RemoteAddr() Addr
    + + +
        func (c *TCPConn) SetDeadline(t time.Time) error
    + + +
        func (c *TCPConn) SetKeepAlive(keepalive bool) error
    + + +
        func (c *TCPConn) SetKeepAlivePeriod(d time.Duration) error
    + + +
        func (c *TCPConn) SetLinger(sec int) error
    + + +
        func (c *TCPConn) SetNoDelay(noDelay bool) error
    + + +
        func (c *TCPConn) SetReadBuffer(bytes int) error
    + + +
        func (c *TCPConn) SetReadDeadline(t time.Time) error
    + + +
        func (c *TCPConn) SetWriteBuffer(bytes int) error
    + + +
        func (c *TCPConn) SetWriteDeadline(t time.Time) error
    + + +
        func (c *TCPConn) Write(b []byte) (int, error)
    + + + +
    type TCPListener
    + + +
        func ListenTCP(net string, laddr *TCPAddr) (*TCPListener, error)
    + + + +
        func (l *TCPListener) Accept() (Conn, error)
    + + +
        func (l *TCPListener) AcceptTCP() (*TCPConn, error)
    + + +
        func (l *TCPListener) Addr() Addr
    + + +
        func (l *TCPListener) Close() error
    + + +
        func (l *TCPListener) File() (f *os.File, err error)
    + + +
        func (l *TCPListener) SetDeadline(t time.Time) error
    + + + +
    type UDPAddr
    + + +
        func ResolveUDPAddr(net, addr string) (*UDPAddr, error)
    + + + +
        func (a *UDPAddr) Network() string
    + + +
        func (a *UDPAddr) String() string
    + + + +
    type UDPConn
    + + +
        func DialUDP(net string, laddr, raddr *UDPAddr) (*UDPConn, error)
    + + +
        func ListenMulticastUDP(network string, ifi *Interface, gaddr *UDPAddr) (*UDPConn, error)
    + + +
        func ListenUDP(net string, laddr *UDPAddr) (*UDPConn, error)
    + + + +
        func (c *UDPConn) Close() error
    + + +
        func (c *UDPConn) File() (f *os.File, err error)
    + + +
        func (c *UDPConn) LocalAddr() Addr
    + + +
        func (c *UDPConn) Read(b []byte) (int, error)
    + + +
        func (c *UDPConn) ReadFrom(b []byte) (int, Addr, error)
    + + +
        func (c *UDPConn) ReadFromUDP(b []byte) (int, *UDPAddr, error)
    + + +
        func (c *UDPConn) ReadMsgUDP(b, oob []byte) (n, oobn, flags int, addr *UDPAddr, err error)
    + + +
        func (c *UDPConn) RemoteAddr() Addr
    + + +
        func (c *UDPConn) SetDeadline(t time.Time) error
    + + +
        func (c *UDPConn) SetReadBuffer(bytes int) error
    + + +
        func (c *UDPConn) SetReadDeadline(t time.Time) error
    + + +
        func (c *UDPConn) SetWriteBuffer(bytes int) error
    + + +
        func (c *UDPConn) SetWriteDeadline(t time.Time) error
    + + +
        func (c *UDPConn) Write(b []byte) (int, error)
    + + +
        func (c *UDPConn) WriteMsgUDP(b, oob []byte, addr *UDPAddr) (n, oobn int, err error)
    + + +
        func (c *UDPConn) WriteTo(b []byte, addr Addr) (int, error)
    + + +
        func (c *UDPConn) WriteToUDP(b []byte, addr *UDPAddr) (int, error)
    + + + +
    type UnixAddr
    + + +
        func ResolveUnixAddr(net, addr string) (*UnixAddr, error)
    + + + +
        func (a *UnixAddr) Network() string
    + + +
        func (a *UnixAddr) String() string
    + + + +
    type UnixConn
    + + +
        func DialUnix(net string, laddr, raddr *UnixAddr) (*UnixConn, error)
    + + +
        func ListenUnixgram(net string, laddr *UnixAddr) (*UnixConn, error)
    + + + +
        func (c *UnixConn) Close() error
    + + +
        func (c *UnixConn) CloseRead() error
    + + +
        func (c *UnixConn) CloseWrite() error
    + + +
        func (c *UnixConn) File() (f *os.File, err error)
    + + +
        func (c *UnixConn) LocalAddr() Addr
    + + +
        func (c *UnixConn) Read(b []byte) (int, error)
    + + +
        func (c *UnixConn) ReadFrom(b []byte) (int, Addr, error)
    + + +
        func (c *UnixConn) ReadFromUnix(b []byte) (int, *UnixAddr, error)
    + + +
        func (c *UnixConn) ReadMsgUnix(b, oob []byte) (n, oobn, flags int, addr *UnixAddr, err error)
    + + +
        func (c *UnixConn) RemoteAddr() Addr
    + + +
        func (c *UnixConn) SetDeadline(t time.Time) error
    + + +
        func (c *UnixConn) SetReadBuffer(bytes int) error
    + + +
        func (c *UnixConn) SetReadDeadline(t time.Time) error
    + + +
        func (c *UnixConn) SetWriteBuffer(bytes int) error
    + + +
        func (c *UnixConn) SetWriteDeadline(t time.Time) error
    + + +
        func (c *UnixConn) Write(b []byte) (int, error)
    + + +
        func (c *UnixConn) WriteMsgUnix(b, oob []byte, addr *UnixAddr) (n, oobn int, err error)
    + + +
        func (c *UnixConn) WriteTo(b []byte, addr Addr) (n int, err error)
    + + +
        func (c *UnixConn) WriteToUnix(b []byte, addr *UnixAddr) (int, error)
    + + + +
    type UnixListener
    + + +
        func ListenUnix(net string, laddr *UnixAddr) (*UnixListener, error)
    + + + +
        func (l *UnixListener) Accept() (c Conn, err error)
    + + +
        func (l *UnixListener) AcceptUnix() (*UnixConn, error)
    + + +
        func (l *UnixListener) Addr() Addr
    + + +
        func (l *UnixListener) Close() error
    + + +
        func (l *UnixListener) File() (f *os.File, err error)
    + + +
        func (l *UnixListener) SetDeadline(t time.Time) error
    + + + +
    type UnknownNetworkError
    + + + +
        func (e UnknownNetworkError) Error() string
    + + +
        func (e UnknownNetworkError) Temporary() bool
    + + +
        func (e UnknownNetworkError) Timeout() bool
    + + + + +
    Bugs
    + + +
    +
    + + +
    +

    Examples

    +
    + +
    Listener
    + +
    +
    + + + +

    Package files

    +

    + + + addrselect.go + + cgo_linux.go + + cgo_resnew.go + + cgo_socknew.go + + cgo_unix.go + + conf.go + + dial.go + + dnsclient.go + + dnsclient_unix.go + + dnsconfig_unix.go + + dnsmsg.go + + fd_mutex.go + + fd_poll_runtime.go + + fd_posix.go + + fd_unix.go + + file.go + + file_unix.go + + hook.go + + hook_cloexec.go + + hook_unix.go + + hosts.go + + interface.go + + interface_linux.go + + ip.go + + iprawsock.go + + iprawsock_posix.go + + ipsock.go + + ipsock_posix.go + + lookup.go + + lookup_unix.go + + mac.go + + net.go + + nss.go + + parse.go + + pipe.go + + port_unix.go + + sendfile_linux.go + + sock_cloexec.go + + sock_linux.go + + sock_posix.go + + sockopt_linux.go + + sockopt_posix.go + + sockoptip_linux.go + + sockoptip_posix.go + + tcpsock.go + + tcpsock_posix.go + + tcpsockopt_posix.go + + tcpsockopt_unix.go + + udpsock.go + + udpsock_posix.go + + unixsock.go + + unixsock_posix.go + + +

    + +
    +
    + + + + +

    Constants

    + +
    const (
    +    IPv4len = 4
    +    IPv6len = 16
    +)
    +

    +IP address lengths (bytes). +

    + + + + +

    Variables

    + +
    var (
    +    IPv4bcast     = IPv4(255, 255, 255, 255) // broadcast
    +    IPv4allsys    = IPv4(224, 0, 0, 1)       // all systems
    +    IPv4allrouter = IPv4(224, 0, 0, 2)       // all routers
    +    IPv4zero      = IPv4(0, 0, 0, 0)         // all zeros
    +)
    +

    +Well-known IPv4 addresses +

    + + +
    var (
    +    IPv6zero                   = IP{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}
    +    IPv6unspecified            = IP{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}
    +    IPv6loopback               = IP{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1}
    +    IPv6interfacelocalallnodes = IP{0xff, 0x01, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x01}
    +    IPv6linklocalallnodes      = IP{0xff, 0x02, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x01}
    +    IPv6linklocalallrouters    = IP{0xff, 0x02, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x02}
    +)
    +

    +Well-known IPv6 addresses +

    + + +
    var (
    +    ErrWriteToConnected = errors.New("use of WriteTo with pre-connected connection")
    +)
    +

    +Various errors contained in OpError. +

    + + + + + + +

    func InterfaceAddrs

    +
    func InterfaceAddrs() ([]Addr, error)
    +

    +InterfaceAddrs returns a list of the system's network interface +addresses. +

    + + + + + + + +

    func Interfaces

    +
    func Interfaces() ([]Interface, error)
    +

    +Interfaces returns a list of the system's network interfaces. +

    + + + + + + + +

    func JoinHostPort

    +
    func JoinHostPort(host, port string) string
    +

    +JoinHostPort combines host and port into a network address of the +form "host:port" or, if host contains a colon or a percent sign, +"[host]:port". +

    + + + + + + + +

    func LookupAddr

    +
    func LookupAddr(addr string) (names []string, err error)
    +

    +LookupAddr performs a reverse lookup for the given address, returning a list +of names mapping to that address. +

    + + + + + + + +

    func LookupCNAME

    +
    func LookupCNAME(name string) (cname string, err error)
    +

    +LookupCNAME returns the canonical DNS host for the given name. +Callers that do not care about the canonical name can call +LookupHost or LookupIP directly; both take care of resolving +the canonical name as part of the lookup. +

    + + + + + + + +

    func LookupHost

    +
    func LookupHost(host string) (addrs []string, err error)
    +

    +LookupHost looks up the given host using the local resolver. +It returns an array of that host's addresses. +

    + + + + + + + +

    func LookupIP

    +
    func LookupIP(host string) (ips []IP, err error)
    +

    +LookupIP looks up host using the local resolver. +It returns an array of that host's IPv4 and IPv6 addresses. +

    + + + + + + + +

    func LookupMX

    +
    func LookupMX(name string) (mxs []*MX, err error)
    +

    +LookupMX returns the DNS MX records for the given domain name sorted by preference. +

    + + + + + + + +

    func LookupNS

    +
    func LookupNS(name string) (nss []*NS, err error)
    +

    +LookupNS returns the DNS NS records for the given domain name. +

    + + + + + + + +

    func LookupPort

    +
    func LookupPort(network, service string) (port int, err error)
    +

    +LookupPort looks up the port for the given network and service. +

    + + + + + + + +

    func LookupSRV

    +
    func LookupSRV(service, proto, name string) (cname string, addrs []*SRV, err error)
    +

    +LookupSRV tries to resolve an SRV query of the given service, +protocol, and domain name. The proto is "tcp" or "udp". +The returned records are sorted by priority and randomized +by weight within a priority. +

    +

    +LookupSRV constructs the DNS name to look up following RFC 2782. +That is, it looks up _service._proto.name. To accommodate services +publishing SRV records under non-standard names, if both service +and proto are empty strings, LookupSRV looks up name directly. +

    + + + + + + + +

    func LookupTXT

    +
    func LookupTXT(name string) (txts []string, err error)
    +

    +LookupTXT returns the DNS TXT records for the given domain name. +

    + + + + + + + +

    func SplitHostPort

    +
    func SplitHostPort(hostport string) (host, port string, err error)
    +

    +SplitHostPort splits a network address of the form "host:port", +"[host]:port" or "[ipv6-host%zone]:port" into host or +ipv6-host%zone and port. A literal address or host name for IPv6 +must be enclosed in square brackets, as in "[::1]:80", +"[ipv6-host]:http" or "[ipv6-host%zone]:80". +

    + + + + + + + + +

    type Addr

    +
    type Addr interface {
    +    Network() string // name of the network
    +    String() string  // string form of address
    +}
    +

    +Addr represents a network end point address. +

    + + + + + + + + + + + + + + + + +

    type AddrError

    +
    type AddrError struct {
    +    Err  string
    +    Addr string
    +}
    + + + + + + + + + + + + + + +

    func (*AddrError) Error

    +
    func (e *AddrError) Error() string
    + + + + + + +

    func (*AddrError) Temporary

    +
    func (e *AddrError) Temporary() bool
    + + + + + + +

    func (*AddrError) Timeout

    +
    func (e *AddrError) Timeout() bool
    + + + + + + + + +

    type Conn

    +
    type Conn interface {
    +    // Read reads data from the connection.
    +    // Read can be made to time out and return a Error with Timeout() == true
    +    // after a fixed time limit; see SetDeadline and SetReadDeadline.
    +    Read(b []byte) (n int, err error)
    +
    +    // Write writes data to the connection.
    +    // Write can be made to time out and return a Error with Timeout() == true
    +    // after a fixed time limit; see SetDeadline and SetWriteDeadline.
    +    Write(b []byte) (n int, err error)
    +
    +    // Close closes the connection.
    +    // Any blocked Read or Write operations will be unblocked and return errors.
    +    Close() error
    +
    +    // LocalAddr returns the local network address.
    +    LocalAddr() Addr
    +
    +    // RemoteAddr returns the remote network address.
    +    RemoteAddr() Addr
    +
    +    // SetDeadline sets the read and write deadlines associated
    +    // with the connection. It is equivalent to calling both
    +    // SetReadDeadline and SetWriteDeadline.
    +    //
    +    // A deadline is an absolute time after which I/O operations
    +    // fail with a timeout (see type Error) instead of
    +    // blocking. The deadline applies to all future I/O, not just
    +    // the immediately following call to Read or Write.
    +    //
    +    // An idle timeout can be implemented by repeatedly extending
    +    // the deadline after successful Read or Write calls.
    +    //
    +    // A zero value for t means I/O operations will not time out.
    +    SetDeadline(t time.Time) error
    +
    +    // SetReadDeadline sets the deadline for future Read calls.
    +    // A zero value for t means Read will not time out.
    +    SetReadDeadline(t time.Time) error
    +
    +    // SetWriteDeadline sets the deadline for future Write calls.
    +    // Even if write times out, it may return n > 0, indicating that
    +    // some of the data was successfully written.
    +    // A zero value for t means Write will not time out.
    +    SetWriteDeadline(t time.Time) error
    +}
    +

    +Conn is a generic stream-oriented network connection. +

    +

    +Multiple goroutines may invoke methods on a Conn simultaneously. +

    + + + + + + + + + + + + +

    func Dial

    +
    func Dial(network, address string) (Conn, error)
    +

    +Dial connects to the address on the named network. +

    +

    +Known networks are "tcp", "tcp4" (IPv4-only), "tcp6" (IPv6-only), +"udp", "udp4" (IPv4-only), "udp6" (IPv6-only), "ip", "ip4" +(IPv4-only), "ip6" (IPv6-only), "unix", "unixgram" and +"unixpacket". +

    +

    +For TCP and UDP networks, addresses have the form host:port. +If host is a literal IPv6 address it must be enclosed +in square brackets as in "[::1]:80" or "[ipv6-host%zone]:80". +The functions JoinHostPort and SplitHostPort manipulate addresses +in this form. +If the host is empty, as in ":80", the local system is assumed. +

    +

    +Examples: +

    +
    Dial("tcp", "12.34.56.78:80")
    +Dial("tcp", "google.com:http")
    +Dial("tcp", "[2001:db8::1]:http")
    +Dial("tcp", "[fe80::1%lo0]:80")
    +Dial("tcp", ":80")
    +
    +

    +For IP networks, the network must be "ip", "ip4" or "ip6" followed +by a colon and a protocol number or name and the addr must be a +literal IP address. +

    +

    +Examples: +

    +
    Dial("ip4:1", "127.0.0.1")
    +Dial("ip6:ospf", "::1")
    +
    +

    +For Unix networks, the address must be a file system path. +

    + + + + + +

    func DialTimeout

    +
    func DialTimeout(network, address string, timeout time.Duration) (Conn, error)
    +

    +DialTimeout acts like Dial but takes a timeout. +The timeout includes name resolution, if required. +

    + + + + + +

    func FileConn

    +
    func FileConn(f *os.File) (c Conn, err error)
    +

    +FileConn returns a copy of the network connection corresponding to +the open file f. +It is the caller's responsibility to close f when finished. +Closing c does not affect f, and closing f does not affect c. +

    + + + + + +

    func Pipe

    +
    func Pipe() (Conn, Conn)
    +

    +Pipe creates a synchronous, in-memory, full duplex +network connection; both ends implement the Conn interface. +Reads on one end are matched with writes on the other, +copying data directly between the two; there is no internal +buffering. +

    + + + + + + + + + +

    type DNSConfigError

    +
    type DNSConfigError struct {
    +    Err error
    +}
    +

    +DNSConfigError represents an error reading the machine's DNS configuration. +(No longer used; kept for compatibility.) +

    + + + + + + + + + + + + + + +

    func (*DNSConfigError) Error

    +
    func (e *DNSConfigError) Error() string
    + + + + + + +

    func (*DNSConfigError) Temporary

    +
    func (e *DNSConfigError) Temporary() bool
    + + + + + + +

    func (*DNSConfigError) Timeout

    +
    func (e *DNSConfigError) Timeout() bool
    + + + + + + + + +

    type DNSError

    +
    type DNSError struct {
    +    Err         string // description of the error
    +    Name        string // name looked for
    +    Server      string // server used
    +    IsTimeout   bool   // if true, timed out; not all timeouts set this
    +    IsTemporary bool   // if true, error is temporary; not all errors set this
    +}
    +

    +DNSError represents a DNS lookup error. +

    + + + + + + + + + + + + + + +

    func (*DNSError) Error

    +
    func (e *DNSError) Error() string
    + + + + + + +

    func (*DNSError) Temporary

    +
    func (e *DNSError) Temporary() bool
    +

    +Temporary reports whether the DNS error is known to be temporary. +This is not always known; a DNS lookup may fail due to a temporary +error and return a DNSError for which Temporary returns false. +

    + + + + + + +

    func (*DNSError) Timeout

    +
    func (e *DNSError) Timeout() bool
    +

    +Timeout reports whether the DNS lookup is known to have timed out. +This is not always known; a DNS lookup may fail due to a timeout +and return a DNSError for which Timeout returns false. +

    + + + + + + + + +

    type Dialer

    +
    type Dialer struct {
    +    // Timeout is the maximum amount of time a dial will wait for
    +    // a connect to complete. If Deadline is also set, it may fail
    +    // earlier.
    +    //
    +    // The default is no timeout.
    +    //
    +    // When dialing a name with multiple IP addresses, the timeout
    +    // may be divided between them.
    +    //
    +    // With or without a timeout, the operating system may impose
    +    // its own earlier timeout. For instance, TCP timeouts are
    +    // often around 3 minutes.
    +    Timeout time.Duration
    +
    +    // Deadline is the absolute point in time after which dials
    +    // will fail. If Timeout is set, it may fail earlier.
    +    // Zero means no deadline, or dependent on the operating system
    +    // as with the Timeout option.
    +    Deadline time.Time
    +
    +    // LocalAddr is the local address to use when dialing an
    +    // address. The address must be of a compatible type for the
    +    // network being dialed.
    +    // If nil, a local address is automatically chosen.
    +    LocalAddr Addr
    +
    +    // DualStack enables RFC 6555-compliant "Happy Eyeballs" dialing
    +    // when the network is "tcp" and the destination is a host name
    +    // with both IPv4 and IPv6 addresses. This allows a client to
    +    // tolerate networks where one address family is silently broken.
    +    DualStack bool
    +
    +    // FallbackDelay specifies the length of time to wait before
    +    // spawning a fallback connection, when DualStack is enabled.
    +    // If zero, a default delay of 300ms is used.
    +    FallbackDelay time.Duration
    +
    +    // KeepAlive specifies the keep-alive period for an active
    +    // network connection.
    +    // If zero, keep-alives are not enabled. Network protocols
    +    // that do not support keep-alives ignore this field.
    +    KeepAlive time.Duration
    +
    +    // Cancel is an optional channel whose closure indicates that
    +    // the dial should be canceled. Not all types of dials support
    +    // cancelation.
    +    Cancel <-chan struct{}
    +}
    +

    +A Dialer contains options for connecting to an address. +

    +

    +The zero value for each field is equivalent to dialing +without that option. Dialing with the zero value of Dialer +is therefore equivalent to just calling the Dial function. +

    + + + + + + + + + + + + + + +

    func (*Dialer) Dial

    +
    func (d *Dialer) Dial(network, address string) (Conn, error)
    +

    +Dial connects to the address on the named network. +

    +

    +See func Dial for a description of the network and address +parameters. +

    + + + + + + + + +

    type Error

    +
    type Error interface {
    +    error
    +    Timeout() bool   // Is the error a timeout?
    +    Temporary() bool // Is the error temporary?
    +}
    +

    +An Error represents a network error. +

    + + + + + + + + + + + + + + + + +

    type Flags

    +
    type Flags uint
    + + + +
    const (
    +    FlagUp           Flags = 1 << iota // interface is up
    +    FlagBroadcast                      // interface supports broadcast access capability
    +    FlagLoopback                       // interface is a loopback interface
    +    FlagPointToPoint                   // interface belongs to a point-to-point link
    +    FlagMulticast                      // interface supports multicast access capability
    +)
    + + + + + + + + + + + + + +

    func (Flags) String

    +
    func (f Flags) String() string
    + + + + + + + + +

    type HardwareAddr

    +
    type HardwareAddr []byte
    +

    +A HardwareAddr represents a physical hardware address. +

    + + + + + + + + + + + + +

    func ParseMAC

    +
    func ParseMAC(s string) (hw HardwareAddr, err error)
    +

    +ParseMAC parses s as an IEEE 802 MAC-48, EUI-48, EUI-64, or a 20-octet +IP over InfiniBand link-layer address using one of the following formats: +

    +
    01:23:45:67:89:ab
    +01:23:45:67:89:ab:cd:ef
    +01:23:45:67:89:ab:cd:ef:00:00:01:23:45:67:89:ab:cd:ef:00:00
    +01-23-45-67-89-ab
    +01-23-45-67-89-ab-cd-ef
    +01-23-45-67-89-ab-cd-ef-00-00-01-23-45-67-89-ab-cd-ef-00-00
    +0123.4567.89ab
    +0123.4567.89ab.cdef
    +0123.4567.89ab.cdef.0000.0123.4567.89ab.cdef.0000
    +
    + + + + + + + +

    func (HardwareAddr) String

    +
    func (a HardwareAddr) String() string
    + + + + + + + + +

    type IP

    +
    type IP []byte
    +

    +An IP is a single IP address, a slice of bytes. +Functions in this package accept either 4-byte (IPv4) +or 16-byte (IPv6) slices as input. +

    +

    +Note that in this documentation, referring to an +IP address as an IPv4 address or an IPv6 address +is a semantic property of the address, not just the +length of the byte slice: a 16-byte slice can still +be an IPv4 address. +

    + + + + + + + + + + + + +

    func IPv4

    +
    func IPv4(a, b, c, d byte) IP
    +

    +IPv4 returns the IP address (in 16-byte form) of the +IPv4 address a.b.c.d. +

    + + + + + +

    func ParseCIDR

    +
    func ParseCIDR(s string) (IP, *IPNet, error)
    +

    +ParseCIDR parses s as a CIDR notation IP address and mask, +like "192.168.100.1/24" or "2001:DB8::/48", as defined in +RFC 4632 and RFC 4291. +

    +

    +It returns the IP address and the network implied by the IP +and mask. For example, ParseCIDR("192.168.100.1/16") returns +the IP address 192.168.100.1 and the network 192.168.0.0/16. +

    + + + + + +

    func ParseIP

    +
    func ParseIP(s string) IP
    +

    +ParseIP parses s as an IP address, returning the result. +The string s can be in dotted decimal ("74.125.19.99") +or IPv6 ("2001:4860:0:2001::68") form. +If s is not a valid textual representation of an IP address, +ParseIP returns nil. +

    + + + + + + + +

    func (IP) DefaultMask

    +
    func (ip IP) DefaultMask() IPMask
    +

    +DefaultMask returns the default IP mask for the IP address ip. +Only IPv4 addresses have default masks; DefaultMask returns +nil if ip is not a valid IPv4 address. +

    + + + + + + +

    func (IP) Equal

    +
    func (ip IP) Equal(x IP) bool
    +

    +Equal reports whether ip and x are the same IP address. +An IPv4 address and that same address in IPv6 form are +considered to be equal. +

    + + + + + + +

    func (IP) IsGlobalUnicast

    +
    func (ip IP) IsGlobalUnicast() bool
    +

    +IsGlobalUnicast reports whether ip is a global unicast +address. +

    + + + + + + +

    func (IP) IsInterfaceLocalMulticast

    +
    func (ip IP) IsInterfaceLocalMulticast() bool
    +

    +IsInterfaceLocalMulticast reports whether ip is +an interface-local multicast address. +

    + + + + + + +

    func (IP) IsLinkLocalMulticast

    +
    func (ip IP) IsLinkLocalMulticast() bool
    +

    +IsLinkLocalMulticast reports whether ip is a link-local +multicast address. +

    + + + + + + +

    func (IP) IsLinkLocalUnicast

    +
    func (ip IP) IsLinkLocalUnicast() bool
    +

    +IsLinkLocalUnicast reports whether ip is a link-local +unicast address. +

    + + + + + + +

    func (IP) IsLoopback

    +
    func (ip IP) IsLoopback() bool
    +

    +IsLoopback reports whether ip is a loopback address. +

    + + + + + + +

    func (IP) IsMulticast

    +
    func (ip IP) IsMulticast() bool
    +

    +IsMulticast reports whether ip is a multicast address. +

    + + + + + + +

    func (IP) IsUnspecified

    +
    func (ip IP) IsUnspecified() bool
    +

    +IsUnspecified reports whether ip is an unspecified address. +

    + + + + + + +

    func (IP) MarshalText

    +
    func (ip IP) MarshalText() ([]byte, error)
    +

    +MarshalText implements the encoding.TextMarshaler interface. +The encoding is the same as returned by String. +

    + + + + + + +

    func (IP) Mask

    +
    func (ip IP) Mask(mask IPMask) IP
    +

    +Mask returns the result of masking the IP address ip with mask. +

    + + + + + + +

    func (IP) String

    +
    func (ip IP) String() string
    +

    +String returns the string form of the IP address ip. +If the address is an IPv4 address, the string representation +is dotted decimal ("74.125.19.99"). Otherwise the representation +is IPv6 ("2001:4860:0:2001::68"). +

    + + + + + + +

    func (IP) To16

    +
    func (ip IP) To16() IP
    +

    +To16 converts the IP address ip to a 16-byte representation. +If ip is not an IP address (it is the wrong length), To16 returns nil. +

    + + + + + + +

    func (IP) To4

    +
    func (ip IP) To4() IP
    +

    +To4 converts the IPv4 address ip to a 4-byte representation. +If ip is not an IPv4 address, To4 returns nil. +

    + + + + + + +

    func (*IP) UnmarshalText

    +
    func (ip *IP) UnmarshalText(text []byte) error
    +

    +UnmarshalText implements the encoding.TextUnmarshaler interface. +The IP address is expected in a form accepted by ParseIP. +

    + + + + + + + + +

    type IPAddr

    +
    type IPAddr struct {
    +    IP   IP
    +    Zone string // IPv6 scoped addressing zone
    +}
    +

    +IPAddr represents the address of an IP end point. +

    + + + + + + + + + + + + +

    func ResolveIPAddr

    +
    func ResolveIPAddr(net, addr string) (*IPAddr, error)
    +

    +ResolveIPAddr parses addr as an IP address of the form "host" or +"ipv6-host%zone" and resolves the domain name on the network net, +which must be "ip", "ip4" or "ip6". +

    + + + + + + + +

    func (*IPAddr) Network

    +
    func (a *IPAddr) Network() string
    +

    +Network returns the address's network name, "ip". +

    + + + + + + +

    func (*IPAddr) String

    +
    func (a *IPAddr) String() string
    + + + + + + + + +

    type IPConn

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

    +IPConn is the implementation of the Conn and PacketConn interfaces +for IP network connections. +

    + + + + + + + + + + + + +

    func DialIP

    +
    func DialIP(netProto string, laddr, raddr *IPAddr) (*IPConn, error)
    +

    +DialIP connects to the remote address raddr on the network protocol +netProto, which must be "ip", "ip4", or "ip6" followed by a colon +and a protocol number or name. +

    + + + + + +

    func ListenIP

    +
    func ListenIP(netProto string, laddr *IPAddr) (*IPConn, error)
    +

    +ListenIP listens for incoming IP packets addressed to the local +address laddr. The returned connection's ReadFrom and WriteTo +methods can be used to receive and send IP packets with per-packet +addressing. +

    + + + + + + + +

    func (*IPConn) Close

    +
    func (c *IPConn) Close() error
    +

    +Close closes the connection. +

    + + + + + + +

    func (*IPConn) File

    +
    func (c *IPConn) File() (f *os.File, err error)
    +

    +File sets the underlying os.File to blocking mode and returns a copy. +It is the caller's responsibility to close f when finished. +Closing c does not affect f, and closing f does not affect c. +

    +

    +The returned os.File's file descriptor is different from the connection's. +Attempting to change properties of the original using this duplicate +may or may not have the desired effect. +

    + + + + + + +

    func (*IPConn) LocalAddr

    +
    func (c *IPConn) LocalAddr() Addr
    +

    +LocalAddr returns the local network address. +The Addr returned is shared by all invocations of LocalAddr, so +do not modify it. +

    + + + + + + +

    func (*IPConn) Read

    +
    func (c *IPConn) Read(b []byte) (int, error)
    +

    +Read implements the Conn Read method. +

    + + + + + + +

    func (*IPConn) ReadFrom

    +
    func (c *IPConn) ReadFrom(b []byte) (int, Addr, error)
    +

    +ReadFrom implements the PacketConn ReadFrom method. +

    + + + + + + +

    func (*IPConn) ReadFromIP

    +
    func (c *IPConn) ReadFromIP(b []byte) (int, *IPAddr, error)
    +

    +ReadFromIP reads an IP packet from c, copying the payload into b. +It returns the number of bytes copied into b and the return address +that was on the packet. +

    +

    +ReadFromIP can be made to time out and return an error with +Timeout() == true after a fixed time limit; see SetDeadline and +SetReadDeadline. +

    + + + + + + +

    func (*IPConn) ReadMsgIP

    +
    func (c *IPConn) ReadMsgIP(b, oob []byte) (n, oobn, flags int, addr *IPAddr, err error)
    +

    +ReadMsgIP reads a packet from c, copying the payload into b and the +associated out-of-band data into oob. It returns the number of +bytes copied into b, the number of bytes copied into oob, the flags +that were set on the packet and the source address of the packet. +

    + + + + + + +

    func (*IPConn) RemoteAddr

    +
    func (c *IPConn) RemoteAddr() Addr
    +

    +RemoteAddr returns the remote network address. +The Addr returned is shared by all invocations of RemoteAddr, so +do not modify it. +

    + + + + + + +

    func (*IPConn) SetDeadline

    +
    func (c *IPConn) SetDeadline(t time.Time) error
    +

    +SetDeadline implements the Conn SetDeadline method. +

    + + + + + + +

    func (*IPConn) SetReadBuffer

    +
    func (c *IPConn) SetReadBuffer(bytes int) error
    +

    +SetReadBuffer sets the size of the operating system's +receive buffer associated with the connection. +

    + + + + + + +

    func (*IPConn) SetReadDeadline

    +
    func (c *IPConn) SetReadDeadline(t time.Time) error
    +

    +SetReadDeadline implements the Conn SetReadDeadline method. +

    + + + + + + +

    func (*IPConn) SetWriteBuffer

    +
    func (c *IPConn) SetWriteBuffer(bytes int) error
    +

    +SetWriteBuffer sets the size of the operating system's +transmit buffer associated with the connection. +

    + + + + + + +

    func (*IPConn) SetWriteDeadline

    +
    func (c *IPConn) SetWriteDeadline(t time.Time) error
    +

    +SetWriteDeadline implements the Conn SetWriteDeadline method. +

    + + + + + + +

    func (*IPConn) Write

    +
    func (c *IPConn) Write(b []byte) (int, error)
    +

    +Write implements the Conn Write method. +

    + + + + + + +

    func (*IPConn) WriteMsgIP

    +
    func (c *IPConn) WriteMsgIP(b, oob []byte, addr *IPAddr) (n, oobn int, err error)
    +

    +WriteMsgIP writes a packet to addr via c, copying the payload from +b and the associated out-of-band data from oob. It returns the +number of payload and out-of-band bytes written. +

    + + + + + + +

    func (*IPConn) WriteTo

    +
    func (c *IPConn) WriteTo(b []byte, addr Addr) (int, error)
    +

    +WriteTo implements the PacketConn WriteTo method. +

    + + + + + + +

    func (*IPConn) WriteToIP

    +
    func (c *IPConn) WriteToIP(b []byte, addr *IPAddr) (int, error)
    +

    +WriteToIP writes an IP packet to addr via c, copying the payload +from b. +

    +

    +WriteToIP can be made to time out and return an error with +Timeout() == true after a fixed time limit; see SetDeadline and +SetWriteDeadline. On packet-oriented connections, write timeouts +are rare. +

    + + + + + + + + +

    type IPMask

    +
    type IPMask []byte
    +

    +An IP mask is an IP address. +

    + + + + + + + + + + + + +

    func CIDRMask

    +
    func CIDRMask(ones, bits int) IPMask
    +

    +CIDRMask returns an IPMask consisting of `ones' 1 bits +followed by 0s up to a total length of `bits' bits. +For a mask of this form, CIDRMask is the inverse of IPMask.Size. +

    + + + + + +

    func IPv4Mask

    +
    func IPv4Mask(a, b, c, d byte) IPMask
    +

    +IPv4Mask returns the IP mask (in 4-byte form) of the +IPv4 mask a.b.c.d. +

    + + + + + + + +

    func (IPMask) Size

    +
    func (m IPMask) Size() (ones, bits int)
    +

    +Size returns the number of leading ones and total bits in the mask. +If the mask is not in the canonical form--ones followed by zeros--then +Size returns 0, 0. +

    + + + + + + +

    func (IPMask) String

    +
    func (m IPMask) String() string
    +

    +String returns the hexadecimal form of m, with no punctuation. +

    + + + + + + + + +

    type IPNet

    +
    type IPNet struct {
    +    IP   IP     // network number
    +    Mask IPMask // network mask
    +}
    +

    +An IPNet represents an IP network. +

    + + + + + + + + + + + + + + +

    func (*IPNet) Contains

    +
    func (n *IPNet) Contains(ip IP) bool
    +

    +Contains reports whether the network includes ip. +

    + + + + + + +

    func (*IPNet) Network

    +
    func (n *IPNet) Network() string
    +

    +Network returns the address's network name, "ip+net". +

    + + + + + + +

    func (*IPNet) String

    +
    func (n *IPNet) String() string
    +

    +String returns the CIDR notation of n like "192.168.100.1/24" +or "2001:DB8::/48" as defined in RFC 4632 and RFC 4291. +If the mask is not in the canonical form, it returns the +string which consists of an IP address, followed by a slash +character and a mask expressed as hexadecimal form with no +punctuation like "192.168.100.1/c000ff00". +

    + + + + + + + + +

    type Interface

    +
    type Interface struct {
    +    Index        int          // positive integer that starts at one, zero is never used
    +    MTU          int          // maximum transmission unit
    +    Name         string       // e.g., "en0", "lo0", "eth0.100"
    +    HardwareAddr HardwareAddr // IEEE MAC-48, EUI-48 and EUI-64 form
    +    Flags        Flags        // e.g., FlagUp, FlagLoopback, FlagMulticast
    +}
    +

    +Interface represents a mapping between network interface name +and index. It also represents network interface facility +information. +

    + + + + + + + + + + + + +

    func InterfaceByIndex

    +
    func InterfaceByIndex(index int) (*Interface, error)
    +

    +InterfaceByIndex returns the interface specified by index. +

    + + + + + +

    func InterfaceByName

    +
    func InterfaceByName(name string) (*Interface, error)
    +

    +InterfaceByName returns the interface specified by name. +

    + + + + + + + +

    func (*Interface) Addrs

    +
    func (ifi *Interface) Addrs() ([]Addr, error)
    +

    +Addrs returns interface addresses for a specific interface. +

    + + + + + + +

    func (*Interface) MulticastAddrs

    +
    func (ifi *Interface) MulticastAddrs() ([]Addr, error)
    +

    +MulticastAddrs returns multicast, joined group addresses for +a specific interface. +

    + + + + + + + + +

    type InvalidAddrError

    +
    type InvalidAddrError string
    + + + + + + + + + + + + + + +

    func (InvalidAddrError) Error

    +
    func (e InvalidAddrError) Error() string
    + + + + + + +

    func (InvalidAddrError) Temporary

    +
    func (e InvalidAddrError) Temporary() bool
    + + + + + + +

    func (InvalidAddrError) Timeout

    +
    func (e InvalidAddrError) Timeout() bool
    + + + + + + + + +

    type Listener

    +
    type Listener interface {
    +    // Accept waits for and returns the next connection to the listener.
    +    Accept() (Conn, error)
    +
    +    // Close closes the listener.
    +    // Any blocked Accept operations will be unblocked and return errors.
    +    Close() error
    +
    +    // Addr returns the listener's network address.
    +    Addr() Addr
    +}
    +

    +A Listener is a generic network listener for stream-oriented protocols. +

    +

    +Multiple goroutines may invoke methods on a Listener simultaneously. +

    + + + + + + +
    + +
    +

    Example

    + + + +

    Code:

    +
    +// Listen on TCP port 2000 on all interfaces.
    +l, err := net.Listen("tcp", ":2000")
    +if err != nil {
    +    log.Fatal(err)
    +}
    +defer l.Close()
    +for {
    +    // Wait for a connection.
    +    conn, err := l.Accept()
    +    if err != nil {
    +        log.Fatal(err)
    +    }
    +    // Handle the connection in a new goroutine.
    +    // The loop then returns to accepting, so that
    +    // multiple connections may be served concurrently.
    +    go func(c net.Conn) {
    +        // Echo all incoming data.
    +        io.Copy(c, c)
    +        // Shut down the connection.
    +        c.Close()
    +    }(conn)
    +}
    +
    + + +
    +
    + + + + + + +

    func FileListener

    +
    func FileListener(f *os.File) (ln Listener, err error)
    +

    +FileListener returns a copy of the network listener corresponding +to the open file f. +It is the caller's responsibility to close ln when finished. +Closing ln does not affect f, and closing f does not affect ln. +

    + + + + + +

    func Listen

    +
    func Listen(net, laddr string) (Listener, error)
    +

    +Listen announces on the local network address laddr. +The network net must be a stream-oriented network: "tcp", "tcp4", +"tcp6", "unix" or "unixpacket". +For TCP and UDP, the syntax of laddr is "host:port", like "127.0.0.1:8080". +If host is omitted, as in ":8080", Listen listens on all available interfaces +instead of just the interface with the given host address. +See Dial for more details about address syntax. +

    + + + + + + + + + +

    type MX

    +
    type MX struct {
    +    Host string
    +    Pref uint16
    +}
    +

    +An MX represents a single DNS MX record. +

    + + + + + + + + + + + + + + + + +

    type NS

    +
    type NS struct {
    +    Host string
    +}
    +

    +An NS represents a single DNS NS record. +

    + + + + + + + + + + + + + + + + +

    type OpError

    +
    type OpError struct {
    +    // Op is the operation which caused the error, such as
    +    // "read" or "write".
    +    Op string
    +
    +    // Net is the network type on which this error occurred,
    +    // such as "tcp" or "udp6".
    +    Net string
    +
    +    // For operations involving a remote network connection, like
    +    // Dial, Read, or Write, Source is the corresponding local
    +    // network address.
    +    Source Addr
    +
    +    // Addr is the network address for which this error occurred.
    +    // For local operations, like Listen or SetDeadline, Addr is
    +    // the address of the local endpoint being manipulated.
    +    // For operations involving a remote network connection, like
    +    // Dial, Read, or Write, Addr is the remote address of that
    +    // connection.
    +    Addr Addr
    +
    +    // Err is the error that occurred during the operation.
    +    Err error
    +}
    +

    +OpError is the error type usually returned by functions in the net +package. It describes the operation, network type, and address of +an error. +

    + + + + + + + + + + + + + + +

    func (*OpError) Error

    +
    func (e *OpError) Error() string
    + + + + + + +

    func (*OpError) Temporary

    +
    func (e *OpError) Temporary() bool
    + + + + + + +

    func (*OpError) Timeout

    +
    func (e *OpError) Timeout() bool
    + + + + + + + + +

    type PacketConn

    +
    type PacketConn interface {
    +    // ReadFrom reads a packet from the connection,
    +    // copying the payload into b.  It returns the number of
    +    // bytes copied into b and the return address that
    +    // was on the packet.
    +    // ReadFrom can be made to time out and return
    +    // an error with Timeout() == true after a fixed time limit;
    +    // see SetDeadline and SetReadDeadline.
    +    ReadFrom(b []byte) (n int, addr Addr, err error)
    +
    +    // WriteTo writes a packet with payload b to addr.
    +    // WriteTo can be made to time out and return
    +    // an error with Timeout() == true after a fixed time limit;
    +    // see SetDeadline and SetWriteDeadline.
    +    // On packet-oriented connections, write timeouts are rare.
    +    WriteTo(b []byte, addr Addr) (n int, err error)
    +
    +    // Close closes the connection.
    +    // Any blocked ReadFrom or WriteTo operations will be unblocked and return errors.
    +    Close() error
    +
    +    // LocalAddr returns the local network address.
    +    LocalAddr() Addr
    +
    +    // SetDeadline sets the read and write deadlines associated
    +    // with the connection.
    +    SetDeadline(t time.Time) error
    +
    +    // SetReadDeadline sets the deadline for future Read calls.
    +    // If the deadline is reached, Read will fail with a timeout
    +    // (see type Error) instead of blocking.
    +    // A zero value for t means Read will not time out.
    +    SetReadDeadline(t time.Time) error
    +
    +    // SetWriteDeadline sets the deadline for future Write calls.
    +    // If the deadline is reached, Write will fail with a timeout
    +    // (see type Error) instead of blocking.
    +    // A zero value for t means Write will not time out.
    +    // Even if write times out, it may return n > 0, indicating that
    +    // some of the data was successfully written.
    +    SetWriteDeadline(t time.Time) error
    +}
    +

    +PacketConn is a generic packet-oriented network connection. +

    +

    +Multiple goroutines may invoke methods on a PacketConn simultaneously. +

    + + + + + + + + + + + + +

    func FilePacketConn

    +
    func FilePacketConn(f *os.File) (c PacketConn, err error)
    +

    +FilePacketConn returns a copy of the packet network connection +corresponding to the open file f. +It is the caller's responsibility to close f when finished. +Closing c does not affect f, and closing f does not affect c. +

    + + + + + +

    func ListenPacket

    +
    func ListenPacket(net, laddr string) (PacketConn, error)
    +

    +ListenPacket announces on the local network address laddr. +The network net must be a packet-oriented network: "udp", "udp4", +"udp6", "ip", "ip4", "ip6" or "unixgram". +For TCP and UDP, the syntax of laddr is "host:port", like "127.0.0.1:8080". +If host is omitted, as in ":8080", ListenPacket listens on all available interfaces +instead of just the interface with the given host address. +See Dial for the syntax of laddr. +

    + + + + + + + + + +

    type ParseError

    +
    type ParseError struct {
    +    // Type is the type of string that was expected, such as
    +    // "IP address", "CIDR address".
    +    Type string
    +
    +    // Text is the malformed text string.
    +    Text string
    +}
    +

    +A ParseError is the error type of literal network address parsers. +

    + + + + + + + + + + + + + + +

    func (*ParseError) Error

    +
    func (e *ParseError) Error() string
    + + + + + + + + +

    type SRV

    +
    type SRV struct {
    +    Target   string
    +    Port     uint16
    +    Priority uint16
    +    Weight   uint16
    +}
    +

    +An SRV represents a single DNS SRV record. +

    + + + + + + + + + + + + + + + + +

    type TCPAddr

    +
    type TCPAddr struct {
    +    IP   IP
    +    Port int
    +    Zone string // IPv6 scoped addressing zone
    +}
    +

    +TCPAddr represents the address of a TCP end point. +

    + + + + + + + + + + + + +

    func ResolveTCPAddr

    +
    func ResolveTCPAddr(net, addr string) (*TCPAddr, error)
    +

    +ResolveTCPAddr parses addr as a TCP address of the form "host:port" +or "[ipv6-host%zone]:port" and resolves a pair of domain name and +port name on the network net, which must be "tcp", "tcp4" or +"tcp6". A literal address or host name for IPv6 must be enclosed +in square brackets, as in "[::1]:80", "[ipv6-host]:http" or +"[ipv6-host%zone]:80". +

    + + + + + + + +

    func (*TCPAddr) Network

    +
    func (a *TCPAddr) Network() string
    +

    +Network returns the address's network name, "tcp". +

    + + + + + + +

    func (*TCPAddr) String

    +
    func (a *TCPAddr) String() string
    + + + + + + + + +

    type TCPConn

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

    +TCPConn is an implementation of the Conn interface for TCP network +connections. +

    + + + + + + + + + + + + +

    func DialTCP

    +
    func DialTCP(net string, laddr, raddr *TCPAddr) (*TCPConn, error)
    +

    +DialTCP connects to the remote address raddr on the network net, +which must be "tcp", "tcp4", or "tcp6". If laddr is not nil, it is +used as the local address for the connection. +

    + + + + + + + +

    func (*TCPConn) Close

    +
    func (c *TCPConn) Close() error
    +

    +Close closes the connection. +

    + + + + + + +

    func (*TCPConn) CloseRead

    +
    func (c *TCPConn) CloseRead() error
    +

    +CloseRead shuts down the reading side of the TCP connection. +Most callers should just use Close. +

    + + + + + + +

    func (*TCPConn) CloseWrite

    +
    func (c *TCPConn) CloseWrite() error
    +

    +CloseWrite shuts down the writing side of the TCP connection. +Most callers should just use Close. +

    + + + + + + +

    func (*TCPConn) File

    +
    func (c *TCPConn) File() (f *os.File, err error)
    +

    +File sets the underlying os.File to blocking mode and returns a copy. +It is the caller's responsibility to close f when finished. +Closing c does not affect f, and closing f does not affect c. +

    +

    +The returned os.File's file descriptor is different from the connection's. +Attempting to change properties of the original using this duplicate +may or may not have the desired effect. +

    + + + + + + +

    func (*TCPConn) LocalAddr

    +
    func (c *TCPConn) LocalAddr() Addr
    +

    +LocalAddr returns the local network address. +The Addr returned is shared by all invocations of LocalAddr, so +do not modify it. +

    + + + + + + +

    func (*TCPConn) Read

    +
    func (c *TCPConn) Read(b []byte) (int, error)
    +

    +Read implements the Conn Read method. +

    + + + + + + +

    func (*TCPConn) ReadFrom

    +
    func (c *TCPConn) ReadFrom(r io.Reader) (int64, error)
    +

    +ReadFrom implements the io.ReaderFrom ReadFrom method. +

    + + + + + + +

    func (*TCPConn) RemoteAddr

    +
    func (c *TCPConn) RemoteAddr() Addr
    +

    +RemoteAddr returns the remote network address. +The Addr returned is shared by all invocations of RemoteAddr, so +do not modify it. +

    + + + + + + +

    func (*TCPConn) SetDeadline

    +
    func (c *TCPConn) SetDeadline(t time.Time) error
    +

    +SetDeadline implements the Conn SetDeadline method. +

    + + + + + + +

    func (*TCPConn) SetKeepAlive

    +
    func (c *TCPConn) SetKeepAlive(keepalive bool) error
    +

    +SetKeepAlive sets whether the operating system should send +keepalive messages on the connection. +

    + + + + + + +

    func (*TCPConn) SetKeepAlivePeriod

    +
    func (c *TCPConn) SetKeepAlivePeriod(d time.Duration) error
    +

    +SetKeepAlivePeriod sets period between keep alives. +

    + + + + + + +

    func (*TCPConn) SetLinger

    +
    func (c *TCPConn) SetLinger(sec int) error
    +

    +SetLinger sets the behavior of Close on a connection which still +has data waiting to be sent or to be acknowledged. +

    +

    +If sec < 0 (the default), the operating system finishes sending the +data in the background. +

    +

    +If sec == 0, the operating system discards any unsent or +unacknowledged data. +

    +

    +If sec > 0, the data is sent in the background as with sec < 0. On +some operating systems after sec seconds have elapsed any remaining +unsent data may be discarded. +

    + + + + + + +

    func (*TCPConn) SetNoDelay

    +
    func (c *TCPConn) SetNoDelay(noDelay bool) error
    +

    +SetNoDelay controls whether the operating system should delay +packet transmission in hopes of sending fewer packets (Nagle's +algorithm). The default is true (no delay), meaning that data is +sent as soon as possible after a Write. +

    + + + + + + +

    func (*TCPConn) SetReadBuffer

    +
    func (c *TCPConn) SetReadBuffer(bytes int) error
    +

    +SetReadBuffer sets the size of the operating system's +receive buffer associated with the connection. +

    + + + + + + +

    func (*TCPConn) SetReadDeadline

    +
    func (c *TCPConn) SetReadDeadline(t time.Time) error
    +

    +SetReadDeadline implements the Conn SetReadDeadline method. +

    + + + + + + +

    func (*TCPConn) SetWriteBuffer

    +
    func (c *TCPConn) SetWriteBuffer(bytes int) error
    +

    +SetWriteBuffer sets the size of the operating system's +transmit buffer associated with the connection. +

    + + + + + + +

    func (*TCPConn) SetWriteDeadline

    +
    func (c *TCPConn) SetWriteDeadline(t time.Time) error
    +

    +SetWriteDeadline implements the Conn SetWriteDeadline method. +

    + + + + + + +

    func (*TCPConn) Write

    +
    func (c *TCPConn) Write(b []byte) (int, error)
    +

    +Write implements the Conn Write method. +

    + + + + + + + + +

    type TCPListener

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

    +TCPListener is a TCP network listener. Clients should typically +use variables of type Listener instead of assuming TCP. +

    + + + + + + + + + + + + +

    func ListenTCP

    +
    func ListenTCP(net string, laddr *TCPAddr) (*TCPListener, error)
    +

    +ListenTCP announces on the TCP address laddr and returns a TCP +listener. Net must be "tcp", "tcp4", or "tcp6". If laddr has a +port of 0, ListenTCP will choose an available port. The caller can +use the Addr method of TCPListener to retrieve the chosen address. +

    + + + + + + + +

    func (*TCPListener) Accept

    +
    func (l *TCPListener) Accept() (Conn, error)
    +

    +Accept implements the Accept method in the Listener interface; it +waits for the next call and returns a generic Conn. +

    + + + + + + +

    func (*TCPListener) AcceptTCP

    +
    func (l *TCPListener) AcceptTCP() (*TCPConn, error)
    +

    +AcceptTCP accepts the next incoming call and returns the new +connection. +

    + + + + + + +

    func (*TCPListener) Addr

    +
    func (l *TCPListener) Addr() Addr
    +

    +Addr returns the listener's network address, a *TCPAddr. +The Addr returned is shared by all invocations of Addr, so +do not modify it. +

    + + + + + + +

    func (*TCPListener) Close

    +
    func (l *TCPListener) Close() error
    +

    +Close stops listening on the TCP address. +Already Accepted connections are not closed. +

    + + + + + + +

    func (*TCPListener) File

    +
    func (l *TCPListener) File() (f *os.File, err error)
    +

    +File returns a copy of the underlying os.File, set to blocking +mode. It is the caller's responsibility to close f when finished. +Closing l does not affect f, and closing f does not affect l. +

    +

    +The returned os.File's file descriptor is different from the +connection's. Attempting to change properties of the original +using this duplicate may or may not have the desired effect. +

    + + + + + + +

    func (*TCPListener) SetDeadline

    +
    func (l *TCPListener) SetDeadline(t time.Time) error
    +

    +SetDeadline sets the deadline associated with the listener. +A zero time value disables the deadline. +

    + + + + + + + + +

    type UDPAddr

    +
    type UDPAddr struct {
    +    IP   IP
    +    Port int
    +    Zone string // IPv6 scoped addressing zone
    +}
    +

    +UDPAddr represents the address of a UDP end point. +

    + + + + + + + + + + + + +

    func ResolveUDPAddr

    +
    func ResolveUDPAddr(net, addr string) (*UDPAddr, error)
    +

    +ResolveUDPAddr parses addr as a UDP address of the form "host:port" +or "[ipv6-host%zone]:port" and resolves a pair of domain name and +port name on the network net, which must be "udp", "udp4" or +"udp6". A literal address or host name for IPv6 must be enclosed +in square brackets, as in "[::1]:80", "[ipv6-host]:http" or +"[ipv6-host%zone]:80". +

    + + + + + + + +

    func (*UDPAddr) Network

    +
    func (a *UDPAddr) Network() string
    +

    +Network returns the address's network name, "udp". +

    + + + + + + +

    func (*UDPAddr) String

    +
    func (a *UDPAddr) String() string
    + + + + + + + + +

    type UDPConn

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

    +UDPConn is the implementation of the Conn and PacketConn interfaces +for UDP network connections. +

    + + + + + + + + + + + + +

    func DialUDP

    +
    func DialUDP(net string, laddr, raddr *UDPAddr) (*UDPConn, error)
    +

    +DialUDP connects to the remote address raddr on the network net, +which must be "udp", "udp4", or "udp6". If laddr is not nil, it is +used as the local address for the connection. +

    + + + + + +

    func ListenMulticastUDP

    +
    func ListenMulticastUDP(network string, ifi *Interface, gaddr *UDPAddr) (*UDPConn, error)
    +

    +ListenMulticastUDP listens for incoming multicast UDP packets +addressed to the group address gaddr on the interface ifi. +Network must be "udp", "udp4" or "udp6". +ListenMulticastUDP uses the system-assigned multicast interface +when ifi is nil, although this is not recommended because the +assignment depends on platforms and sometimes it might require +routing configuration. +

    +

    +ListenMulticastUDP is just for convenience of simple, small +applications. There are golang.org/x/net/ipv4 and +golang.org/x/net/ipv6 packages for general purpose uses. +

    + + + + + +

    func ListenUDP

    +
    func ListenUDP(net string, laddr *UDPAddr) (*UDPConn, error)
    +

    +ListenUDP listens for incoming UDP packets addressed to the local +address laddr. Net must be "udp", "udp4", or "udp6". If laddr has +a port of 0, ListenUDP will choose an available port. +The LocalAddr method of the returned UDPConn can be used to +discover the port. The returned connection's ReadFrom and WriteTo +methods can be used to receive and send UDP packets with per-packet +addressing. +

    + + + + + + + +

    func (*UDPConn) Close

    +
    func (c *UDPConn) Close() error
    +

    +Close closes the connection. +

    + + + + + + +

    func (*UDPConn) File

    +
    func (c *UDPConn) File() (f *os.File, err error)
    +

    +File sets the underlying os.File to blocking mode and returns a copy. +It is the caller's responsibility to close f when finished. +Closing c does not affect f, and closing f does not affect c. +

    +

    +The returned os.File's file descriptor is different from the connection's. +Attempting to change properties of the original using this duplicate +may or may not have the desired effect. +

    + + + + + + +

    func (*UDPConn) LocalAddr

    +
    func (c *UDPConn) LocalAddr() Addr
    +

    +LocalAddr returns the local network address. +The Addr returned is shared by all invocations of LocalAddr, so +do not modify it. +

    + + + + + + +

    func (*UDPConn) Read

    +
    func (c *UDPConn) Read(b []byte) (int, error)
    +

    +Read implements the Conn Read method. +

    + + + + + + +

    func (*UDPConn) ReadFrom

    +
    func (c *UDPConn) ReadFrom(b []byte) (int, Addr, error)
    +

    +ReadFrom implements the PacketConn ReadFrom method. +

    + + + + + + +

    func (*UDPConn) ReadFromUDP

    +
    func (c *UDPConn) ReadFromUDP(b []byte) (int, *UDPAddr, error)
    +

    +ReadFromUDP reads a UDP packet from c, copying the payload into b. +It returns the number of bytes copied into b and the return address +that was on the packet. +

    +

    +ReadFromUDP can be made to time out and return an error with +Timeout() == true after a fixed time limit; see SetDeadline and +SetReadDeadline. +

    + + + + + + +

    func (*UDPConn) ReadMsgUDP

    +
    func (c *UDPConn) ReadMsgUDP(b, oob []byte) (n, oobn, flags int, addr *UDPAddr, err error)
    +

    +ReadMsgUDP reads a packet from c, copying the payload into b and +the associated out-of-band data into oob. It returns the number +of bytes copied into b, the number of bytes copied into oob, the +flags that were set on the packet and the source address of the +packet. +

    + + + + + + +

    func (*UDPConn) RemoteAddr

    +
    func (c *UDPConn) RemoteAddr() Addr
    +

    +RemoteAddr returns the remote network address. +The Addr returned is shared by all invocations of RemoteAddr, so +do not modify it. +

    + + + + + + +

    func (*UDPConn) SetDeadline

    +
    func (c *UDPConn) SetDeadline(t time.Time) error
    +

    +SetDeadline implements the Conn SetDeadline method. +

    + + + + + + +

    func (*UDPConn) SetReadBuffer

    +
    func (c *UDPConn) SetReadBuffer(bytes int) error
    +

    +SetReadBuffer sets the size of the operating system's +receive buffer associated with the connection. +

    + + + + + + +

    func (*UDPConn) SetReadDeadline

    +
    func (c *UDPConn) SetReadDeadline(t time.Time) error
    +

    +SetReadDeadline implements the Conn SetReadDeadline method. +

    + + + + + + +

    func (*UDPConn) SetWriteBuffer

    +
    func (c *UDPConn) SetWriteBuffer(bytes int) error
    +

    +SetWriteBuffer sets the size of the operating system's +transmit buffer associated with the connection. +

    + + + + + + +

    func (*UDPConn) SetWriteDeadline

    +
    func (c *UDPConn) SetWriteDeadline(t time.Time) error
    +

    +SetWriteDeadline implements the Conn SetWriteDeadline method. +

    + + + + + + +

    func (*UDPConn) Write

    +
    func (c *UDPConn) Write(b []byte) (int, error)
    +

    +Write implements the Conn Write method. +

    + + + + + + +

    func (*UDPConn) WriteMsgUDP

    +
    func (c *UDPConn) WriteMsgUDP(b, oob []byte, addr *UDPAddr) (n, oobn int, err error)
    +

    +WriteMsgUDP writes a packet to addr via c if c isn't connected, or +to c's remote destination address if c is connected (in which case +addr must be nil). The payload is copied from b and the associated +out-of-band data is copied from oob. It returns the number of +payload and out-of-band bytes written. +

    + + + + + + +

    func (*UDPConn) WriteTo

    +
    func (c *UDPConn) WriteTo(b []byte, addr Addr) (int, error)
    +

    +WriteTo implements the PacketConn WriteTo method. +

    + + + + + + +

    func (*UDPConn) WriteToUDP

    +
    func (c *UDPConn) WriteToUDP(b []byte, addr *UDPAddr) (int, error)
    +

    +WriteToUDP writes a UDP packet to addr via c, copying the payload +from b. +

    +

    +WriteToUDP can be made to time out and return an error with +Timeout() == true after a fixed time limit; see SetDeadline and +SetWriteDeadline. On packet-oriented connections, write timeouts +are rare. +

    + + + + + + + + +

    type UnixAddr

    +
    type UnixAddr struct {
    +    Name string
    +    Net  string
    +}
    +

    +UnixAddr represents the address of a Unix domain socket end point. +

    + + + + + + + + + + + + +

    func ResolveUnixAddr

    +
    func ResolveUnixAddr(net, addr string) (*UnixAddr, error)
    +

    +ResolveUnixAddr parses addr as a Unix domain socket address. +The string net gives the network name, "unix", "unixgram" or +"unixpacket". +

    + + + + + + + +

    func (*UnixAddr) Network

    +
    func (a *UnixAddr) Network() string
    +

    +Network returns the address's network name, "unix", "unixgram" or +"unixpacket". +

    + + + + + + +

    func (*UnixAddr) String

    +
    func (a *UnixAddr) String() string
    + + + + + + + + +

    type UnixConn

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

    +UnixConn is an implementation of the Conn interface for connections +to Unix domain sockets. +

    + + + + + + + + + + + + +

    func DialUnix

    +
    func DialUnix(net string, laddr, raddr *UnixAddr) (*UnixConn, error)
    +

    +DialUnix connects to the remote address raddr on the network net, +which must be "unix", "unixgram" or "unixpacket". If laddr is not +nil, it is used as the local address for the connection. +

    + + + + + +

    func ListenUnixgram

    +
    func ListenUnixgram(net string, laddr *UnixAddr) (*UnixConn, error)
    +

    +ListenUnixgram listens for incoming Unix datagram packets addressed +to the local address laddr. The network net must be "unixgram". +The returned connection's ReadFrom and WriteTo methods can be used +to receive and send packets with per-packet addressing. +

    + + + + + + + +

    func (*UnixConn) Close

    +
    func (c *UnixConn) Close() error
    +

    +Close closes the connection. +

    + + + + + + +

    func (*UnixConn) CloseRead

    +
    func (c *UnixConn) CloseRead() error
    +

    +CloseRead shuts down the reading side of the Unix domain connection. +Most callers should just use Close. +

    + + + + + + +

    func (*UnixConn) CloseWrite

    +
    func (c *UnixConn) CloseWrite() error
    +

    +CloseWrite shuts down the writing side of the Unix domain connection. +Most callers should just use Close. +

    + + + + + + +

    func (*UnixConn) File

    +
    func (c *UnixConn) File() (f *os.File, err error)
    +

    +File sets the underlying os.File to blocking mode and returns a copy. +It is the caller's responsibility to close f when finished. +Closing c does not affect f, and closing f does not affect c. +

    +

    +The returned os.File's file descriptor is different from the connection's. +Attempting to change properties of the original using this duplicate +may or may not have the desired effect. +

    + + + + + + +

    func (*UnixConn) LocalAddr

    +
    func (c *UnixConn) LocalAddr() Addr
    +

    +LocalAddr returns the local network address. +The Addr returned is shared by all invocations of LocalAddr, so +do not modify it. +

    + + + + + + +

    func (*UnixConn) Read

    +
    func (c *UnixConn) Read(b []byte) (int, error)
    +

    +Read implements the Conn Read method. +

    + + + + + + +

    func (*UnixConn) ReadFrom

    +
    func (c *UnixConn) ReadFrom(b []byte) (int, Addr, error)
    +

    +ReadFrom implements the PacketConn ReadFrom method. +

    + + + + + + +

    func (*UnixConn) ReadFromUnix

    +
    func (c *UnixConn) ReadFromUnix(b []byte) (int, *UnixAddr, error)
    +

    +ReadFromUnix reads a packet from c, copying the payload into b. It +returns the number of bytes copied into b and the source address of +the packet. +

    +

    +ReadFromUnix can be made to time out and return an error with +Timeout() == true after a fixed time limit; see SetDeadline and +SetReadDeadline. +

    + + + + + + +

    func (*UnixConn) ReadMsgUnix

    +
    func (c *UnixConn) ReadMsgUnix(b, oob []byte) (n, oobn, flags int, addr *UnixAddr, err error)
    +

    +ReadMsgUnix reads a packet from c, copying the payload into b and +the associated out-of-band data into oob. It returns the number of +bytes copied into b, the number of bytes copied into oob, the flags +that were set on the packet, and the source address of the packet. +

    + + + + + + +

    func (*UnixConn) RemoteAddr

    +
    func (c *UnixConn) RemoteAddr() Addr
    +

    +RemoteAddr returns the remote network address. +The Addr returned is shared by all invocations of RemoteAddr, so +do not modify it. +

    + + + + + + +

    func (*UnixConn) SetDeadline

    +
    func (c *UnixConn) SetDeadline(t time.Time) error
    +

    +SetDeadline implements the Conn SetDeadline method. +

    + + + + + + +

    func (*UnixConn) SetReadBuffer

    +
    func (c *UnixConn) SetReadBuffer(bytes int) error
    +

    +SetReadBuffer sets the size of the operating system's +receive buffer associated with the connection. +

    + + + + + + +

    func (*UnixConn) SetReadDeadline

    +
    func (c *UnixConn) SetReadDeadline(t time.Time) error
    +

    +SetReadDeadline implements the Conn SetReadDeadline method. +

    + + + + + + +

    func (*UnixConn) SetWriteBuffer

    +
    func (c *UnixConn) SetWriteBuffer(bytes int) error
    +

    +SetWriteBuffer sets the size of the operating system's +transmit buffer associated with the connection. +

    + + + + + + +

    func (*UnixConn) SetWriteDeadline

    +
    func (c *UnixConn) SetWriteDeadline(t time.Time) error
    +

    +SetWriteDeadline implements the Conn SetWriteDeadline method. +

    + + + + + + +

    func (*UnixConn) Write

    +
    func (c *UnixConn) Write(b []byte) (int, error)
    +

    +Write implements the Conn Write method. +

    + + + + + + +

    func (*UnixConn) WriteMsgUnix

    +
    func (c *UnixConn) WriteMsgUnix(b, oob []byte, addr *UnixAddr) (n, oobn int, err error)
    +

    +WriteMsgUnix writes a packet to addr via c, copying the payload +from b and the associated out-of-band data from oob. It returns +the number of payload and out-of-band bytes written. +

    + + + + + + +

    func (*UnixConn) WriteTo

    +
    func (c *UnixConn) WriteTo(b []byte, addr Addr) (n int, err error)
    +

    +WriteTo implements the PacketConn WriteTo method. +

    + + + + + + +

    func (*UnixConn) WriteToUnix

    +
    func (c *UnixConn) WriteToUnix(b []byte, addr *UnixAddr) (int, error)
    +

    +WriteToUnix writes a packet to addr via c, copying the payload from b. +

    +

    +WriteToUnix can be made to time out and return an error with +Timeout() == true after a fixed time limit; see SetDeadline and +SetWriteDeadline. On packet-oriented connections, write timeouts +are rare. +

    + + + + + + + + +

    type UnixListener

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

    +UnixListener is a Unix domain socket listener. Clients should +typically use variables of type Listener instead of assuming Unix +domain sockets. +

    + + + + + + + + + + + + +

    func ListenUnix

    +
    func ListenUnix(net string, laddr *UnixAddr) (*UnixListener, error)
    +

    +ListenUnix announces on the Unix domain socket laddr and returns a +Unix listener. The network net must be "unix" or "unixpacket". +

    + + + + + + + +

    func (*UnixListener) Accept

    +
    func (l *UnixListener) Accept() (c Conn, err error)
    +

    +Accept implements the Accept method in the Listener interface; it +waits for the next call and returns a generic Conn. +

    + + + + + + +

    func (*UnixListener) AcceptUnix

    +
    func (l *UnixListener) AcceptUnix() (*UnixConn, error)
    +

    +AcceptUnix accepts the next incoming call and returns the new +connection. +

    + + + + + + +

    func (*UnixListener) Addr

    +
    func (l *UnixListener) Addr() Addr
    +

    +Addr returns the listener's network address. +The Addr returned is shared by all invocations of Addr, so +do not modify it. +

    + + + + + + +

    func (*UnixListener) Close

    +
    func (l *UnixListener) Close() error
    +

    +Close stops listening on the Unix address. Already accepted +connections are not closed. +

    + + + + + + +

    func (*UnixListener) File

    +
    func (l *UnixListener) File() (f *os.File, err error)
    +

    +File returns a copy of the underlying os.File, set to blocking +mode. It is the caller's responsibility to close f when finished. +Closing l does not affect f, and closing f does not affect l. +

    +

    +The returned os.File's file descriptor is different from the +connection's. Attempting to change properties of the original +using this duplicate may or may not have the desired effect. +

    + + + + + + +

    func (*UnixListener) SetDeadline

    +
    func (l *UnixListener) SetDeadline(t time.Time) error
    +

    +SetDeadline sets the deadline associated with the listener. +A zero time value disables the deadline. +

    + + + + + + + + +

    type UnknownNetworkError

    +
    type UnknownNetworkError string
    + + + + + + + + + + + + + + +

    func (UnknownNetworkError) Error

    +
    func (e UnknownNetworkError) Error() string
    + + + + + + +

    func (UnknownNetworkError) Temporary

    +
    func (e UnknownNetworkError) Temporary() bool
    + + + + + + +

    func (UnknownNetworkError) Timeout

    +
    func (e UnknownNetworkError) Timeout() bool
    + + + + + + + + + + +

    Bugs

    +
      + +
    • On every POSIX platform, reads from the "ip4" network +using the ReadFrom or ReadFromIP method might not return a complete +IPv4 packet, including its header, even if there is space +available. This can occur even in cases where Read or ReadMsgIP +could return a complete packet. For this reason, it is recommended +that you do not uses these methods if it is important to receive a +full packet. + +The Go 1 compatibility guidelines make it impossible for us to +change the behavior of these methods; use Read or ReadMsgIP +instead. +
    • + +
    • On DragonFly BSD and OpenBSD, listening on the +"tcp" and "udp" networks does not listen for both IPv4 and IPv6 +connections. This is due to the fact that IPv4 traffic will not be +routed to an IPv6 socket - two separate sockets are required if +both address families are to be supported. +See inet6(4) for details. +
    • + +
    + + + + + + + + + +

    Subdirectories

    + + + + +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    NameSynopsis
    ..
    + http + + Package http provides HTTP client and server implementations. +
    + cgi + + Package cgi implements CGI (Common Gateway Interface) as specified in RFC 3875. +
    + cookiejar + + Package cookiejar implements an in-memory RFC 6265-compliant http.CookieJar. +
    + fcgi + + Package fcgi implements the FastCGI protocol. +
    + httptest + + Package httptest provides utilities for HTTP testing. +
    + httputil + + Package httputil provides HTTP utility functions, complementing the more common ones in the net/http package. +
    + pprof + + Package pprof serves via its HTTP server runtime profiling data in the format expected by the pprof visualization tool. +
    + mail + + Package mail implements parsing of mail messages. +
    + rpc + + Package rpc provides access to the exported methods of an object across a network or other I/O connection. +
    + jsonrpc + + Package jsonrpc implements a JSON-RPC ClientCodec and ServerCodec for the rpc package. +
    + smtp + + Package smtp implements the Simple Mail Transfer Protocol as defined in RFC 5321. +
    + textproto + + Package textproto implements generic support for text-based request/response protocols in the style of HTTP, NNTP, and SMTP. +
    + url + + Package url parses URLs and implements query escaping. +
    +
    + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/net/mail/index.html b/pkg/net/mail/index.html new file mode 100644 index 0000000..32cd972 --- /dev/null +++ b/pkg/net/mail/index.html @@ -0,0 +1,591 @@ + + + + + + + + mail - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Package mail

    + + + + + + + + + + + + + + +
    +
    +
    import "net/mail"
    +
    +
    +
    Overview
    +
    Index
    + +
    Examples
    + + +
    +
    + +
    + +
    +

    Overview ▾

    +

    +Package mail implements parsing of mail messages. +

    +

    +For the most part, this package follows the syntax as specified by RFC 5322. +Notable divergences: +

    +
    * Obsolete address formats are not parsed, including addresses with
    +  embedded route information.
    +* Group addresses are not parsed.
    +* The full range of spacing (the CFWS syntax element) is not supported,
    +  such as breaking addresses across lines.
    +
    + +
    +
    + + + + + + + + +

    Variables

    + +
    var ErrHeaderNotPresent = errors.New("mail: header not in message")
    + + + + + + +

    func ParseAddressList

    +
    func ParseAddressList(list string) ([]*Address, error)
    +

    +ParseAddressList parses the given string as a list of addresses. +

    + +
    + +
    +

    Example

    + + + +

    Code:

    +
    const list = "Alice <alice@example.com>, Bob <bob@example.com>, Eve <eve@example.com>"
    +emails, err := mail.ParseAddressList(list)
    +if err != nil {
    +    log.Fatal(err)
    +}
    +
    +for _, v := range emails {
    +    fmt.Println(v.Name, v.Address)
    +}
    +
    +
    + +

    Output:

    +
    Alice alice@example.com
    +Bob bob@example.com
    +Eve eve@example.com
    +
    + + +
    +
    + + + + + + + +

    type Address

    +
    type Address struct {
    +    Name    string // Proper name; may be empty.
    +    Address string // user@domain
    +}
    +

    +Address represents a single mail address. +An address such as "Barry Gibbs <bg@example.com>" is represented +as Address{Name: "Barry Gibbs", Address: "bg@example.com"}. +

    + + + + + + + + + + + + +

    func ParseAddress

    +
    func ParseAddress(address string) (*Address, error)
    +

    +Parses a single RFC 5322 address, e.g. "Barry Gibbs <bg@example.com>" +

    + +
    + +
    +

    Example

    + + + +

    Code:

    +
    e, err := mail.ParseAddress("Alice <alice@example.com>")
    +if err != nil {
    +    log.Fatal(err)
    +}
    +
    +fmt.Println(e.Name, e.Address)
    +
    +
    + +

    Output:

    +
    Alice alice@example.com
    +
    + + +
    +
    + + + + + + +

    func (*Address) String

    +
    func (a *Address) String() string
    +

    +String formats the address as a valid RFC 5322 address. +If the address's name contains non-ASCII characters +the name will be rendered according to RFC 2047. +

    + + + + + + + + +

    type AddressParser

    +
    type AddressParser struct {
    +    // WordDecoder optionally specifies a decoder for RFC 2047 encoded-words.
    +    WordDecoder *mime.WordDecoder
    +}
    +

    +An AddressParser is an RFC 5322 address parser. +

    + + + + + + + + + + + + + + +

    func (*AddressParser) Parse

    +
    func (p *AddressParser) Parse(address string) (*Address, error)
    +

    +Parse parses a single RFC 5322 address of the +form "Gogh Fir <gf@example.com>" or "foo@example.com". +

    + + + + + + +

    func (*AddressParser) ParseList

    +
    func (p *AddressParser) ParseList(list string) ([]*Address, error)
    +

    +ParseList parses the given string as a list of comma-separated addresses +of the form "Gogh Fir <gf@example.com>" or "foo@example.com". +

    + + + + + + + + + +
    type Header map[string][]string
    +

    +A Header represents the key-value pairs in a mail message header. +

    + + + + + + + + + + + + + + +

    func (Header) AddressList

    +
    func (h Header) AddressList(key string) ([]*Address, error)
    +

    +AddressList parses the named header field as a list of addresses. +

    + + + + + + +

    func (Header) Date

    +
    func (h Header) Date() (time.Time, error)
    +

    +Date parses the Date header field. +

    + + + + + + +

    func (Header) Get

    +
    func (h Header) Get(key string) string
    +

    +Get gets the first value associated with the given key. +If there are no values associated with the key, Get returns "". +

    + + + + + + + + +

    type Message

    +
    type Message struct {
    +    Header Header
    +    Body   io.Reader
    +}
    +

    +A Message represents a parsed mail message. +

    + + + + + + + + + + + + +

    func ReadMessage

    +
    func ReadMessage(r io.Reader) (msg *Message, err error)
    +

    +ReadMessage reads a message from r. +The headers are parsed, and the body of the message will be available +for reading from r. +

    + +
    + +
    +

    Example

    + + + +

    Code:

    +
    msg := `Date: Mon, 23 Jun 2015 11:40:36 -0400
    +From: Gopher <from@example.com>
    +To: Another Gopher <to@example.com>
    +Subject: Gophers at Gophercon
    +
    +Message body
    +`
    +
    +r := strings.NewReader(msg)
    +m, err := mail.ReadMessage(r)
    +if err != nil {
    +    log.Fatal(err)
    +}
    +
    +header := m.Header
    +fmt.Println("Date:", header.Get("Date"))
    +fmt.Println("From:", header.Get("From"))
    +fmt.Println("To:", header.Get("To"))
    +fmt.Println("Subject:", header.Get("Subject"))
    +
    +body, err := ioutil.ReadAll(m.Body)
    +if err != nil {
    +    log.Fatal(err)
    +}
    +fmt.Printf("%s", body)
    +
    +
    + +

    Output:

    +
    Date: Mon, 23 Jun 2015 11:40:36 -0400
    +From: Gopher <from@example.com>
    +To: Another Gopher <to@example.com>
    +Subject: Gophers at Gophercon
    +Message body
    +
    + + +
    +
    + + + + + + + + + + + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/net/rpc/index.html b/pkg/net/rpc/index.html new file mode 100644 index 0000000..db426f8 --- /dev/null +++ b/pkg/net/rpc/index.html @@ -0,0 +1,1055 @@ + + + + + + + + rpc - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Package rpc

    + + + + + + + + + + + + + + +
    +
    +
    import "net/rpc"
    +
    +
    +
    Overview
    +
    Index
    + + +
    Subdirectories
    + +
    +
    + +
    + +
    +

    Overview ▾

    +

    +Package rpc provides access to the exported methods of an object across a +network or other I/O connection. A server registers an object, making it visible +as a service with the name of the type of the object. After registration, exported +methods of the object will be accessible remotely. A server may register multiple +objects (services) of different types but it is an error to register multiple +objects of the same type. +

    +

    +Only methods that satisfy these criteria will be made available for remote access; +other methods will be ignored: +

    +
    - the method's type is exported.
    +- the method is exported.
    +- the method has two arguments, both exported (or builtin) types.
    +- the method's second argument is a pointer.
    +- the method has return type error.
    +
    +

    +In effect, the method must look schematically like +

    +
    func (t *T) MethodName(argType T1, replyType *T2) error
    +
    +

    +where T, T1 and T2 can be marshaled by encoding/gob. +These requirements apply even if a different codec is used. +(In the future, these requirements may soften for custom codecs.) +

    +

    +The method's first argument represents the arguments provided by the caller; the +second argument represents the result parameters to be returned to the caller. +The method's return value, if non-nil, is passed back as a string that the client +sees as if created by errors.New. If an error is returned, the reply parameter +will not be sent back to the client. +

    +

    +The server may handle requests on a single connection by calling ServeConn. More +typically it will create a network listener and call Accept or, for an HTTP +listener, HandleHTTP and http.Serve. +

    +

    +A client wishing to use the service establishes a connection and then invokes +NewClient on the connection. The convenience function Dial (DialHTTP) performs +both steps for a raw network connection (an HTTP connection). The resulting +Client object has two methods, Call and Go, that specify the service and method to +call, a pointer containing the arguments, and a pointer to receive the result +parameters. +

    +

    +The Call method waits for the remote call to complete while the Go method +launches the call asynchronously and signals completion using the Call +structure's Done channel. +

    +

    +Unless an explicit codec is set up, package encoding/gob is used to +transport the data. +

    +

    +Here is a simple example. A server wishes to export an object of type Arith: +

    +
    package server
    +
    +type Args struct {
    +	A, B int
    +}
    +
    +type Quotient struct {
    +	Quo, Rem int
    +}
    +
    +type Arith int
    +
    +func (t *Arith) Multiply(args *Args, reply *int) error {
    +	*reply = args.A * args.B
    +	return nil
    +}
    +
    +func (t *Arith) Divide(args *Args, quo *Quotient) error {
    +	if args.B == 0 {
    +		return errors.New("divide by zero")
    +	}
    +	quo.Quo = args.A / args.B
    +	quo.Rem = args.A % args.B
    +	return nil
    +}
    +
    +

    +The server calls (for HTTP service): +

    +
    arith := new(Arith)
    +rpc.Register(arith)
    +rpc.HandleHTTP()
    +l, e := net.Listen("tcp", ":1234")
    +if e != nil {
    +	log.Fatal("listen error:", e)
    +}
    +go http.Serve(l, nil)
    +
    +

    +At this point, clients can see a service "Arith" with methods "Arith.Multiply" and +"Arith.Divide". To invoke one, a client first dials the server: +

    +
    client, err := rpc.DialHTTP("tcp", serverAddress + ":1234")
    +if err != nil {
    +	log.Fatal("dialing:", err)
    +}
    +
    +

    +Then it can make a remote call: +

    +
    // Synchronous call
    +args := &server.Args{7,8}
    +var reply int
    +err = client.Call("Arith.Multiply", args, &reply)
    +if err != nil {
    +	log.Fatal("arith error:", err)
    +}
    +fmt.Printf("Arith: %d*%d=%d", args.A, args.B, reply)
    +
    +

    +or +

    +
    // Asynchronous call
    +quotient := new(Quotient)
    +divCall := client.Go("Arith.Divide", args, quotient, nil)
    +replyCall := <-divCall.Done	// will be equal to divCall
    +// check errors, print, etc.
    +
    +

    +A server implementation will often provide a simple, type-safe wrapper for the +client. +

    + +
    +
    + + +
    + +
    +

    Index ▾

    + + +
    +
    + +
    Constants
    + + +
    Variables
    + + + +
    func Accept(lis net.Listener)
    + + +
    func HandleHTTP()
    + + +
    func Register(rcvr interface{}) error
    + + +
    func RegisterName(name string, rcvr interface{}) error
    + + +
    func ServeCodec(codec ServerCodec)
    + + +
    func ServeConn(conn io.ReadWriteCloser)
    + + +
    func ServeRequest(codec ServerCodec) error
    + + + +
    type Call
    + + + + +
    type Client
    + + +
        func Dial(network, address string) (*Client, error)
    + + +
        func DialHTTP(network, address string) (*Client, error)
    + + +
        func DialHTTPPath(network, address, path string) (*Client, error)
    + + +
        func NewClient(conn io.ReadWriteCloser) *Client
    + + +
        func NewClientWithCodec(codec ClientCodec) *Client
    + + + +
        func (client *Client) Call(serviceMethod string, args interface{}, reply interface{}) error
    + + +
        func (client *Client) Close() error
    + + +
        func (client *Client) Go(serviceMethod string, args interface{}, reply interface{}, done chan *Call) *Call
    + + + +
    type ClientCodec
    + + + + +
    type Request
    + + + + +
    type Response
    + + + + +
    type Server
    + + +
        func NewServer() *Server
    + + + +
        func (server *Server) Accept(lis net.Listener)
    + + +
        func (server *Server) HandleHTTP(rpcPath, debugPath string)
    + + +
        func (server *Server) Register(rcvr interface{}) error
    + + +
        func (server *Server) RegisterName(name string, rcvr interface{}) error
    + + +
        func (server *Server) ServeCodec(codec ServerCodec)
    + + +
        func (server *Server) ServeConn(conn io.ReadWriteCloser)
    + + +
        func (server *Server) ServeHTTP(w http.ResponseWriter, req *http.Request)
    + + +
        func (server *Server) ServeRequest(codec ServerCodec) error
    + + + +
    type ServerCodec
    + + + + +
    type ServerError
    + + + +
        func (e ServerError) Error() string
    + + + +
    +
    + + + + +

    Package files

    +

    + + + client.go + + debug.go + + server.go + + +

    + +
    +
    + + + + +

    Constants

    + +
    const (
    +    // Defaults used by HandleHTTP
    +    DefaultRPCPath   = "/_goRPC_"
    +    DefaultDebugPath = "/debug/rpc"
    +)
    + + + + +

    Variables

    + +
    var DefaultServer = NewServer()
    +

    +DefaultServer is the default instance of *Server. +

    + + +
    var ErrShutdown = errors.New("connection is shut down")
    + + + + + + +

    func Accept

    +
    func Accept(lis net.Listener)
    +

    +Accept accepts connections on the listener and serves requests +to DefaultServer for each incoming connection. +Accept blocks; the caller typically invokes it in a go statement. +

    + + + + + + + +

    func HandleHTTP

    +
    func HandleHTTP()
    +

    +HandleHTTP registers an HTTP handler for RPC messages to DefaultServer +on DefaultRPCPath and a debugging handler on DefaultDebugPath. +It is still necessary to invoke http.Serve(), typically in a go statement. +

    + + + + + + + +

    func Register

    +
    func Register(rcvr interface{}) error
    +

    +Register publishes the receiver's methods in the DefaultServer. +

    + + + + + + + +

    func RegisterName

    +
    func RegisterName(name string, rcvr interface{}) error
    +

    +RegisterName is like Register but uses the provided name for the type +instead of the receiver's concrete type. +

    + + + + + + + +

    func ServeCodec

    +
    func ServeCodec(codec ServerCodec)
    +

    +ServeCodec is like ServeConn but uses the specified codec to +decode requests and encode responses. +

    + + + + + + + +

    func ServeConn

    +
    func ServeConn(conn io.ReadWriteCloser)
    +

    +ServeConn runs the DefaultServer on a single connection. +ServeConn blocks, serving the connection until the client hangs up. +The caller typically invokes ServeConn in a go statement. +ServeConn uses the gob wire format (see package gob) on the +connection. To use an alternate codec, use ServeCodec. +

    + + + + + + + +

    func ServeRequest

    +
    func ServeRequest(codec ServerCodec) error
    +

    +ServeRequest is like ServeCodec but synchronously serves a single request. +It does not close the codec upon completion. +

    + + + + + + + + +

    type Call

    +
    type Call struct {
    +    ServiceMethod string      // The name of the service and method to call.
    +    Args          interface{} // The argument to the function (*struct).
    +    Reply         interface{} // The reply from the function (*struct).
    +    Error         error       // After completion, the error status.
    +    Done          chan *Call  // Strobes when call is complete.
    +}
    +

    +Call represents an active RPC. +

    + + + + + + + + + + + + + + + + +

    type Client

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

    +Client represents an RPC Client. +There may be multiple outstanding Calls associated +with a single Client, and a Client may be used by +multiple goroutines simultaneously. +

    + + + + + + + + + + + + +

    func Dial

    +
    func Dial(network, address string) (*Client, error)
    +

    +Dial connects to an RPC server at the specified network address. +

    + + + + + +

    func DialHTTP

    +
    func DialHTTP(network, address string) (*Client, error)
    +

    +DialHTTP connects to an HTTP RPC server at the specified network address +listening on the default HTTP RPC path. +

    + + + + + +

    func DialHTTPPath

    +
    func DialHTTPPath(network, address, path string) (*Client, error)
    +

    +DialHTTPPath connects to an HTTP RPC server +at the specified network address and path. +

    + + + + + +

    func NewClient

    +
    func NewClient(conn io.ReadWriteCloser) *Client
    +

    +NewClient returns a new Client to handle requests to the +set of services at the other end of the connection. +It adds a buffer to the write side of the connection so +the header and payload are sent as a unit. +

    + + + + + +

    func NewClientWithCodec

    +
    func NewClientWithCodec(codec ClientCodec) *Client
    +

    +NewClientWithCodec is like NewClient but uses the specified +codec to encode requests and decode responses. +

    + + + + + + + +

    func (*Client) Call

    +
    func (client *Client) Call(serviceMethod string, args interface{}, reply interface{}) error
    +

    +Call invokes the named function, waits for it to complete, and returns its error status. +

    + + + + + + +

    func (*Client) Close

    +
    func (client *Client) Close() error
    + + + + + + +

    func (*Client) Go

    +
    func (client *Client) Go(serviceMethod string, args interface{}, reply interface{}, done chan *Call) *Call
    +

    +Go invokes the function asynchronously. It returns the Call structure representing +the invocation. The done channel will signal when the call is complete by returning +the same Call object. If done is nil, Go will allocate a new channel. +If non-nil, done must be buffered or Go will deliberately crash. +

    + + + + + + + + +

    type ClientCodec

    +
    type ClientCodec interface {
    +    // WriteRequest must be safe for concurrent use by multiple goroutines.
    +    WriteRequest(*Request, interface{}) error
    +    ReadResponseHeader(*Response) error
    +    ReadResponseBody(interface{}) error
    +
    +    Close() error
    +}
    +

    +A ClientCodec implements writing of RPC requests and +reading of RPC responses for the client side of an RPC session. +The client calls WriteRequest to write a request to the connection +and calls ReadResponseHeader and ReadResponseBody in pairs +to read responses. The client calls Close when finished with the +connection. ReadResponseBody may be called with a nil +argument to force the body of the response to be read and then +discarded. +

    + + + + + + + + + + + + + + + + +

    type Request

    +
    type Request struct {
    +    ServiceMethod string // format: "Service.Method"
    +    Seq           uint64 // sequence number chosen by client
    +    // contains filtered or unexported fields
    +}
    +

    +Request is a header written before every RPC call. It is used internally +but documented here as an aid to debugging, such as when analyzing +network traffic. +

    + + + + + + + + + + + + + + + + +

    type Response

    +
    type Response struct {
    +    ServiceMethod string // echoes that of the Request
    +    Seq           uint64 // echoes that of the request
    +    Error         string // error, if any.
    +    // contains filtered or unexported fields
    +}
    +

    +Response is a header written before every RPC return. It is used internally +but documented here as an aid to debugging, such as when analyzing +network traffic. +

    + + + + + + + + + + + + + + + + +

    type Server

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

    +Server represents an RPC Server. +

    + + + + + + + + + + + + +

    func NewServer

    +
    func NewServer() *Server
    +

    +NewServer returns a new Server. +

    + + + + + + + +

    func (*Server) Accept

    +
    func (server *Server) Accept(lis net.Listener)
    +

    +Accept accepts connections on the listener and serves requests +for each incoming connection. Accept blocks until the listener +returns a non-nil error. The caller typically invokes Accept in a +go statement. +

    + + + + + + +

    func (*Server) HandleHTTP

    +
    func (server *Server) HandleHTTP(rpcPath, debugPath string)
    +

    +HandleHTTP registers an HTTP handler for RPC messages on rpcPath, +and a debugging handler on debugPath. +It is still necessary to invoke http.Serve(), typically in a go statement. +

    + + + + + + +

    func (*Server) Register

    +
    func (server *Server) Register(rcvr interface{}) error
    +

    +Register publishes in the server the set of methods of the +receiver value that satisfy the following conditions: +

    +
    - exported method of exported type
    +- two arguments, both of exported type
    +- the second argument is a pointer
    +- one return value, of type error
    +
    +

    +It returns an error if the receiver is not an exported type or has +no suitable methods. It also logs the error using package log. +The client accesses each method using a string of the form "Type.Method", +where Type is the receiver's concrete type. +

    + + + + + + +

    func (*Server) RegisterName

    +
    func (server *Server) RegisterName(name string, rcvr interface{}) error
    +

    +RegisterName is like Register but uses the provided name for the type +instead of the receiver's concrete type. +

    + + + + + + +

    func (*Server) ServeCodec

    +
    func (server *Server) ServeCodec(codec ServerCodec)
    +

    +ServeCodec is like ServeConn but uses the specified codec to +decode requests and encode responses. +

    + + + + + + +

    func (*Server) ServeConn

    +
    func (server *Server) ServeConn(conn io.ReadWriteCloser)
    +

    +ServeConn runs the server on a single connection. +ServeConn blocks, serving the connection until the client hangs up. +The caller typically invokes ServeConn in a go statement. +ServeConn uses the gob wire format (see package gob) on the +connection. To use an alternate codec, use ServeCodec. +

    + + + + + + +

    func (*Server) ServeHTTP

    +
    func (server *Server) ServeHTTP(w http.ResponseWriter, req *http.Request)
    +

    +ServeHTTP implements an http.Handler that answers RPC requests. +

    + + + + + + +

    func (*Server) ServeRequest

    +
    func (server *Server) ServeRequest(codec ServerCodec) error
    +

    +ServeRequest is like ServeCodec but synchronously serves a single request. +It does not close the codec upon completion. +

    + + + + + + + + +

    type ServerCodec

    +
    type ServerCodec interface {
    +    ReadRequestHeader(*Request) error
    +    ReadRequestBody(interface{}) error
    +    // WriteResponse must be safe for concurrent use by multiple goroutines.
    +    WriteResponse(*Response, interface{}) error
    +
    +    Close() error
    +}
    +

    +A ServerCodec implements reading of RPC requests and writing of +RPC responses for the server side of an RPC session. +The server calls ReadRequestHeader and ReadRequestBody in pairs +to read requests from the connection, and it calls WriteResponse to +write a response back. The server calls Close when finished with the +connection. ReadRequestBody may be called with a nil +argument to force the body of the request to be read and discarded. +

    + + + + + + + + + + + + + + + + +

    type ServerError

    +
    type ServerError string
    +

    +ServerError represents an error that has been returned from +the remote side of the RPC connection. +

    + + + + + + + + + + + + + + +

    func (ServerError) Error

    +
    func (e ServerError) Error() string
    + + + + + + + + + + + + + + + + +

    Subdirectories

    + + + + +
    + + + + + + + + + + + + + + + + + + + + +
    NameSynopsis
    ..
    + jsonrpc + + Package jsonrpc implements a JSON-RPC ClientCodec and ServerCodec for the rpc package. +
    +
    + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/net/rpc/jsonrpc/index.html b/pkg/net/rpc/jsonrpc/index.html new file mode 100644 index 0000000..0158aa6 --- /dev/null +++ b/pkg/net/rpc/jsonrpc/index.html @@ -0,0 +1,286 @@ + + + + + + + + jsonrpc - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Package jsonrpc

    + + + + + + + + + + + + + + +
    +
    +
    import "net/rpc/jsonrpc"
    +
    +
    +
    Overview
    +
    Index
    + + +
    +
    + +
    + +
    +

    Overview ▾

    +

    +Package jsonrpc implements a JSON-RPC ClientCodec and ServerCodec +for the rpc package. +

    + +
    +
    + + + + + + + + + + + +

    func Dial

    +
    func Dial(network, address string) (*rpc.Client, error)
    +

    +Dial connects to a JSON-RPC server at the specified network address. +

    + + + + + + + +

    func NewClient

    +
    func NewClient(conn io.ReadWriteCloser) *rpc.Client
    +

    +NewClient returns a new rpc.Client to handle requests to the +set of services at the other end of the connection. +

    + + + + + + + +

    func NewClientCodec

    +
    func NewClientCodec(conn io.ReadWriteCloser) rpc.ClientCodec
    +

    +NewClientCodec returns a new rpc.ClientCodec using JSON-RPC on conn. +

    + + + + + + + +

    func NewServerCodec

    +
    func NewServerCodec(conn io.ReadWriteCloser) rpc.ServerCodec
    +

    +NewServerCodec returns a new rpc.ServerCodec using JSON-RPC on conn. +

    + + + + + + + +

    func ServeConn

    +
    func ServeConn(conn io.ReadWriteCloser)
    +

    +ServeConn runs the JSON-RPC server on a single connection. +ServeConn blocks, serving the connection until the client hangs up. +The caller typically invokes ServeConn in a go statement. +

    + + + + + + + + + + + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/net/smtp/index.html b/pkg/net/smtp/index.html new file mode 100644 index 0000000..ef701df --- /dev/null +++ b/pkg/net/smtp/index.html @@ -0,0 +1,727 @@ + + + + + + + + smtp - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Package smtp

    + + + + + + + + + + + + + + +
    +
    +
    import "net/smtp"
    +
    +
    +
    Overview
    +
    Index
    + +
    Examples
    + + +
    +
    + +
    + +
    +

    Overview ▾

    +

    +Package smtp implements the Simple Mail Transfer Protocol as defined in RFC 5321. +It also implements the following extensions: +

    +
    8BITMIME  RFC 1652
    +AUTH      RFC 2554
    +STARTTLS  RFC 3207
    +
    +

    +Additional extensions may be handled by clients. +

    + +
    +
    +
    + +
    +

    Example

    + + + +

    Code:

    +
    +// Connect to the remote SMTP server.
    +c, err := smtp.Dial("mail.example.com:25")
    +if err != nil {
    +    log.Fatal(err)
    +}
    +
    +// Set the sender and recipient first
    +if err := c.Mail("sender@example.org"); err != nil {
    +    log.Fatal(err)
    +}
    +if err := c.Rcpt("recipient@example.net"); err != nil {
    +    log.Fatal(err)
    +}
    +
    +// Send the email body.
    +wc, err := c.Data()
    +if err != nil {
    +    log.Fatal(err)
    +}
    +_, err = fmt.Fprintf(wc, "This is the email body")
    +if err != nil {
    +    log.Fatal(err)
    +}
    +err = wc.Close()
    +if err != nil {
    +    log.Fatal(err)
    +}
    +
    +// Send the QUIT command and close the connection.
    +err = c.Quit()
    +if err != nil {
    +    log.Fatal(err)
    +}
    +
    + + +
    +
    + + + + + + + + + + + +

    func SendMail

    +
    func SendMail(addr string, a Auth, from string, to []string, msg []byte) error
    +

    +SendMail connects to the server at addr, switches to TLS if +possible, authenticates with the optional mechanism a if possible, +and then sends an email from address from, to addresses to, with +message msg. +The addr must include a port, as in "mail.example.com:smtp". +

    +

    +The addresses in the to parameter are the SMTP RCPT addresses. +

    +

    +The msg parameter should be an RFC 822-style email with headers +first, a blank line, and then the message body. The lines of msg +should be CRLF terminated. The msg headers should usually include +fields such as "From", "To", "Subject", and "Cc". Sending "Bcc" +messages is accomplished by including an email address in the to +parameter but not including it in the msg headers. +

    +

    +The SendMail function and the the net/smtp package are low-level +mechanisms and provide no support for DKIM signing, MIME +attachments (see the mime/multipart package), or other mail +functionality. Higher-level packages exist outside of the standard +library. +

    + +
    + +
    +

    Example

    + + + +

    Code:

    +
    +// Set up authentication information.
    +auth := smtp.PlainAuth("", "user@example.com", "password", "mail.example.com")
    +
    +// Connect to the server, authenticate, set the sender and recipient,
    +// and send the email all in one step.
    +to := []string{"recipient@example.net"}
    +msg := []byte("To: recipient@example.net\r\n" +
    +    "Subject: discount Gophers!\r\n" +
    +    "\r\n" +
    +    "This is the email body.\r\n")
    +err := smtp.SendMail("mail.example.com:25", auth, "sender@example.org", to, msg)
    +if err != nil {
    +    log.Fatal(err)
    +}
    +
    + + +
    +
    + + + + + + + +

    type Auth

    +
    type Auth interface {
    +    // Start begins an authentication with a server.
    +    // It returns the name of the authentication protocol
    +    // and optionally data to include in the initial AUTH message
    +    // sent to the server. It can return proto == "" to indicate
    +    // that the authentication should be skipped.
    +    // If it returns a non-nil error, the SMTP client aborts
    +    // the authentication attempt and closes the connection.
    +    Start(server *ServerInfo) (proto string, toServer []byte, err error)
    +
    +    // Next continues the authentication. The server has just sent
    +    // the fromServer data. If more is true, the server expects a
    +    // response, which Next should return as toServer; otherwise
    +    // Next should return toServer == nil.
    +    // If Next returns a non-nil error, the SMTP client aborts
    +    // the authentication attempt and closes the connection.
    +    Next(fromServer []byte, more bool) (toServer []byte, err error)
    +}
    +

    +Auth is implemented by an SMTP authentication mechanism. +

    + + + + + + + + + + + + +

    func CRAMMD5Auth

    +
    func CRAMMD5Auth(username, secret string) Auth
    +

    +CRAMMD5Auth returns an Auth that implements the CRAM-MD5 authentication +mechanism as defined in RFC 2195. +The returned Auth uses the given username and secret to authenticate +to the server using the challenge-response mechanism. +

    + + + + + +

    func PlainAuth

    +
    func PlainAuth(identity, username, password, host string) Auth
    +

    +PlainAuth returns an Auth that implements the PLAIN authentication +mechanism as defined in RFC 4616. +The returned Auth uses the given username and password to authenticate +on TLS connections to host and act as identity. Usually identity will be +left blank to act as username. +

    + +
    + +
    +

    Example

    + + + +

    Code:

    +
    +// hostname is used by PlainAuth to validate the TLS certificate.
    +hostname := "mail.example.com"
    +auth := smtp.PlainAuth("", "user@example.com", "password", hostname)
    +
    +err := smtp.SendMail(hostname+":25", auth, from, recipients, msg)
    +if err != nil {
    +    log.Fatal(err)
    +}
    +
    + + +
    +
    + + + + + + + + +

    type Client

    +
    type Client struct {
    +    // Text is the textproto.Conn used by the Client. It is exported to allow for
    +    // clients to add extensions.
    +    Text *textproto.Conn
    +    // contains filtered or unexported fields
    +}
    +

    +A Client represents a client connection to an SMTP server. +

    + + + + + + + + + + + + +

    func Dial

    +
    func Dial(addr string) (*Client, error)
    +

    +Dial returns a new Client connected to an SMTP server at addr. +The addr must include a port, as in "mail.example.com:smtp". +

    + + + + + +

    func NewClient

    +
    func NewClient(conn net.Conn, host string) (*Client, error)
    +

    +NewClient returns a new Client using an existing connection and host as a +server name to be used when authenticating. +

    + + + + + + + +

    func (*Client) Auth

    +
    func (c *Client) Auth(a Auth) error
    +

    +Auth authenticates a client using the provided authentication mechanism. +A failed authentication closes the connection. +Only servers that advertise the AUTH extension support this function. +

    + + + + + + +

    func (*Client) Close

    +
    func (c *Client) Close() error
    +

    +Close closes the connection. +

    + + + + + + +

    func (*Client) Data

    +
    func (c *Client) Data() (io.WriteCloser, error)
    +

    +Data issues a DATA command to the server and returns a writer that +can be used to write the mail headers and body. The caller should +close the writer before calling any more methods on c. A call to +Data must be preceded by one or more calls to Rcpt. +

    + + + + + + +

    func (*Client) Extension

    +
    func (c *Client) Extension(ext string) (bool, string)
    +

    +Extension reports whether an extension is support by the server. +The extension name is case-insensitive. If the extension is supported, +Extension also returns a string that contains any parameters the +server specifies for the extension. +

    + + + + + + +

    func (*Client) Hello

    +
    func (c *Client) Hello(localName string) error
    +

    +Hello sends a HELO or EHLO to the server as the given host name. +Calling this method is only necessary if the client needs control +over the host name used. The client will introduce itself as "localhost" +automatically otherwise. If Hello is called, it must be called before +any of the other methods. +

    + + + + + + +

    func (*Client) Mail

    +
    func (c *Client) Mail(from string) error
    +

    +Mail issues a MAIL command to the server using the provided email address. +If the server supports the 8BITMIME extension, Mail adds the BODY=8BITMIME +parameter. +This initiates a mail transaction and is followed by one or more Rcpt calls. +

    + + + + + + +

    func (*Client) Quit

    +
    func (c *Client) Quit() error
    +

    +Quit sends the QUIT command and closes the connection to the server. +

    + + + + + + +

    func (*Client) Rcpt

    +
    func (c *Client) Rcpt(to string) error
    +

    +Rcpt issues a RCPT command to the server using the provided email address. +A call to Rcpt must be preceded by a call to Mail and may be followed by +a Data call or another Rcpt call. +

    + + + + + + +

    func (*Client) Reset

    +
    func (c *Client) Reset() error
    +

    +Reset sends the RSET command to the server, aborting the current mail +transaction. +

    + + + + + + +

    func (*Client) StartTLS

    +
    func (c *Client) StartTLS(config *tls.Config) error
    +

    +StartTLS sends the STARTTLS command and encrypts all further communication. +Only servers that advertise the STARTTLS extension support this function. +

    + + + + + + +

    func (*Client) TLSConnectionState

    +
    func (c *Client) TLSConnectionState() (state tls.ConnectionState, ok bool)
    +

    +TLSConnectionState returns the client's TLS connection state. +The return values are their zero values if StartTLS did +not succeed. +

    + + + + + + +

    func (*Client) Verify

    +
    func (c *Client) Verify(addr string) error
    +

    +Verify checks the validity of an email address on the server. +If Verify returns nil, the address is valid. A non-nil return +does not necessarily indicate an invalid address. Many servers +will not verify addresses for security reasons. +

    + + + + + + + + +

    type ServerInfo

    +
    type ServerInfo struct {
    +    Name string   // SMTP server name
    +    TLS  bool     // using TLS, with valid certificate for Name
    +    Auth []string // advertised authentication mechanisms
    +}
    +

    +ServerInfo records information about an SMTP server. +

    + + + + + + + + + + + + + + + + + + + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/net/textproto/index.html b/pkg/net/textproto/index.html new file mode 100644 index 0000000..65d5c1a --- /dev/null +++ b/pkg/net/textproto/index.html @@ -0,0 +1,1072 @@ + + + + + + + + textproto - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Package textproto

    + + + + + + + + + + + + + + +
    +
    +
    import "net/textproto"
    +
    +
    +
    Overview
    +
    Index
    + + +
    +
    + +
    + +
    +

    Overview ▾

    +

    +Package textproto implements generic support for text-based request/response +protocols in the style of HTTP, NNTP, and SMTP. +

    +

    +The package provides: +

    +

    +Error, which represents a numeric error response from +a server. +

    +

    +Pipeline, to manage pipelined requests and responses +in a client. +

    +

    +Reader, to read numeric response code lines, +key: value headers, lines wrapped with leading spaces +on continuation lines, and whole text blocks ending +with a dot on a line by itself. +

    +

    +Writer, to write dot-encoded text blocks. +

    +

    +Conn, a convenient packaging of Reader, Writer, and Pipeline for use +with a single network connection. +

    + +
    +
    + + +
    + +
    +

    Index ▾

    + + +
    +
    + + + + +
    func CanonicalMIMEHeaderKey(s string) string
    + + +
    func TrimBytes(b []byte) []byte
    + + +
    func TrimString(s string) string
    + + + +
    type Conn
    + + +
        func Dial(network, addr string) (*Conn, error)
    + + +
        func NewConn(conn io.ReadWriteCloser) *Conn
    + + + +
        func (c *Conn) Close() error
    + + +
        func (c *Conn) Cmd(format string, args ...interface{}) (id uint, err error)
    + + + +
    type Error
    + + + +
        func (e *Error) Error() string
    + + + +
    type MIMEHeader
    + + + +
        func (h MIMEHeader) Add(key, value string)
    + + +
        func (h MIMEHeader) Del(key string)
    + + +
        func (h MIMEHeader) Get(key string) string
    + + +
        func (h MIMEHeader) Set(key, value string)
    + + + +
    type Pipeline
    + + + +
        func (p *Pipeline) EndRequest(id uint)
    + + +
        func (p *Pipeline) EndResponse(id uint)
    + + +
        func (p *Pipeline) Next() uint
    + + +
        func (p *Pipeline) StartRequest(id uint)
    + + +
        func (p *Pipeline) StartResponse(id uint)
    + + + +
    type ProtocolError
    + + + +
        func (p ProtocolError) Error() string
    + + + +
    type Reader
    + + +
        func NewReader(r *bufio.Reader) *Reader
    + + + +
        func (r *Reader) DotReader() io.Reader
    + + +
        func (r *Reader) ReadCodeLine(expectCode int) (code int, message string, err error)
    + + +
        func (r *Reader) ReadContinuedLine() (string, error)
    + + +
        func (r *Reader) ReadContinuedLineBytes() ([]byte, error)
    + + +
        func (r *Reader) ReadDotBytes() ([]byte, error)
    + + +
        func (r *Reader) ReadDotLines() ([]string, error)
    + + +
        func (r *Reader) ReadLine() (string, error)
    + + +
        func (r *Reader) ReadLineBytes() ([]byte, error)
    + + +
        func (r *Reader) ReadMIMEHeader() (MIMEHeader, error)
    + + +
        func (r *Reader) ReadResponse(expectCode int) (code int, message string, err error)
    + + + +
    type Writer
    + + +
        func NewWriter(w *bufio.Writer) *Writer
    + + + +
        func (w *Writer) DotWriter() io.WriteCloser
    + + +
        func (w *Writer) PrintfLine(format string, args ...interface{}) error
    + + + +
    +
    + + + + +

    Package files

    +

    + + + header.go + + pipeline.go + + reader.go + + textproto.go + + writer.go + + +

    + +
    +
    + + + + + + + + +

    func CanonicalMIMEHeaderKey

    +
    func CanonicalMIMEHeaderKey(s string) string
    +

    +CanonicalMIMEHeaderKey returns the canonical format of the +MIME header key s. The canonicalization converts the first +letter and any letter following a hyphen to upper case; +the rest are converted to lowercase. For example, the +canonical key for "accept-encoding" is "Accept-Encoding". +MIME header keys are assumed to be ASCII only. +If s contains a space or invalid header field bytes, it is +returned without modifications. +

    + + + + + + + +

    func TrimBytes

    +
    func TrimBytes(b []byte) []byte
    +

    +TrimBytes returns b without leading and trailing ASCII space. +

    + + + + + + + +

    func TrimString

    +
    func TrimString(s string) string
    +

    +TrimString returns s without leading and trailing ASCII space. +

    + + + + + + + + +

    type Conn

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

    +A Conn represents a textual network protocol connection. +It consists of a Reader and Writer to manage I/O +and a Pipeline to sequence concurrent requests on the connection. +These embedded types carry methods with them; +see the documentation of those types for details. +

    + + + + + + + + + + + + +

    func Dial

    +
    func Dial(network, addr string) (*Conn, error)
    +

    +Dial connects to the given address on the given network using net.Dial +and then returns a new Conn for the connection. +

    + + + + + +

    func NewConn

    +
    func NewConn(conn io.ReadWriteCloser) *Conn
    +

    +NewConn returns a new Conn using conn for I/O. +

    + + + + + + + +

    func (*Conn) Close

    +
    func (c *Conn) Close() error
    +

    +Close closes the connection. +

    + + + + + + +

    func (*Conn) Cmd

    +
    func (c *Conn) Cmd(format string, args ...interface{}) (id uint, err error)
    +

    +Cmd is a convenience method that sends a command after +waiting its turn in the pipeline. The command text is the +result of formatting format with args and appending \r\n. +Cmd returns the id of the command, for use with StartResponse and EndResponse. +

    +

    +For example, a client might run a HELP command that returns a dot-body +by using: +

    +
    id, err := c.Cmd("HELP")
    +if err != nil {
    +	return nil, err
    +}
    +
    +c.StartResponse(id)
    +defer c.EndResponse(id)
    +
    +if _, _, err = c.ReadCodeLine(110); err != nil {
    +	return nil, err
    +}
    +text, err := c.ReadDotBytes()
    +if err != nil {
    +	return nil, err
    +}
    +return c.ReadCodeLine(250)
    +
    + + + + + + + + +

    type Error

    +
    type Error struct {
    +    Code int
    +    Msg  string
    +}
    +

    +An Error represents a numeric error response from a server. +

    + + + + + + + + + + + + + + +

    func (*Error) Error

    +
    func (e *Error) Error() string
    + + + + + + + + +

    type MIMEHeader

    +
    type MIMEHeader map[string][]string
    +

    +A MIMEHeader represents a MIME-style header mapping +keys to sets of values. +

    + + + + + + + + + + + + + + +

    func (MIMEHeader) Add

    +
    func (h MIMEHeader) Add(key, value string)
    +

    +Add adds the key, value pair to the header. +It appends to any existing values associated with key. +

    + + + + + + +

    func (MIMEHeader) Del

    +
    func (h MIMEHeader) Del(key string)
    +

    +Del deletes the values associated with key. +

    + + + + + + +

    func (MIMEHeader) Get

    +
    func (h MIMEHeader) Get(key string) string
    +

    +Get gets the first value associated with the given key. +If there are no values associated with the key, Get returns "". +Get is a convenience method. For more complex queries, +access the map directly. +

    + + + + + + +

    func (MIMEHeader) Set

    +
    func (h MIMEHeader) Set(key, value string)
    +

    +Set sets the header entries associated with key to +the single element value. It replaces any existing +values associated with key. +

    + + + + + + + + +

    type Pipeline

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

    +A Pipeline manages a pipelined in-order request/response sequence. +

    +

    +To use a Pipeline p to manage multiple clients on a connection, +each client should run: +

    +
    id := p.Next()	// take a number
    +
    +p.StartRequest(id)	// wait for turn to send request
    +«send request»
    +p.EndRequest(id)	// notify Pipeline that request is sent
    +
    +p.StartResponse(id)	// wait for turn to read response
    +«read response»
    +p.EndResponse(id)	// notify Pipeline that response is read
    +
    +

    +A pipelined server can use the same calls to ensure that +responses computed in parallel are written in the correct order. +

    + + + + + + + + + + + + + + +

    func (*Pipeline) EndRequest

    +
    func (p *Pipeline) EndRequest(id uint)
    +

    +EndRequest notifies p that the request with the given id has been sent +(or, if this is a server, received). +

    + + + + + + +

    func (*Pipeline) EndResponse

    +
    func (p *Pipeline) EndResponse(id uint)
    +

    +EndResponse notifies p that the response with the given id has been received +(or, if this is a server, sent). +

    + + + + + + +

    func (*Pipeline) Next

    +
    func (p *Pipeline) Next() uint
    +

    +Next returns the next id for a request/response pair. +

    + + + + + + +

    func (*Pipeline) StartRequest

    +
    func (p *Pipeline) StartRequest(id uint)
    +

    +StartRequest blocks until it is time to send (or, if this is a server, receive) +the request with the given id. +

    + + + + + + +

    func (*Pipeline) StartResponse

    +
    func (p *Pipeline) StartResponse(id uint)
    +

    +StartResponse blocks until it is time to receive (or, if this is a server, send) +the request with the given id. +

    + + + + + + + + +

    type ProtocolError

    +
    type ProtocolError string
    +

    +A ProtocolError describes a protocol violation such +as an invalid response or a hung-up connection. +

    + + + + + + + + + + + + + + +

    func (ProtocolError) Error

    +
    func (p ProtocolError) Error() string
    + + + + + + + + +

    type Reader

    +
    type Reader struct {
    +    R *bufio.Reader
    +    // contains filtered or unexported fields
    +}
    +

    +A Reader implements convenience methods for reading requests +or responses from a text protocol network connection. +

    + + + + + + + + + + + + +

    func NewReader

    +
    func NewReader(r *bufio.Reader) *Reader
    +

    +NewReader returns a new Reader reading from r. +

    +

    +To avoid denial of service attacks, the provided bufio.Reader +should be reading from an io.LimitReader or similar Reader to bound +the size of responses. +

    + + + + + + + +

    func (*Reader) DotReader

    +
    func (r *Reader) DotReader() io.Reader
    +

    +DotReader returns a new Reader that satisfies Reads using the +decoded text of a dot-encoded block read from r. +The returned Reader is only valid until the next call +to a method on r. +

    +

    +Dot encoding is a common framing used for data blocks +in text protocols such as SMTP. The data consists of a sequence +of lines, each of which ends in "\r\n". The sequence itself +ends at a line containing just a dot: ".\r\n". Lines beginning +with a dot are escaped with an additional dot to avoid +looking like the end of the sequence. +

    +

    +The decoded form returned by the Reader's Read method +rewrites the "\r\n" line endings into the simpler "\n", +removes leading dot escapes if present, and stops with error io.EOF +after consuming (and discarding) the end-of-sequence line. +

    + + + + + + +

    func (*Reader) ReadCodeLine

    +
    func (r *Reader) ReadCodeLine(expectCode int) (code int, message string, err error)
    +

    +ReadCodeLine reads a response code line of the form +

    +
    code message
    +
    +

    +where code is a three-digit status code and the message +extends to the rest of the line. An example of such a line is: +

    +
    220 plan9.bell-labs.com ESMTP
    +
    +

    +If the prefix of the status does not match the digits in expectCode, +ReadCodeLine returns with err set to &Error{code, message}. +For example, if expectCode is 31, an error will be returned if +the status is not in the range [310,319]. +

    +

    +If the response is multi-line, ReadCodeLine returns an error. +

    +

    +An expectCode <= 0 disables the check of the status code. +

    + + + + + + +

    func (*Reader) ReadContinuedLine

    +
    func (r *Reader) ReadContinuedLine() (string, error)
    +

    +ReadContinuedLine reads a possibly continued line from r, +eliding the final trailing ASCII white space. +Lines after the first are considered continuations if they +begin with a space or tab character. In the returned data, +continuation lines are separated from the previous line +only by a single space: the newline and leading white space +are removed. +

    +

    +For example, consider this input: +

    +
    Line 1
    +  continued...
    +Line 2
    +
    +

    +The first call to ReadContinuedLine will return "Line 1 continued..." +and the second will return "Line 2". +

    +

    +A line consisting of only white space is never continued. +

    + + + + + + +

    func (*Reader) ReadContinuedLineBytes

    +
    func (r *Reader) ReadContinuedLineBytes() ([]byte, error)
    +

    +ReadContinuedLineBytes is like ReadContinuedLine but +returns a []byte instead of a string. +

    + + + + + + +

    func (*Reader) ReadDotBytes

    +
    func (r *Reader) ReadDotBytes() ([]byte, error)
    +

    +ReadDotBytes reads a dot-encoding and returns the decoded data. +

    +

    +See the documentation for the DotReader method for details about dot-encoding. +

    + + + + + + +

    func (*Reader) ReadDotLines

    +
    func (r *Reader) ReadDotLines() ([]string, error)
    +

    +ReadDotLines reads a dot-encoding and returns a slice +containing the decoded lines, with the final \r\n or \n elided from each. +

    +

    +See the documentation for the DotReader method for details about dot-encoding. +

    + + + + + + +

    func (*Reader) ReadLine

    +
    func (r *Reader) ReadLine() (string, error)
    +

    +ReadLine reads a single line from r, +eliding the final \n or \r\n from the returned string. +

    + + + + + + +

    func (*Reader) ReadLineBytes

    +
    func (r *Reader) ReadLineBytes() ([]byte, error)
    +

    +ReadLineBytes is like ReadLine but returns a []byte instead of a string. +

    + + + + + + +

    func (*Reader) ReadMIMEHeader

    +
    func (r *Reader) ReadMIMEHeader() (MIMEHeader, error)
    +

    +ReadMIMEHeader reads a MIME-style header from r. +The header is a sequence of possibly continued Key: Value lines +ending in a blank line. +The returned map m maps CanonicalMIMEHeaderKey(key) to a +sequence of values in the same order encountered in the input. +

    +

    +For example, consider this input: +

    +
    My-Key: Value 1
    +Long-Key: Even
    +       Longer Value
    +My-Key: Value 2
    +
    +

    +Given that input, ReadMIMEHeader returns the map: +

    +
    map[string][]string{
    +	"My-Key": {"Value 1", "Value 2"},
    +	"Long-Key": {"Even Longer Value"},
    +}
    +
    + + + + + + +

    func (*Reader) ReadResponse

    +
    func (r *Reader) ReadResponse(expectCode int) (code int, message string, err error)
    +

    +ReadResponse reads a multi-line response of the form: +

    +
    code-message line 1
    +code-message line 2
    +...
    +code message line n
    +
    +

    +where code is a three-digit status code. The first line starts with the +code and a hyphen. The response is terminated by a line that starts +with the same code followed by a space. Each line in message is +separated by a newline (\n). +

    +

    +See page 36 of RFC 959 (http://www.ietf.org/rfc/rfc959.txt) for +details of another form of response accepted: +

    +
    code-message line 1
    +message line 2
    +...
    +code message line n
    +
    +

    +If the prefix of the status does not match the digits in expectCode, +ReadResponse returns with err set to &Error{code, message}. +For example, if expectCode is 31, an error will be returned if +the status is not in the range [310,319]. +

    +

    +An expectCode <= 0 disables the check of the status code. +

    + + + + + + + + +

    type Writer

    +
    type Writer struct {
    +    W *bufio.Writer
    +    // contains filtered or unexported fields
    +}
    +

    +A Writer implements convenience methods for writing +requests or responses to a text protocol network connection. +

    + + + + + + + + + + + + +

    func NewWriter

    +
    func NewWriter(w *bufio.Writer) *Writer
    +

    +NewWriter returns a new Writer writing to w. +

    + + + + + + + +

    func (*Writer) DotWriter

    +
    func (w *Writer) DotWriter() io.WriteCloser
    +

    +DotWriter returns a writer that can be used to write a dot-encoding to w. +It takes care of inserting leading dots when necessary, +translating line-ending \n into \r\n, and adding the final .\r\n line +when the DotWriter is closed. The caller should close the +DotWriter before the next call to a method on w. +

    +

    +See the documentation for Reader's DotReader method for details about dot-encoding. +

    + + + + + + +

    func (*Writer) PrintfLine

    +
    func (w *Writer) PrintfLine(format string, args ...interface{}) error
    +

    +PrintfLine writes the formatted output followed by \r\n. +

    + + + + + + + + + + + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/net/url/index.html b/pkg/net/url/index.html new file mode 100644 index 0000000..b59d6df --- /dev/null +++ b/pkg/net/url/index.html @@ -0,0 +1,1002 @@ + + + + + + + + url - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Package url

    + + + + + + + + + + + + + + +
    +
    +
    import "net/url"
    +
    +
    +
    Overview
    +
    Index
    + +
    Examples
    + + +
    +
    + +
    + +
    +

    Overview ▾

    +

    +Package url parses URLs and implements query escaping. +See RFC 3986. +

    + +
    +
    + + +
    + +
    +

    Index ▾

    + + +
    +
    + + + + +
    func QueryEscape(s string) string
    + + +
    func QueryUnescape(s string) (string, error)
    + + + +
    type Error
    + + + +
        func (e *Error) Error() string
    + + +
        func (e *Error) Temporary() bool
    + + +
        func (e *Error) Timeout() bool
    + + + +
    type EscapeError
    + + + +
        func (e EscapeError) Error() string
    + + + +
    type InvalidHostError
    + + + +
        func (e InvalidHostError) Error() string
    + + + +
    type URL
    + + +
        func Parse(rawurl string) (url *URL, err error)
    + + +
        func ParseRequestURI(rawurl string) (url *URL, err error)
    + + + +
        func (u *URL) EscapedPath() string
    + + +
        func (u *URL) IsAbs() bool
    + + +
        func (u *URL) Parse(ref string) (*URL, error)
    + + +
        func (u *URL) Query() Values
    + + +
        func (u *URL) RequestURI() string
    + + +
        func (u *URL) ResolveReference(ref *URL) *URL
    + + +
        func (u *URL) String() string
    + + + +
    type Userinfo
    + + +
        func User(username string) *Userinfo
    + + +
        func UserPassword(username, password string) *Userinfo
    + + + +
        func (u *Userinfo) Password() (string, bool)
    + + +
        func (u *Userinfo) String() string
    + + +
        func (u *Userinfo) Username() string
    + + + +
    type Values
    + + +
        func ParseQuery(query string) (m Values, err error)
    + + + +
        func (v Values) Add(key, value string)
    + + +
        func (v Values) Del(key string)
    + + +
        func (v Values) Encode() string
    + + +
        func (v Values) Get(key string) string
    + + +
        func (v Values) Set(key, value string)
    + + + +
    +
    + + +
    +

    Examples

    +
    + +
    URL
    + +
    URL.ResolveReference
    + +
    URL (Opaque)
    + +
    URL (Roundtrip)
    + +
    Values
    + +
    +
    + + + +

    Package files

    +

    + + + url.go + + +

    + +
    +
    + + + + + + + + +

    func QueryEscape

    +
    func QueryEscape(s string) string
    +

    +QueryEscape escapes the string so it can be safely placed +inside a URL query. +

    + + + + + + + +

    func QueryUnescape

    +
    func QueryUnescape(s string) (string, error)
    +

    +QueryUnescape does the inverse transformation of QueryEscape, converting +%AB into the byte 0xAB and '+' into ' ' (space). It returns an error if +any % is not followed by two hexadecimal digits. +

    + + + + + + + + +

    type Error

    +
    type Error struct {
    +    Op  string
    +    URL string
    +    Err error
    +}
    +

    +Error reports an error and the operation and URL that caused it. +

    + + + + + + + + + + + + + + +

    func (*Error) Error

    +
    func (e *Error) Error() string
    + + + + + + +

    func (*Error) Temporary

    +
    func (e *Error) Temporary() bool
    + + + + + + +

    func (*Error) Timeout

    +
    func (e *Error) Timeout() bool
    + + + + + + + + +

    type EscapeError

    +
    type EscapeError string
    + + + + + + + + + + + + + + +

    func (EscapeError) Error

    +
    func (e EscapeError) Error() string
    + + + + + + + + +

    type InvalidHostError

    +
    type InvalidHostError string
    + + + + + + + + + + + + + + +

    func (InvalidHostError) Error

    +
    func (e InvalidHostError) Error() string
    + + + + + + + + +

    type URL

    +
    type URL struct {
    +    Scheme   string
    +    Opaque   string    // encoded opaque data
    +    User     *Userinfo // username and password information
    +    Host     string    // host or host:port
    +    Path     string
    +    RawPath  string // encoded path hint (Go 1.5 and later only; see EscapedPath method)
    +    RawQuery string // encoded query values, without '?'
    +    Fragment string // fragment for references, without '#'
    +}
    +

    +A URL represents a parsed URL (technically, a URI reference). +The general form represented is: +

    +
    scheme://[userinfo@]host/path[?query][#fragment]
    +
    +

    +URLs that do not start with a slash after the scheme are interpreted as: +

    +
    scheme:opaque[?query][#fragment]
    +
    +

    +Note that the Path field is stored in decoded form: /%47%6f%2f becomes /Go/. +A consequence is that it is impossible to tell which slashes in the Path were +slashes in the raw URL and which were %2f. This distinction is rarely important, +but when it is, code must not use Path directly. +

    +

    +Go 1.5 introduced the RawPath field to hold the encoded form of Path. +The Parse function sets both Path and RawPath in the URL it returns, +and URL's String method uses RawPath if it is a valid encoding of Path, +by calling the EscapedPath method. +

    +

    +In earlier versions of Go, the more indirect workarounds were that an +HTTP server could consult req.RequestURI and an HTTP client could +construct a URL struct directly and set the Opaque field instead of Path. +These still work as well. +

    + + + + + + +
    + +
    +

    Example

    + + + +

    Code:

    +
    u, err := url.Parse("http://bing.com/search?q=dotnet")
    +if err != nil {
    +    log.Fatal(err)
    +}
    +u.Scheme = "https"
    +u.Host = "google.com"
    +q := u.Query()
    +q.Set("q", "golang")
    +u.RawQuery = q.Encode()
    +fmt.Println(u)
    +
    + +

    Output:

    +
    https://google.com/search?q=golang
    +
    + + +
    +
    +
    + +
    +

    Example (Opaque)

    + + + +

    Code:

    +
    // Sending a literal '%' in an HTTP request's Path
    +req := &http.Request{
    +    Method: "GET",
    +    Host:   "example.com", // takes precedence over URL.Host
    +    URL: &url.URL{
    +        Host:   "ignored",
    +        Scheme: "https",
    +        Opaque: "/%2f/",
    +    },
    +    Header: http.Header{
    +        "User-Agent": {"godoc-example/0.1"},
    +    },
    +}
    +out, err := httputil.DumpRequestOut(req, true)
    +if err != nil {
    +    log.Fatal(err)
    +}
    +fmt.Println(strings.Replace(string(out), "\r", "", -1))
    +
    + +

    Output:

    +
    GET /%2f/ HTTP/1.1
    +Host: example.com
    +User-Agent: godoc-example/0.1
    +Accept-Encoding: gzip
    +
    + + +
    +
    +
    + +
    +

    Example (Roundtrip)

    + + + +

    Code:

    +
    // Parse + String preserve the original encoding.
    +u, err := url.Parse("https://example.com/foo%2fbar")
    +if err != nil {
    +    log.Fatal(err)
    +}
    +fmt.Println(u.Path)
    +fmt.Println(u.RawPath)
    +fmt.Println(u.String())
    +
    + +

    Output:

    +
    /foo/bar
    +/foo%2fbar
    +https://example.com/foo%2fbar
    +
    + + +
    +
    + + + + + + +

    func Parse

    +
    func Parse(rawurl string) (url *URL, err error)
    +

    +Parse parses rawurl into a URL structure. +The rawurl may be relative or absolute. +

    + + + + + +

    func ParseRequestURI

    +
    func ParseRequestURI(rawurl string) (url *URL, err error)
    +

    +ParseRequestURI parses rawurl into a URL structure. It assumes that +rawurl was received in an HTTP request, so the rawurl is interpreted +only as an absolute URI or an absolute path. +The string rawurl is assumed not to have a #fragment suffix. +(Web browsers strip #fragment before sending the URL to a web server.) +

    + + + + + + + +

    func (*URL) EscapedPath

    +
    func (u *URL) EscapedPath() string
    +

    +EscapedPath returns the escaped form of u.Path. +In general there are multiple possible escaped forms of any path. +EscapedPath returns u.RawPath when it is a valid escaping of u.Path. +Otherwise EscapedPath ignores u.RawPath and computes an escaped +form on its own. +The String and RequestURI methods use EscapedPath to construct +their results. +In general, code should call EscapedPath instead of +reading u.RawPath directly. +

    + + + + + + +

    func (*URL) IsAbs

    +
    func (u *URL) IsAbs() bool
    +

    +IsAbs reports whether the URL is absolute. +

    + + + + + + +

    func (*URL) Parse

    +
    func (u *URL) Parse(ref string) (*URL, error)
    +

    +Parse parses a URL in the context of the receiver. The provided URL +may be relative or absolute. Parse returns nil, err on parse +failure, otherwise its return value is the same as ResolveReference. +

    + + + + + + +

    func (*URL) Query

    +
    func (u *URL) Query() Values
    +

    +Query parses RawQuery and returns the corresponding values. +

    + + + + + + +

    func (*URL) RequestURI

    +
    func (u *URL) RequestURI() string
    +

    +RequestURI returns the encoded path?query or opaque?query +string that would be used in an HTTP request for u. +

    + + + + + + +

    func (*URL) ResolveReference

    +
    func (u *URL) ResolveReference(ref *URL) *URL
    +

    +ResolveReference resolves a URI reference to an absolute URI from +an absolute base URI, per RFC 3986 Section 5.2. The URI reference +may be relative or absolute. ResolveReference always returns a new +URL instance, even if the returned URL is identical to either the +base or reference. If ref is an absolute URL, then ResolveReference +ignores base and returns a copy of ref. +

    + + +
    + +
    +

    Example

    + + + +

    Code:

    +
    u, err := url.Parse("../../..//search?q=dotnet")
    +if err != nil {
    +    log.Fatal(err)
    +}
    +base, err := url.Parse("http://example.com/directory/")
    +if err != nil {
    +    log.Fatal(err)
    +}
    +fmt.Println(base.ResolveReference(u))
    +
    + +

    Output:

    +
    http://example.com/search?q=dotnet
    +
    + + +
    +
    + + + + +

    func (*URL) String

    +
    func (u *URL) String() string
    +

    +String reassembles the URL into a valid URL string. +The general form of the result is one of: +

    +
    scheme:opaque?query#fragment
    +scheme://userinfo@host/path?query#fragment
    +
    +

    +If u.Opaque is non-empty, String uses the first form; +otherwise it uses the second form. +To obtain the path, String uses u.EscapedPath(). +

    +

    +In the second form, the following rules apply: +

    +
    - if u.Scheme is empty, scheme: is omitted.
    +- if u.User is nil, userinfo@ is omitted.
    +- if u.Host is empty, host/ is omitted.
    +- if u.Scheme and u.Host are empty and u.User is nil,
    +   the entire scheme://userinfo@host/ is omitted.
    +- if u.Host is non-empty and u.Path begins with a /,
    +   the form host/path does not add its own /.
    +- if u.RawQuery is empty, ?query is omitted.
    +- if u.Fragment is empty, #fragment is omitted.
    +
    + + + + + + + + +

    type Userinfo

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

    +The Userinfo type is an immutable encapsulation of username and +password details for a URL. An existing Userinfo value is guaranteed +to have a username set (potentially empty, as allowed by RFC 2396), +and optionally a password. +

    + + + + + + + + + + + + +

    func User

    +
    func User(username string) *Userinfo
    +

    +User returns a Userinfo containing the provided username +and no password set. +

    + + + + + +

    func UserPassword

    +
    func UserPassword(username, password string) *Userinfo
    +

    +UserPassword returns a Userinfo containing the provided username +and password. +This functionality should only be used with legacy web sites. +RFC 2396 warns that interpreting Userinfo this way +“is NOT RECOMMENDED, because the passing of authentication +information in clear text (such as URI) has proven to be a +security risk in almost every case where it has been used.” +

    + + + + + + + +

    func (*Userinfo) Password

    +
    func (u *Userinfo) Password() (string, bool)
    +

    +Password returns the password in case it is set, and whether it is set. +

    + + + + + + +

    func (*Userinfo) String

    +
    func (u *Userinfo) String() string
    +

    +String returns the encoded userinfo information in the standard form +of "username[:password]". +

    + + + + + + +

    func (*Userinfo) Username

    +
    func (u *Userinfo) Username() string
    +

    +Username returns the username. +

    + + + + + + + + +

    type Values

    +
    type Values map[string][]string
    +

    +Values maps a string key to a list of values. +It is typically used for query parameters and form values. +Unlike in the http.Header map, the keys in a Values map +are case-sensitive. +

    + + + + + + +
    + +
    +

    Example

    + + + +

    Code:

    +
    v := url.Values{}
    +v.Set("name", "Ava")
    +v.Add("friend", "Jess")
    +v.Add("friend", "Sarah")
    +v.Add("friend", "Zoe")
    +// v.Encode() == "name=Ava&friend=Jess&friend=Sarah&friend=Zoe"
    +fmt.Println(v.Get("name"))
    +fmt.Println(v.Get("friend"))
    +fmt.Println(v["friend"])
    +
    + +

    Output:

    +
    Ava
    +Jess
    +[Jess Sarah Zoe]
    +
    + + +
    +
    + + + + + + +

    func ParseQuery

    +
    func ParseQuery(query string) (m Values, err error)
    +

    +ParseQuery parses the URL-encoded query string and returns +a map listing the values specified for each key. +ParseQuery always returns a non-nil map containing all the +valid query parameters found; err describes the first decoding error +encountered, if any. +

    + + + + + + + +

    func (Values) Add

    +
    func (v Values) Add(key, value string)
    +

    +Add adds the value to key. It appends to any existing +values associated with key. +

    + + + + + + +

    func (Values) Del

    +
    func (v Values) Del(key string)
    +

    +Del deletes the values associated with key. +

    + + + + + + +

    func (Values) Encode

    +
    func (v Values) Encode() string
    +

    +Encode encodes the values into “URL encoded” form +("bar=baz&foo=quux") sorted by key. +

    + + + + + + +

    func (Values) Get

    +
    func (v Values) Get(key string) string
    +

    +Get gets the first value associated with the given key. +If there are no values associated with the key, Get returns +the empty string. To access multiple values, use the map +directly. +

    + + + + + + +

    func (Values) Set

    +
    func (v Values) Set(key, value string)
    +

    +Set sets the key to value. It replaces any existing +values. +

    + + + + + + + + + + + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/os/exec/index.html b/pkg/os/exec/index.html new file mode 100644 index 0000000..f96263a --- /dev/null +++ b/pkg/os/exec/index.html @@ -0,0 +1,786 @@ + + + + + + + + exec - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Package exec

    + + + + + + + + + + + + + + +
    +
    +
    import "os/exec"
    +
    +
    +
    Overview
    +
    Index
    + +
    Examples
    + + +
    +
    + +
    + +
    +

    Overview ▾

    +

    +Package exec runs external commands. It wraps os.StartProcess to make it +easier to remap stdin and stdout, connect I/O with pipes, and do other +adjustments. +

    +

    +Note that the examples in this package assume a Unix system. +They may not run on Windows, and they do not run in the Go Playground +used by golang.org and godoc.org. +

    + +
    +
    + + + + + + + + +

    Variables

    + +
    var ErrNotFound = errors.New("executable file not found in $PATH")
    +

    +ErrNotFound is the error resulting if a path search failed to find an executable file. +

    + + + + + + +

    func LookPath

    +
    func LookPath(file string) (string, error)
    +

    +LookPath searches for an executable binary named file +in the directories named by the PATH environment variable. +If file contains a slash, it is tried directly and the PATH is not consulted. +The result may be an absolute path or a path relative to the current directory. +

    + +
    + +
    +

    Example

    + + + +

    Code:

    +
    +path, err := exec.LookPath("fortune")
    +if err != nil {
    +    log.Fatal("installing fortune is in your future")
    +}
    +fmt.Printf("fortune is available at %s\n", path)
    +
    + + +
    +
    + + + + + + + +

    type Cmd

    +
    type Cmd struct {
    +    // Path is the path of the command to run.
    +    //
    +    // This is the only field that must be set to a non-zero
    +    // value. If Path is relative, it is evaluated relative
    +    // to Dir.
    +    Path string
    +
    +    // Args holds command line arguments, including the command as Args[0].
    +    // If the Args field is empty or nil, Run uses {Path}.
    +    //
    +    // In typical use, both Path and Args are set by calling Command.
    +    Args []string
    +
    +    // Env specifies the environment of the process.
    +    // If Env is nil, Run uses the current process's environment.
    +    Env []string
    +
    +    // Dir specifies the working directory of the command.
    +    // If Dir is the empty string, Run runs the command in the
    +    // calling process's current directory.
    +    Dir string
    +
    +    // Stdin specifies the process's standard input.
    +    // If Stdin is nil, the process reads from the null device (os.DevNull).
    +    // If Stdin is an *os.File, the process's standard input is connected
    +    // directly to that file.
    +    // Otherwise, during the execution of the command a separate
    +    // goroutine reads from Stdin and delivers that data to the command
    +    // over a pipe. In this case, Wait does not complete until the goroutine
    +    // stops copying, either because it has reached the end of Stdin
    +    // (EOF or a read error) or because writing to the pipe returned an error.
    +    Stdin io.Reader
    +
    +    // Stdout and Stderr specify the process's standard output and error.
    +    //
    +    // If either is nil, Run connects the corresponding file descriptor
    +    // to the null device (os.DevNull).
    +    //
    +    // If Stdout and Stderr are the same writer, at most one
    +    // goroutine at a time will call Write.
    +    Stdout io.Writer
    +    Stderr io.Writer
    +
    +    // ExtraFiles specifies additional open files to be inherited by the
    +    // new process. It does not include standard input, standard output, or
    +    // standard error. If non-nil, entry i becomes file descriptor 3+i.
    +    //
    +    // BUG(rsc): On OS X 10.6, child processes may sometimes inherit unwanted fds.
    +    // https://golang.org/issue/2603
    +    ExtraFiles []*os.File
    +
    +    // SysProcAttr holds optional, operating system-specific attributes.
    +    // Run passes it to os.StartProcess as the os.ProcAttr's Sys field.
    +    SysProcAttr *syscall.SysProcAttr
    +
    +    // Process is the underlying process, once started.
    +    Process *os.Process
    +
    +    // ProcessState contains information about an exited process,
    +    // available after a call to Wait or Run.
    +    ProcessState *os.ProcessState
    +    // contains filtered or unexported fields
    +}
    +

    +Cmd represents an external command being prepared or run. +

    +

    +A Cmd cannot be reused after calling its Run, Output or CombinedOutput +methods. +

    + + + + + + + + + + + + +

    func Command

    +
    func Command(name string, arg ...string) *Cmd
    +

    +Command returns the Cmd struct to execute the named program with +the given arguments. +

    +

    +It sets only the Path and Args in the returned structure. +

    +

    +If name contains no path separators, Command uses LookPath to +resolve the path to a complete name if possible. Otherwise it uses +name directly. +

    +

    +The returned Cmd's Args field is constructed from the command name +followed by the elements of arg, so arg should not include the +command name itself. For example, Command("echo", "hello") +

    + +
    + +
    +

    Example

    + + + +

    Code:

    +
    +cmd := exec.Command("tr", "a-z", "A-Z")
    +cmd.Stdin = strings.NewReader("some input")
    +var out bytes.Buffer
    +cmd.Stdout = &out
    +err := cmd.Run()
    +if err != nil {
    +    log.Fatal(err)
    +}
    +fmt.Printf("in all caps: %q\n", out.String())
    +
    + + +
    +
    + + + + + + +

    func (*Cmd) CombinedOutput

    +
    func (c *Cmd) CombinedOutput() ([]byte, error)
    +

    +CombinedOutput runs the command and returns its combined standard +output and standard error. +

    + + + + + + +

    func (*Cmd) Output

    +
    func (c *Cmd) Output() ([]byte, error)
    +

    +Output runs the command and returns its standard output. +Any returned error will usually be of type *ExitError. +If c.Stderr was nil, Output populates ExitError.Stderr. +

    + + +
    + +
    +

    Example

    + + + +

    Code:

    +
    +out, err := exec.Command("date").Output()
    +if err != nil {
    +    log.Fatal(err)
    +}
    +fmt.Printf("The date is %s\n", out)
    +
    + + +
    +
    + + + + +

    func (*Cmd) Run

    +
    func (c *Cmd) Run() error
    +

    +Run starts the specified command and waits for it to complete. +

    +

    +The returned error is nil if the command runs, has no problems +copying stdin, stdout, and stderr, and exits with a zero exit +status. +

    +

    +If the command fails to run or doesn't complete successfully, the +error is of type *ExitError. Other error types may be +returned for I/O problems. +

    + + + + + + +

    func (*Cmd) Start

    +
    func (c *Cmd) Start() error
    +

    +Start starts the specified command but does not wait for it to complete. +

    +

    +The Wait method will return the exit code and release associated resources +once the command exits. +

    + + +
    + +
    +

    Example

    + + + +

    Code:

    +
    +cmd := exec.Command("sleep", "5")
    +err := cmd.Start()
    +if err != nil {
    +    log.Fatal(err)
    +}
    +log.Printf("Waiting for command to finish...")
    +err = cmd.Wait()
    +log.Printf("Command finished with error: %v", err)
    +
    + + +
    +
    + + + + +

    func (*Cmd) StderrPipe

    +
    func (c *Cmd) StderrPipe() (io.ReadCloser, error)
    +

    +StderrPipe returns a pipe that will be connected to the command's +standard error when the command starts. +

    +

    +Wait will close the pipe after seeing the command exit, so most callers +need not close the pipe themselves; however, an implication is that +it is incorrect to call Wait before all reads from the pipe have completed. +For the same reason, it is incorrect to use Run when using StderrPipe. +See the StdoutPipe example for idiomatic usage. +

    + + + + + + +

    func (*Cmd) StdinPipe

    +
    func (c *Cmd) StdinPipe() (io.WriteCloser, error)
    +

    +StdinPipe returns a pipe that will be connected to the command's +standard input when the command starts. +The pipe will be closed automatically after Wait sees the command exit. +A caller need only call Close to force the pipe to close sooner. +For example, if the command being run will not exit until standard input +is closed, the caller must close the pipe. +

    + + + + + + +

    func (*Cmd) StdoutPipe

    +
    func (c *Cmd) StdoutPipe() (io.ReadCloser, error)
    +

    +StdoutPipe returns a pipe that will be connected to the command's +standard output when the command starts. +

    +

    +Wait will close the pipe after seeing the command exit, so most callers +need not close the pipe themselves; however, an implication is that +it is incorrect to call Wait before all reads from the pipe have completed. +For the same reason, it is incorrect to call Run when using StdoutPipe. +See the example for idiomatic usage. +

    + + +
    + +
    +

    Example

    + + + +

    Code:

    +
    +cmd := exec.Command("echo", "-n", `{"Name": "Bob", "Age": 32}`)
    +stdout, err := cmd.StdoutPipe()
    +if err != nil {
    +    log.Fatal(err)
    +}
    +if err := cmd.Start(); err != nil {
    +    log.Fatal(err)
    +}
    +var person struct {
    +    Name string
    +    Age  int
    +}
    +if err := json.NewDecoder(stdout).Decode(&person); err != nil {
    +    log.Fatal(err)
    +}
    +if err := cmd.Wait(); err != nil {
    +    log.Fatal(err)
    +}
    +fmt.Printf("%s is %d years old\n", person.Name, person.Age)
    +
    + + +
    +
    + + + + +

    func (*Cmd) Wait

    +
    func (c *Cmd) Wait() error
    +

    +Wait waits for the command to exit. +It must have been started by Start. +

    +

    +The returned error is nil if the command runs, has no problems +copying stdin, stdout, and stderr, and exits with a zero exit +status. +

    +

    +If the command fails to run or doesn't complete successfully, the +error is of type *ExitError. Other error types may be +returned for I/O problems. +

    +

    +If c.Stdin is not an *os.File, Wait also waits for the I/O loop +copying from c.Stdin into the process's standard input +to complete. +

    +

    +Wait releases any resources associated with the Cmd. +

    + + + + + + + + +

    type Error

    +
    type Error struct {
    +    Name string
    +    Err  error
    +}
    +

    +Error records the name of a binary that failed to be executed +and the reason it failed. +

    + + + + + + + + + + + + + + +

    func (*Error) Error

    +
    func (e *Error) Error() string
    + + + + + + + + +

    type ExitError

    +
    type ExitError struct {
    +    *os.ProcessState
    +
    +    // Stderr holds a subset of the standard error output from the
    +    // Cmd.Output method if standard error was not otherwise being
    +    // collected.
    +    //
    +    // If the error output is long, Stderr may contain only a prefix
    +    // and suffix of the output, with the middle replaced with
    +    // text about the number of omitted bytes.
    +    //
    +    // Stderr is provided for debugging, for inclusion in error messages.
    +    // Users with other needs should redirect Cmd.Stderr as needed.
    +    Stderr []byte
    +}
    +

    +An ExitError reports an unsuccessful exit by a command. +

    + + + + + + + + + + + + + + +

    func (*ExitError) Error

    +
    func (e *ExitError) Error() string
    + + + + + + + + + + +

    Bugs

    +
      + +
    • On OS X 10.6, child processes may sometimes inherit unwanted fds. +https://golang.org/issue/2603 +
    • + +
    + + + + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/os/index.html b/pkg/os/index.html new file mode 100644 index 0000000..174a42a --- /dev/null +++ b/pkg/os/index.html @@ -0,0 +1,2148 @@ + + + + + + + + os - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Package os

    + + + + + + + + + + + + + + +
    +
    +
    import "os"
    +
    +
    +
    Overview
    +
    Index
    + + +
    Subdirectories
    + +
    +
    + +
    + +
    +

    Overview ▾

    +

    +Package os provides a platform-independent interface to operating system +functionality. The design is Unix-like, although the error handling is +Go-like; failing calls return values of type error rather than error numbers. +Often, more information is available within the error. For example, +if a call that takes a file name fails, such as Open or Stat, the error +will include the failing file name when printed and will be of type +*PathError, which may be unpacked for more information. +

    +

    +The os interface is intended to be uniform across all operating systems. +Features not generally available appear in the system-specific package syscall. +

    +

    +Here is a simple example, opening a file and reading some of it. +

    +
    file, err := os.Open("file.go") // For read access.
    +if err != nil {
    +	log.Fatal(err)
    +}
    +
    +

    +If the open fails, the error string will be self-explanatory, like +

    +
    open file.go: no such file or directory
    +
    +

    +The file's data can then be read into a slice of bytes. Read and +Write take their byte counts from the length of the argument slice. +

    +
    data := make([]byte, 100)
    +count, err := file.Read(data)
    +if err != nil {
    +	log.Fatal(err)
    +}
    +fmt.Printf("read %d bytes: %q\n", count, data[:count])
    +
    + +
    +
    + + +
    + +
    +

    Index ▾

    + + +
    +
    + +
    Constants
    + + +
    Variables
    + + + +
    func Chdir(dir string) error
    + + +
    func Chmod(name string, mode FileMode) error
    + + +
    func Chown(name string, uid, gid int) error
    + + +
    func Chtimes(name string, atime time.Time, mtime time.Time) error
    + + +
    func Clearenv()
    + + +
    func Environ() []string
    + + +
    func Exit(code int)
    + + +
    func Expand(s string, mapping func(string) string) string
    + + +
    func ExpandEnv(s string) string
    + + +
    func Getegid() int
    + + +
    func Getenv(key string) string
    + + +
    func Geteuid() int
    + + +
    func Getgid() int
    + + +
    func Getgroups() ([]int, error)
    + + +
    func Getpagesize() int
    + + +
    func Getpid() int
    + + +
    func Getppid() int
    + + +
    func Getuid() int
    + + +
    func Getwd() (dir string, err error)
    + + +
    func Hostname() (name string, err error)
    + + +
    func IsExist(err error) bool
    + + +
    func IsNotExist(err error) bool
    + + +
    func IsPathSeparator(c uint8) bool
    + + +
    func IsPermission(err error) bool
    + + +
    func Lchown(name string, uid, gid int) error
    + + +
    func Link(oldname, newname string) error
    + + +
    func LookupEnv(key string) (string, bool)
    + + +
    func Mkdir(name string, perm FileMode) error
    + + +
    func MkdirAll(path string, perm FileMode) error
    + + +
    func NewSyscallError(syscall string, err error) error
    + + +
    func Readlink(name string) (string, error)
    + + +
    func Remove(name string) error
    + + +
    func RemoveAll(path string) error
    + + +
    func Rename(oldpath, newpath string) error
    + + +
    func SameFile(fi1, fi2 FileInfo) bool
    + + +
    func Setenv(key, value string) error
    + + +
    func Symlink(oldname, newname string) error
    + + +
    func TempDir() string
    + + +
    func Truncate(name string, size int64) error
    + + +
    func Unsetenv(key string) error
    + + + +
    type File
    + + +
        func Create(name string) (*File, error)
    + + +
        func NewFile(fd uintptr, name string) *File
    + + +
        func Open(name string) (*File, error)
    + + +
        func OpenFile(name string, flag int, perm FileMode) (*File, error)
    + + +
        func Pipe() (r *File, w *File, err error)
    + + + +
        func (f *File) Chdir() error
    + + +
        func (f *File) Chmod(mode FileMode) error
    + + +
        func (f *File) Chown(uid, gid int) error
    + + +
        func (f *File) Close() error
    + + +
        func (f *File) Fd() uintptr
    + + +
        func (f *File) Name() string
    + + +
        func (f *File) Read(b []byte) (n int, err error)
    + + +
        func (f *File) ReadAt(b []byte, off int64) (n int, err error)
    + + +
        func (f *File) Readdir(n int) (fi []FileInfo, err error)
    + + +
        func (f *File) Readdirnames(n int) (names []string, err error)
    + + +
        func (f *File) Seek(offset int64, whence int) (ret int64, err error)
    + + +
        func (f *File) Stat() (FileInfo, error)
    + + +
        func (f *File) Sync() error
    + + +
        func (f *File) Truncate(size int64) error
    + + +
        func (f *File) Write(b []byte) (n int, err error)
    + + +
        func (f *File) WriteAt(b []byte, off int64) (n int, err error)
    + + +
        func (f *File) WriteString(s string) (n int, err error)
    + + + +
    type FileInfo
    + + +
        func Lstat(name string) (FileInfo, error)
    + + +
        func Stat(name string) (FileInfo, error)
    + + + + +
    type FileMode
    + + + +
        func (m FileMode) IsDir() bool
    + + +
        func (m FileMode) IsRegular() bool
    + + +
        func (m FileMode) Perm() FileMode
    + + +
        func (m FileMode) String() string
    + + + +
    type LinkError
    + + + +
        func (e *LinkError) Error() string
    + + + +
    type PathError
    + + + +
        func (e *PathError) Error() string
    + + + +
    type ProcAttr
    + + + + +
    type Process
    + + +
        func FindProcess(pid int) (*Process, error)
    + + +
        func StartProcess(name string, argv []string, attr *ProcAttr) (*Process, error)
    + + + +
        func (p *Process) Kill() error
    + + +
        func (p *Process) Release() error
    + + +
        func (p *Process) Signal(sig Signal) error
    + + +
        func (p *Process) Wait() (*ProcessState, error)
    + + + +
    type ProcessState
    + + + +
        func (p *ProcessState) Exited() bool
    + + +
        func (p *ProcessState) Pid() int
    + + +
        func (p *ProcessState) String() string
    + + +
        func (p *ProcessState) Success() bool
    + + +
        func (p *ProcessState) Sys() interface{}
    + + +
        func (p *ProcessState) SysUsage() interface{}
    + + +
        func (p *ProcessState) SystemTime() time.Duration
    + + +
        func (p *ProcessState) UserTime() time.Duration
    + + + +
    type Signal
    + + + + +
    type SyscallError
    + + + +
        func (e *SyscallError) Error() string
    + + + +
    +
    + + + + +

    Package files

    +

    + + + dir_unix.go + + doc.go + + env.go + + error.go + + error_unix.go + + exec.go + + exec_posix.go + + exec_unix.go + + file.go + + file_posix.go + + file_unix.go + + getwd.go + + path.go + + path_unix.go + + pipe_linux.go + + proc.go + + stat_linux.go + + sticky_notbsd.go + + str.go + + sys_linux.go + + sys_unix.go + + types.go + + types_unix.go + + +

    + +
    +
    + + + + +

    Constants

    + +
    const (
    +    O_RDONLY int = syscall.O_RDONLY // open the file read-only.
    +    O_WRONLY int = syscall.O_WRONLY // open the file write-only.
    +    O_RDWR   int = syscall.O_RDWR   // open the file read-write.
    +    O_APPEND int = syscall.O_APPEND // append data to the file when writing.
    +    O_CREATE int = syscall.O_CREAT  // create a new file if none exists.
    +    O_EXCL   int = syscall.O_EXCL   // used with O_CREATE, file must not exist
    +    O_SYNC   int = syscall.O_SYNC   // open for synchronous I/O.
    +    O_TRUNC  int = syscall.O_TRUNC  // if possible, truncate file when opened.
    +)
    +

    +Flags to OpenFile wrapping those of the underlying system. Not all +flags may be implemented on a given system. +

    + + +
    const (
    +    SEEK_SET int = 0 // seek relative to the origin of the file
    +    SEEK_CUR int = 1 // seek relative to the current offset
    +    SEEK_END int = 2 // seek relative to the end
    +)
    +

    +Seek whence values. +

    + + +
    const (
    +    PathSeparator     = '/' // OS-specific path separator
    +    PathListSeparator = ':' // OS-specific path list separator
    +)
    + + +
    const DevNull = "/dev/null"
    +

    +DevNull is the name of the operating system's “null device.” +On Unix-like systems, it is "/dev/null"; on Windows, "NUL". +

    + + + + +

    Variables

    + +
    var (
    +    ErrInvalid    = errors.New("invalid argument") // methods on File will return this error when the receiver is nil
    +    ErrPermission = errors.New("permission denied")
    +    ErrExist      = errors.New("file already exists")
    +    ErrNotExist   = errors.New("file does not exist")
    +)
    +

    +Portable analogs of some common system call errors. +

    + + +
    var (
    +    Stdin  = NewFile(uintptr(syscall.Stdin), "/dev/stdin")
    +    Stdout = NewFile(uintptr(syscall.Stdout), "/dev/stdout")
    +    Stderr = NewFile(uintptr(syscall.Stderr), "/dev/stderr")
    +)
    +

    +Stdin, Stdout, and Stderr are open Files pointing to the standard input, +standard output, and standard error file descriptors. +

    + + +
    var Args []string
    +

    +Args hold the command-line arguments, starting with the program name. +

    + + + + + + +

    func Chdir

    +
    func Chdir(dir string) error
    +

    +Chdir changes the current working directory to the named directory. +If there is an error, it will be of type *PathError. +

    + + + + + + + +

    func Chmod

    +
    func Chmod(name string, mode FileMode) error
    +

    +Chmod changes the mode of the named file to mode. +If the file is a symbolic link, it changes the mode of the link's target. +If there is an error, it will be of type *PathError. +

    + + + + + + + +

    func Chown

    +
    func Chown(name string, uid, gid int) error
    +

    +Chown changes the numeric uid and gid of the named file. +If the file is a symbolic link, it changes the uid and gid of the link's target. +If there is an error, it will be of type *PathError. +

    + + + + + + + +

    func Chtimes

    +
    func Chtimes(name string, atime time.Time, mtime time.Time) error
    +

    +Chtimes changes the access and modification times of the named +file, similar to the Unix utime() or utimes() functions. +

    +

    +The underlying filesystem may truncate or round the values to a +less precise time unit. +If there is an error, it will be of type *PathError. +

    + + + + + + + +

    func Clearenv

    +
    func Clearenv()
    +

    +Clearenv deletes all environment variables. +

    + + + + + + + +

    func Environ

    +
    func Environ() []string
    +

    +Environ returns a copy of strings representing the environment, +in the form "key=value". +

    + + + + + + + +

    func Exit

    +
    func Exit(code int)
    +

    +Exit causes the current program to exit with the given status code. +Conventionally, code zero indicates success, non-zero an error. +The program terminates immediately; deferred functions are not run. +

    + + + + + + + +

    func Expand

    +
    func Expand(s string, mapping func(string) string) string
    +

    +Expand replaces ${var} or $var in the string based on the mapping function. +For example, os.ExpandEnv(s) is equivalent to os.Expand(s, os.Getenv). +

    + + + + + + + +

    func ExpandEnv

    +
    func ExpandEnv(s string) string
    +

    +ExpandEnv replaces ${var} or $var in the string according to the values +of the current environment variables. References to undefined +variables are replaced by the empty string. +

    + + + + + + + +

    func Getegid

    +
    func Getegid() int
    +

    +Getegid returns the numeric effective group id of the caller. +

    + + + + + + + +

    func Getenv

    +
    func Getenv(key string) string
    +

    +Getenv retrieves the value of the environment variable named by the key. +It returns the value, which will be empty if the variable is not present. +

    + + + + + + + +

    func Geteuid

    +
    func Geteuid() int
    +

    +Geteuid returns the numeric effective user id of the caller. +

    + + + + + + + +

    func Getgid

    +
    func Getgid() int
    +

    +Getgid returns the numeric group id of the caller. +

    + + + + + + + +

    func Getgroups

    +
    func Getgroups() ([]int, error)
    +

    +Getgroups returns a list of the numeric ids of groups that the caller belongs to. +

    + + + + + + + +

    func Getpagesize

    +
    func Getpagesize() int
    +

    +Getpagesize returns the underlying system's memory page size. +

    + + + + + + + +

    func Getpid

    +
    func Getpid() int
    +

    +Getpid returns the process id of the caller. +

    + + + + + + + +

    func Getppid

    +
    func Getppid() int
    +

    +Getppid returns the process id of the caller's parent. +

    + + + + + + + +

    func Getuid

    +
    func Getuid() int
    +

    +Getuid returns the numeric user id of the caller. +

    + + + + + + + +

    func Getwd

    +
    func Getwd() (dir string, err error)
    +

    +Getwd returns a rooted path name corresponding to the +current directory. If the current directory can be +reached via multiple paths (due to symbolic links), +Getwd may return any one of them. +

    + + + + + + + +

    func Hostname

    +
    func Hostname() (name string, err error)
    +

    +Hostname returns the host name reported by the kernel. +

    + + + + + + + +

    func IsExist

    +
    func IsExist(err error) bool
    +

    +IsExist returns a boolean indicating whether the error is known to report +that a file or directory already exists. It is satisfied by ErrExist as +well as some syscall errors. +

    + + + + + + + +

    func IsNotExist

    +
    func IsNotExist(err error) bool
    +

    +IsNotExist returns a boolean indicating whether the error is known to +report that a file or directory does not exist. It is satisfied by +ErrNotExist as well as some syscall errors. +

    + + + + + + + +

    func IsPathSeparator

    +
    func IsPathSeparator(c uint8) bool
    +

    +IsPathSeparator reports whether c is a directory separator character. +

    + + + + + + + +

    func IsPermission

    +
    func IsPermission(err error) bool
    +

    +IsPermission returns a boolean indicating whether the error is known to +report that permission is denied. It is satisfied by ErrPermission as well +as some syscall errors. +

    + + + + + + + +

    func Lchown

    +
    func Lchown(name string, uid, gid int) error
    +

    +Lchown changes the numeric uid and gid of the named file. +If the file is a symbolic link, it changes the uid and gid of the link itself. +If there is an error, it will be of type *PathError. +

    + + + + + + + + +
    func Link(oldname, newname string) error
    +

    +Link creates newname as a hard link to the oldname file. +If there is an error, it will be of type *LinkError. +

    + + + + + + + +

    func LookupEnv

    +
    func LookupEnv(key string) (string, bool)
    +

    +LookupEnv retrieves the value of the environment variable named +by the key. If the variable is present in the environment the +value (which may be empty) is returned and the boolean is true. +Otherwise the returned value will be empty and the boolean will +be false. +

    + + + + + + + +

    func Mkdir

    +
    func Mkdir(name string, perm FileMode) error
    +

    +Mkdir creates a new directory with the specified name and permission bits. +If there is an error, it will be of type *PathError. +

    + + + + + + + +

    func MkdirAll

    +
    func MkdirAll(path string, perm FileMode) error
    +

    +MkdirAll creates a directory named path, +along with any necessary parents, and returns nil, +or else returns an error. +The permission bits perm are used for all +directories that MkdirAll creates. +If path is already a directory, MkdirAll does nothing +and returns nil. +

    + + + + + + + +

    func NewSyscallError

    +
    func NewSyscallError(syscall string, err error) error
    +

    +NewSyscallError returns, as an error, a new SyscallError +with the given system call name and error details. +As a convenience, if err is nil, NewSyscallError returns nil. +

    + + + + + + + + +
    func Readlink(name string) (string, error)
    +

    +Readlink returns the destination of the named symbolic link. +If there is an error, it will be of type *PathError. +

    + + + + + + + +

    func Remove

    +
    func Remove(name string) error
    +

    +Remove removes the named file or directory. +If there is an error, it will be of type *PathError. +

    + + + + + + + +

    func RemoveAll

    +
    func RemoveAll(path string) error
    +

    +RemoveAll removes path and any children it contains. +It removes everything it can but returns the first error +it encounters. If the path does not exist, RemoveAll +returns nil (no error). +

    + + + + + + + +

    func Rename

    +
    func Rename(oldpath, newpath string) error
    +

    +Rename renames (moves) oldpath to newpath. +If newpath already exists, Rename replaces it. +OS-specific restrictions may apply when oldpath and newpath are in different directories. +If there is an error, it will be of type *LinkError. +

    + + + + + + + +

    func SameFile

    +
    func SameFile(fi1, fi2 FileInfo) bool
    +

    +SameFile reports whether fi1 and fi2 describe the same file. +For example, on Unix this means that the device and inode fields +of the two underlying structures are identical; on other systems +the decision may be based on the path names. +SameFile only applies to results returned by this package's Stat. +It returns false in other cases. +

    + + + + + + + +

    func Setenv

    +
    func Setenv(key, value string) error
    +

    +Setenv sets the value of the environment variable named by the key. +It returns an error, if any. +

    + + + + + + + + +
    func Symlink(oldname, newname string) error
    +

    +Symlink creates newname as a symbolic link to oldname. +If there is an error, it will be of type *LinkError. +

    + + + + + + + +

    func TempDir

    +
    func TempDir() string
    +

    +TempDir returns the default directory to use for temporary files. +

    + + + + + + + +

    func Truncate

    +
    func Truncate(name string, size int64) error
    +

    +Truncate changes the size of the named file. +If the file is a symbolic link, it changes the size of the link's target. +If there is an error, it will be of type *PathError. +

    + + + + + + + +

    func Unsetenv

    +
    func Unsetenv(key string) error
    +

    +Unsetenv unsets a single environment variable. +

    + + + + + + + + +

    type File

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

    +File represents an open file descriptor. +

    + + + + + + + + + + + + +

    func Create

    +
    func Create(name string) (*File, error)
    +

    +Create creates the named file with mode 0666 (before umask), truncating +it if it already exists. If successful, methods on the returned +File can be used for I/O; the associated file descriptor has mode +O_RDWR. +If there is an error, it will be of type *PathError. +

    + + + + + +

    func NewFile

    +
    func NewFile(fd uintptr, name string) *File
    +

    +NewFile returns a new File with the given file descriptor and name. +

    + + + + + +

    func Open

    +
    func Open(name string) (*File, error)
    +

    +Open opens the named file for reading. If successful, methods on +the returned file can be used for reading; the associated file +descriptor has mode O_RDONLY. +If there is an error, it will be of type *PathError. +

    + + + + + +

    func OpenFile

    +
    func OpenFile(name string, flag int, perm FileMode) (*File, error)
    +

    +OpenFile is the generalized open call; most users will use Open +or Create instead. It opens the named file with specified flag +(O_RDONLY etc.) and perm, (0666 etc.) if applicable. If successful, +methods on the returned File can be used for I/O. +If there is an error, it will be of type *PathError. +

    + + + + + +

    func Pipe

    +
    func Pipe() (r *File, w *File, err error)
    +

    +Pipe returns a connected pair of Files; reads from r return bytes written to w. +It returns the files and an error, if any. +

    + + + + + + + +

    func (*File) Chdir

    +
    func (f *File) Chdir() error
    +

    +Chdir changes the current working directory to the file, +which must be a directory. +If there is an error, it will be of type *PathError. +

    + + + + + + +

    func (*File) Chmod

    +
    func (f *File) Chmod(mode FileMode) error
    +

    +Chmod changes the mode of the file to mode. +If there is an error, it will be of type *PathError. +

    + + + + + + +

    func (*File) Chown

    +
    func (f *File) Chown(uid, gid int) error
    +

    +Chown changes the numeric uid and gid of the named file. +If there is an error, it will be of type *PathError. +

    + + + + + + +

    func (*File) Close

    +
    func (f *File) Close() error
    +

    +Close closes the File, rendering it unusable for I/O. +It returns an error, if any. +

    + + + + + + +

    func (*File) Fd

    +
    func (f *File) Fd() uintptr
    +

    +Fd returns the integer Unix file descriptor referencing the open file. +The file descriptor is valid only until f.Close is called or f is garbage collected. +

    + + + + + + +

    func (*File) Name

    +
    func (f *File) Name() string
    +

    +Name returns the name of the file as presented to Open. +

    + + + + + + +

    func (*File) Read

    +
    func (f *File) Read(b []byte) (n int, err error)
    +

    +Read reads up to len(b) bytes from the File. +It returns the number of bytes read and an error, if any. +EOF is signaled by a zero count with err set to io.EOF. +

    + + + + + + +

    func (*File) ReadAt

    +
    func (f *File) ReadAt(b []byte, off int64) (n int, err error)
    +

    +ReadAt reads len(b) bytes from the File starting at byte offset off. +It returns the number of bytes read and the error, if any. +ReadAt always returns a non-nil error when n < len(b). +At end of file, that error is io.EOF. +

    + + + + + + +

    func (*File) Readdir

    +
    func (f *File) Readdir(n int) (fi []FileInfo, err error)
    +

    +Readdir reads the contents of the directory associated with file and +returns a slice of up to n FileInfo values, as would be returned +by Lstat, in directory order. Subsequent calls on the same file will yield +further FileInfos. +

    +

    +If n > 0, Readdir returns at most n FileInfo structures. In this case, if +Readdir returns an empty slice, it will return a non-nil error +explaining why. At the end of a directory, the error is io.EOF. +

    +

    +If n <= 0, Readdir returns all the FileInfo from the directory in +a single slice. In this case, if Readdir succeeds (reads all +the way to the end of the directory), it returns the slice and a +nil error. If it encounters an error before the end of the +directory, Readdir returns the FileInfo read until that point +and a non-nil error. +

    + + + + + + +

    func (*File) Readdirnames

    +
    func (f *File) Readdirnames(n int) (names []string, err error)
    +

    +Readdirnames reads and returns a slice of names from the directory f. +

    +

    +If n > 0, Readdirnames returns at most n names. In this case, if +Readdirnames returns an empty slice, it will return a non-nil error +explaining why. At the end of a directory, the error is io.EOF. +

    +

    +If n <= 0, Readdirnames returns all the names from the directory in +a single slice. In this case, if Readdirnames succeeds (reads all +the way to the end of the directory), it returns the slice and a +nil error. If it encounters an error before the end of the +directory, Readdirnames returns the names read until that point and +a non-nil error. +

    + + + + + + +

    func (*File) Seek

    +
    func (f *File) Seek(offset int64, whence int) (ret int64, err error)
    +

    +Seek sets the offset for the next Read or Write on file to offset, interpreted +according to whence: 0 means relative to the origin of the file, 1 means +relative to the current offset, and 2 means relative to the end. +It returns the new offset and an error, if any. +The behavior of Seek on a file opened with O_APPEND is not specified. +

    + + + + + + +

    func (*File) Stat

    +
    func (f *File) Stat() (FileInfo, error)
    +

    +Stat returns the FileInfo structure describing file. +If there is an error, it will be of type *PathError. +

    + + + + + + +

    func (*File) Sync

    +
    func (f *File) Sync() error
    +

    +Sync commits the current contents of the file to stable storage. +Typically, this means flushing the file system's in-memory copy +of recently written data to disk. +

    + + + + + + +

    func (*File) Truncate

    +
    func (f *File) Truncate(size int64) error
    +

    +Truncate changes the size of the file. +It does not change the I/O offset. +If there is an error, it will be of type *PathError. +

    + + + + + + +

    func (*File) Write

    +
    func (f *File) Write(b []byte) (n int, err error)
    +

    +Write writes len(b) bytes to the File. +It returns the number of bytes written and an error, if any. +Write returns a non-nil error when n != len(b). +

    + + + + + + +

    func (*File) WriteAt

    +
    func (f *File) WriteAt(b []byte, off int64) (n int, err error)
    +

    +WriteAt writes len(b) bytes to the File starting at byte offset off. +It returns the number of bytes written and an error, if any. +WriteAt returns a non-nil error when n != len(b). +

    + + + + + + +

    func (*File) WriteString

    +
    func (f *File) WriteString(s string) (n int, err error)
    +

    +WriteString is like Write, but writes the contents of string s rather than +a slice of bytes. +

    + + + + + + + + +

    type FileInfo

    +
    type FileInfo interface {
    +    Name() string       // base name of the file
    +    Size() int64        // length in bytes for regular files; system-dependent for others
    +    Mode() FileMode     // file mode bits
    +    ModTime() time.Time // modification time
    +    IsDir() bool        // abbreviation for Mode().IsDir()
    +    Sys() interface{}   // underlying data source (can return nil)
    +}
    +

    +A FileInfo describes a file and is returned by Stat and Lstat. +

    + + + + + + + + + + + + +

    func Lstat

    +
    func Lstat(name string) (FileInfo, error)
    +

    +Lstat returns a FileInfo describing the named file. +If the file is a symbolic link, the returned FileInfo +describes the symbolic link. Lstat makes no attempt to follow the link. +If there is an error, it will be of type *PathError. +

    + + + + + +

    func Stat

    +
    func Stat(name string) (FileInfo, error)
    +

    +Stat returns a FileInfo describing the named file. +If there is an error, it will be of type *PathError. +

    + + + + + + + + + +

    type FileMode

    +
    type FileMode uint32
    +

    +A FileMode represents a file's mode and permission bits. +The bits have the same definition on all systems, so that +information about files can be moved from one system +to another portably. Not all bits apply to all systems. +The only required bit is ModeDir for directories. +

    + + + +
    const (
    +    // The single letters are the abbreviations
    +    // used by the String method's formatting.
    +    ModeDir        FileMode = 1 << (32 - 1 - iota) // d: is a directory
    +    ModeAppend                                     // a: append-only
    +    ModeExclusive                                  // l: exclusive use
    +    ModeTemporary                                  // T: temporary file (not backed up)
    +    ModeSymlink                                    // L: symbolic link
    +    ModeDevice                                     // D: device file
    +    ModeNamedPipe                                  // p: named pipe (FIFO)
    +    ModeSocket                                     // S: Unix domain socket
    +    ModeSetuid                                     // u: setuid
    +    ModeSetgid                                     // g: setgid
    +    ModeCharDevice                                 // c: Unix character device, when ModeDevice is set
    +    ModeSticky                                     // t: sticky
    +
    +    // Mask for the type bits. For regular files, none will be set.
    +    ModeType = ModeDir | ModeSymlink | ModeNamedPipe | ModeSocket | ModeDevice
    +
    +    ModePerm FileMode = 0777 // Unix permission bits
    +)
    +

    +The defined file mode bits are the most significant bits of the FileMode. +The nine least-significant bits are the standard Unix rwxrwxrwx permissions. +The values of these bits should be considered part of the public API and +may be used in wire protocols or disk representations: they must not be +changed, although new bits might be added. +

    + + + + + + + + + + + + + +

    func (FileMode) IsDir

    +
    func (m FileMode) IsDir() bool
    +

    +IsDir reports whether m describes a directory. +That is, it tests for the ModeDir bit being set in m. +

    + + + + + + +

    func (FileMode) IsRegular

    +
    func (m FileMode) IsRegular() bool
    +

    +IsRegular reports whether m describes a regular file. +That is, it tests that no mode type bits are set. +

    + + + + + + +

    func (FileMode) Perm

    +
    func (m FileMode) Perm() FileMode
    +

    +Perm returns the Unix permission bits in m. +

    + + + + + + +

    func (FileMode) String

    +
    func (m FileMode) String() string
    + + + + + + + + +

    type LinkError

    +
    type LinkError struct {
    +    Op  string
    +    Old string
    +    New string
    +    Err error
    +}
    +

    +LinkError records an error during a link or symlink or rename +system call and the paths that caused it. +

    + + + + + + + + + + + + + + +

    func (*LinkError) Error

    +
    func (e *LinkError) Error() string
    + + + + + + + + +

    type PathError

    +
    type PathError struct {
    +    Op   string
    +    Path string
    +    Err  error
    +}
    +

    +PathError records an error and the operation and file path that caused it. +

    + + + + + + + + + + + + + + +

    func (*PathError) Error

    +
    func (e *PathError) Error() string
    + + + + + + + + +

    type ProcAttr

    +
    type ProcAttr struct {
    +    // If Dir is non-empty, the child changes into the directory before
    +    // creating the process.
    +    Dir string
    +    // If Env is non-nil, it gives the environment variables for the
    +    // new process in the form returned by Environ.
    +    // If it is nil, the result of Environ will be used.
    +    Env []string
    +    // Files specifies the open files inherited by the new process.  The
    +    // first three entries correspond to standard input, standard output, and
    +    // standard error.  An implementation may support additional entries,
    +    // depending on the underlying operating system.  A nil entry corresponds
    +    // to that file being closed when the process starts.
    +    Files []*File
    +
    +    // Operating system-specific process creation attributes.
    +    // Note that setting this field means that your program
    +    // may not execute properly or even compile on some
    +    // operating systems.
    +    Sys *syscall.SysProcAttr
    +}
    +

    +ProcAttr holds the attributes that will be applied to a new process +started by StartProcess. +

    + + + + + + + + + + + + + + + + +

    type Process

    +
    type Process struct {
    +    Pid int
    +    // contains filtered or unexported fields
    +}
    +

    +Process stores the information about a process created by StartProcess. +

    + + + + + + + + + + + + +

    func FindProcess

    +
    func FindProcess(pid int) (*Process, error)
    +

    +FindProcess looks for a running process by its pid. +

    +

    +The Process it returns can be used to obtain information +about the underlying operating system process. +

    +

    +On Unix systems, FindProcess always succeeds and returns a Process +for the given pid, regardless of whether the process exists. +

    + + + + + +

    func StartProcess

    +
    func StartProcess(name string, argv []string, attr *ProcAttr) (*Process, error)
    +

    +StartProcess starts a new process with the program, arguments and attributes +specified by name, argv and attr. +

    +

    +StartProcess is a low-level interface. The os/exec package provides +higher-level interfaces. +

    +

    +If there is an error, it will be of type *PathError. +

    + + + + + + + +

    func (*Process) Kill

    +
    func (p *Process) Kill() error
    +

    +Kill causes the Process to exit immediately. +

    + + + + + + +

    func (*Process) Release

    +
    func (p *Process) Release() error
    +

    +Release releases any resources associated with the Process p, +rendering it unusable in the future. +Release only needs to be called if Wait is not. +

    + + + + + + +

    func (*Process) Signal

    +
    func (p *Process) Signal(sig Signal) error
    +

    +Signal sends a signal to the Process. +Sending Interrupt on Windows is not implemented. +

    + + + + + + +

    func (*Process) Wait

    +
    func (p *Process) Wait() (*ProcessState, error)
    +

    +Wait waits for the Process to exit, and then returns a +ProcessState describing its status and an error, if any. +Wait releases any resources associated with the Process. +On most operating systems, the Process must be a child +of the current process or an error will be returned. +

    + + + + + + + + +

    type ProcessState

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

    +ProcessState stores information about a process, as reported by Wait. +

    + + + + + + + + + + + + + + +

    func (*ProcessState) Exited

    +
    func (p *ProcessState) Exited() bool
    +

    +Exited reports whether the program has exited. +

    + + + + + + +

    func (*ProcessState) Pid

    +
    func (p *ProcessState) Pid() int
    +

    +Pid returns the process id of the exited process. +

    + + + + + + +

    func (*ProcessState) String

    +
    func (p *ProcessState) String() string
    + + + + + + +

    func (*ProcessState) Success

    +
    func (p *ProcessState) Success() bool
    +

    +Success reports whether the program exited successfully, +such as with exit status 0 on Unix. +

    + + + + + + +

    func (*ProcessState) Sys

    +
    func (p *ProcessState) Sys() interface{}
    +

    +Sys returns system-dependent exit information about +the process. Convert it to the appropriate underlying +type, such as syscall.WaitStatus on Unix, to access its contents. +

    + + + + + + +

    func (*ProcessState) SysUsage

    +
    func (p *ProcessState) SysUsage() interface{}
    +

    +SysUsage returns system-dependent resource usage information about +the exited process. Convert it to the appropriate underlying +type, such as *syscall.Rusage on Unix, to access its contents. +(On Unix, *syscall.Rusage matches struct rusage as defined in the +getrusage(2) manual page.) +

    + + + + + + +

    func (*ProcessState) SystemTime

    +
    func (p *ProcessState) SystemTime() time.Duration
    +

    +SystemTime returns the system CPU time of the exited process and its children. +

    + + + + + + +

    func (*ProcessState) UserTime

    +
    func (p *ProcessState) UserTime() time.Duration
    +

    +UserTime returns the user CPU time of the exited process and its children. +

    + + + + + + + + +

    type Signal

    +
    type Signal interface {
    +    String() string
    +    Signal() // to distinguish from other Stringers
    +}
    +

    +A Signal represents an operating system signal. +The usual underlying implementation is operating system-dependent: +on Unix it is syscall.Signal. +

    + + + + + +
    var (
    +    Interrupt Signal = syscall.SIGINT
    +    Kill      Signal = syscall.SIGKILL
    +)
    +

    +The only signal values guaranteed to be present on all systems +are Interrupt (send the process an interrupt) and Kill (force +the process to exit). +

    + + + + + + + + + + + + + +

    type SyscallError

    +
    type SyscallError struct {
    +    Syscall string
    +    Err     error
    +}
    +

    +SyscallError records an error from a specific system call. +

    + + + + + + + + + + + + + + +

    func (*SyscallError) Error

    +
    func (e *SyscallError) Error() string
    + + + + + + + + + + + + + + + + +

    Subdirectories

    + + + + +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    NameSynopsis
    ..
    + exec + + Package exec runs external commands. +
    + signal + + Package signal implements access to incoming signals. +
    + user + + Package user allows user account lookups by name or id. +
    +
    + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/os/signal/index.html b/pkg/os/signal/index.html new file mode 100644 index 0000000..e36417e --- /dev/null +++ b/pkg/os/signal/index.html @@ -0,0 +1,564 @@ + + + + + + + + signal - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Package signal

    + + + + + + + + + + + + + + +
    +
    +
    import "os/signal"
    +
    +
    +
    Overview
    +
    Index
    + +
    Examples
    + + +
    +
    + +
    + +
    +

    Overview ▾

    +

    +Package signal implements access to incoming signals. +

    +

    +Signals are primarily used on Unix-like systems. For the use of this +package on Windows and Plan 9, see below. +

    +

    Types of signals

    +

    +The signals SIGKILL and SIGSTOP may not be caught by a program, and +therefore can not be affected by this package. +

    +

    +Synchronous signals are signals triggered by errors in program +execution: SIGBUS, SIGFPE, and SIGSEGV. These are only considered +synchronous when caused by program execution, not when sent using +os.Process.Kill or the kill program or some similar mechanism. In +general, except as discussed below, Go programs will convert a +synchronous signal into a run-time panic. +

    +

    +The remaining signals are asynchronous signals. They are not +triggered by program errors, but are instead sent from the kernel or +from some other program. +

    +

    +Of the asynchronous signals, the SIGHUP signal is sent when a program +loses its controlling terminal. The SIGINT signal is sent when the +user at the controlling terminal presses the interrupt character, +which by default is ^C (Control-C). The SIGQUIT signal is sent when +the user at the controlling terminal presses the quit character, which +by default is ^\ (Control-Backslash). In general you can cause a +program to simply exit by pressing ^C, and you can cause it to exit +with a stack dump by pressing ^\. +

    +

    Default behavior of signals in Go programs

    +

    +By default, a synchronous signal is converted into a run-time panic. A +SIGHUP, SIGINT, or SIGTERM signal causes the program to exit. A +SIGQUIT, SIGILL, SIGTRAP, SIGABRT, SIGSTKFLT, SIGEMT, or SIGSYS signal +causes the program to exit with a stack dump. A SIGTSTP, SIGTTIN, or +SIGTTOU signal gets the system default behavior (these signals are +used by the shell for job control). The SIGPROF signal is handled +directly by the Go runtime to implement runtime.CPUProfile. Other +signals will be caught but no action will be taken. +

    +

    +If the Go program is started with either SIGHUP or SIGINT ignored +(signal handler set to SIG_IGN), they will remain ignored. +

    +

    +If the Go program is started with a non-empty signal mask, that will +generally be honored. However, some signals are explicitly unblocked: +the synchronous signals, SIGILL, SIGTRAP, SIGSTKFLT, SIGCHLD, SIGPROF, +and, on GNU/Linux, signals 32 (SIGCANCEL) and 33 (SIGSETXID) +(SIGCANCEL and SIGSETXID are used internally by glibc). Subprocesses +started by os.Exec, or by the os/exec package, will inherit the +modified signal mask. +

    +

    Changing the behavior of signals in Go programs

    +

    +The functions in this package allow a program to change the way Go +programs handle signals. +

    +

    +Notify disables the default behavior for a given set of asynchronous +signals and instead delivers them over one or more registered +channels. Specifically, it applies to the signals SIGHUP, SIGINT, +SIGQUIT, SIGABRT, and SIGTERM. It also applies to the job control +signals SIGTSTP, SIGTTIN, and SIGTTOU, in which case the system +default behavior does not occur. It also applies to some signals that +otherwise cause no action: SIGUSR1, SIGUSR2, SIGPIPE, SIGALRM, +SIGCHLD, SIGCONT, SIGURG, SIGXCPU, SIGXFSZ, SIGVTALRM, SIGWINCH, +SIGIO, SIGPWR, SIGSYS, SIGINFO, SIGTHR, SIGWAITING, SIGLWP, SIGFREEZE, +SIGTHAW, SIGLOST, SIGXRES, SIGJVM1, SIGJVM2, and any real time signals +used on the system. Note that not all of these signals are available +on all systems. +

    +

    +If the program was started with SIGHUP or SIGINT ignored, and Notify +is called for either signal, a signal handler will be installed for +that signal and it will no longer be ignored. If, later, Reset or +Ignore is called for that signal, or Stop is called on all channels +passed to Notify for that signal, the signal will once again be +ignored. Reset will restore the system default behavior for the +signal, while Ignore will cause the system to ignore the signal +entirely. +

    +

    +If the program is started with a non-empty signal mask, some signals +will be explicitly unblocked as described above. If Notify is called +for a blocked signal, it will be unblocked. If, later, Reset is +called for that signal, or Stop is called on all channels passed to +Notify for that signal, the signal will once again be blocked. +

    +

    SIGPIPE

    +

    +When a Go program writes to a broken pipe, the kernel will raise a +SIGPIPE signal. +

    +

    +If the program has not called Notify to receive SIGPIPE signals, then +the behavior depends on the file descriptor number. A write to a +broken pipe on file descriptors 1 or 2 (standard output or standard +error) will cause the program to exit with a SIGPIPE signal. A write +to a broken pipe on some other file descriptor will take no action on +the SIGPIPE signal, and the write will fail with an EPIPE error. +

    +

    +If the program has called Notify to receive SIGPIPE signals, the file +descriptor number does not matter. The SIGPIPE signal will be +delivered to the Notify channel, and the write will fail with an EPIPE +error. +

    +

    +This means that, by default, command line programs will behave like +typical Unix command line programs, while other programs will not +crash with SIGPIPE when writing to a closed network connection. +

    +

    Go programs that use cgo or SWIG

    +

    +In a Go program that includes non-Go code, typically C/C++ code +accessed using cgo or SWIG, Go's startup code normally runs first. It +configures the signal handlers as expected by the Go runtime, before +the non-Go startup code runs. If the non-Go startup code wishes to +install its own signal handlers, it must take certain steps to keep Go +working well. This section documents those steps and the overall +effect changes to signal handler settings by the non-Go code can have +on Go programs. In rare cases, the non-Go code may run before the Go +code, in which case the next section also applies. +

    +

    +If the non-Go code called by the Go program does not change any signal +handlers or masks, then the behavior is the same as for a pure Go +program. +

    +

    +If the non-Go code installs any signal handlers, it must use the +SA_ONSTACK flag with sigaction. Failing to do so is likely to cause +the program to crash if the signal is received. Go programs routinely +run with a limited stack, and therefore set up an alternate signal +stack. Also, the Go standard library expects that any signal handlers +will use the SA_RESTART flag. Failing to do so may cause some library +calls to return "interrupted system call" errors. +

    +

    +If the non-Go code installs a signal handler for any of the +synchronous signals (SIGBUS, SIGFPE, SIGSEGV), then it should record +the existing Go signal handler. If those signals occur while +executing Go code, it should invoke the Go signal handler (whether the +signal occurs while executing Go code can be determined by looking at +the PC passed to the signal handler). Otherwise some Go run-time +panics will not occur as expected. +

    +

    +If the non-Go code installs a signal handler for any of the +asynchronous signals, it may invoke the Go signal handler or not as it +chooses. Naturally, if it does not invoke the Go signal handler, the +Go behavior described above will not occur. This can be an issue with +the SIGPROF signal in particular. +

    +

    +The non-Go code should not change the signal mask on any threads +created by the Go runtime. If the non-Go code starts new threads of +its own, it may set the signal mask as it pleases. +

    +

    +If the non-Go code starts a new thread, changes the signal mask, and +then invokes a Go function in that thread, the Go runtime will +automatically unblock certain signals: the synchronous signals, +SIGILL, SIGTRAP, SIGSTKFLT, SIGCHLD, SIGPROF, SIGCANCEL, and +SIGSETXID. When the Go function returns, the non-Go signal mask will +be restored. +

    +

    +If the Go signal handler is invoked on a non-Go thread not running Go +code, the handler generally forwards the signal to the non-Go code, as +follows. If the signal is SIGPROF, the Go handler does +nothing. Otherwise, the Go handler removes itself, unblocks the +signal, and raises it again, to invoke any non-Go handler or default +system handler. If the program does not exit, the Go handler then +reinstalls itself and continues execution of the program. +

    +

    Non-Go programs that call Go code

    +

    +When Go code is built with options like -buildmode=c-shared, it will +be run as part of an existing non-Go program. The non-Go code may +have already installed signal handlers when the Go code starts (that +may also happen in unusual cases when using cgo or SWIG; in that case, +the discussion here applies). For -buildmode=c-archive the Go runtime +will initialize signals at global constructor time. For +-buildmode=c-shared the Go runtime will initialize signals when the +shared library is loaded. +

    +

    +If the Go runtime sees an existing signal handler for the SIGCANCEL or +SIGSETXID signals (which are used only on GNU/Linux), it will turn on +the SA_ONSTACK flag and otherwise keep the signal handler. +

    +

    +For the synchronous signals, the Go runtime will install a signal +handler. It will save any existing signal handler. If a synchronous +signal arrives while executing non-Go code, the Go runtime will invoke +the existing signal handler instead of the Go signal handler. +

    +

    +Go code built with -buildmode=c-archive or -buildmode=c-shared will +not install any other signal handlers by default. If there is an +existing signal handler, the Go runtime will turn on the SA_ONSTACK +flag and otherwise keep the signal handler. If Notify is called for an +asynchronous signal, a Go signal handler will be installed for that +signal. If, later, Reset is called for that signal, the original +handling for that signal will be reinstalled, restoring the non-Go +signal handler if any. +

    +

    +Go code built without -buildmode=c-archive or -buildmode=c-shared will +install a signal handler for the asynchronous signals listed above, +and save any existing signal handler. If a signal is delivered to a +non-Go thread, it will act as described above, except that if there is +an existing non-Go signal handler, that handler will be installed +before raising the signal. +

    +

    Windows

    +

    +On Windows a ^C (Control-C) or ^BREAK (Control-Break) normally cause +the program to exit. If Notify is called for os.SIGINT, ^C or ^BREAK +will cause os.SIGINT to be sent on the channel, and the program will +not exit. If Reset is called, or Stop is called on all channels passed +to Notify, then the default behavior will be restored. +

    +

    Plan 9

    +

    +On Plan 9, signals have type syscall.Note, which is a string. Calling +Notify with a syscall.Note will cause that value to be sent on the +channel when that string is posted as a note. +

    + +
    +
    + + +
    + +
    +

    Index ▾

    + + + + + +
    +

    Examples

    +
    + +
    Notify
    + +
    +
    + + + +

    Package files

    +

    + + + doc.go + + signal.go + + signal_unix.go + + +

    + +
    +
    + + + + + + + + +

    func Ignore

    +
    func Ignore(sig ...os.Signal)
    +

    +Ignore causes the provided signals to be ignored. If they are received by +the program, nothing will happen. Ignore undoes the effect of any prior +calls to Notify for the provided signals. +If no signals are provided, all incoming signals will be ignored. +

    + + + + + + + +

    func Notify

    +
    func Notify(c chan<- os.Signal, sig ...os.Signal)
    +

    +Notify causes package signal to relay incoming signals to c. +If no signals are provided, all incoming signals will be relayed to c. +Otherwise, just the provided signals will. +

    +

    +Package signal will not block sending to c: the caller must ensure +that c has sufficient buffer space to keep up with the expected +signal rate. For a channel used for notification of just one signal value, +a buffer of size 1 is sufficient. +

    +

    +It is allowed to call Notify multiple times with the same channel: +each call expands the set of signals sent to that channel. +The only way to remove signals from the set is to call Stop. +

    +

    +It is allowed to call Notify multiple times with different channels +and the same signals: each channel receives copies of incoming +signals independently. +

    + +
    + +
    +

    Example

    + + + +

    Code:

    +
    +// Set up channel on which to send signal notifications.
    +// We must use a buffered channel or risk missing the signal
    +// if we're not ready to receive when the signal is sent.
    +c := make(chan os.Signal, 1)
    +signal.Notify(c, os.Interrupt)
    +
    +// Block until a signal is received.
    +s := <-c
    +fmt.Println("Got signal:", s)
    +
    + + +
    +
    + + + + + + +

    func Reset

    +
    func Reset(sig ...os.Signal)
    +

    +Reset undoes the effect of any prior calls to Notify for the provided +signals. +If no signals are provided, all signal handlers will be reset. +

    + + + + + + + +

    func Stop

    +
    func Stop(c chan<- os.Signal)
    +

    +Stop causes package signal to stop relaying incoming signals to c. +It undoes the effect of all prior calls to Notify using c. +When Stop returns, it is guaranteed that c will receive no more signals. +

    + + + + + + + + + + + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/os/user/index.html b/pkg/os/user/index.html new file mode 100644 index 0000000..0016ced --- /dev/null +++ b/pkg/os/user/index.html @@ -0,0 +1,365 @@ + + + + + + + + user - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Package user

    + + + + + + + + + + + + + + +
    +
    +
    import "os/user"
    +
    +
    +
    Overview
    +
    Index
    + + +
    +
    + +
    + +
    +

    Overview ▾

    +

    +Package user allows user account lookups by name or id. +

    + +
    +
    + + +
    + +
    +

    Index ▾

    + + + + + + + +

    Package files

    +

    + + + lookup.go + + lookup_unix.go + + user.go + + +

    + +
    +
    + + + + + + + + + +

    type UnknownUserError

    +
    type UnknownUserError string
    +

    +UnknownUserError is returned by Lookup when +a user cannot be found. +

    + + + + + + + + + + + + + + +

    func (UnknownUserError) Error

    +
    func (e UnknownUserError) Error() string
    + + + + + + + + +

    type UnknownUserIdError

    +
    type UnknownUserIdError int
    +

    +UnknownUserIdError is returned by LookupId when +a user cannot be found. +

    + + + + + + + + + + + + + + +

    func (UnknownUserIdError) Error

    +
    func (e UnknownUserIdError) Error() string
    + + + + + + + + +

    type User

    +
    type User struct {
    +    Uid      string // user id
    +    Gid      string // primary group id
    +    Username string
    +    Name     string
    +    HomeDir  string
    +}
    +

    +User represents a user account. +

    +

    +On posix systems Uid and Gid contain a decimal number +representing uid and gid. On windows Uid and Gid +contain security identifier (SID) in a string format. +On Plan 9, Uid, Gid, Username, and Name will be the +contents of /dev/user. +

    + + + + + + + + + + + + +

    func Current

    +
    func Current() (*User, error)
    +

    +Current returns the current user. +

    + + + + + +

    func Lookup

    +
    func Lookup(username string) (*User, error)
    +

    +Lookup looks up a user by username. If the user cannot be found, the +returned error is of type UnknownUserError. +

    + + + + + +

    func LookupId

    +
    func LookupId(uid string) (*User, error)
    +

    +LookupId looks up a user by userid. If the user cannot be found, the +returned error is of type UnknownUserIdError. +

    + + + + + + + + + + + + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/reflect/index.html b/pkg/reflect/index.html new file mode 100644 index 0000000..9877f1f --- /dev/null +++ b/pkg/reflect/index.html @@ -0,0 +1,2404 @@ + + + + + + + + reflect - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Package reflect

    + + + + + + + + + + + + + + +
    +
    +
    import "reflect"
    +
    +
    +
    Overview
    +
    Index
    + +
    Examples
    + + +
    +
    + +
    + +
    +

    Overview ▾

    +

    +Package reflect implements run-time reflection, allowing a program to +manipulate objects with arbitrary types. The typical use is to take a value +with static type interface{} and extract its dynamic type information by +calling TypeOf, which returns a Type. +

    +

    +A call to ValueOf returns a Value representing the run-time data. +Zero takes a Type and returns a Value representing a zero value +for that type. +

    +

    +See "The Laws of Reflection" for an introduction to reflection in Go: +https://golang.org/doc/articles/laws_of_reflection.html +

    + +
    +
    + + +
    + +
    +

    Index ▾

    + + +
    +
    + + + + +
    func Copy(dst, src Value) int
    + + +
    func DeepEqual(x, y interface{}) bool
    + + +
    func Select(cases []SelectCase) (chosen int, recv Value, recvOK bool)
    + + + +
    type ChanDir
    + + + +
        func (d ChanDir) String() string
    + + + +
    type Kind
    + + + +
        func (k Kind) String() string
    + + + +
    type Method
    + + + + +
    type SelectCase
    + + + + +
    type SelectDir
    + + + + +
    type SliceHeader
    + + + + +
    type StringHeader
    + + + + +
    type StructField
    + + + + +
    type StructTag
    + + + +
        func (tag StructTag) Get(key string) string
    + + + +
    type Type
    + + +
        func ArrayOf(count int, elem Type) Type
    + + +
        func ChanOf(dir ChanDir, t Type) Type
    + + +
        func FuncOf(in, out []Type, variadic bool) Type
    + + +
        func MapOf(key, elem Type) Type
    + + +
        func PtrTo(t Type) Type
    + + +
        func SliceOf(t Type) Type
    + + +
        func TypeOf(i interface{}) Type
    + + + + +
    type Value
    + + +
        func Append(s Value, x ...Value) Value
    + + +
        func AppendSlice(s, t Value) Value
    + + +
        func Indirect(v Value) Value
    + + +
        func MakeChan(typ Type, buffer int) Value
    + + +
        func MakeFunc(typ Type, fn func(args []Value) (results []Value)) Value
    + + +
        func MakeMap(typ Type) Value
    + + +
        func MakeSlice(typ Type, len, cap int) Value
    + + +
        func New(typ Type) Value
    + + +
        func NewAt(typ Type, p unsafe.Pointer) Value
    + + +
        func ValueOf(i interface{}) Value
    + + +
        func Zero(typ Type) Value
    + + + +
        func (v Value) Addr() Value
    + + +
        func (v Value) Bool() bool
    + + +
        func (v Value) Bytes() []byte
    + + +
        func (v Value) Call(in []Value) []Value
    + + +
        func (v Value) CallSlice(in []Value) []Value
    + + +
        func (v Value) CanAddr() bool
    + + +
        func (v Value) CanInterface() bool
    + + +
        func (v Value) CanSet() bool
    + + +
        func (v Value) Cap() int
    + + +
        func (v Value) Close()
    + + +
        func (v Value) Complex() complex128
    + + +
        func (v Value) Convert(t Type) Value
    + + +
        func (v Value) Elem() Value
    + + +
        func (v Value) Field(i int) Value
    + + +
        func (v Value) FieldByIndex(index []int) Value
    + + +
        func (v Value) FieldByName(name string) Value
    + + +
        func (v Value) FieldByNameFunc(match func(string) bool) Value
    + + +
        func (v Value) Float() float64
    + + +
        func (v Value) Index(i int) Value
    + + +
        func (v Value) Int() int64
    + + +
        func (v Value) Interface() (i interface{})
    + + +
        func (v Value) InterfaceData() [2]uintptr
    + + +
        func (v Value) IsNil() bool
    + + +
        func (v Value) IsValid() bool
    + + +
        func (v Value) Kind() Kind
    + + +
        func (v Value) Len() int
    + + +
        func (v Value) MapIndex(key Value) Value
    + + +
        func (v Value) MapKeys() []Value
    + + +
        func (v Value) Method(i int) Value
    + + +
        func (v Value) MethodByName(name string) Value
    + + +
        func (v Value) NumField() int
    + + +
        func (v Value) NumMethod() int
    + + +
        func (v Value) OverflowComplex(x complex128) bool
    + + +
        func (v Value) OverflowFloat(x float64) bool
    + + +
        func (v Value) OverflowInt(x int64) bool
    + + +
        func (v Value) OverflowUint(x uint64) bool
    + + +
        func (v Value) Pointer() uintptr
    + + +
        func (v Value) Recv() (x Value, ok bool)
    + + +
        func (v Value) Send(x Value)
    + + +
        func (v Value) Set(x Value)
    + + +
        func (v Value) SetBool(x bool)
    + + +
        func (v Value) SetBytes(x []byte)
    + + +
        func (v Value) SetCap(n int)
    + + +
        func (v Value) SetComplex(x complex128)
    + + +
        func (v Value) SetFloat(x float64)
    + + +
        func (v Value) SetInt(x int64)
    + + +
        func (v Value) SetLen(n int)
    + + +
        func (v Value) SetMapIndex(key, val Value)
    + + +
        func (v Value) SetPointer(x unsafe.Pointer)
    + + +
        func (v Value) SetString(x string)
    + + +
        func (v Value) SetUint(x uint64)
    + + +
        func (v Value) Slice(i, j int) Value
    + + +
        func (v Value) Slice3(i, j, k int) Value
    + + +
        func (v Value) String() string
    + + +
        func (v Value) TryRecv() (x Value, ok bool)
    + + +
        func (v Value) TrySend(x Value) bool
    + + +
        func (v Value) Type() Type
    + + +
        func (v Value) Uint() uint64
    + + +
        func (v Value) UnsafeAddr() uintptr
    + + + +
    type ValueError
    + + + +
        func (e *ValueError) Error() string
    + + + + +
    Bugs
    + + +
    +
    + + +
    +

    Examples

    +
    + +
    MakeFunc
    + +
    StructTag
    + +
    TypeOf
    + +
    +
    + + + +

    Package files

    +

    + + + deepequal.go + + makefunc.go + + type.go + + value.go + + +

    + +
    +
    + + + + + + + + +

    func Copy

    +
    func Copy(dst, src Value) int
    +

    +Copy copies the contents of src into dst until either +dst has been filled or src has been exhausted. +It returns the number of elements copied. +Dst and src each must have kind Slice or Array, and +dst and src must have the same element type. +

    + + + + + + + +

    func DeepEqual

    +
    func DeepEqual(x, y interface{}) bool
    +

    +DeepEqual reports whether x and y are “deeply equal,” defined as follows. +Two values of identical type are deeply equal if one of the following cases applies. +Values of distinct types are never deeply equal. +

    +

    +Array values are deeply equal when their corresponding elements are deeply equal. +

    +

    +Struct values are deeply equal if their corresponding fields, +both exported and unexported, are deeply equal. +

    +

    +Func values are deeply equal if both are nil; otherwise they are not deeply equal. +

    +

    +Interface values are deeply equal if they hold deeply equal concrete values. +

    +

    +Map values are deeply equal if they are the same map object +or if they have the same length and their corresponding keys +(matched using Go equality) map to deeply equal values. +

    +

    +Pointer values are deeply equal if they are equal using Go's == operator +or if they point to deeply equal values. +

    +

    +Slice values are deeply equal when all of the following are true: +they are both nil or both non-nil, they have the same length, +and either they point to the same initial entry of the same underlying array +(that is, &x[0] == &y[0]) or their corresponding elements (up to length) are deeply equal. +Note that a non-nil empty slice and a nil slice (for example, []byte{} and []byte(nil)) +are not deeply equal. +

    +

    +Other values - numbers, bools, strings, and channels - are deeply equal +if they are equal using Go's == operator. +

    +

    +In general DeepEqual is a recursive relaxation of Go's == operator. +However, this idea is impossible to implement without some inconsistency. +Specifically, it is possible for a value to be unequal to itself, +either because it is of func type (uncomparable in general) +or because it is a floating-point NaN value (not equal to itself in floating-point comparison), +or because it is an array, struct, or interface containing +such a value. +On the other hand, pointer values are always equal to themselves, +even if they point at or contain such problematic values, +because they compare equal using Go's == operator, and that +is a sufficient condition to be deeply equal, regardless of content. +DeepEqual has been defined so that the same short-cut applies +to slices and maps: if x and y are the same slice or the same map, +they are deeply equal regardless of content. +

    + + + + + + + +

    func Select

    +
    func Select(cases []SelectCase) (chosen int, recv Value, recvOK bool)
    +

    +Select executes a select operation described by the list of cases. +Like the Go select statement, it blocks until at least one of the cases +can proceed, makes a uniform pseudo-random choice, +and then executes that case. It returns the index of the chosen case +and, if that case was a receive operation, the value received and a +boolean indicating whether the value corresponds to a send on the channel +(as opposed to a zero value received because the channel is closed). +

    + + + + + + + + +

    type ChanDir

    +
    type ChanDir int
    +

    +ChanDir represents a channel type's direction. +

    + + + +
    const (
    +    RecvDir ChanDir             = 1 << iota // <-chan
    +    SendDir                                 // chan<-
    +    BothDir = RecvDir | SendDir             // chan
    +)
    + + + + + + + + + + + + + +

    func (ChanDir) String

    +
    func (d ChanDir) String() string
    + + + + + + + + +

    type Kind

    +
    type Kind uint
    +

    +A Kind represents the specific kind of type that a Type represents. +The zero Kind is not a valid kind. +

    + + + +
    const (
    +    Invalid Kind = iota
    +    Bool
    +    Int
    +    Int8
    +    Int16
    +    Int32
    +    Int64
    +    Uint
    +    Uint8
    +    Uint16
    +    Uint32
    +    Uint64
    +    Uintptr
    +    Float32
    +    Float64
    +    Complex64
    +    Complex128
    +    Array
    +    Chan
    +    Func
    +    Interface
    +    Map
    +    Ptr
    +    Slice
    +    String
    +    Struct
    +    UnsafePointer
    +)
    + + + + + + + + + + + + + +

    func (Kind) String

    +
    func (k Kind) String() string
    + + + + + + + + +

    type Method

    +
    type Method struct {
    +    // Name is the method name.
    +    // PkgPath is the package path that qualifies a lower case (unexported)
    +    // method name.  It is empty for upper case (exported) method names.
    +    // The combination of PkgPath and Name uniquely identifies a method
    +    // in a method set.
    +    // See https://golang.org/ref/spec#Uniqueness_of_identifiers
    +    Name    string
    +    PkgPath string
    +
    +    Type  Type  // method type
    +    Func  Value // func with receiver as first argument
    +    Index int   // index for Type.Method
    +}
    +

    +Method represents a single method. +

    + + + + + + + + + + + + + + + + +

    type SelectCase

    +
    type SelectCase struct {
    +    Dir  SelectDir // direction of case
    +    Chan Value     // channel to use (for send or receive)
    +    Send Value     // value to send (for send)
    +}
    +

    +A SelectCase describes a single case in a select operation. +The kind of case depends on Dir, the communication direction. +

    +

    +If Dir is SelectDefault, the case represents a default case. +Chan and Send must be zero Values. +

    +

    +If Dir is SelectSend, the case represents a send operation. +Normally Chan's underlying value must be a channel, and Send's underlying value must be +assignable to the channel's element type. As a special case, if Chan is a zero Value, +then the case is ignored, and the field Send will also be ignored and may be either zero +or non-zero. +

    +

    +If Dir is SelectRecv, the case represents a receive operation. +Normally Chan's underlying value must be a channel and Send must be a zero Value. +If Chan is a zero Value, then the case is ignored, but Send must still be a zero Value. +When a receive operation is selected, the received Value is returned by Select. +

    + + + + + + + + + + + + + + + + +

    type SelectDir

    +
    type SelectDir int
    +

    +A SelectDir describes the communication direction of a select case. +

    + + + +
    const (
    +    SelectSend    SelectDir // case Chan <- Send
    +    SelectRecv              // case <-Chan:
    +    SelectDefault           // default
    +)
    + + + + + + + + + + + + + + + +

    type SliceHeader

    +
    type SliceHeader struct {
    +    Data uintptr
    +    Len  int
    +    Cap  int
    +}
    +

    +SliceHeader is the runtime representation of a slice. +It cannot be used safely or portably and its representation may +change in a later release. +Moreover, the Data field is not sufficient to guarantee the data +it references will not be garbage collected, so programs must keep +a separate, correctly typed pointer to the underlying data. +

    + + + + + + + + + + + + + + + + +

    type StringHeader

    +
    type StringHeader struct {
    +    Data uintptr
    +    Len  int
    +}
    +

    +StringHeader is the runtime representation of a string. +It cannot be used safely or portably and its representation may +change in a later release. +Moreover, the Data field is not sufficient to guarantee the data +it references will not be garbage collected, so programs must keep +a separate, correctly typed pointer to the underlying data. +

    + + + + + + + + + + + + + + + + +

    type StructField

    +
    type StructField struct {
    +    // Name is the field name.
    +    Name string
    +    // PkgPath is the package path that qualifies a lower case (unexported)
    +    // field name.  It is empty for upper case (exported) field names.
    +    // See https://golang.org/ref/spec#Uniqueness_of_identifiers
    +    PkgPath string
    +
    +    Type      Type      // field type
    +    Tag       StructTag // field tag string
    +    Offset    uintptr   // offset within struct, in bytes
    +    Index     []int     // index sequence for Type.FieldByIndex
    +    Anonymous bool      // is an embedded field
    +}
    +

    +A StructField describes a single field in a struct. +

    + + + + + + + + + + + + + + + + +

    type StructTag

    +
    type StructTag string
    +

    +A StructTag is the tag string in a struct field. +

    +

    +By convention, tag strings are a concatenation of +optionally space-separated key:"value" pairs. +Each key is a non-empty string consisting of non-control +characters other than space (U+0020 ' '), quote (U+0022 '"'), +and colon (U+003A ':'). Each value is quoted using U+0022 '"' +characters and Go string literal syntax. +

    + + + + + + +
    + +
    +

    Example

    + + + +

    Code:

    +
    type S struct {
    +    F string `species:"gopher" color:"blue"`
    +}
    +
    +s := S{}
    +st := reflect.TypeOf(s)
    +field := st.Field(0)
    +fmt.Println(field.Tag.Get("color"), field.Tag.Get("species"))
    +
    +
    + +

    Output:

    +
    blue gopher
    +
    + + +
    +
    + + + + + + + + +

    func (StructTag) Get

    +
    func (tag StructTag) Get(key string) string
    +

    +Get returns the value associated with key in the tag string. +If there is no such key in the tag, Get returns the empty string. +If the tag does not have the conventional format, the value +returned by Get is unspecified. +

    + + + + + + + + +

    type Type

    +
    type Type interface {
    +
    +    // Align returns the alignment in bytes of a value of
    +    // this type when allocated in memory.
    +    Align() int
    +
    +    // FieldAlign returns the alignment in bytes of a value of
    +    // this type when used as a field in a struct.
    +    FieldAlign() int
    +
    +    // Method returns the i'th method in the type's method set.
    +    // It panics if i is not in the range [0, NumMethod()).
    +    //
    +    // For a non-interface type T or *T, the returned Method's Type and Func
    +    // fields describe a function whose first argument is the receiver.
    +    //
    +    // For an interface type, the returned Method's Type field gives the
    +    // method signature, without a receiver, and the Func field is nil.
    +    Method(int) Method
    +
    +    // MethodByName returns the method with that name in the type's
    +    // method set and a boolean indicating if the method was found.
    +    //
    +    // For a non-interface type T or *T, the returned Method's Type and Func
    +    // fields describe a function whose first argument is the receiver.
    +    //
    +    // For an interface type, the returned Method's Type field gives the
    +    // method signature, without a receiver, and the Func field is nil.
    +    MethodByName(string) (Method, bool)
    +
    +    // NumMethod returns the number of methods in the type's method set.
    +    NumMethod() int
    +
    +    // Name returns the type's name within its package.
    +    // It returns an empty string for unnamed types.
    +    Name() string
    +
    +    // PkgPath returns a named type's package path, that is, the import path
    +    // that uniquely identifies the package, such as "encoding/base64".
    +    // If the type was predeclared (string, error) or unnamed (*T, struct{}, []int),
    +    // the package path will be the empty string.
    +    PkgPath() string
    +
    +    // Size returns the number of bytes needed to store
    +    // a value of the given type; it is analogous to unsafe.Sizeof.
    +    Size() uintptr
    +
    +    // String returns a string representation of the type.
    +    // The string representation may use shortened package names
    +    // (e.g., base64 instead of "encoding/base64") and is not
    +    // guaranteed to be unique among types.  To test for equality,
    +    // compare the Types directly.
    +    String() string
    +
    +    // Kind returns the specific kind of this type.
    +    Kind() Kind
    +
    +    // Implements reports whether the type implements the interface type u.
    +    Implements(u Type) bool
    +
    +    // AssignableTo reports whether a value of the type is assignable to type u.
    +    AssignableTo(u Type) bool
    +
    +    // ConvertibleTo reports whether a value of the type is convertible to type u.
    +    ConvertibleTo(u Type) bool
    +
    +    // Comparable reports whether values of this type are comparable.
    +    Comparable() bool
    +
    +    // Bits returns the size of the type in bits.
    +    // It panics if the type's Kind is not one of the
    +    // sized or unsized Int, Uint, Float, or Complex kinds.
    +    Bits() int
    +
    +    // ChanDir returns a channel type's direction.
    +    // It panics if the type's Kind is not Chan.
    +    ChanDir() ChanDir
    +
    +    // IsVariadic reports whether a function type's final input parameter
    +    // is a "..." parameter.  If so, t.In(t.NumIn() - 1) returns the parameter's
    +    // implicit actual type []T.
    +    //
    +    // For concreteness, if t represents func(x int, y ... float64), then
    +    //
    +    //	t.NumIn() == 2
    +    //	t.In(0) is the reflect.Type for "int"
    +    //	t.In(1) is the reflect.Type for "[]float64"
    +    //	t.IsVariadic() == true
    +    //
    +    // IsVariadic panics if the type's Kind is not Func.
    +    IsVariadic() bool
    +
    +    // Elem returns a type's element type.
    +    // It panics if the type's Kind is not Array, Chan, Map, Ptr, or Slice.
    +    Elem() Type
    +
    +    // Field returns a struct type's i'th field.
    +    // It panics if the type's Kind is not Struct.
    +    // It panics if i is not in the range [0, NumField()).
    +    Field(i int) StructField
    +
    +    // FieldByIndex returns the nested field corresponding
    +    // to the index sequence.  It is equivalent to calling Field
    +    // successively for each index i.
    +    // It panics if the type's Kind is not Struct.
    +    FieldByIndex(index []int) StructField
    +
    +    // FieldByName returns the struct field with the given name
    +    // and a boolean indicating if the field was found.
    +    FieldByName(name string) (StructField, bool)
    +
    +    // FieldByNameFunc returns the first struct field with a name
    +    // that satisfies the match function and a boolean indicating if
    +    // the field was found.
    +    FieldByNameFunc(match func(string) bool) (StructField, bool)
    +
    +    // In returns the type of a function type's i'th input parameter.
    +    // It panics if the type's Kind is not Func.
    +    // It panics if i is not in the range [0, NumIn()).
    +    In(i int) Type
    +
    +    // Key returns a map type's key type.
    +    // It panics if the type's Kind is not Map.
    +    Key() Type
    +
    +    // Len returns an array type's length.
    +    // It panics if the type's Kind is not Array.
    +    Len() int
    +
    +    // NumField returns a struct type's field count.
    +    // It panics if the type's Kind is not Struct.
    +    NumField() int
    +
    +    // NumIn returns a function type's input parameter count.
    +    // It panics if the type's Kind is not Func.
    +    NumIn() int
    +
    +    // NumOut returns a function type's output parameter count.
    +    // It panics if the type's Kind is not Func.
    +    NumOut() int
    +
    +    // Out returns the type of a function type's i'th output parameter.
    +    // It panics if the type's Kind is not Func.
    +    // It panics if i is not in the range [0, NumOut()).
    +    Out(i int) Type
    +    // contains filtered or unexported methods
    +}
    +

    +Type is the representation of a Go type. +

    +

    +Not all methods apply to all kinds of types. Restrictions, +if any, are noted in the documentation for each method. +Use the Kind method to find out the kind of type before +calling kind-specific methods. Calling a method +inappropriate to the kind of type causes a run-time panic. +

    + + + + + + + + + + + + +

    func ArrayOf

    +
    func ArrayOf(count int, elem Type) Type
    +

    +ArrayOf returns the array type with the given count and element type. +For example, if t represents int, ArrayOf(5, t) represents [5]int. +

    +

    +If the resulting type would be larger than the available address space, +ArrayOf panics. +

    + + + + + +

    func ChanOf

    +
    func ChanOf(dir ChanDir, t Type) Type
    +

    +ChanOf returns the channel type with the given direction and element type. +For example, if t represents int, ChanOf(RecvDir, t) represents <-chan int. +

    +

    +The gc runtime imposes a limit of 64 kB on channel element types. +If t's size is equal to or exceeds this limit, ChanOf panics. +

    + + + + + +

    func FuncOf

    +
    func FuncOf(in, out []Type, variadic bool) Type
    +

    +FuncOf returns the function type with the given argument and result types. +For example if k represents int and e represents string, +FuncOf([]Type{k}, []Type{e}, false) represents func(int) string. +

    +

    +The variadic argument controls whether the function is variadic. FuncOf +panics if the in[len(in)-1] does not represent a slice and variadic is +true. +

    + + + + + +

    func MapOf

    +
    func MapOf(key, elem Type) Type
    +

    +MapOf returns the map type with the given key and element types. +For example, if k represents int and e represents string, +MapOf(k, e) represents map[int]string. +

    +

    +If the key type is not a valid map key type (that is, if it does +not implement Go's == operator), MapOf panics. +

    + + + + + +

    func PtrTo

    +
    func PtrTo(t Type) Type
    +

    +PtrTo returns the pointer type with element t. +For example, if t represents type Foo, PtrTo(t) represents *Foo. +

    + + + + + +

    func SliceOf

    +
    func SliceOf(t Type) Type
    +

    +SliceOf returns the slice type with element type t. +For example, if t represents int, SliceOf(t) represents []int. +

    + + + + + +

    func TypeOf

    +
    func TypeOf(i interface{}) Type
    +

    +TypeOf returns the reflection Type that represents the dynamic type of i. +If i is a nil interface value, TypeOf returns nil. +

    + +
    + +
    +

    Example

    + + + +

    Code:

    +
    // As interface types are only used for static typing, a
    +// common idiom to find the reflection Type for an interface
    +// type Foo is to use a *Foo value.
    +writerType := reflect.TypeOf((*io.Writer)(nil)).Elem()
    +
    +fileType := reflect.TypeOf((*os.File)(nil))
    +fmt.Println(fileType.Implements(writerType))
    +
    +
    + +

    Output:

    +
    true
    +
    + + +
    +
    + + + + + + + + +

    type Value

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

    +Value is the reflection interface to a Go value. +

    +

    +Not all methods apply to all kinds of values. Restrictions, +if any, are noted in the documentation for each method. +Use the Kind method to find out the kind of value before +calling kind-specific methods. Calling a method +inappropriate to the kind of type causes a run time panic. +

    +

    +The zero Value represents no value. +Its IsValid method returns false, its Kind method returns Invalid, +its String method returns "<invalid Value>", and all other methods panic. +Most functions and methods never return an invalid value. +If one does, its documentation states the conditions explicitly. +

    +

    +A Value can be used concurrently by multiple goroutines provided that +the underlying Go value can be used concurrently for the equivalent +direct operations. +

    +

    +Using == on two Values does not compare the underlying values +they represent, but rather the contents of the Value structs. +To compare two Values, compare the results of the Interface method. +

    + + + + + + + + + + + + +

    func Append

    +
    func Append(s Value, x ...Value) Value
    +

    +Append appends the values x to a slice s and returns the resulting slice. +As in Go, each x's value must be assignable to the slice's element type. +

    + + + + + +

    func AppendSlice

    +
    func AppendSlice(s, t Value) Value
    +

    +AppendSlice appends a slice t to a slice s and returns the resulting slice. +The slices s and t must have the same element type. +

    + + + + + +

    func Indirect

    +
    func Indirect(v Value) Value
    +

    +Indirect returns the value that v points to. +If v is a nil pointer, Indirect returns a zero Value. +If v is not a pointer, Indirect returns v. +

    + + + + + +

    func MakeChan

    +
    func MakeChan(typ Type, buffer int) Value
    +

    +MakeChan creates a new channel with the specified type and buffer size. +

    + + + + + +

    func MakeFunc

    +
    func MakeFunc(typ Type, fn func(args []Value) (results []Value)) Value
    +

    +MakeFunc returns a new function of the given Type +that wraps the function fn. When called, that new function +does the following: +

    +
    - converts its arguments to a slice of Values.
    +- runs results := fn(args).
    +- returns the results as a slice of Values, one per formal result.
    +
    +

    +The implementation fn can assume that the argument Value slice +has the number and type of arguments given by typ. +If typ describes a variadic function, the final Value is itself +a slice representing the variadic arguments, as in the +body of a variadic function. The result Value slice returned by fn +must have the number and type of results given by typ. +

    +

    +The Value.Call method allows the caller to invoke a typed function +in terms of Values; in contrast, MakeFunc allows the caller to implement +a typed function in terms of Values. +

    +

    +The Examples section of the documentation includes an illustration +of how to use MakeFunc to build a swap function for different types. +

    + +
    + +
    +

    Example

    + + + +

    Code:

    +
    // swap is the implementation passed to MakeFunc.
    +// It must work in terms of reflect.Values so that it is possible
    +// to write code without knowing beforehand what the types
    +// will be.
    +swap := func(in []reflect.Value) []reflect.Value {
    +    return []reflect.Value{in[1], in[0]}
    +}
    +
    +// makeSwap expects fptr to be a pointer to a nil function.
    +// It sets that pointer to a new function created with MakeFunc.
    +// When the function is invoked, reflect turns the arguments
    +// into Values, calls swap, and then turns swap's result slice
    +// into the values returned by the new function.
    +makeSwap := func(fptr interface{}) {
    +    // fptr is a pointer to a function.
    +    // Obtain the function value itself (likely nil) as a reflect.Value
    +    // so that we can query its type and then set the value.
    +    fn := reflect.ValueOf(fptr).Elem()
    +
    +    // Make a function of the right type.
    +    v := reflect.MakeFunc(fn.Type(), swap)
    +
    +    // Assign it to the value fn represents.
    +    fn.Set(v)
    +}
    +
    +// Make and call a swap function for ints.
    +var intSwap func(int, int) (int, int)
    +makeSwap(&intSwap)
    +fmt.Println(intSwap(0, 1))
    +
    +// Make and call a swap function for float64s.
    +var floatSwap func(float64, float64) (float64, float64)
    +makeSwap(&floatSwap)
    +fmt.Println(floatSwap(2.72, 3.14))
    +
    +
    + +

    Output:

    +
    1 0
    +3.14 2.72
    +
    + + +
    +
    + + + + +

    func MakeMap

    +
    func MakeMap(typ Type) Value
    +

    +MakeMap creates a new map of the specified type. +

    + + + + + +

    func MakeSlice

    +
    func MakeSlice(typ Type, len, cap int) Value
    +

    +MakeSlice creates a new zero-initialized slice value +for the specified slice type, length, and capacity. +

    + + + + + +

    func New

    +
    func New(typ Type) Value
    +

    +New returns a Value representing a pointer to a new zero value +for the specified type. That is, the returned Value's Type is PtrTo(typ). +

    + + + + + +

    func NewAt

    +
    func NewAt(typ Type, p unsafe.Pointer) Value
    +

    +NewAt returns a Value representing a pointer to a value of the +specified type, using p as that pointer. +

    + + + + + +

    func ValueOf

    +
    func ValueOf(i interface{}) Value
    +

    +ValueOf returns a new Value initialized to the concrete value +stored in the interface i. ValueOf(nil) returns the zero Value. +

    + + + + + +

    func Zero

    +
    func Zero(typ Type) Value
    +

    +Zero returns a Value representing the zero value for the specified type. +The result is different from the zero value of the Value struct, +which represents no value at all. +For example, Zero(TypeOf(42)) returns a Value with Kind Int and value 0. +The returned value is neither addressable nor settable. +

    + + + + + + + +

    func (Value) Addr

    +
    func (v Value) Addr() Value
    +

    +Addr returns a pointer value representing the address of v. +It panics if CanAddr() returns false. +Addr is typically used to obtain a pointer to a struct field +or slice element in order to call a method that requires a +pointer receiver. +

    + + + + + + +

    func (Value) Bool

    +
    func (v Value) Bool() bool
    +

    +Bool returns v's underlying value. +It panics if v's kind is not Bool. +

    + + + + + + +

    func (Value) Bytes

    +
    func (v Value) Bytes() []byte
    +

    +Bytes returns v's underlying value. +It panics if v's underlying value is not a slice of bytes. +

    + + + + + + +

    func (Value) Call

    +
    func (v Value) Call(in []Value) []Value
    +

    +Call calls the function v with the input arguments in. +For example, if len(in) == 3, v.Call(in) represents the Go call v(in[0], in[1], in[2]). +Call panics if v's Kind is not Func. +It returns the output results as Values. +As in Go, each input argument must be assignable to the +type of the function's corresponding input parameter. +If v is a variadic function, Call creates the variadic slice parameter +itself, copying in the corresponding values. +

    + + + + + + +

    func (Value) CallSlice

    +
    func (v Value) CallSlice(in []Value) []Value
    +

    +CallSlice calls the variadic function v with the input arguments in, +assigning the slice in[len(in)-1] to v's final variadic argument. +For example, if len(in) == 3, v.CallSlice(in) represents the Go call v(in[0], in[1], in[2]...). +CallSlice panics if v's Kind is not Func or if v is not variadic. +It returns the output results as Values. +As in Go, each input argument must be assignable to the +type of the function's corresponding input parameter. +

    + + + + + + +

    func (Value) CanAddr

    +
    func (v Value) CanAddr() bool
    +

    +CanAddr reports whether the value's address can be obtained with Addr. +Such values are called addressable. A value is addressable if it is +an element of a slice, an element of an addressable array, +a field of an addressable struct, or the result of dereferencing a pointer. +If CanAddr returns false, calling Addr will panic. +

    + + + + + + +

    func (Value) CanInterface

    +
    func (v Value) CanInterface() bool
    +

    +CanInterface reports whether Interface can be used without panicking. +

    + + + + + + +

    func (Value) CanSet

    +
    func (v Value) CanSet() bool
    +

    +CanSet reports whether the value of v can be changed. +A Value can be changed only if it is addressable and was not +obtained by the use of unexported struct fields. +If CanSet returns false, calling Set or any type-specific +setter (e.g., SetBool, SetInt) will panic. +

    + + + + + + +

    func (Value) Cap

    +
    func (v Value) Cap() int
    +

    +Cap returns v's capacity. +It panics if v's Kind is not Array, Chan, or Slice. +

    + + + + + + +

    func (Value) Close

    +
    func (v Value) Close()
    +

    +Close closes the channel v. +It panics if v's Kind is not Chan. +

    + + + + + + +

    func (Value) Complex

    +
    func (v Value) Complex() complex128
    +

    +Complex returns v's underlying value, as a complex128. +It panics if v's Kind is not Complex64 or Complex128 +

    + + + + + + +

    func (Value) Convert

    +
    func (v Value) Convert(t Type) Value
    +

    +Convert returns the value v converted to type t. +If the usual Go conversion rules do not allow conversion +of the value v to type t, Convert panics. +

    + + + + + + +

    func (Value) Elem

    +
    func (v Value) Elem() Value
    +

    +Elem returns the value that the interface v contains +or that the pointer v points to. +It panics if v's Kind is not Interface or Ptr. +It returns the zero Value if v is nil. +

    + + + + + + +

    func (Value) Field

    +
    func (v Value) Field(i int) Value
    +

    +Field returns the i'th field of the struct v. +It panics if v's Kind is not Struct or i is out of range. +

    + + + + + + +

    func (Value) FieldByIndex

    +
    func (v Value) FieldByIndex(index []int) Value
    +

    +FieldByIndex returns the nested field corresponding to index. +It panics if v's Kind is not struct. +

    + + + + + + +

    func (Value) FieldByName

    +
    func (v Value) FieldByName(name string) Value
    +

    +FieldByName returns the struct field with the given name. +It returns the zero Value if no field was found. +It panics if v's Kind is not struct. +

    + + + + + + +

    func (Value) FieldByNameFunc

    +
    func (v Value) FieldByNameFunc(match func(string) bool) Value
    +

    +FieldByNameFunc returns the struct field with a name +that satisfies the match function. +It panics if v's Kind is not struct. +It returns the zero Value if no field was found. +

    + + + + + + +

    func (Value) Float

    +
    func (v Value) Float() float64
    +

    +Float returns v's underlying value, as a float64. +It panics if v's Kind is not Float32 or Float64 +

    + + + + + + +

    func (Value) Index

    +
    func (v Value) Index(i int) Value
    +

    +Index returns v's i'th element. +It panics if v's Kind is not Array, Slice, or String or i is out of range. +

    + + + + + + +

    func (Value) Int

    +
    func (v Value) Int() int64
    +

    +Int returns v's underlying value, as an int64. +It panics if v's Kind is not Int, Int8, Int16, Int32, or Int64. +

    + + + + + + +

    func (Value) Interface

    +
    func (v Value) Interface() (i interface{})
    +

    +Interface returns v's current value as an interface{}. +It is equivalent to: +

    +
    var i interface{} = (v's underlying value)
    +
    +

    +It panics if the Value was obtained by accessing +unexported struct fields. +

    + + + + + + +

    func (Value) InterfaceData

    +
    func (v Value) InterfaceData() [2]uintptr
    +

    +InterfaceData returns the interface v's value as a uintptr pair. +It panics if v's Kind is not Interface. +

    + + + + + + +

    func (Value) IsNil

    +
    func (v Value) IsNil() bool
    +

    +IsNil reports whether its argument v is nil. The argument must be +a chan, func, interface, map, pointer, or slice value; if it is +not, IsNil panics. Note that IsNil is not always equivalent to a +regular comparison with nil in Go. For example, if v was created +by calling ValueOf with an uninitialized interface variable i, +i==nil will be true but v.IsNil will panic as v will be the zero +Value. +

    + + + + + + +

    func (Value) IsValid

    +
    func (v Value) IsValid() bool
    +

    +IsValid reports whether v represents a value. +It returns false if v is the zero Value. +If IsValid returns false, all other methods except String panic. +Most functions and methods never return an invalid value. +If one does, its documentation states the conditions explicitly. +

    + + + + + + +

    func (Value) Kind

    +
    func (v Value) Kind() Kind
    +

    +Kind returns v's Kind. +If v is the zero Value (IsValid returns false), Kind returns Invalid. +

    + + + + + + +

    func (Value) Len

    +
    func (v Value) Len() int
    +

    +Len returns v's length. +It panics if v's Kind is not Array, Chan, Map, Slice, or String. +

    + + + + + + +

    func (Value) MapIndex

    +
    func (v Value) MapIndex(key Value) Value
    +

    +MapIndex returns the value associated with key in the map v. +It panics if v's Kind is not Map. +It returns the zero Value if key is not found in the map or if v represents a nil map. +As in Go, the key's value must be assignable to the map's key type. +

    + + + + + + +

    func (Value) MapKeys

    +
    func (v Value) MapKeys() []Value
    +

    +MapKeys returns a slice containing all the keys present in the map, +in unspecified order. +It panics if v's Kind is not Map. +It returns an empty slice if v represents a nil map. +

    + + + + + + +

    func (Value) Method

    +
    func (v Value) Method(i int) Value
    +

    +Method returns a function value corresponding to v's i'th method. +The arguments to a Call on the returned function should not include +a receiver; the returned function will always use v as the receiver. +Method panics if i is out of range or if v is a nil interface value. +

    + + + + + + +

    func (Value) MethodByName

    +
    func (v Value) MethodByName(name string) Value
    +

    +MethodByName returns a function value corresponding to the method +of v with the given name. +The arguments to a Call on the returned function should not include +a receiver; the returned function will always use v as the receiver. +It returns the zero Value if no method was found. +

    + + + + + + +

    func (Value) NumField

    +
    func (v Value) NumField() int
    +

    +NumField returns the number of fields in the struct v. +It panics if v's Kind is not Struct. +

    + + + + + + +

    func (Value) NumMethod

    +
    func (v Value) NumMethod() int
    +

    +NumMethod returns the number of methods in the value's method set. +

    + + + + + + +

    func (Value) OverflowComplex

    +
    func (v Value) OverflowComplex(x complex128) bool
    +

    +OverflowComplex reports whether the complex128 x cannot be represented by v's type. +It panics if v's Kind is not Complex64 or Complex128. +

    + + + + + + +

    func (Value) OverflowFloat

    +
    func (v Value) OverflowFloat(x float64) bool
    +

    +OverflowFloat reports whether the float64 x cannot be represented by v's type. +It panics if v's Kind is not Float32 or Float64. +

    + + + + + + +

    func (Value) OverflowInt

    +
    func (v Value) OverflowInt(x int64) bool
    +

    +OverflowInt reports whether the int64 x cannot be represented by v's type. +It panics if v's Kind is not Int, Int8, int16, Int32, or Int64. +

    + + + + + + +

    func (Value) OverflowUint

    +
    func (v Value) OverflowUint(x uint64) bool
    +

    +OverflowUint reports whether the uint64 x cannot be represented by v's type. +It panics if v's Kind is not Uint, Uintptr, Uint8, Uint16, Uint32, or Uint64. +

    + + + + + + +

    func (Value) Pointer

    +
    func (v Value) Pointer() uintptr
    +

    +Pointer returns v's value as a uintptr. +It returns uintptr instead of unsafe.Pointer so that +code using reflect cannot obtain unsafe.Pointers +without importing the unsafe package explicitly. +It panics if v's Kind is not Chan, Func, Map, Ptr, Slice, or UnsafePointer. +

    +

    +If v's Kind is Func, the returned pointer is an underlying +code pointer, but not necessarily enough to identify a +single function uniquely. The only guarantee is that the +result is zero if and only if v is a nil func Value. +

    +

    +If v's Kind is Slice, the returned pointer is to the first +element of the slice. If the slice is nil the returned value +is 0. If the slice is empty but non-nil the return value is non-zero. +

    + + + + + + +

    func (Value) Recv

    +
    func (v Value) Recv() (x Value, ok bool)
    +

    +Recv receives and returns a value from the channel v. +It panics if v's Kind is not Chan. +The receive blocks until a value is ready. +The boolean value ok is true if the value x corresponds to a send +on the channel, false if it is a zero value received because the channel is closed. +

    + + + + + + +

    func (Value) Send

    +
    func (v Value) Send(x Value)
    +

    +Send sends x on the channel v. +It panics if v's kind is not Chan or if x's type is not the same type as v's element type. +As in Go, x's value must be assignable to the channel's element type. +

    + + + + + + +

    func (Value) Set

    +
    func (v Value) Set(x Value)
    +

    +Set assigns x to the value v. +It panics if CanSet returns false. +As in Go, x's value must be assignable to v's type. +

    + + + + + + +

    func (Value) SetBool

    +
    func (v Value) SetBool(x bool)
    +

    +SetBool sets v's underlying value. +It panics if v's Kind is not Bool or if CanSet() is false. +

    + + + + + + +

    func (Value) SetBytes

    +
    func (v Value) SetBytes(x []byte)
    +

    +SetBytes sets v's underlying value. +It panics if v's underlying value is not a slice of bytes. +

    + + + + + + +

    func (Value) SetCap

    +
    func (v Value) SetCap(n int)
    +

    +SetCap sets v's capacity to n. +It panics if v's Kind is not Slice or if n is smaller than the length or +greater than the capacity of the slice. +

    + + + + + + +

    func (Value) SetComplex

    +
    func (v Value) SetComplex(x complex128)
    +

    +SetComplex sets v's underlying value to x. +It panics if v's Kind is not Complex64 or Complex128, or if CanSet() is false. +

    + + + + + + +

    func (Value) SetFloat

    +
    func (v Value) SetFloat(x float64)
    +

    +SetFloat sets v's underlying value to x. +It panics if v's Kind is not Float32 or Float64, or if CanSet() is false. +

    + + + + + + +

    func (Value) SetInt

    +
    func (v Value) SetInt(x int64)
    +

    +SetInt sets v's underlying value to x. +It panics if v's Kind is not Int, Int8, Int16, Int32, or Int64, or if CanSet() is false. +

    + + + + + + +

    func (Value) SetLen

    +
    func (v Value) SetLen(n int)
    +

    +SetLen sets v's length to n. +It panics if v's Kind is not Slice or if n is negative or +greater than the capacity of the slice. +

    + + + + + + +

    func (Value) SetMapIndex

    +
    func (v Value) SetMapIndex(key, val Value)
    +

    +SetMapIndex sets the value associated with key in the map v to val. +It panics if v's Kind is not Map. +If val is the zero Value, SetMapIndex deletes the key from the map. +Otherwise if v holds a nil map, SetMapIndex will panic. +As in Go, key's value must be assignable to the map's key type, +and val's value must be assignable to the map's value type. +

    + + + + + + +

    func (Value) SetPointer

    +
    func (v Value) SetPointer(x unsafe.Pointer)
    +

    +SetPointer sets the unsafe.Pointer value v to x. +It panics if v's Kind is not UnsafePointer. +

    + + + + + + +

    func (Value) SetString

    +
    func (v Value) SetString(x string)
    +

    +SetString sets v's underlying value to x. +It panics if v's Kind is not String or if CanSet() is false. +

    + + + + + + +

    func (Value) SetUint

    +
    func (v Value) SetUint(x uint64)
    +

    +SetUint sets v's underlying value to x. +It panics if v's Kind is not Uint, Uintptr, Uint8, Uint16, Uint32, or Uint64, or if CanSet() is false. +

    + + + + + + +

    func (Value) Slice

    +
    func (v Value) Slice(i, j int) Value
    +

    +Slice returns v[i:j]. +It panics if v's Kind is not Array, Slice or String, or if v is an unaddressable array, +or if the indexes are out of bounds. +

    + + + + + + +

    func (Value) Slice3

    +
    func (v Value) Slice3(i, j, k int) Value
    +

    +Slice3 is the 3-index form of the slice operation: it returns v[i:j:k]. +It panics if v's Kind is not Array or Slice, or if v is an unaddressable array, +or if the indexes are out of bounds. +

    + + + + + + +

    func (Value) String

    +
    func (v Value) String() string
    +

    +String returns the string v's underlying value, as a string. +String is a special case because of Go's String method convention. +Unlike the other getters, it does not panic if v's Kind is not String. +Instead, it returns a string of the form "<T value>" where T is v's type. +The fmt package treats Values specially. It does not call their String +method implicitly but instead prints the concrete values they hold. +

    + + + + + + +

    func (Value) TryRecv

    +
    func (v Value) TryRecv() (x Value, ok bool)
    +

    +TryRecv attempts to receive a value from the channel v but will not block. +It panics if v's Kind is not Chan. +If the receive delivers a value, x is the transferred value and ok is true. +If the receive cannot finish without blocking, x is the zero Value and ok is false. +If the channel is closed, x is the zero value for the channel's element type and ok is false. +

    + + + + + + +

    func (Value) TrySend

    +
    func (v Value) TrySend(x Value) bool
    +

    +TrySend attempts to send x on the channel v but will not block. +It panics if v's Kind is not Chan. +It reports whether the value was sent. +As in Go, x's value must be assignable to the channel's element type. +

    + + + + + + +

    func (Value) Type

    +
    func (v Value) Type() Type
    +

    +Type returns v's type. +

    + + + + + + +

    func (Value) Uint

    +
    func (v Value) Uint() uint64
    +

    +Uint returns v's underlying value, as a uint64. +It panics if v's Kind is not Uint, Uintptr, Uint8, Uint16, Uint32, or Uint64. +

    + + + + + + +

    func (Value) UnsafeAddr

    +
    func (v Value) UnsafeAddr() uintptr
    +

    +UnsafeAddr returns a pointer to v's data. +It is for advanced clients that also import the "unsafe" package. +It panics if v is not addressable. +

    + + + + + + + + +

    type ValueError

    +
    type ValueError struct {
    +    Method string
    +    Kind   Kind
    +}
    +

    +A ValueError occurs when a Value method is invoked on +a Value that does not support it. Such cases are documented +in the description of each method. +

    + + + + + + + + + + + + + + +

    func (*ValueError) Error

    +
    func (e *ValueError) Error() string
    + + + + + + + + + + +

    Bugs

    +
      + +
    • FieldByName and related functions consider struct field names to be equal +if the names are equal, even if they are unexported names originating +in different packages. The practical effect of this is that the result of +t.FieldByName("x") is not well defined if the struct type t contains +multiple fields named x (embedded from different packages). +FieldByName may return one of the fields named x or may report that there are none. +See golang.org/issue/4876 for more details. +
    • + +
    + + + + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/regexp/index.html b/pkg/regexp/index.html new file mode 100644 index 0000000..e67cb47 --- /dev/null +++ b/pkg/regexp/index.html @@ -0,0 +1,1500 @@ + + + + + + + + regexp - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Package regexp

    + + + + + + + + + + + + + + +
    +
    +
    import "regexp"
    +
    +
    +
    Overview
    +
    Index
    + +
    Examples
    + + +
    Subdirectories
    + +
    +
    + +
    + +
    +

    Overview ▾

    +

    +Package regexp implements regular expression search. +

    +

    +The syntax of the regular expressions accepted is the same +general syntax used by Perl, Python, and other languages. +More precisely, it is the syntax accepted by RE2 and described at +https://golang.org/s/re2syntax, except for \C. +For an overview of the syntax, run +

    +
    go doc regexp/syntax
    +
    +

    +The regexp implementation provided by this package is +guaranteed to run in time linear in the size of the input. +(This is a property not guaranteed by most open source +implementations of regular expressions.) For more information +about this property, see +

    +
    http://swtch.com/~rsc/regexp/regexp1.html
    +
    +

    +or any book about automata theory. +

    +

    +All characters are UTF-8-encoded code points. +

    +

    +There are 16 methods of Regexp that match a regular expression and identify +the matched text. Their names are matched by this regular expression: +

    +
    Find(All)?(String)?(Submatch)?(Index)?
    +
    +

    +If 'All' is present, the routine matches successive non-overlapping +matches of the entire expression. Empty matches abutting a preceding +match are ignored. The return value is a slice containing the successive +return values of the corresponding non-'All' routine. These routines take +an extra integer argument, n; if n >= 0, the function returns at most n +matches/submatches. +

    +

    +If 'String' is present, the argument is a string; otherwise it is a slice +of bytes; return values are adjusted as appropriate. +

    +

    +If 'Submatch' is present, the return value is a slice identifying the +successive submatches of the expression. Submatches are matches of +parenthesized subexpressions (also known as capturing groups) within the +regular expression, numbered from left to right in order of opening +parenthesis. Submatch 0 is the match of the entire expression, submatch 1 +the match of the first parenthesized subexpression, and so on. +

    +

    +If 'Index' is present, matches and submatches are identified by byte index +pairs within the input string: result[2*n:2*n+1] identifies the indexes of +the nth submatch. The pair for n==0 identifies the match of the entire +expression. If 'Index' is not present, the match is identified by the +text of the match/submatch. If an index is negative, it means that +subexpression did not match any string in the input. +

    +

    +There is also a subset of the methods that can be applied to text read +from a RuneReader: +

    +
    MatchReader, FindReaderIndex, FindReaderSubmatchIndex
    +
    +

    +This set may grow. Note that regular expression matches may need to +examine text beyond the text returned by a match, so the methods that +match text from a RuneReader may read arbitrarily far into the input +before returning. +

    +

    +(There are a few other methods that do not match this pattern.) +

    + +
    +
    +
    + +
    +

    Example

    + + + +

    Code:

    +
    // Compile the expression once, usually at init time.
    +// Use raw strings to avoid having to quote the backslashes.
    +var validID = regexp.MustCompile(`^[a-z]+\[[0-9]+\]$`)
    +
    +fmt.Println(validID.MatchString("adam[23]"))
    +fmt.Println(validID.MatchString("eve[7]"))
    +fmt.Println(validID.MatchString("Job[48]"))
    +fmt.Println(validID.MatchString("snakey"))
    +
    + +

    Output:

    +
    true
    +true
    +false
    +false
    +
    + + +
    +
    + + +
    + +
    +

    Index ▾

    + + +
    +
    + + + + +
    func Match(pattern string, b []byte) (matched bool, err error)
    + + +
    func MatchReader(pattern string, r io.RuneReader) (matched bool, err error)
    + + +
    func MatchString(pattern string, s string) (matched bool, err error)
    + + +
    func QuoteMeta(s string) string
    + + + +
    type Regexp
    + + +
        func Compile(expr string) (*Regexp, error)
    + + +
        func CompilePOSIX(expr string) (*Regexp, error)
    + + +
        func MustCompile(str string) *Regexp
    + + +
        func MustCompilePOSIX(str string) *Regexp
    + + + +
        func (re *Regexp) Copy() *Regexp
    + + +
        func (re *Regexp) Expand(dst []byte, template []byte, src []byte, match []int) []byte
    + + +
        func (re *Regexp) ExpandString(dst []byte, template string, src string, match []int) []byte
    + + +
        func (re *Regexp) Find(b []byte) []byte
    + + +
        func (re *Regexp) FindAll(b []byte, n int) [][]byte
    + + +
        func (re *Regexp) FindAllIndex(b []byte, n int) [][]int
    + + +
        func (re *Regexp) FindAllString(s string, n int) []string
    + + +
        func (re *Regexp) FindAllStringIndex(s string, n int) [][]int
    + + +
        func (re *Regexp) FindAllStringSubmatch(s string, n int) [][]string
    + + +
        func (re *Regexp) FindAllStringSubmatchIndex(s string, n int) [][]int
    + + +
        func (re *Regexp) FindAllSubmatch(b []byte, n int) [][][]byte
    + + +
        func (re *Regexp) FindAllSubmatchIndex(b []byte, n int) [][]int
    + + +
        func (re *Regexp) FindIndex(b []byte) (loc []int)
    + + +
        func (re *Regexp) FindReaderIndex(r io.RuneReader) (loc []int)
    + + +
        func (re *Regexp) FindReaderSubmatchIndex(r io.RuneReader) []int
    + + +
        func (re *Regexp) FindString(s string) string
    + + +
        func (re *Regexp) FindStringIndex(s string) (loc []int)
    + + +
        func (re *Regexp) FindStringSubmatch(s string) []string
    + + +
        func (re *Regexp) FindStringSubmatchIndex(s string) []int
    + + +
        func (re *Regexp) FindSubmatch(b []byte) [][]byte
    + + +
        func (re *Regexp) FindSubmatchIndex(b []byte) []int
    + + +
        func (re *Regexp) LiteralPrefix() (prefix string, complete bool)
    + + +
        func (re *Regexp) Longest()
    + + +
        func (re *Regexp) Match(b []byte) bool
    + + +
        func (re *Regexp) MatchReader(r io.RuneReader) bool
    + + +
        func (re *Regexp) MatchString(s string) bool
    + + +
        func (re *Regexp) NumSubexp() int
    + + +
        func (re *Regexp) ReplaceAll(src, repl []byte) []byte
    + + +
        func (re *Regexp) ReplaceAllFunc(src []byte, repl func([]byte) []byte) []byte
    + + +
        func (re *Regexp) ReplaceAllLiteral(src, repl []byte) []byte
    + + +
        func (re *Regexp) ReplaceAllLiteralString(src, repl string) string
    + + +
        func (re *Regexp) ReplaceAllString(src, repl string) string
    + + +
        func (re *Regexp) ReplaceAllStringFunc(src string, repl func(string) string) string
    + + +
        func (re *Regexp) Split(s string, n int) []string
    + + +
        func (re *Regexp) String() string
    + + +
        func (re *Regexp) SubexpNames() []string
    + + + +
    +
    + + + + + + +

    Package files

    +

    + + + backtrack.go + + exec.go + + onepass.go + + regexp.go + + +

    + +
    +
    + + + + + + + + +

    func Match

    +
    func Match(pattern string, b []byte) (matched bool, err error)
    +

    +Match checks whether a textual regular expression +matches a byte slice. More complicated queries need +to use Compile and the full Regexp interface. +

    + + + + + + + +

    func MatchReader

    +
    func MatchReader(pattern string, r io.RuneReader) (matched bool, err error)
    +

    +MatchReader checks whether a textual regular expression matches the text +read by the RuneReader. More complicated queries need to use Compile and +the full Regexp interface. +

    + + + + + + + +

    func MatchString

    +
    func MatchString(pattern string, s string) (matched bool, err error)
    +

    +MatchString checks whether a textual regular expression +matches a string. More complicated queries need +to use Compile and the full Regexp interface. +

    + +
    + +
    +

    Example

    + + + +

    Code:

    +
    matched, err := regexp.MatchString("foo.*", "seafood")
    +fmt.Println(matched, err)
    +matched, err = regexp.MatchString("bar.*", "seafood")
    +fmt.Println(matched, err)
    +matched, err = regexp.MatchString("a(b", "seafood")
    +fmt.Println(matched, err)
    +
    + +

    Output:

    +
    true <nil>
    +false <nil>
    +false error parsing regexp: missing closing ): `a(b`
    +
    + + +
    +
    + + + + + + +

    func QuoteMeta

    +
    func QuoteMeta(s string) string
    +

    +QuoteMeta returns a string that quotes all regular expression metacharacters +inside the argument text; the returned string is a regular expression matching +the literal text. For example, QuoteMeta(`[foo]`) returns `\[foo\]`. +

    + + + + + + + + +

    type Regexp

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

    +Regexp is the representation of a compiled regular expression. +A Regexp is safe for concurrent use by multiple goroutines. +

    + + + + + + + + + + + + +

    func Compile

    +
    func Compile(expr string) (*Regexp, error)
    +

    +Compile parses a regular expression and returns, if successful, +a Regexp object that can be used to match against text. +

    +

    +When matching against text, the regexp returns a match that +begins as early as possible in the input (leftmost), and among those +it chooses the one that a backtracking search would have found first. +This so-called leftmost-first matching is the same semantics +that Perl, Python, and other implementations use, although this +package implements it without the expense of backtracking. +For POSIX leftmost-longest matching, see CompilePOSIX. +

    + + + + + +

    func CompilePOSIX

    +
    func CompilePOSIX(expr string) (*Regexp, error)
    +

    +CompilePOSIX is like Compile but restricts the regular expression +to POSIX ERE (egrep) syntax and changes the match semantics to +leftmost-longest. +

    +

    +That is, when matching against text, the regexp returns a match that +begins as early as possible in the input (leftmost), and among those +it chooses a match that is as long as possible. +This so-called leftmost-longest matching is the same semantics +that early regular expression implementations used and that POSIX +specifies. +

    +

    +However, there can be multiple leftmost-longest matches, with different +submatch choices, and here this package diverges from POSIX. +Among the possible leftmost-longest matches, this package chooses +the one that a backtracking search would have found first, while POSIX +specifies that the match be chosen to maximize the length of the first +subexpression, then the second, and so on from left to right. +The POSIX rule is computationally prohibitive and not even well-defined. +See http://swtch.com/~rsc/regexp/regexp2.html#posix for details. +

    + + + + + +

    func MustCompile

    +
    func MustCompile(str string) *Regexp
    +

    +MustCompile is like Compile but panics if the expression cannot be parsed. +It simplifies safe initialization of global variables holding compiled regular +expressions. +

    + + + + + +

    func MustCompilePOSIX

    +
    func MustCompilePOSIX(str string) *Regexp
    +

    +MustCompilePOSIX is like CompilePOSIX but panics if the expression cannot be parsed. +It simplifies safe initialization of global variables holding compiled regular +expressions. +

    + + + + + + + +

    func (*Regexp) Copy

    +
    func (re *Regexp) Copy() *Regexp
    +

    +Copy returns a new Regexp object copied from re. +

    +

    +When using a Regexp in multiple goroutines, giving each goroutine +its own copy helps to avoid lock contention. +

    + + + + + + +

    func (*Regexp) Expand

    +
    func (re *Regexp) Expand(dst []byte, template []byte, src []byte, match []int) []byte
    +

    +Expand appends template to dst and returns the result; during the +append, Expand replaces variables in the template with corresponding +matches drawn from src. The match slice should have been returned by +FindSubmatchIndex. +

    +

    +In the template, a variable is denoted by a substring of the form +$name or ${name}, where name is a non-empty sequence of letters, +digits, and underscores. A purely numeric name like $1 refers to +the submatch with the corresponding index; other names refer to +capturing parentheses named with the (?P<name>...) syntax. A +reference to an out of range or unmatched index or a name that is not +present in the regular expression is replaced with an empty slice. +

    +

    +In the $name form, name is taken to be as long as possible: $1x is +equivalent to ${1x}, not ${1}x, and, $10 is equivalent to ${10}, not ${1}0. +

    +

    +To insert a literal $ in the output, use $$ in the template. +

    + + + + + + +

    func (*Regexp) ExpandString

    +
    func (re *Regexp) ExpandString(dst []byte, template string, src string, match []int) []byte
    +

    +ExpandString is like Expand but the template and source are strings. +It appends to and returns a byte slice in order to give the calling +code control over allocation. +

    + + + + + + +

    func (*Regexp) Find

    +
    func (re *Regexp) Find(b []byte) []byte
    +

    +Find returns a slice holding the text of the leftmost match in b of the regular expression. +A return value of nil indicates no match. +

    + + + + + + +

    func (*Regexp) FindAll

    +
    func (re *Regexp) FindAll(b []byte, n int) [][]byte
    +

    +FindAll is the 'All' version of Find; it returns a slice of all successive +matches of the expression, as defined by the 'All' description in the +package comment. +A return value of nil indicates no match. +

    + + + + + + +

    func (*Regexp) FindAllIndex

    +
    func (re *Regexp) FindAllIndex(b []byte, n int) [][]int
    +

    +FindAllIndex is the 'All' version of FindIndex; it returns a slice of all +successive matches of the expression, as defined by the 'All' description +in the package comment. +A return value of nil indicates no match. +

    + + + + + + +

    func (*Regexp) FindAllString

    +
    func (re *Regexp) FindAllString(s string, n int) []string
    +

    +FindAllString is the 'All' version of FindString; it returns a slice of all +successive matches of the expression, as defined by the 'All' description +in the package comment. +A return value of nil indicates no match. +

    + + +
    + +
    +

    Example

    + + + +

    Code:

    +
    re := regexp.MustCompile("a.")
    +fmt.Println(re.FindAllString("paranormal", -1))
    +fmt.Println(re.FindAllString("paranormal", 2))
    +fmt.Println(re.FindAllString("graal", -1))
    +fmt.Println(re.FindAllString("none", -1))
    +
    + +

    Output:

    +
    [ar an al]
    +[ar an]
    +[aa]
    +[]
    +
    + + +
    +
    + + + + +

    func (*Regexp) FindAllStringIndex

    +
    func (re *Regexp) FindAllStringIndex(s string, n int) [][]int
    +

    +FindAllStringIndex is the 'All' version of FindStringIndex; it returns a +slice of all successive matches of the expression, as defined by the 'All' +description in the package comment. +A return value of nil indicates no match. +

    + + + + + + +

    func (*Regexp) FindAllStringSubmatch

    +
    func (re *Regexp) FindAllStringSubmatch(s string, n int) [][]string
    +

    +FindAllStringSubmatch is the 'All' version of FindStringSubmatch; it +returns a slice of all successive matches of the expression, as defined by +the 'All' description in the package comment. +A return value of nil indicates no match. +

    + + +
    + +
    +

    Example

    + + + +

    Code:

    +
    re := regexp.MustCompile("a(x*)b")
    +fmt.Printf("%q\n", re.FindAllStringSubmatch("-ab-", -1))
    +fmt.Printf("%q\n", re.FindAllStringSubmatch("-axxb-", -1))
    +fmt.Printf("%q\n", re.FindAllStringSubmatch("-ab-axb-", -1))
    +fmt.Printf("%q\n", re.FindAllStringSubmatch("-axxb-ab-", -1))
    +
    + +

    Output:

    +
    [["ab" ""]]
    +[["axxb" "xx"]]
    +[["ab" ""] ["axb" "x"]]
    +[["axxb" "xx"] ["ab" ""]]
    +
    + + +
    +
    + + + + +

    func (*Regexp) FindAllStringSubmatchIndex

    +
    func (re *Regexp) FindAllStringSubmatchIndex(s string, n int) [][]int
    +

    +FindAllStringSubmatchIndex is the 'All' version of +FindStringSubmatchIndex; it returns a slice of all successive matches of +the expression, as defined by the 'All' description in the package +comment. +A return value of nil indicates no match. +

    + + +
    + +
    +

    Example

    + + + +

    Code:

    +
    re := regexp.MustCompile("a(x*)b")
    +// Indices:
    +//    01234567   012345678
    +//    -ab-axb-   -axxb-ab-
    +fmt.Println(re.FindAllStringSubmatchIndex("-ab-", -1))
    +fmt.Println(re.FindAllStringSubmatchIndex("-axxb-", -1))
    +fmt.Println(re.FindAllStringSubmatchIndex("-ab-axb-", -1))
    +fmt.Println(re.FindAllStringSubmatchIndex("-axxb-ab-", -1))
    +fmt.Println(re.FindAllStringSubmatchIndex("-foo-", -1))
    +
    + +

    Output:

    +
    [[1 3 2 2]]
    +[[1 5 2 4]]
    +[[1 3 2 2] [4 7 5 6]]
    +[[1 5 2 4] [6 8 7 7]]
    +[]
    +
    + + +
    +
    + + + + +

    func (*Regexp) FindAllSubmatch

    +
    func (re *Regexp) FindAllSubmatch(b []byte, n int) [][][]byte
    +

    +FindAllSubmatch is the 'All' version of FindSubmatch; it returns a slice +of all successive matches of the expression, as defined by the 'All' +description in the package comment. +A return value of nil indicates no match. +

    + + + + + + +

    func (*Regexp) FindAllSubmatchIndex

    +
    func (re *Regexp) FindAllSubmatchIndex(b []byte, n int) [][]int
    +

    +FindAllSubmatchIndex is the 'All' version of FindSubmatchIndex; it returns +a slice of all successive matches of the expression, as defined by the +'All' description in the package comment. +A return value of nil indicates no match. +

    + + + + + + +

    func (*Regexp) FindIndex

    +
    func (re *Regexp) FindIndex(b []byte) (loc []int)
    +

    +FindIndex returns a two-element slice of integers defining the location of +the leftmost match in b of the regular expression. The match itself is at +b[loc[0]:loc[1]]. +A return value of nil indicates no match. +

    + + + + + + +

    func (*Regexp) FindReaderIndex

    +
    func (re *Regexp) FindReaderIndex(r io.RuneReader) (loc []int)
    +

    +FindReaderIndex returns a two-element slice of integers defining the +location of the leftmost match of the regular expression in text read from +the RuneReader. The match text was found in the input stream at +byte offset loc[0] through loc[1]-1. +A return value of nil indicates no match. +

    + + + + + + +

    func (*Regexp) FindReaderSubmatchIndex

    +
    func (re *Regexp) FindReaderSubmatchIndex(r io.RuneReader) []int
    +

    +FindReaderSubmatchIndex returns a slice holding the index pairs +identifying the leftmost match of the regular expression of text read by +the RuneReader, and the matches, if any, of its subexpressions, as defined +by the 'Submatch' and 'Index' descriptions in the package comment. A +return value of nil indicates no match. +

    + + + + + + +

    func (*Regexp) FindString

    +
    func (re *Regexp) FindString(s string) string
    +

    +FindString returns a string holding the text of the leftmost match in s of the regular +expression. If there is no match, the return value is an empty string, +but it will also be empty if the regular expression successfully matches +an empty string. Use FindStringIndex or FindStringSubmatch if it is +necessary to distinguish these cases. +

    + + +
    + +
    +

    Example

    + + + +

    Code:

    +
    re := regexp.MustCompile("fo.?")
    +fmt.Printf("%q\n", re.FindString("seafood"))
    +fmt.Printf("%q\n", re.FindString("meat"))
    +
    + +

    Output:

    +
    "foo"
    +""
    +
    + + +
    +
    + + + + +

    func (*Regexp) FindStringIndex

    +
    func (re *Regexp) FindStringIndex(s string) (loc []int)
    +

    +FindStringIndex returns a two-element slice of integers defining the +location of the leftmost match in s of the regular expression. The match +itself is at s[loc[0]:loc[1]]. +A return value of nil indicates no match. +

    + + +
    + +
    +

    Example

    + + + +

    Code:

    +
    re := regexp.MustCompile("ab?")
    +fmt.Println(re.FindStringIndex("tablett"))
    +fmt.Println(re.FindStringIndex("foo") == nil)
    +
    + +

    Output:

    +
    [1 3]
    +true
    +
    + + +
    +
    + + + + +

    func (*Regexp) FindStringSubmatch

    +
    func (re *Regexp) FindStringSubmatch(s string) []string
    +

    +FindStringSubmatch returns a slice of strings holding the text of the +leftmost match of the regular expression in s and the matches, if any, of +its subexpressions, as defined by the 'Submatch' description in the +package comment. +A return value of nil indicates no match. +

    + + +
    + +
    +

    Example

    + + + +

    Code:

    +
    re := regexp.MustCompile("a(x*)b(y|z)c")
    +fmt.Printf("%q\n", re.FindStringSubmatch("-axxxbyc-"))
    +fmt.Printf("%q\n", re.FindStringSubmatch("-abzc-"))
    +
    + +

    Output:

    +
    ["axxxbyc" "xxx" "y"]
    +["abzc" "" "z"]
    +
    + + +
    +
    + + + + +

    func (*Regexp) FindStringSubmatchIndex

    +
    func (re *Regexp) FindStringSubmatchIndex(s string) []int
    +

    +FindStringSubmatchIndex returns a slice holding the index pairs +identifying the leftmost match of the regular expression in s and the +matches, if any, of its subexpressions, as defined by the 'Submatch' and +'Index' descriptions in the package comment. +A return value of nil indicates no match. +

    + + + + + + +

    func (*Regexp) FindSubmatch

    +
    func (re *Regexp) FindSubmatch(b []byte) [][]byte
    +

    +FindSubmatch returns a slice of slices holding the text of the leftmost +match of the regular expression in b and the matches, if any, of its +subexpressions, as defined by the 'Submatch' descriptions in the package +comment. +A return value of nil indicates no match. +

    + + + + + + +

    func (*Regexp) FindSubmatchIndex

    +
    func (re *Regexp) FindSubmatchIndex(b []byte) []int
    +

    +FindSubmatchIndex returns a slice holding the index pairs identifying the +leftmost match of the regular expression in b and the matches, if any, of +its subexpressions, as defined by the 'Submatch' and 'Index' descriptions +in the package comment. +A return value of nil indicates no match. +

    + + + + + + +

    func (*Regexp) LiteralPrefix

    +
    func (re *Regexp) LiteralPrefix() (prefix string, complete bool)
    +

    +LiteralPrefix returns a literal string that must begin any match +of the regular expression re. It returns the boolean true if the +literal string comprises the entire regular expression. +

    + + + + + + +

    func (*Regexp) Longest

    +
    func (re *Regexp) Longest()
    +

    +Longest makes future searches prefer the leftmost-longest match. +That is, when matching against text, the regexp returns a match that +begins as early as possible in the input (leftmost), and among those +it chooses a match that is as long as possible. +

    + + + + + + +

    func (*Regexp) Match

    +
    func (re *Regexp) Match(b []byte) bool
    +

    +Match reports whether the Regexp matches the byte slice b. +

    + + + + + + +

    func (*Regexp) MatchReader

    +
    func (re *Regexp) MatchReader(r io.RuneReader) bool
    +

    +MatchReader reports whether the Regexp matches the text read by the +RuneReader. +

    + + + + + + +

    func (*Regexp) MatchString

    +
    func (re *Regexp) MatchString(s string) bool
    +

    +MatchString reports whether the Regexp matches the string s. +

    + + + + + + +

    func (*Regexp) NumSubexp

    +
    func (re *Regexp) NumSubexp() int
    +

    +NumSubexp returns the number of parenthesized subexpressions in this Regexp. +

    + + + + + + +

    func (*Regexp) ReplaceAll

    +
    func (re *Regexp) ReplaceAll(src, repl []byte) []byte
    +

    +ReplaceAll returns a copy of src, replacing matches of the Regexp +with the replacement text repl. Inside repl, $ signs are interpreted as +in Expand, so for instance $1 represents the text of the first submatch. +

    + + + + + + +

    func (*Regexp) ReplaceAllFunc

    +
    func (re *Regexp) ReplaceAllFunc(src []byte, repl func([]byte) []byte) []byte
    +

    +ReplaceAllFunc returns a copy of src in which all matches of the +Regexp have been replaced by the return value of function repl applied +to the matched byte slice. The replacement returned by repl is substituted +directly, without using Expand. +

    + + + + + + +

    func (*Regexp) ReplaceAllLiteral

    +
    func (re *Regexp) ReplaceAllLiteral(src, repl []byte) []byte
    +

    +ReplaceAllLiteral returns a copy of src, replacing matches of the Regexp +with the replacement bytes repl. The replacement repl is substituted directly, +without using Expand. +

    + + + + + + +

    func (*Regexp) ReplaceAllLiteralString

    +
    func (re *Regexp) ReplaceAllLiteralString(src, repl string) string
    +

    +ReplaceAllLiteralString returns a copy of src, replacing matches of the Regexp +with the replacement string repl. The replacement repl is substituted directly, +without using Expand. +

    + + +
    + +
    +

    Example

    + + + +

    Code:

    +
    re := regexp.MustCompile("a(x*)b")
    +fmt.Println(re.ReplaceAllLiteralString("-ab-axxb-", "T"))
    +fmt.Println(re.ReplaceAllLiteralString("-ab-axxb-", "$1"))
    +fmt.Println(re.ReplaceAllLiteralString("-ab-axxb-", "${1}"))
    +
    + +

    Output:

    +
    -T-T-
    +-$1-$1-
    +-${1}-${1}-
    +
    + + +
    +
    + + + + +

    func (*Regexp) ReplaceAllString

    +
    func (re *Regexp) ReplaceAllString(src, repl string) string
    +

    +ReplaceAllString returns a copy of src, replacing matches of the Regexp +with the replacement string repl. Inside repl, $ signs are interpreted as +in Expand, so for instance $1 represents the text of the first submatch. +

    + + +
    + +
    +

    Example

    + + + +

    Code:

    +
    re := regexp.MustCompile("a(x*)b")
    +fmt.Println(re.ReplaceAllString("-ab-axxb-", "T"))
    +fmt.Println(re.ReplaceAllString("-ab-axxb-", "$1"))
    +fmt.Println(re.ReplaceAllString("-ab-axxb-", "$1W"))
    +fmt.Println(re.ReplaceAllString("-ab-axxb-", "${1}W"))
    +
    + +

    Output:

    +
    -T-T-
    +--xx-
    +---
    +-W-xxW-
    +
    + + +
    +
    + + + + +

    func (*Regexp) ReplaceAllStringFunc

    +
    func (re *Regexp) ReplaceAllStringFunc(src string, repl func(string) string) string
    +

    +ReplaceAllStringFunc returns a copy of src in which all matches of the +Regexp have been replaced by the return value of function repl applied +to the matched substring. The replacement returned by repl is substituted +directly, without using Expand. +

    + + + + + + +

    func (*Regexp) Split

    +
    func (re *Regexp) Split(s string, n int) []string
    +

    +Split slices s into substrings separated by the expression and returns a slice of +the substrings between those expression matches. +

    +

    +The slice returned by this method consists of all the substrings of s +not contained in the slice returned by FindAllString. When called on an expression +that contains no metacharacters, it is equivalent to strings.SplitN. +

    +

    +Example: +

    +
    s := regexp.MustCompile("a*").Split("abaabaccadaaae", 5)
    +// s: ["", "b", "b", "c", "cadaaae"]
    +
    +

    +The count determines the number of substrings to return: +

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

    Example

    + + + +

    Code:

    +
    a := regexp.MustCompile("a")
    +fmt.Println(a.Split("banana", -1))
    +fmt.Println(a.Split("banana", 0))
    +fmt.Println(a.Split("banana", 1))
    +fmt.Println(a.Split("banana", 2))
    +zp := regexp.MustCompile("z+")
    +fmt.Println(zp.Split("pizza", -1))
    +fmt.Println(zp.Split("pizza", 0))
    +fmt.Println(zp.Split("pizza", 1))
    +fmt.Println(zp.Split("pizza", 2))
    +
    + +

    Output:

    +
    [b n n ]
    +[]
    +[banana]
    +[b nana]
    +[pi a]
    +[]
    +[pizza]
    +[pi a]
    +
    + + +
    +
    + + + + +

    func (*Regexp) String

    +
    func (re *Regexp) String() string
    +

    +String returns the source text used to compile the regular expression. +

    + + + + + + +

    func (*Regexp) SubexpNames

    +
    func (re *Regexp) SubexpNames() []string
    +

    +SubexpNames returns the names of the parenthesized subexpressions +in this Regexp. The name for the first sub-expression is names[1], +so that if m is a match slice, the name for m[i] is SubexpNames()[i]. +Since the Regexp as a whole cannot be named, names[0] is always +the empty string. The slice should not be modified. +

    + + +
    + +
    +

    Example

    + + + +

    Code:

    +
    re := regexp.MustCompile("(?P<first>[a-zA-Z]+) (?P<last>[a-zA-Z]+)")
    +fmt.Println(re.MatchString("Alan Turing"))
    +fmt.Printf("%q\n", re.SubexpNames())
    +reversed := fmt.Sprintf("${%s} ${%s}", re.SubexpNames()[2], re.SubexpNames()[1])
    +fmt.Println(reversed)
    +fmt.Println(re.ReplaceAllString("Alan Turing", reversed))
    +
    + +

    Output:

    +
    true
    +["" "first" "last"]
    +${last} ${first}
    +Turing Alan
    +
    + + +
    +
    + + + + + + + + + + + + + + +

    Subdirectories

    + + + + +
    + + + + + + + + + + + + + + + + + + + + +
    NameSynopsis
    ..
    + syntax + + Package syntax parses regular expressions into parse trees and compiles parse trees into programs. +
    +
    + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/regexp/syntax/index.html b/pkg/regexp/syntax/index.html new file mode 100644 index 0000000..71b89ef --- /dev/null +++ b/pkg/regexp/syntax/index.html @@ -0,0 +1,974 @@ + + + + + + + + syntax - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Package syntax

    + + + + + + + + + + + + + + +
    +
    +
    import "regexp/syntax"
    +
    +
    +
    Overview
    +
    Index
    + + +
    +
    + +
    + +
    +

    Overview ▾

    +

    +Package syntax parses regular expressions into parse trees and compiles +parse trees into programs. Most clients of regular expressions will use the +facilities of package regexp (such as Compile and Match) instead of this package. +

    +

    Syntax

    +

    +The regular expression syntax understood by this package when parsing with the Perl flag is as follows. +Parts of the syntax can be disabled by passing alternate flags to Parse. +

    +

    +Single characters: +

    +
    .              any character, possibly including newline (flag s=true)
    +[xyz]          character class
    +[^xyz]         negated character class
    +\d             Perl character class
    +\D             negated Perl character class
    +[[:alpha:]]    ASCII character class
    +[[:^alpha:]]   negated ASCII character class
    +\pN            Unicode character class (one-letter name)
    +\p{Greek}      Unicode character class
    +\PN            negated Unicode character class (one-letter name)
    +\P{Greek}      negated Unicode character class
    +
    +

    +Composites: +

    +
    xy             x followed by y
    +x|y            x or y (prefer x)
    +
    +

    +Repetitions: +

    +
    x*             zero or more x, prefer more
    +x+             one or more x, prefer more
    +x?             zero or one x, prefer one
    +x{n,m}         n or n+1 or ... or m x, prefer more
    +x{n,}          n or more x, prefer more
    +x{n}           exactly n x
    +x*?            zero or more x, prefer fewer
    +x+?            one or more x, prefer fewer
    +x??            zero or one x, prefer zero
    +x{n,m}?        n or n+1 or ... or m x, prefer fewer
    +x{n,}?         n or more x, prefer fewer
    +x{n}?          exactly n x
    +
    +

    +Implementation restriction: The counting forms x{n,m}, x{n,}, and x{n} +reject forms that create a minimum or maximum repetition count above 1000. +Unlimited repetitions are not subject to this restriction. +

    +

    +Grouping: +

    +
    (re)           numbered capturing group (submatch)
    +(?P<name>re)   named & numbered capturing group (submatch)
    +(?:re)         non-capturing group
    +(?flags)       set flags within current group; non-capturing
    +(?flags:re)    set flags during re; non-capturing
    +
    +Flag syntax is xyz (set) or -xyz (clear) or xy-z (set xy, clear z). The flags are:
    +
    +i              case-insensitive (default false)
    +m              multi-line mode: ^ and $ match begin/end line in addition to begin/end text (default false)
    +s              let . match \n (default false)
    +U              ungreedy: swap meaning of x* and x*?, x+ and x+?, etc (default false)
    +
    +

    +Empty strings: +

    +
    ^              at beginning of text or line (flag m=true)
    +$              at end of text (like \z not \Z) or line (flag m=true)
    +\A             at beginning of text
    +\b             at ASCII word boundary (\w on one side and \W, \A, or \z on the other)
    +\B             not at ASCII word boundary
    +\z             at end of text
    +
    +

    +Escape sequences: +

    +
    \a             bell (== \007)
    +\f             form feed (== \014)
    +\t             horizontal tab (== \011)
    +\n             newline (== \012)
    +\r             carriage return (== \015)
    +\v             vertical tab character (== \013)
    +\*             literal *, for any punctuation character *
    +\123           octal character code (up to three digits)
    +\x7F           hex character code (exactly two digits)
    +\x{10FFFF}     hex character code
    +\Q...\E        literal text ... even if ... has punctuation
    +
    +

    +Character class elements: +

    +
    x              single character
    +A-Z            character range (inclusive)
    +\d             Perl character class
    +[:foo:]        ASCII character class foo
    +\p{Foo}        Unicode character class Foo
    +\pF            Unicode character class F (one-letter name)
    +
    +

    +Named character classes as character class elements: +

    +
    [\d]           digits (== \d)
    +[^\d]          not digits (== \D)
    +[\D]           not digits (== \D)
    +[^\D]          not not digits (== \d)
    +[[:name:]]     named ASCII class inside character class (== [:name:])
    +[^[:name:]]    named ASCII class inside negated character class (== [:^name:])
    +[\p{Name}]     named Unicode property inside character class (== \p{Name})
    +[^\p{Name}]    named Unicode property inside negated character class (== \P{Name})
    +
    +

    +Perl character classes (all ASCII-only): +

    +
    \d             digits (== [0-9])
    +\D             not digits (== [^0-9])
    +\s             whitespace (== [\t\n\f\r ])
    +\S             not whitespace (== [^\t\n\f\r ])
    +\w             word characters (== [0-9A-Za-z_])
    +\W             not word characters (== [^0-9A-Za-z_])
    +
    +

    +ASCII character classes: +

    +
    [[:alnum:]]    alphanumeric (== [0-9A-Za-z])
    +[[:alpha:]]    alphabetic (== [A-Za-z])
    +[[:ascii:]]    ASCII (== [\x00-\x7F])
    +[[:blank:]]    blank (== [\t ])
    +[[:cntrl:]]    control (== [\x00-\x1F\x7F])
    +[[:digit:]]    digits (== [0-9])
    +[[:graph:]]    graphical (== [!-~] == [A-Za-z0-9!"#$%&'()*+,\-./:;<=>?@[\\\]^_`{|}~])
    +[[:lower:]]    lower case (== [a-z])
    +[[:print:]]    printable (== [ -~] == [ [:graph:]])
    +[[:punct:]]    punctuation (== [!-/:-@[-`{-~])
    +[[:space:]]    whitespace (== [\t\n\v\f\r ])
    +[[:upper:]]    upper case (== [A-Z])
    +[[:word:]]     word characters (== [0-9A-Za-z_])
    +[[:xdigit:]]   hex digit (== [0-9A-Fa-f])
    +
    + +
    +
    + + + + + + + + + + + +

    func IsWordChar

    +
    func IsWordChar(r rune) bool
    +

    +IsWordChar reports whether r is consider a “word character” +during the evaluation of the \b and \B zero-width assertions. +These assertions are ASCII-only: the word characters are [A-Za-z0-9_]. +

    + + + + + + + + +

    type EmptyOp

    +
    type EmptyOp uint8
    +

    +An EmptyOp specifies a kind or mixture of zero-width assertions. +

    + + + +
    const (
    +    EmptyBeginLine EmptyOp = 1 << iota
    +    EmptyEndLine
    +    EmptyBeginText
    +    EmptyEndText
    +    EmptyWordBoundary
    +    EmptyNoWordBoundary
    +)
    + + + + + + + + + + + +

    func EmptyOpContext

    +
    func EmptyOpContext(r1, r2 rune) EmptyOp
    +

    +EmptyOpContext returns the zero-width assertions +satisfied at the position between the runes r1 and r2. +Passing r1 == -1 indicates that the position is +at the beginning of the text. +Passing r2 == -1 indicates that the position is +at the end of the text. +

    + + + + + + + + + +

    type Error

    +
    type Error struct {
    +    Code ErrorCode
    +    Expr string
    +}
    +

    +An Error describes a failure to parse a regular expression +and gives the offending expression. +

    + + + + + + + + + + + + + + +

    func (*Error) Error

    +
    func (e *Error) Error() string
    + + + + + + + + +

    type ErrorCode

    +
    type ErrorCode string
    +

    +An ErrorCode describes a failure to parse a regular expression. +

    + + + +
    const (
    +    // Unexpected error
    +    ErrInternalError ErrorCode = "regexp/syntax: internal error"
    +
    +    // Parse errors
    +    ErrInvalidCharClass      ErrorCode = "invalid character class"
    +    ErrInvalidCharRange      ErrorCode = "invalid character class range"
    +    ErrInvalidEscape         ErrorCode = "invalid escape sequence"
    +    ErrInvalidNamedCapture   ErrorCode = "invalid named capture"
    +    ErrInvalidPerlOp         ErrorCode = "invalid or unsupported Perl syntax"
    +    ErrInvalidRepeatOp       ErrorCode = "invalid nested repetition operator"
    +    ErrInvalidRepeatSize     ErrorCode = "invalid repeat count"
    +    ErrInvalidUTF8           ErrorCode = "invalid UTF-8"
    +    ErrMissingBracket        ErrorCode = "missing closing ]"
    +    ErrMissingParen          ErrorCode = "missing closing )"
    +    ErrMissingRepeatArgument ErrorCode = "missing argument to repetition operator"
    +    ErrTrailingBackslash     ErrorCode = "trailing backslash at end of expression"
    +    ErrUnexpectedParen       ErrorCode = "unexpected )"
    +)
    + + + + + + + + + + + + + +

    func (ErrorCode) String

    +
    func (e ErrorCode) String() string
    + + + + + + + + +

    type Flags

    +
    type Flags uint16
    +

    +Flags control the behavior of the parser and record information about regexp context. +

    + + + +
    const (
    +    FoldCase      Flags = 1 << iota // case-insensitive match
    +    Literal                         // treat pattern as literal string
    +    ClassNL                         // allow character classes like [^a-z] and [[:space:]] to match newline
    +    DotNL                           // allow . to match newline
    +    OneLine                         // treat ^ and $ as only matching at beginning and end of text
    +    NonGreedy                       // make repetition operators default to non-greedy
    +    PerlX                           // allow Perl extensions
    +    UnicodeGroups                   // allow \p{Han}, \P{Han} for Unicode group and negation
    +    WasDollar                       // regexp OpEndText was $, not \z
    +    Simple                          // regexp contains no counted repetition
    +
    +    MatchNL = ClassNL | DotNL
    +
    +    Perl        = ClassNL | OneLine | PerlX | UnicodeGroups // as close to Perl as possible
    +    POSIX Flags = 0                                         // POSIX syntax
    +)
    + + + + + + + + + + + + + + + +

    type Inst

    +
    type Inst struct {
    +    Op   InstOp
    +    Out  uint32 // all but InstMatch, InstFail
    +    Arg  uint32 // InstAlt, InstAltMatch, InstCapture, InstEmptyWidth
    +    Rune []rune
    +}
    +

    +An Inst is a single instruction in a regular expression program. +

    + + + + + + + + + + + + + + +

    func (*Inst) MatchEmptyWidth

    +
    func (i *Inst) MatchEmptyWidth(before rune, after rune) bool
    +

    +MatchEmptyWidth reports whether the instruction matches +an empty string between the runes before and after. +It should only be called when i.Op == InstEmptyWidth. +

    + + + + + + +

    func (*Inst) MatchRune

    +
    func (i *Inst) MatchRune(r rune) bool
    +

    +MatchRune reports whether the instruction matches (and consumes) r. +It should only be called when i.Op == InstRune. +

    + + + + + + +

    func (*Inst) MatchRunePos

    +
    func (i *Inst) MatchRunePos(r rune) int
    +

    +MatchRunePos checks whether the instruction matches (and consumes) r. +If so, MatchRunePos returns the index of the matching rune pair +(or, when len(i.Rune) == 1, rune singleton). +If not, MatchRunePos returns -1. +MatchRunePos should only be called when i.Op == InstRune. +

    + + + + + + +

    func (*Inst) String

    +
    func (i *Inst) String() string
    + + + + + + + + +

    type InstOp

    +
    type InstOp uint8
    +

    +An InstOp is an instruction opcode. +

    + + + +
    const (
    +    InstAlt InstOp = iota
    +    InstAltMatch
    +    InstCapture
    +    InstEmptyWidth
    +    InstMatch
    +    InstFail
    +    InstNop
    +    InstRune
    +    InstRune1
    +    InstRuneAny
    +    InstRuneAnyNotNL
    +)
    + + + + + + + + + + + + + +

    func (InstOp) String

    +
    func (i InstOp) String() string
    + + + + + + + + +

    type Op

    +
    type Op uint8
    +

    +An Op is a single regular expression operator. +

    + + + +
    const (
    +    OpNoMatch        Op = 1 + iota // matches no strings
    +    OpEmptyMatch                   // matches empty string
    +    OpLiteral                      // matches Runes sequence
    +    OpCharClass                    // matches Runes interpreted as range pair list
    +    OpAnyCharNotNL                 // matches any character except newline
    +    OpAnyChar                      // matches any character
    +    OpBeginLine                    // matches empty string at beginning of line
    +    OpEndLine                      // matches empty string at end of line
    +    OpBeginText                    // matches empty string at beginning of text
    +    OpEndText                      // matches empty string at end of text
    +    OpWordBoundary                 // matches word boundary `\b`
    +    OpNoWordBoundary               // matches word non-boundary `\B`
    +    OpCapture                      // capturing subexpression with index Cap, optional name Name
    +    OpStar                         // matches Sub[0] zero or more times
    +    OpPlus                         // matches Sub[0] one or more times
    +    OpQuest                        // matches Sub[0] zero or one times
    +    OpRepeat                       // matches Sub[0] at least Min times, at most Max (Max == -1 is no limit)
    +    OpConcat                       // matches concatenation of Subs
    +    OpAlternate                    // matches alternation of Subs
    +)
    + + + + + + + + + + + + + + + +

    type Prog

    +
    type Prog struct {
    +    Inst   []Inst
    +    Start  int // index of start instruction
    +    NumCap int // number of InstCapture insts in re
    +}
    +

    +A Prog is a compiled regular expression program. +

    + + + + + + + + + + + + +

    func Compile

    +
    func Compile(re *Regexp) (*Prog, error)
    +

    +Compile compiles the regexp into a program to be executed. +The regexp should have been simplified already (returned from re.Simplify). +

    + + + + + + + +

    func (*Prog) Prefix

    +
    func (p *Prog) Prefix() (prefix string, complete bool)
    +

    +Prefix returns a literal string that all matches for the +regexp must start with. Complete is true if the prefix +is the entire match. +

    + + + + + + +

    func (*Prog) StartCond

    +
    func (p *Prog) StartCond() EmptyOp
    +

    +StartCond returns the leading empty-width conditions that must +be true in any match. It returns ^EmptyOp(0) if no matches are possible. +

    + + + + + + +

    func (*Prog) String

    +
    func (p *Prog) String() string
    + + + + + + + + +

    type Regexp

    +
    type Regexp struct {
    +    Op       Op // operator
    +    Flags    Flags
    +    Sub      []*Regexp  // subexpressions, if any
    +    Sub0     [1]*Regexp // storage for short Sub
    +    Rune     []rune     // matched runes, for OpLiteral, OpCharClass
    +    Rune0    [2]rune    // storage for short Rune
    +    Min, Max int        // min, max for OpRepeat
    +    Cap      int        // capturing index, for OpCapture
    +    Name     string     // capturing name, for OpCapture
    +}
    +

    +A Regexp is a node in a regular expression syntax tree. +

    + + + + + + + + + + + + +

    func Parse

    +
    func Parse(s string, flags Flags) (*Regexp, error)
    +

    +Parse parses a regular expression string s, controlled by the specified +Flags, and returns a regular expression parse tree. The syntax is +described in the top-level comment. +

    + + + + + + + +

    func (*Regexp) CapNames

    +
    func (re *Regexp) CapNames() []string
    +

    +CapNames walks the regexp to find the names of capturing groups. +

    + + + + + + +

    func (*Regexp) Equal

    +
    func (x *Regexp) Equal(y *Regexp) bool
    +

    +Equal returns true if x and y have identical structure. +

    + + + + + + +

    func (*Regexp) MaxCap

    +
    func (re *Regexp) MaxCap() int
    +

    +MaxCap walks the regexp to find the maximum capture index. +

    + + + + + + +

    func (*Regexp) Simplify

    +
    func (re *Regexp) Simplify() *Regexp
    +

    +Simplify returns a regexp equivalent to re but without counted repetitions +and with various other simplifications, such as rewriting /(?:a+)+/ to /a+/. +The resulting regexp will execute correctly but its string representation +will not produce the same parse tree, because capturing parentheses +may have been duplicated or removed. For example, the simplified form +for /(x){1,2}/ is /(x)(x)?/ but both parentheses capture as $1. +The returned regexp may share structure with or be the original. +

    + + + + + + +

    func (*Regexp) String

    +
    func (re *Regexp) String() string
    + + + + + + + + + + + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/sync/atomic/index.html b/pkg/sync/atomic/index.html new file mode 100644 index 0000000..ef7c5a5 --- /dev/null +++ b/pkg/sync/atomic/index.html @@ -0,0 +1,863 @@ + + + + + + + + atomic - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Package atomic

    + + + + + + + + + + + + + + +
    +
    +
    import "sync/atomic"
    +
    +
    +
    Overview
    +
    Index
    + +
    Examples
    + + +
    +
    + +
    + +
    +

    Overview ▾

    +

    +Package atomic provides low-level atomic memory primitives +useful for implementing synchronization algorithms. +

    +

    +These functions require great care to be used correctly. +Except for special, low-level applications, synchronization is better +done with channels or the facilities of the sync package. +Share memory by communicating; +don't communicate by sharing memory. +

    +

    +The swap operation, implemented by the SwapT functions, is the atomic +equivalent of: +

    +
    old = *addr
    +*addr = new
    +return old
    +
    +

    +The compare-and-swap operation, implemented by the CompareAndSwapT +functions, is the atomic equivalent of: +

    +
    if *addr == old {
    +	*addr = new
    +	return true
    +}
    +return false
    +
    +

    +The add operation, implemented by the AddT functions, is the atomic +equivalent of: +

    +
    *addr += delta
    +return *addr
    +
    +

    +The load and store operations, implemented by the LoadT and StoreT +functions, are the atomic equivalents of "return *addr" and +"*addr = val". +

    + +
    +
    + + +
    + +
    +

    Index ▾

    + + +
    +
    + + + + +
    func AddInt32(addr *int32, delta int32) (new int32)
    + + +
    func AddInt64(addr *int64, delta int64) (new int64)
    + + +
    func AddUint32(addr *uint32, delta uint32) (new uint32)
    + + +
    func AddUint64(addr *uint64, delta uint64) (new uint64)
    + + +
    func AddUintptr(addr *uintptr, delta uintptr) (new uintptr)
    + + +
    func CompareAndSwapInt32(addr *int32, old, new int32) (swapped bool)
    + + +
    func CompareAndSwapInt64(addr *int64, old, new int64) (swapped bool)
    + + +
    func CompareAndSwapPointer(addr *unsafe.Pointer, old, new unsafe.Pointer) (swapped bool)
    + + +
    func CompareAndSwapUint32(addr *uint32, old, new uint32) (swapped bool)
    + + +
    func CompareAndSwapUint64(addr *uint64, old, new uint64) (swapped bool)
    + + +
    func CompareAndSwapUintptr(addr *uintptr, old, new uintptr) (swapped bool)
    + + +
    func LoadInt32(addr *int32) (val int32)
    + + +
    func LoadInt64(addr *int64) (val int64)
    + + +
    func LoadPointer(addr *unsafe.Pointer) (val unsafe.Pointer)
    + + +
    func LoadUint32(addr *uint32) (val uint32)
    + + +
    func LoadUint64(addr *uint64) (val uint64)
    + + +
    func LoadUintptr(addr *uintptr) (val uintptr)
    + + +
    func StoreInt32(addr *int32, val int32)
    + + +
    func StoreInt64(addr *int64, val int64)
    + + +
    func StorePointer(addr *unsafe.Pointer, val unsafe.Pointer)
    + + +
    func StoreUint32(addr *uint32, val uint32)
    + + +
    func StoreUint64(addr *uint64, val uint64)
    + + +
    func StoreUintptr(addr *uintptr, val uintptr)
    + + +
    func SwapInt32(addr *int32, new int32) (old int32)
    + + +
    func SwapInt64(addr *int64, new int64) (old int64)
    + + +
    func SwapPointer(addr *unsafe.Pointer, new unsafe.Pointer) (old unsafe.Pointer)
    + + +
    func SwapUint32(addr *uint32, new uint32) (old uint32)
    + + +
    func SwapUint64(addr *uint64, new uint64) (old uint64)
    + + +
    func SwapUintptr(addr *uintptr, new uintptr) (old uintptr)
    + + + +
    type Value
    + + + +
        func (v *Value) Load() (x interface{})
    + + +
        func (v *Value) Store(x interface{})
    + + + + +
    Bugs
    + + +
    +
    + + +
    +

    Examples

    +
    + +
    Value (Config)
    + +
    Value (ReadMostly)
    + +
    +
    + + + +

    Package files

    +

    + + + doc.go + + value.go + + +

    + +
    +
    + + + + + + + + +

    func AddInt32

    +
    func AddInt32(addr *int32, delta int32) (new int32)
    +

    +AddInt32 atomically adds delta to *addr and returns the new value. +

    + + + + + + + +

    func AddInt64

    +
    func AddInt64(addr *int64, delta int64) (new int64)
    +

    +AddInt64 atomically adds delta to *addr and returns the new value. +

    + + + + + + + +

    func AddUint32

    +
    func AddUint32(addr *uint32, delta uint32) (new uint32)
    +

    +AddUint32 atomically adds delta to *addr and returns the new value. +To subtract a signed positive constant value c from x, do AddUint32(&x, ^uint32(c-1)). +In particular, to decrement x, do AddUint32(&x, ^uint32(0)). +

    + + + + + + + +

    func AddUint64

    +
    func AddUint64(addr *uint64, delta uint64) (new uint64)
    +

    +AddUint64 atomically adds delta to *addr and returns the new value. +To subtract a signed positive constant value c from x, do AddUint64(&x, ^uint64(c-1)). +In particular, to decrement x, do AddUint64(&x, ^uint64(0)). +

    + + + + + + + +

    func AddUintptr

    +
    func AddUintptr(addr *uintptr, delta uintptr) (new uintptr)
    +

    +AddUintptr atomically adds delta to *addr and returns the new value. +

    + + + + + + + +

    func CompareAndSwapInt32

    +
    func CompareAndSwapInt32(addr *int32, old, new int32) (swapped bool)
    +

    +CompareAndSwapInt32 executes the compare-and-swap operation for an int32 value. +

    + + + + + + + +

    func CompareAndSwapInt64

    +
    func CompareAndSwapInt64(addr *int64, old, new int64) (swapped bool)
    +

    +CompareAndSwapInt64 executes the compare-and-swap operation for an int64 value. +

    + + + + + + + +

    func CompareAndSwapPointer

    +
    func CompareAndSwapPointer(addr *unsafe.Pointer, old, new unsafe.Pointer) (swapped bool)
    +

    +CompareAndSwapPointer executes the compare-and-swap operation for a unsafe.Pointer value. +

    + + + + + + + +

    func CompareAndSwapUint32

    +
    func CompareAndSwapUint32(addr *uint32, old, new uint32) (swapped bool)
    +

    +CompareAndSwapUint32 executes the compare-and-swap operation for a uint32 value. +

    + + + + + + + +

    func CompareAndSwapUint64

    +
    func CompareAndSwapUint64(addr *uint64, old, new uint64) (swapped bool)
    +

    +CompareAndSwapUint64 executes the compare-and-swap operation for a uint64 value. +

    + + + + + + + +

    func CompareAndSwapUintptr

    +
    func CompareAndSwapUintptr(addr *uintptr, old, new uintptr) (swapped bool)
    +

    +CompareAndSwapUintptr executes the compare-and-swap operation for a uintptr value. +

    + + + + + + + +

    func LoadInt32

    +
    func LoadInt32(addr *int32) (val int32)
    +

    +LoadInt32 atomically loads *addr. +

    + + + + + + + +

    func LoadInt64

    +
    func LoadInt64(addr *int64) (val int64)
    +

    +LoadInt64 atomically loads *addr. +

    + + + + + + + +

    func LoadPointer

    +
    func LoadPointer(addr *unsafe.Pointer) (val unsafe.Pointer)
    +

    +LoadPointer atomically loads *addr. +

    + + + + + + + +

    func LoadUint32

    +
    func LoadUint32(addr *uint32) (val uint32)
    +

    +LoadUint32 atomically loads *addr. +

    + + + + + + + +

    func LoadUint64

    +
    func LoadUint64(addr *uint64) (val uint64)
    +

    +LoadUint64 atomically loads *addr. +

    + + + + + + + +

    func LoadUintptr

    +
    func LoadUintptr(addr *uintptr) (val uintptr)
    +

    +LoadUintptr atomically loads *addr. +

    + + + + + + + +

    func StoreInt32

    +
    func StoreInt32(addr *int32, val int32)
    +

    +StoreInt32 atomically stores val into *addr. +

    + + + + + + + +

    func StoreInt64

    +
    func StoreInt64(addr *int64, val int64)
    +

    +StoreInt64 atomically stores val into *addr. +

    + + + + + + + +

    func StorePointer

    +
    func StorePointer(addr *unsafe.Pointer, val unsafe.Pointer)
    +

    +StorePointer atomically stores val into *addr. +

    + + + + + + + +

    func StoreUint32

    +
    func StoreUint32(addr *uint32, val uint32)
    +

    +StoreUint32 atomically stores val into *addr. +

    + + + + + + + +

    func StoreUint64

    +
    func StoreUint64(addr *uint64, val uint64)
    +

    +StoreUint64 atomically stores val into *addr. +

    + + + + + + + +

    func StoreUintptr

    +
    func StoreUintptr(addr *uintptr, val uintptr)
    +

    +StoreUintptr atomically stores val into *addr. +

    + + + + + + + +

    func SwapInt32

    +
    func SwapInt32(addr *int32, new int32) (old int32)
    +

    +SwapInt32 atomically stores new into *addr and returns the previous *addr value. +

    + + + + + + + +

    func SwapInt64

    +
    func SwapInt64(addr *int64, new int64) (old int64)
    +

    +SwapInt64 atomically stores new into *addr and returns the previous *addr value. +

    + + + + + + + +

    func SwapPointer

    +
    func SwapPointer(addr *unsafe.Pointer, new unsafe.Pointer) (old unsafe.Pointer)
    +

    +SwapPointer atomically stores new into *addr and returns the previous *addr value. +

    + + + + + + + +

    func SwapUint32

    +
    func SwapUint32(addr *uint32, new uint32) (old uint32)
    +

    +SwapUint32 atomically stores new into *addr and returns the previous *addr value. +

    + + + + + + + +

    func SwapUint64

    +
    func SwapUint64(addr *uint64, new uint64) (old uint64)
    +

    +SwapUint64 atomically stores new into *addr and returns the previous *addr value. +

    + + + + + + + +

    func SwapUintptr

    +
    func SwapUintptr(addr *uintptr, new uintptr) (old uintptr)
    +

    +SwapUintptr atomically stores new into *addr and returns the previous *addr value. +

    + + + + + + + + +

    type Value

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

    +A Value provides an atomic load and store of a consistently typed value. +Values can be created as part of other data structures. +The zero value for a Value returns nil from Load. +Once Store has been called, a Value must not be copied. +

    + + + + + + +
    + +
    +

    Example (Config)

    +

    The following example shows how to use Value for periodic program config updates +and propagation of the changes to worker goroutines. +

    + + +

    Code:

    +
    +var config Value // holds current server configuration
    +// Create initial config value and store into config.
    +config.Store(loadConfig())
    +go func() {
    +    // Reload config every 10 seconds
    +    // and update config value with the new version.
    +    for {
    +        time.Sleep(10 * time.Second)
    +        config.Store(loadConfig())
    +    }
    +}()
    +// Create worker goroutines that handle incoming requests
    +// using the latest config value.
    +for i := 0; i < 10; i++ {
    +    go func() {
    +        for r := range requests() {
    +            c := config.Load()
    +            // Handle request r using config c.
    +            _, _ = r, c
    +        }
    +    }()
    +}
    +
    + + +
    +
    +
    + +
    +

    Example (ReadMostly)

    +

    The following example shows how to maintain a scalable frequently read, +but infrequently updated data structure using copy-on-write idiom. +

    + + +

    Code:

    +
    +type Map map[string]string
    +var m Value
    +m.Store(make(Map))
    +var mu sync.Mutex // used only by writers
    +// read function can be used to read the data without further synchronization
    +read := func(key string) (val string) {
    +    m1 := m.Load().(Map)
    +    return m1[key]
    +}
    +// insert function can be used to update the data without further synchronization
    +insert := func(key, val string) {
    +    mu.Lock() // synchronize with other potential writers
    +    defer mu.Unlock()
    +    m1 := m.Load().(Map) // load current value of the data structure
    +    m2 := make(Map)      // create a new value
    +    for k, v := range m1 {
    +        m2[k] = v // copy all data from the current object to the new one
    +    }
    +    m2[key] = val // do the update that we need
    +    m.Store(m2)   // atomically replace the current object with the new one
    +    // At this point all new readers start working with the new version.
    +    // The old version will be garbage collected once the existing readers
    +    // (if any) are done with it.
    +}
    +_, _ = read, insert
    +
    + + +
    +
    + + + + + + + + +

    func (*Value) Load

    +
    func (v *Value) Load() (x interface{})
    +

    +Load returns the value set by the most recent Store. +It returns nil if there has been no call to Store for this Value. +

    + + + + + + +

    func (*Value) Store

    +
    func (v *Value) Store(x interface{})
    +

    +Store sets the value of the Value to x. +All calls to Store for a given Value must use values of the same concrete type. +Store of an inconsistent type panics, as does Store(nil). +

    + + + + + + + + + + +

    Bugs

    +
      + +
    • On x86-32, the 64-bit functions use instructions unavailable before the Pentium MMX. + +On non-Linux ARM, the 64-bit functions use instructions unavailable before the ARMv6k core. + +On both ARM and x86-32, it is the caller's responsibility to arrange for 64-bit +alignment of 64-bit words accessed atomically. The first word in a global +variable or in an allocated struct or slice can be relied upon to be +64-bit aligned. +
    • + +
    + + + + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/sync/index.html b/pkg/sync/index.html new file mode 100644 index 0000000..77814a7 --- /dev/null +++ b/pkg/sync/index.html @@ -0,0 +1,932 @@ + + + + + + + + sync - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Package sync

    + + + + + + + + + + + + + + +
    +
    +
    import "sync"
    +
    +
    +
    Overview
    +
    Index
    + +
    Examples
    + + +
    Subdirectories
    + +
    +
    + +
    + +
    +

    Overview ▾

    +

    +Package sync provides basic synchronization primitives such as mutual +exclusion locks. Other than the Once and WaitGroup types, most are intended +for use by low-level library routines. Higher-level synchronization is +better done via channels and communication. +

    +

    +Values containing the types defined in this package should not be copied. +

    + +
    +
    + + +
    + +
    +

    Index ▾

    + + + + + +
    +

    Examples

    +
    + +
    Once
    + +
    WaitGroup
    + +
    +
    + + + +

    Package files

    +

    + + + cond.go + + mutex.go + + once.go + + pool.go + + runtime.go + + rwmutex.go + + waitgroup.go + + +

    + +
    +
    + + + + + + + + + +

    type Cond

    +
    type Cond struct {
    +    // L is held while observing or changing the condition
    +    L Locker
    +    // contains filtered or unexported fields
    +}
    +

    +Cond implements a condition variable, a rendezvous point +for goroutines waiting for or announcing the occurrence +of an event. +

    +

    +Each Cond has an associated Locker L (often a *Mutex or *RWMutex), +which must be held when changing the condition and +when calling the Wait method. +

    +

    +A Cond can be created as part of other structures. +A Cond must not be copied after first use. +

    + + + + + + + + + + + + +

    func NewCond

    +
    func NewCond(l Locker) *Cond
    +

    +NewCond returns a new Cond with Locker l. +

    + + + + + + + +

    func (*Cond) Broadcast

    +
    func (c *Cond) Broadcast()
    +

    +Broadcast wakes all goroutines waiting on c. +

    +

    +It is allowed but not required for the caller to hold c.L +during the call. +

    + + + + + + +

    func (*Cond) Signal

    +
    func (c *Cond) Signal()
    +

    +Signal wakes one goroutine waiting on c, if there is any. +

    +

    +It is allowed but not required for the caller to hold c.L +during the call. +

    + + + + + + +

    func (*Cond) Wait

    +
    func (c *Cond) Wait()
    +

    +Wait atomically unlocks c.L and suspends execution +of the calling goroutine. After later resuming execution, +Wait locks c.L before returning. Unlike in other systems, +Wait cannot return unless awoken by Broadcast or Signal. +

    +

    +Because c.L is not locked when Wait first resumes, the caller +typically cannot assume that the condition is true when +Wait returns. Instead, the caller should Wait in a loop: +

    +
    c.L.Lock()
    +for !condition() {
    +    c.Wait()
    +}
    +... make use of condition ...
    +c.L.Unlock()
    +
    + + + + + + + + +

    type Locker

    +
    type Locker interface {
    +    Lock()
    +    Unlock()
    +}
    +

    +A Locker represents an object that can be locked and unlocked. +

    + + + + + + + + + + + + + + + + +

    type Mutex

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

    +A Mutex is a mutual exclusion lock. +Mutexes can be created as part of other structures; +the zero value for a Mutex is an unlocked mutex. +

    + + + + + + + + + + + + + + +

    func (*Mutex) Lock

    +
    func (m *Mutex) Lock()
    +

    +Lock locks m. +If the lock is already in use, the calling goroutine +blocks until the mutex is available. +

    + + + + + + +

    func (*Mutex) Unlock

    +
    func (m *Mutex) Unlock()
    +

    +Unlock unlocks m. +It is a run-time error if m is not locked on entry to Unlock. +

    +

    +A locked Mutex is not associated with a particular goroutine. +It is allowed for one goroutine to lock a Mutex and then +arrange for another goroutine to unlock it. +

    + + + + + + + + +

    type Once

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

    +Once is an object that will perform exactly one action. +

    + + + + + + +
    + +
    +

    Example

    + + + +

    Code:

    +
    var once sync.Once
    +onceBody := func() {
    +    fmt.Println("Only once")
    +}
    +done := make(chan bool)
    +for i := 0; i < 10; i++ {
    +    go func() {
    +        once.Do(onceBody)
    +        done <- true
    +    }()
    +}
    +for i := 0; i < 10; i++ {
    +    <-done
    +}
    +
    + +

    Output:

    +
    Only once
    +
    + + +
    +
    + + + + + + + + +

    func (*Once) Do

    +
    func (o *Once) Do(f func())
    +

    +Do calls the function f if and only if Do is being called for the +first time for this instance of Once. In other words, given +

    +
    var once Once
    +
    +

    +if once.Do(f) is called multiple times, only the first call will invoke f, +even if f has a different value in each invocation. A new instance of +Once is required for each function to execute. +

    +

    +Do is intended for initialization that must be run exactly once. Since f +is niladic, it may be necessary to use a function literal to capture the +arguments to a function to be invoked by Do: +

    +
    config.once.Do(func() { config.init(filename) })
    +
    +

    +Because no call to Do returns until the one call to f returns, if f causes +Do to be called, it will deadlock. +

    +

    +If f panics, Do considers it to have returned; future calls of Do return +without calling f. +

    + + + + + + + + +

    type Pool

    +
    type Pool struct {
    +
    +    // New optionally specifies a function to generate
    +    // a value when Get would otherwise return nil.
    +    // It may not be changed concurrently with calls to Get.
    +    New func() interface{}
    +    // contains filtered or unexported fields
    +}
    +

    +A Pool is a set of temporary objects that may be individually saved and +retrieved. +

    +

    +Any item stored in the Pool may be removed automatically at any time without +notification. If the Pool holds the only reference when this happens, the +item might be deallocated. +

    +

    +A Pool is safe for use by multiple goroutines simultaneously. +

    +

    +Pool's purpose is to cache allocated but unused items for later reuse, +relieving pressure on the garbage collector. That is, it makes it easy to +build efficient, thread-safe free lists. However, it is not suitable for all +free lists. +

    +

    +An appropriate use of a Pool is to manage a group of temporary items +silently shared among and potentially reused by concurrent independent +clients of a package. Pool provides a way to amortize allocation overhead +across many clients. +

    +

    +An example of good use of a Pool is in the fmt package, which maintains a +dynamically-sized store of temporary output buffers. The store scales under +load (when many goroutines are actively printing) and shrinks when +quiescent. +

    +

    +On the other hand, a free list maintained as part of a short-lived object is +not a suitable use for a Pool, since the overhead does not amortize well in +that scenario. It is more efficient to have such objects implement their own +free list. +

    + + + + + + + + + + + + + + +

    func (*Pool) Get

    +
    func (p *Pool) Get() interface{}
    +

    +Get selects an arbitrary item from the Pool, removes it from the +Pool, and returns it to the caller. +Get may choose to ignore the pool and treat it as empty. +Callers should not assume any relation between values passed to Put and +the values returned by Get. +

    +

    +If Get would otherwise return nil and p.New is non-nil, Get returns +the result of calling p.New. +

    + + + + + + +

    func (*Pool) Put

    +
    func (p *Pool) Put(x interface{})
    +

    +Put adds x to the pool. +

    + + + + + + + + +

    type RWMutex

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

    +An RWMutex is a reader/writer mutual exclusion lock. +The lock can be held by an arbitrary number of readers +or a single writer. +RWMutexes can be created as part of other +structures; the zero value for a RWMutex is +an unlocked mutex. +

    + + + + + + + + + + + + + + +

    func (*RWMutex) Lock

    +
    func (rw *RWMutex) Lock()
    +

    +Lock locks rw for writing. +If the lock is already locked for reading or writing, +Lock blocks until the lock is available. +To ensure that the lock eventually becomes available, +a blocked Lock call excludes new readers from acquiring +the lock. +

    + + + + + + +

    func (*RWMutex) RLock

    +
    func (rw *RWMutex) RLock()
    +

    +RLock locks rw for reading. +

    + + + + + + +

    func (*RWMutex) RLocker

    +
    func (rw *RWMutex) RLocker() Locker
    +

    +RLocker returns a Locker interface that implements +the Lock and Unlock methods by calling rw.RLock and rw.RUnlock. +

    + + + + + + +

    func (*RWMutex) RUnlock

    +
    func (rw *RWMutex) RUnlock()
    +

    +RUnlock undoes a single RLock call; +it does not affect other simultaneous readers. +It is a run-time error if rw is not locked for reading +on entry to RUnlock. +

    + + + + + + +

    func (*RWMutex) Unlock

    +
    func (rw *RWMutex) Unlock()
    +

    +Unlock unlocks rw for writing. It is a run-time error if rw is +not locked for writing on entry to Unlock. +

    +

    +As with Mutexes, a locked RWMutex is not associated with a particular +goroutine. One goroutine may RLock (Lock) an RWMutex and then +arrange for another goroutine to RUnlock (Unlock) it. +

    + + + + + + + + +

    type WaitGroup

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

    +A WaitGroup waits for a collection of goroutines to finish. +The main goroutine calls Add to set the number of +goroutines to wait for. Then each of the goroutines +runs and calls Done when finished. At the same time, +Wait can be used to block until all goroutines have finished. +

    + + + + + + +
    + +
    +

    Example

    +

    This example fetches several URLs concurrently, +using a WaitGroup to block until all the fetches are complete. +

    + + +

    Code:

    +
    +var wg sync.WaitGroup
    +var urls = []string{
    +    "http://www.golang.org/",
    +    "http://www.google.com/",
    +    "http://www.somestupidname.com/",
    +}
    +for _, url := range urls {
    +    // Increment the WaitGroup counter.
    +    wg.Add(1)
    +    // Launch a goroutine to fetch the URL.
    +    go func(url string) {
    +        // Decrement the counter when the goroutine completes.
    +        defer wg.Done()
    +        // Fetch the URL.
    +        http.Get(url)
    +    }(url)
    +}
    +// Wait for all HTTP fetches to complete.
    +wg.Wait()
    +
    + + +
    +
    + + + + + + + + +

    func (*WaitGroup) Add

    +
    func (wg *WaitGroup) Add(delta int)
    +

    +Add adds delta, which may be negative, to the WaitGroup counter. +If the counter becomes zero, all goroutines blocked on Wait are released. +If the counter goes negative, Add panics. +

    +

    +Note that calls with a positive delta that occur when the counter is zero +must happen before a Wait. Calls with a negative delta, or calls with a +positive delta that start when the counter is greater than zero, may happen +at any time. +Typically this means the calls to Add should execute before the statement +creating the goroutine or other event to be waited for. +If a WaitGroup is reused to wait for several independent sets of events, +new Add calls must happen after all previous Wait calls have returned. +See the WaitGroup example. +

    + + + + + + +

    func (*WaitGroup) Done

    +
    func (wg *WaitGroup) Done()
    +

    +Done decrements the WaitGroup counter. +

    + + + + + + +

    func (*WaitGroup) Wait

    +
    func (wg *WaitGroup) Wait()
    +

    +Wait blocks until the WaitGroup counter is zero. +

    + + + + + + + + + + + + + + + + +

    Subdirectories

    + + + + +
    + + + + + + + + + + + + + + + + + + + + +
    NameSynopsis
    ..
    + atomic + + Package atomic provides low-level atomic memory primitives useful for implementing synchronization algorithms. +
    +
    + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/syscall/index.html b/pkg/syscall/index.html new file mode 100644 index 0000000..65cca7e --- /dev/null +++ b/pkg/syscall/index.html @@ -0,0 +1,7304 @@ + + + + + + + + syscall - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Package syscall

    + + + + + + + + + + + + + + +
    +
    +
    import "syscall"
    +
    +
    +
    Overview
    +
    Index
    + + +
    +
    + +
    + +
    +

    Overview ▾

    +

    +Package syscall contains an interface to the low-level operating system +primitives. The details vary depending on the underlying system, and +by default, godoc will display the syscall documentation for the current +system. If you want godoc to display syscall documentation for another +system, set $GOOS and $GOARCH to the desired system. For example, if +you want to view documentation for freebsd/arm on linux/amd64, set $GOOS +to freebsd and $GOARCH to arm. +The primary use of syscall is inside other packages that provide a more +portable interface to the system, such as "os", "time" and "net". Use +those packages rather than this one if you can. +For details of the functions and data types in this package consult +the manuals for the appropriate operating system. +These calls return err == nil to indicate success; otherwise +err is an operating system error describing the failure. +On most systems, that error has type syscall.Errno. +

    +

    +NOTE: This package is locked down. Code outside the standard +Go repository should be migrated to use the corresponding +package in the golang.org/x/sys repository. That is also where updates +required by new systems or versions should be applied. +See https://golang.org/s/go1.4-syscall for more information. +

    + +
    +
    + + +
    + +
    +

    Index ▾

    + + +
    +
    + +
    Constants
    + + +
    Variables
    + + + +
    func Accept(fd int) (nfd int, sa Sockaddr, err error)
    + + +
    func Accept4(fd int, flags int) (nfd int, sa Sockaddr, err error)
    + + +
    func Access(path string, mode uint32) (err error)
    + + +
    func Acct(path string) (err error)
    + + +
    func Adjtimex(buf *Timex) (state int, err error)
    + + +
    func AttachLsf(fd int, i []SockFilter) error
    + + +
    func Bind(fd int, sa Sockaddr) (err error)
    + + +
    func BindToDevice(fd int, device string) (err error)
    + + +
    func BytePtrFromString(s string) (*byte, error)
    + + +
    func ByteSliceFromString(s string) ([]byte, error)
    + + +
    func Chdir(path string) (err error)
    + + +
    func Chmod(path string, mode uint32) (err error)
    + + +
    func Chown(path string, uid int, gid int) (err error)
    + + +
    func Chroot(path string) (err error)
    + + +
    func Clearenv()
    + + +
    func Close(fd int) (err error)
    + + +
    func CloseOnExec(fd int)
    + + +
    func CmsgLen(datalen int) int
    + + +
    func CmsgSpace(datalen int) int
    + + +
    func Connect(fd int, sa Sockaddr) (err error)
    + + +
    func Creat(path string, mode uint32) (fd int, err error)
    + + +
    func DetachLsf(fd int) error
    + + +
    func Dup(oldfd int) (fd int, err error)
    + + +
    func Dup2(oldfd int, newfd int) (err error)
    + + +
    func Dup3(oldfd int, newfd int, flags int) (err error)
    + + +
    func Environ() []string
    + + +
    func EpollCreate(size int) (fd int, err error)
    + + +
    func EpollCreate1(flag int) (fd int, err error)
    + + +
    func EpollCtl(epfd int, op int, fd int, event *EpollEvent) (err error)
    + + +
    func EpollWait(epfd int, events []EpollEvent, msec int) (n int, err error)
    + + +
    func Exec(argv0 string, argv []string, envv []string) (err error)
    + + +
    func Exit(code int)
    + + +
    func Faccessat(dirfd int, path string, mode uint32, flags int) (err error)
    + + +
    func Fallocate(fd int, mode uint32, off int64, len int64) (err error)
    + + +
    func Fchdir(fd int) (err error)
    + + +
    func Fchmod(fd int, mode uint32) (err error)
    + + +
    func Fchmodat(dirfd int, path string, mode uint32, flags int) (err error)
    + + +
    func Fchown(fd int, uid int, gid int) (err error)
    + + +
    func Fchownat(dirfd int, path string, uid int, gid int, flags int) (err error)
    + + +
    func FcntlFlock(fd uintptr, cmd int, lk *Flock_t) error
    + + +
    func Fdatasync(fd int) (err error)
    + + +
    func Flock(fd int, how int) (err error)
    + + +
    func ForkExec(argv0 string, argv []string, attr *ProcAttr) (pid int, err error)
    + + +
    func Fstat(fd int, stat *Stat_t) (err error)
    + + +
    func Fstatfs(fd int, buf *Statfs_t) (err error)
    + + +
    func Fsync(fd int) (err error)
    + + +
    func Ftruncate(fd int, length int64) (err error)
    + + +
    func Futimes(fd int, tv []Timeval) (err error)
    + + +
    func Futimesat(dirfd int, path string, tv []Timeval) (err error)
    + + +
    func Getcwd(buf []byte) (n int, err error)
    + + +
    func Getdents(fd int, buf []byte) (n int, err error)
    + + +
    func Getegid() (egid int)
    + + +
    func Getenv(key string) (value string, found bool)
    + + +
    func Geteuid() (euid int)
    + + +
    func Getgid() (gid int)
    + + +
    func Getgroups() (gids []int, err error)
    + + +
    func Getpagesize() int
    + + +
    func Getpgid(pid int) (pgid int, err error)
    + + +
    func Getpgrp() (pid int)
    + + +
    func Getpid() (pid int)
    + + +
    func Getppid() (ppid int)
    + + +
    func Getpriority(which int, who int) (prio int, err error)
    + + +
    func Getrlimit(resource int, rlim *Rlimit) (err error)
    + + +
    func Getrusage(who int, rusage *Rusage) (err error)
    + + +
    func GetsockoptInet4Addr(fd, level, opt int) (value [4]byte, err error)
    + + +
    func GetsockoptInt(fd, level, opt int) (value int, err error)
    + + +
    func Gettid() (tid int)
    + + +
    func Gettimeofday(tv *Timeval) (err error)
    + + +
    func Getuid() (uid int)
    + + +
    func Getwd() (wd string, err error)
    + + +
    func Getxattr(path string, attr string, dest []byte) (sz int, err error)
    + + +
    func InotifyAddWatch(fd int, pathname string, mask uint32) (watchdesc int, err error)
    + + +
    func InotifyInit() (fd int, err error)
    + + +
    func InotifyInit1(flags int) (fd int, err error)
    + + +
    func InotifyRmWatch(fd int, watchdesc uint32) (success int, err error)
    + + +
    func Ioperm(from int, num int, on int) (err error)
    + + +
    func Iopl(level int) (err error)
    + + +
    func Kill(pid int, sig Signal) (err error)
    + + +
    func Klogctl(typ int, buf []byte) (n int, err error)
    + + +
    func Lchown(path string, uid int, gid int) (err error)
    + + +
    func Link(oldpath string, newpath string) (err error)
    + + +
    func Listen(s int, n int) (err error)
    + + +
    func Listxattr(path string, dest []byte) (sz int, err error)
    + + +
    func LsfSocket(ifindex, proto int) (int, error)
    + + +
    func Lstat(path string, stat *Stat_t) (err error)
    + + +
    func Madvise(b []byte, advice int) (err error)
    + + +
    func Mkdir(path string, mode uint32) (err error)
    + + +
    func Mkdirat(dirfd int, path string, mode uint32) (err error)
    + + +
    func Mkfifo(path string, mode uint32) (err error)
    + + +
    func Mknod(path string, mode uint32, dev int) (err error)
    + + +
    func Mknodat(dirfd int, path string, mode uint32, dev int) (err error)
    + + +
    func Mlock(b []byte) (err error)
    + + +
    func Mlockall(flags int) (err error)
    + + +
    func Mmap(fd int, offset int64, length int, prot int, flags int) (data []byte, err error)
    + + +
    func Mount(source string, target string, fstype string, flags uintptr, data string) (err error)
    + + +
    func Mprotect(b []byte, prot int) (err error)
    + + +
    func Munlock(b []byte) (err error)
    + + +
    func Munlockall() (err error)
    + + +
    func Munmap(b []byte) (err error)
    + + +
    func Nanosleep(time *Timespec, leftover *Timespec) (err error)
    + + +
    func NetlinkRIB(proto, family int) ([]byte, error)
    + + +
    func Open(path string, mode int, perm uint32) (fd int, err error)
    + + +
    func Openat(dirfd int, path string, flags int, mode uint32) (fd int, err error)
    + + +
    func ParseDirent(buf []byte, max int, names []string) (consumed int, count int, newnames []string)
    + + +
    func ParseNetlinkMessage(b []byte) ([]NetlinkMessage, error)
    + + +
    func ParseNetlinkRouteAttr(m *NetlinkMessage) ([]NetlinkRouteAttr, error)
    + + +
    func ParseSocketControlMessage(b []byte) ([]SocketControlMessage, error)
    + + +
    func ParseUnixRights(m *SocketControlMessage) ([]int, error)
    + + +
    func Pause() (err error)
    + + +
    func Pipe(p []int) (err error)
    + + +
    func Pipe2(p []int, flags int) (err error)
    + + +
    func PivotRoot(newroot string, putold string) (err error)
    + + +
    func Pread(fd int, p []byte, offset int64) (n int, err error)
    + + +
    func PtraceAttach(pid int) (err error)
    + + +
    func PtraceCont(pid int, signal int) (err error)
    + + +
    func PtraceDetach(pid int) (err error)
    + + +
    func PtraceGetEventMsg(pid int) (msg uint, err error)
    + + +
    func PtraceGetRegs(pid int, regsout *PtraceRegs) (err error)
    + + +
    func PtracePeekData(pid int, addr uintptr, out []byte) (count int, err error)
    + + +
    func PtracePeekText(pid int, addr uintptr, out []byte) (count int, err error)
    + + +
    func PtracePokeData(pid int, addr uintptr, data []byte) (count int, err error)
    + + +
    func PtracePokeText(pid int, addr uintptr, data []byte) (count int, err error)
    + + +
    func PtraceSetOptions(pid int, options int) (err error)
    + + +
    func PtraceSetRegs(pid int, regs *PtraceRegs) (err error)
    + + +
    func PtraceSingleStep(pid int) (err error)
    + + +
    func PtraceSyscall(pid int, signal int) (err error)
    + + +
    func Pwrite(fd int, p []byte, offset int64) (n int, err error)
    + + +
    func RawSyscall(trap, a1, a2, a3 uintptr) (r1, r2 uintptr, err Errno)
    + + +
    func RawSyscall6(trap, a1, a2, a3, a4, a5, a6 uintptr) (r1, r2 uintptr, err Errno)
    + + +
    func Read(fd int, p []byte) (n int, err error)
    + + +
    func ReadDirent(fd int, buf []byte) (n int, err error)
    + + +
    func Readlink(path string, buf []byte) (n int, err error)
    + + +
    func Reboot(cmd int) (err error)
    + + +
    func Recvfrom(fd int, p []byte, flags int) (n int, from Sockaddr, err error)
    + + +
    func Recvmsg(fd int, p, oob []byte, flags int) (n, oobn int, recvflags int, from Sockaddr, err error)
    + + +
    func Removexattr(path string, attr string) (err error)
    + + +
    func Rename(oldpath string, newpath string) (err error)
    + + +
    func Renameat(olddirfd int, oldpath string, newdirfd int, newpath string) (err error)
    + + +
    func Rmdir(path string) error
    + + +
    func Seek(fd int, offset int64, whence int) (off int64, err error)
    + + +
    func Select(nfd int, r *FdSet, w *FdSet, e *FdSet, timeout *Timeval) (n int, err error)
    + + +
    func Sendfile(outfd int, infd int, offset *int64, count int) (written int, err error)
    + + +
    func Sendmsg(fd int, p, oob []byte, to Sockaddr, flags int) (err error)
    + + +
    func SendmsgN(fd int, p, oob []byte, to Sockaddr, flags int) (n int, err error)
    + + +
    func Sendto(fd int, p []byte, flags int, to Sockaddr) (err error)
    + + +
    func SetLsfPromisc(name string, m bool) error
    + + +
    func SetNonblock(fd int, nonblocking bool) (err error)
    + + +
    func Setdomainname(p []byte) (err error)
    + + +
    func Setenv(key, value string) error
    + + +
    func Setfsgid(gid int) (err error)
    + + +
    func Setfsuid(uid int) (err error)
    + + +
    func Setgid(gid int) (err error)
    + + +
    func Setgroups(gids []int) (err error)
    + + +
    func Sethostname(p []byte) (err error)
    + + +
    func Setpgid(pid int, pgid int) (err error)
    + + +
    func Setpriority(which int, who int, prio int) (err error)
    + + +
    func Setregid(rgid int, egid int) (err error)
    + + +
    func Setresgid(rgid int, egid int, sgid int) (err error)
    + + +
    func Setresuid(ruid int, euid int, suid int) (err error)
    + + +
    func Setreuid(ruid int, euid int) (err error)
    + + +
    func Setrlimit(resource int, rlim *Rlimit) (err error)
    + + +
    func Setsid() (pid int, err error)
    + + +
    func SetsockoptByte(fd, level, opt int, value byte) (err error)
    + + +
    func SetsockoptICMPv6Filter(fd, level, opt int, filter *ICMPv6Filter) error
    + + +
    func SetsockoptIPMreq(fd, level, opt int, mreq *IPMreq) (err error)
    + + +
    func SetsockoptIPMreqn(fd, level, opt int, mreq *IPMreqn) (err error)
    + + +
    func SetsockoptIPv6Mreq(fd, level, opt int, mreq *IPv6Mreq) (err error)
    + + +
    func SetsockoptInet4Addr(fd, level, opt int, value [4]byte) (err error)
    + + +
    func SetsockoptInt(fd, level, opt int, value int) (err error)
    + + +
    func SetsockoptLinger(fd, level, opt int, l *Linger) (err error)
    + + +
    func SetsockoptString(fd, level, opt int, s string) (err error)
    + + +
    func SetsockoptTimeval(fd, level, opt int, tv *Timeval) (err error)
    + + +
    func Settimeofday(tv *Timeval) (err error)
    + + +
    func Setuid(uid int) (err error)
    + + +
    func Setxattr(path string, attr string, data []byte, flags int) (err error)
    + + +
    func Shutdown(fd int, how int) (err error)
    + + +
    func SlicePtrFromStrings(ss []string) ([]*byte, error)
    + + +
    func Socket(domain, typ, proto int) (fd int, err error)
    + + +
    func Socketpair(domain, typ, proto int) (fd [2]int, err error)
    + + +
    func Splice(rfd int, roff *int64, wfd int, woff *int64, len int, flags int) (n int64, err error)
    + + +
    func StartProcess(argv0 string, argv []string, attr *ProcAttr) (pid int, handle uintptr, err error)
    + + +
    func Stat(path string, stat *Stat_t) (err error)
    + + +
    func Statfs(path string, buf *Statfs_t) (err error)
    + + +
    func StringBytePtr(s string) *byte
    + + +
    func StringByteSlice(s string) []byte
    + + +
    func StringSlicePtr(ss []string) []*byte
    + + +
    func Symlink(oldpath string, newpath string) (err error)
    + + +
    func Sync()
    + + +
    func SyncFileRange(fd int, off int64, n int64, flags int) (err error)
    + + +
    func Syscall(trap, a1, a2, a3 uintptr) (r1, r2 uintptr, err Errno)
    + + +
    func Syscall6(trap, a1, a2, a3, a4, a5, a6 uintptr) (r1, r2 uintptr, err Errno)
    + + +
    func Sysinfo(info *Sysinfo_t) (err error)
    + + +
    func Tee(rfd int, wfd int, len int, flags int) (n int64, err error)
    + + +
    func Tgkill(tgid int, tid int, sig Signal) (err error)
    + + +
    func Times(tms *Tms) (ticks uintptr, err error)
    + + +
    func TimespecToNsec(ts Timespec) int64
    + + +
    func TimevalToNsec(tv Timeval) int64
    + + +
    func Truncate(path string, length int64) (err error)
    + + +
    func Umask(mask int) (oldmask int)
    + + +
    func Uname(buf *Utsname) (err error)
    + + +
    func UnixCredentials(ucred *Ucred) []byte
    + + +
    func UnixRights(fds ...int) []byte
    + + +
    func Unlink(path string) error
    + + +
    func Unlinkat(dirfd int, path string) error
    + + +
    func Unmount(target string, flags int) (err error)
    + + +
    func Unsetenv(key string) error
    + + +
    func Unshare(flags int) (err error)
    + + +
    func Ustat(dev int, ubuf *Ustat_t) (err error)
    + + +
    func Utime(path string, buf *Utimbuf) (err error)
    + + +
    func Utimes(path string, tv []Timeval) (err error)
    + + +
    func UtimesNano(path string, ts []Timespec) (err error)
    + + +
    func Wait4(pid int, wstatus *WaitStatus, options int, rusage *Rusage) (wpid int, err error)
    + + +
    func Write(fd int, p []byte) (n int, err error)
    + + + +
    type Cmsghdr
    + + + +
        func (cmsg *Cmsghdr) SetLen(length int)
    + + + +
    type Credential
    + + + + +
    type Dirent
    + + + + +
    type EpollEvent
    + + + + +
    type Errno
    + + + +
        func (e Errno) Error() string
    + + +
        func (e Errno) Temporary() bool
    + + +
        func (e Errno) Timeout() bool
    + + + +
    type FdSet
    + + + + +
    type Flock_t
    + + + + +
    type Fsid
    + + + + +
    type ICMPv6Filter
    + + +
        func GetsockoptICMPv6Filter(fd, level, opt int) (*ICMPv6Filter, error)
    + + + + +
    type IPMreq
    + + +
        func GetsockoptIPMreq(fd, level, opt int) (*IPMreq, error)
    + + + + +
    type IPMreqn
    + + +
        func GetsockoptIPMreqn(fd, level, opt int) (*IPMreqn, error)
    + + + + +
    type IPv6MTUInfo
    + + +
        func GetsockoptIPv6MTUInfo(fd, level, opt int) (*IPv6MTUInfo, error)
    + + + + +
    type IPv6Mreq
    + + +
        func GetsockoptIPv6Mreq(fd, level, opt int) (*IPv6Mreq, error)
    + + + + +
    type IfAddrmsg
    + + + + +
    type IfInfomsg
    + + + + +
    type Inet4Pktinfo
    + + + + +
    type Inet6Pktinfo
    + + + + +
    type InotifyEvent
    + + + + +
    type Iovec
    + + + +
        func (iov *Iovec) SetLen(length int)
    + + + +
    type Linger
    + + + + +
    type Msghdr
    + + + +
        func (msghdr *Msghdr) SetControllen(length int)
    + + + +
    type NetlinkMessage
    + + + + +
    type NetlinkRouteAttr
    + + + + +
    type NetlinkRouteRequest
    + + + + +
    type NlAttr
    + + + + +
    type NlMsgerr
    + + + + +
    type NlMsghdr
    + + + + +
    type ProcAttr
    + + + + +
    type PtraceRegs
    + + + +
        func (r *PtraceRegs) PC() uint64
    + + +
        func (r *PtraceRegs) SetPC(pc uint64)
    + + + +
    type RawSockaddr
    + + + + +
    type RawSockaddrAny
    + + + + +
    type RawSockaddrInet4
    + + + + +
    type RawSockaddrInet6
    + + + + +
    type RawSockaddrLinklayer
    + + + + +
    type RawSockaddrNetlink
    + + + + +
    type RawSockaddrUnix
    + + + + +
    type Rlimit
    + + + + +
    type RtAttr
    + + + + +
    type RtGenmsg
    + + + + +
    type RtMsg
    + + + + +
    type RtNexthop
    + + + + +
    type Rusage
    + + + + +
    type Signal
    + + + +
        func (s Signal) Signal()
    + + +
        func (s Signal) String() string
    + + + +
    type SockFilter
    + + +
        func LsfJump(code, k, jt, jf int) *SockFilter
    + + +
        func LsfStmt(code, k int) *SockFilter
    + + + + +
    type SockFprog
    + + + + +
    type Sockaddr
    + + +
        func Getpeername(fd int) (sa Sockaddr, err error)
    + + +
        func Getsockname(fd int) (sa Sockaddr, err error)
    + + + + +
    type SockaddrInet4
    + + + + +
    type SockaddrInet6
    + + + + +
    type SockaddrLinklayer
    + + + + +
    type SockaddrNetlink
    + + + + +
    type SockaddrUnix
    + + + + +
    type SocketControlMessage
    + + + + +
    type Stat_t
    + + + + +
    type Statfs_t
    + + + + +
    type SysProcAttr
    + + + + +
    type SysProcIDMap
    + + + + +
    type Sysinfo_t
    + + + + +
    type TCPInfo
    + + + + +
    type Termios
    + + + + +
    type Time_t
    + + +
        func Time(t *Time_t) (tt Time_t, err error)
    + + + + +
    type Timespec
    + + +
        func NsecToTimespec(nsec int64) (ts Timespec)
    + + + +
        func (ts *Timespec) Nano() int64
    + + +
        func (ts *Timespec) Unix() (sec int64, nsec int64)
    + + + +
    type Timeval
    + + +
        func NsecToTimeval(nsec int64) (tv Timeval)
    + + + +
        func (tv *Timeval) Nano() int64
    + + +
        func (tv *Timeval) Unix() (sec int64, nsec int64)
    + + + +
    type Timex
    + + + + +
    type Tms
    + + + + +
    type Ucred
    + + +
        func GetsockoptUcred(fd, level, opt int) (*Ucred, error)
    + + +
        func ParseUnixCredentials(m *SocketControlMessage) (*Ucred, error)
    + + + + +
    type Ustat_t
    + + + + +
    type Utimbuf
    + + + + +
    type Utsname
    + + + + +
    type WaitStatus
    + + + +
        func (w WaitStatus) Continued() bool
    + + +
        func (w WaitStatus) CoreDump() bool
    + + +
        func (w WaitStatus) ExitStatus() int
    + + +
        func (w WaitStatus) Exited() bool
    + + +
        func (w WaitStatus) Signal() Signal
    + + +
        func (w WaitStatus) Signaled() bool
    + + +
        func (w WaitStatus) StopSignal() Signal
    + + +
        func (w WaitStatus) Stopped() bool
    + + +
        func (w WaitStatus) TrapCause() int
    + + + +
    +
    + + + + +

    Package files

    +

    + + + env_unix.go + + exec_linux.go + + exec_unix.go + + flock.go + + lsf_linux.go + + msan0.go + + netlink_linux.go + + sockcmsg_linux.go + + sockcmsg_unix.go + + str.go + + syscall.go + + syscall_linux.go + + syscall_linux_amd64.go + + syscall_unix.go + + zerrors_linux_amd64.go + + zsyscall_linux_amd64.go + + zsysnum_linux_amd64.go + + ztypes_linux_amd64.go + + +

    + +
    +
    + + + + +

    Constants

    + +
    const (
    +    AF_ALG                           = 0x26
    +    AF_APPLETALK                     = 0x5
    +    AF_ASH                           = 0x12
    +    AF_ATMPVC                        = 0x8
    +    AF_ATMSVC                        = 0x14
    +    AF_AX25                          = 0x3
    +    AF_BLUETOOTH                     = 0x1f
    +    AF_BRIDGE                        = 0x7
    +    AF_CAIF                          = 0x25
    +    AF_CAN                           = 0x1d
    +    AF_DECnet                        = 0xc
    +    AF_ECONET                        = 0x13
    +    AF_FILE                          = 0x1
    +    AF_IEEE802154                    = 0x24
    +    AF_INET                          = 0x2
    +    AF_INET6                         = 0xa
    +    AF_IPX                           = 0x4
    +    AF_IRDA                          = 0x17
    +    AF_ISDN                          = 0x22
    +    AF_IUCV                          = 0x20
    +    AF_KEY                           = 0xf
    +    AF_LLC                           = 0x1a
    +    AF_LOCAL                         = 0x1
    +    AF_MAX                           = 0x27
    +    AF_NETBEUI                       = 0xd
    +    AF_NETLINK                       = 0x10
    +    AF_NETROM                        = 0x6
    +    AF_PACKET                        = 0x11
    +    AF_PHONET                        = 0x23
    +    AF_PPPOX                         = 0x18
    +    AF_RDS                           = 0x15
    +    AF_ROSE                          = 0xb
    +    AF_ROUTE                         = 0x10
    +    AF_RXRPC                         = 0x21
    +    AF_SECURITY                      = 0xe
    +    AF_SNA                           = 0x16
    +    AF_TIPC                          = 0x1e
    +    AF_UNIX                          = 0x1
    +    AF_UNSPEC                        = 0x0
    +    AF_WANPIPE                       = 0x19
    +    AF_X25                           = 0x9
    +    ARPHRD_ADAPT                     = 0x108
    +    ARPHRD_APPLETLK                  = 0x8
    +    ARPHRD_ARCNET                    = 0x7
    +    ARPHRD_ASH                       = 0x30d
    +    ARPHRD_ATM                       = 0x13
    +    ARPHRD_AX25                      = 0x3
    +    ARPHRD_BIF                       = 0x307
    +    ARPHRD_CHAOS                     = 0x5
    +    ARPHRD_CISCO                     = 0x201
    +    ARPHRD_CSLIP                     = 0x101
    +    ARPHRD_CSLIP6                    = 0x103
    +    ARPHRD_DDCMP                     = 0x205
    +    ARPHRD_DLCI                      = 0xf
    +    ARPHRD_ECONET                    = 0x30e
    +    ARPHRD_EETHER                    = 0x2
    +    ARPHRD_ETHER                     = 0x1
    +    ARPHRD_EUI64                     = 0x1b
    +    ARPHRD_FCAL                      = 0x311
    +    ARPHRD_FCFABRIC                  = 0x313
    +    ARPHRD_FCPL                      = 0x312
    +    ARPHRD_FCPP                      = 0x310
    +    ARPHRD_FDDI                      = 0x306
    +    ARPHRD_FRAD                      = 0x302
    +    ARPHRD_HDLC                      = 0x201
    +    ARPHRD_HIPPI                     = 0x30c
    +    ARPHRD_HWX25                     = 0x110
    +    ARPHRD_IEEE1394                  = 0x18
    +    ARPHRD_IEEE802                   = 0x6
    +    ARPHRD_IEEE80211                 = 0x321
    +    ARPHRD_IEEE80211_PRISM           = 0x322
    +    ARPHRD_IEEE80211_RADIOTAP        = 0x323
    +    ARPHRD_IEEE802154                = 0x324
    +    ARPHRD_IEEE802154_PHY            = 0x325
    +    ARPHRD_IEEE802_TR                = 0x320
    +    ARPHRD_INFINIBAND                = 0x20
    +    ARPHRD_IPDDP                     = 0x309
    +    ARPHRD_IPGRE                     = 0x30a
    +    ARPHRD_IRDA                      = 0x30f
    +    ARPHRD_LAPB                      = 0x204
    +    ARPHRD_LOCALTLK                  = 0x305
    +    ARPHRD_LOOPBACK                  = 0x304
    +    ARPHRD_METRICOM                  = 0x17
    +    ARPHRD_NETROM                    = 0x0
    +    ARPHRD_NONE                      = 0xfffe
    +    ARPHRD_PIMREG                    = 0x30b
    +    ARPHRD_PPP                       = 0x200
    +    ARPHRD_PRONET                    = 0x4
    +    ARPHRD_RAWHDLC                   = 0x206
    +    ARPHRD_ROSE                      = 0x10e
    +    ARPHRD_RSRVD                     = 0x104
    +    ARPHRD_SIT                       = 0x308
    +    ARPHRD_SKIP                      = 0x303
    +    ARPHRD_SLIP                      = 0x100
    +    ARPHRD_SLIP6                     = 0x102
    +    ARPHRD_TUNNEL                    = 0x300
    +    ARPHRD_TUNNEL6                   = 0x301
    +    ARPHRD_VOID                      = 0xffff
    +    ARPHRD_X25                       = 0x10f
    +    BPF_A                            = 0x10
    +    BPF_ABS                          = 0x20
    +    BPF_ADD                          = 0x0
    +    BPF_ALU                          = 0x4
    +    BPF_AND                          = 0x50
    +    BPF_B                            = 0x10
    +    BPF_DIV                          = 0x30
    +    BPF_H                            = 0x8
    +    BPF_IMM                          = 0x0
    +    BPF_IND                          = 0x40
    +    BPF_JA                           = 0x0
    +    BPF_JEQ                          = 0x10
    +    BPF_JGE                          = 0x30
    +    BPF_JGT                          = 0x20
    +    BPF_JMP                          = 0x5
    +    BPF_JSET                         = 0x40
    +    BPF_K                            = 0x0
    +    BPF_LD                           = 0x0
    +    BPF_LDX                          = 0x1
    +    BPF_LEN                          = 0x80
    +    BPF_LSH                          = 0x60
    +    BPF_MAJOR_VERSION                = 0x1
    +    BPF_MAXINSNS                     = 0x1000
    +    BPF_MEM                          = 0x60
    +    BPF_MEMWORDS                     = 0x10
    +    BPF_MINOR_VERSION                = 0x1
    +    BPF_MISC                         = 0x7
    +    BPF_MSH                          = 0xa0
    +    BPF_MUL                          = 0x20
    +    BPF_NEG                          = 0x80
    +    BPF_OR                           = 0x40
    +    BPF_RET                          = 0x6
    +    BPF_RSH                          = 0x70
    +    BPF_ST                           = 0x2
    +    BPF_STX                          = 0x3
    +    BPF_SUB                          = 0x10
    +    BPF_TAX                          = 0x0
    +    BPF_TXA                          = 0x80
    +    BPF_W                            = 0x0
    +    BPF_X                            = 0x8
    +    CLONE_CHILD_CLEARTID             = 0x200000
    +    CLONE_CHILD_SETTID               = 0x1000000
    +    CLONE_DETACHED                   = 0x400000
    +    CLONE_FILES                      = 0x400
    +    CLONE_FS                         = 0x200
    +    CLONE_IO                         = 0x80000000
    +    CLONE_NEWIPC                     = 0x8000000
    +    CLONE_NEWNET                     = 0x40000000
    +    CLONE_NEWNS                      = 0x20000
    +    CLONE_NEWPID                     = 0x20000000
    +    CLONE_NEWUSER                    = 0x10000000
    +    CLONE_NEWUTS                     = 0x4000000
    +    CLONE_PARENT                     = 0x8000
    +    CLONE_PARENT_SETTID              = 0x100000
    +    CLONE_PTRACE                     = 0x2000
    +    CLONE_SETTLS                     = 0x80000
    +    CLONE_SIGHAND                    = 0x800
    +    CLONE_SYSVSEM                    = 0x40000
    +    CLONE_THREAD                     = 0x10000
    +    CLONE_UNTRACED                   = 0x800000
    +    CLONE_VFORK                      = 0x4000
    +    CLONE_VM                         = 0x100
    +    DT_BLK                           = 0x6
    +    DT_CHR                           = 0x2
    +    DT_DIR                           = 0x4
    +    DT_FIFO                          = 0x1
    +    DT_LNK                           = 0xa
    +    DT_REG                           = 0x8
    +    DT_SOCK                          = 0xc
    +    DT_UNKNOWN                       = 0x0
    +    DT_WHT                           = 0xe
    +    EPOLLERR                         = 0x8
    +    EPOLLET                          = -0x80000000
    +    EPOLLHUP                         = 0x10
    +    EPOLLIN                          = 0x1
    +    EPOLLMSG                         = 0x400
    +    EPOLLONESHOT                     = 0x40000000
    +    EPOLLOUT                         = 0x4
    +    EPOLLPRI                         = 0x2
    +    EPOLLRDBAND                      = 0x80
    +    EPOLLRDHUP                       = 0x2000
    +    EPOLLRDNORM                      = 0x40
    +    EPOLLWRBAND                      = 0x200
    +    EPOLLWRNORM                      = 0x100
    +    EPOLL_CLOEXEC                    = 0x80000
    +    EPOLL_CTL_ADD                    = 0x1
    +    EPOLL_CTL_DEL                    = 0x2
    +    EPOLL_CTL_MOD                    = 0x3
    +    EPOLL_NONBLOCK                   = 0x800
    +    ETH_P_1588                       = 0x88f7
    +    ETH_P_8021Q                      = 0x8100
    +    ETH_P_802_2                      = 0x4
    +    ETH_P_802_3                      = 0x1
    +    ETH_P_AARP                       = 0x80f3
    +    ETH_P_ALL                        = 0x3
    +    ETH_P_AOE                        = 0x88a2
    +    ETH_P_ARCNET                     = 0x1a
    +    ETH_P_ARP                        = 0x806
    +    ETH_P_ATALK                      = 0x809b
    +    ETH_P_ATMFATE                    = 0x8884
    +    ETH_P_ATMMPOA                    = 0x884c
    +    ETH_P_AX25                       = 0x2
    +    ETH_P_BPQ                        = 0x8ff
    +    ETH_P_CAIF                       = 0xf7
    +    ETH_P_CAN                        = 0xc
    +    ETH_P_CONTROL                    = 0x16
    +    ETH_P_CUST                       = 0x6006
    +    ETH_P_DDCMP                      = 0x6
    +    ETH_P_DEC                        = 0x6000
    +    ETH_P_DIAG                       = 0x6005
    +    ETH_P_DNA_DL                     = 0x6001
    +    ETH_P_DNA_RC                     = 0x6002
    +    ETH_P_DNA_RT                     = 0x6003
    +    ETH_P_DSA                        = 0x1b
    +    ETH_P_ECONET                     = 0x18
    +    ETH_P_EDSA                       = 0xdada
    +    ETH_P_FCOE                       = 0x8906
    +    ETH_P_FIP                        = 0x8914
    +    ETH_P_HDLC                       = 0x19
    +    ETH_P_IEEE802154                 = 0xf6
    +    ETH_P_IEEEPUP                    = 0xa00
    +    ETH_P_IEEEPUPAT                  = 0xa01
    +    ETH_P_IP                         = 0x800
    +    ETH_P_IPV6                       = 0x86dd
    +    ETH_P_IPX                        = 0x8137
    +    ETH_P_IRDA                       = 0x17
    +    ETH_P_LAT                        = 0x6004
    +    ETH_P_LINK_CTL                   = 0x886c
    +    ETH_P_LOCALTALK                  = 0x9
    +    ETH_P_LOOP                       = 0x60
    +    ETH_P_MOBITEX                    = 0x15
    +    ETH_P_MPLS_MC                    = 0x8848
    +    ETH_P_MPLS_UC                    = 0x8847
    +    ETH_P_PAE                        = 0x888e
    +    ETH_P_PAUSE                      = 0x8808
    +    ETH_P_PHONET                     = 0xf5
    +    ETH_P_PPPTALK                    = 0x10
    +    ETH_P_PPP_DISC                   = 0x8863
    +    ETH_P_PPP_MP                     = 0x8
    +    ETH_P_PPP_SES                    = 0x8864
    +    ETH_P_PUP                        = 0x200
    +    ETH_P_PUPAT                      = 0x201
    +    ETH_P_RARP                       = 0x8035
    +    ETH_P_SCA                        = 0x6007
    +    ETH_P_SLOW                       = 0x8809
    +    ETH_P_SNAP                       = 0x5
    +    ETH_P_TEB                        = 0x6558
    +    ETH_P_TIPC                       = 0x88ca
    +    ETH_P_TRAILER                    = 0x1c
    +    ETH_P_TR_802_2                   = 0x11
    +    ETH_P_WAN_PPP                    = 0x7
    +    ETH_P_WCCP                       = 0x883e
    +    ETH_P_X25                        = 0x805
    +    FD_CLOEXEC                       = 0x1
    +    FD_SETSIZE                       = 0x400
    +    F_DUPFD                          = 0x0
    +    F_DUPFD_CLOEXEC                  = 0x406
    +    F_EXLCK                          = 0x4
    +    F_GETFD                          = 0x1
    +    F_GETFL                          = 0x3
    +    F_GETLEASE                       = 0x401
    +    F_GETLK                          = 0x5
    +    F_GETLK64                        = 0x5
    +    F_GETOWN                         = 0x9
    +    F_GETOWN_EX                      = 0x10
    +    F_GETPIPE_SZ                     = 0x408
    +    F_GETSIG                         = 0xb
    +    F_LOCK                           = 0x1
    +    F_NOTIFY                         = 0x402
    +    F_OK                             = 0x0
    +    F_RDLCK                          = 0x0
    +    F_SETFD                          = 0x2
    +    F_SETFL                          = 0x4
    +    F_SETLEASE                       = 0x400
    +    F_SETLK                          = 0x6
    +    F_SETLK64                        = 0x6
    +    F_SETLKW                         = 0x7
    +    F_SETLKW64                       = 0x7
    +    F_SETOWN                         = 0x8
    +    F_SETOWN_EX                      = 0xf
    +    F_SETPIPE_SZ                     = 0x407
    +    F_SETSIG                         = 0xa
    +    F_SHLCK                          = 0x8
    +    F_TEST                           = 0x3
    +    F_TLOCK                          = 0x2
    +    F_ULOCK                          = 0x0
    +    F_UNLCK                          = 0x2
    +    F_WRLCK                          = 0x1
    +    ICMPV6_FILTER                    = 0x1
    +    IFA_F_DADFAILED                  = 0x8
    +    IFA_F_DEPRECATED                 = 0x20
    +    IFA_F_HOMEADDRESS                = 0x10
    +    IFA_F_NODAD                      = 0x2
    +    IFA_F_OPTIMISTIC                 = 0x4
    +    IFA_F_PERMANENT                  = 0x80
    +    IFA_F_SECONDARY                  = 0x1
    +    IFA_F_TEMPORARY                  = 0x1
    +    IFA_F_TENTATIVE                  = 0x40
    +    IFA_MAX                          = 0x7
    +    IFF_ALLMULTI                     = 0x200
    +    IFF_AUTOMEDIA                    = 0x4000
    +    IFF_BROADCAST                    = 0x2
    +    IFF_DEBUG                        = 0x4
    +    IFF_DYNAMIC                      = 0x8000
    +    IFF_LOOPBACK                     = 0x8
    +    IFF_MASTER                       = 0x400
    +    IFF_MULTICAST                    = 0x1000
    +    IFF_NOARP                        = 0x80
    +    IFF_NOTRAILERS                   = 0x20
    +    IFF_NO_PI                        = 0x1000
    +    IFF_ONE_QUEUE                    = 0x2000
    +    IFF_POINTOPOINT                  = 0x10
    +    IFF_PORTSEL                      = 0x2000
    +    IFF_PROMISC                      = 0x100
    +    IFF_RUNNING                      = 0x40
    +    IFF_SLAVE                        = 0x800
    +    IFF_TAP                          = 0x2
    +    IFF_TUN                          = 0x1
    +    IFF_TUN_EXCL                     = 0x8000
    +    IFF_UP                           = 0x1
    +    IFF_VNET_HDR                     = 0x4000
    +    IFNAMSIZ                         = 0x10
    +    IN_ACCESS                        = 0x1
    +    IN_ALL_EVENTS                    = 0xfff
    +    IN_ATTRIB                        = 0x4
    +    IN_CLASSA_HOST                   = 0xffffff
    +    IN_CLASSA_MAX                    = 0x80
    +    IN_CLASSA_NET                    = 0xff000000
    +    IN_CLASSA_NSHIFT                 = 0x18
    +    IN_CLASSB_HOST                   = 0xffff
    +    IN_CLASSB_MAX                    = 0x10000
    +    IN_CLASSB_NET                    = 0xffff0000
    +    IN_CLASSB_NSHIFT                 = 0x10
    +    IN_CLASSC_HOST                   = 0xff
    +    IN_CLASSC_NET                    = 0xffffff00
    +    IN_CLASSC_NSHIFT                 = 0x8
    +    IN_CLOEXEC                       = 0x80000
    +    IN_CLOSE                         = 0x18
    +    IN_CLOSE_NOWRITE                 = 0x10
    +    IN_CLOSE_WRITE                   = 0x8
    +    IN_CREATE                        = 0x100
    +    IN_DELETE                        = 0x200
    +    IN_DELETE_SELF                   = 0x400
    +    IN_DONT_FOLLOW                   = 0x2000000
    +    IN_EXCL_UNLINK                   = 0x4000000
    +    IN_IGNORED                       = 0x8000
    +    IN_ISDIR                         = 0x40000000
    +    IN_LOOPBACKNET                   = 0x7f
    +    IN_MASK_ADD                      = 0x20000000
    +    IN_MODIFY                        = 0x2
    +    IN_MOVE                          = 0xc0
    +    IN_MOVED_FROM                    = 0x40
    +    IN_MOVED_TO                      = 0x80
    +    IN_MOVE_SELF                     = 0x800
    +    IN_NONBLOCK                      = 0x800
    +    IN_ONESHOT                       = 0x80000000
    +    IN_ONLYDIR                       = 0x1000000
    +    IN_OPEN                          = 0x20
    +    IN_Q_OVERFLOW                    = 0x4000
    +    IN_UNMOUNT                       = 0x2000
    +    IPPROTO_AH                       = 0x33
    +    IPPROTO_COMP                     = 0x6c
    +    IPPROTO_DCCP                     = 0x21
    +    IPPROTO_DSTOPTS                  = 0x3c
    +    IPPROTO_EGP                      = 0x8
    +    IPPROTO_ENCAP                    = 0x62
    +    IPPROTO_ESP                      = 0x32
    +    IPPROTO_FRAGMENT                 = 0x2c
    +    IPPROTO_GRE                      = 0x2f
    +    IPPROTO_HOPOPTS                  = 0x0
    +    IPPROTO_ICMP                     = 0x1
    +    IPPROTO_ICMPV6                   = 0x3a
    +    IPPROTO_IDP                      = 0x16
    +    IPPROTO_IGMP                     = 0x2
    +    IPPROTO_IP                       = 0x0
    +    IPPROTO_IPIP                     = 0x4
    +    IPPROTO_IPV6                     = 0x29
    +    IPPROTO_MTP                      = 0x5c
    +    IPPROTO_NONE                     = 0x3b
    +    IPPROTO_PIM                      = 0x67
    +    IPPROTO_PUP                      = 0xc
    +    IPPROTO_RAW                      = 0xff
    +    IPPROTO_ROUTING                  = 0x2b
    +    IPPROTO_RSVP                     = 0x2e
    +    IPPROTO_SCTP                     = 0x84
    +    IPPROTO_TCP                      = 0x6
    +    IPPROTO_TP                       = 0x1d
    +    IPPROTO_UDP                      = 0x11
    +    IPPROTO_UDPLITE                  = 0x88
    +    IPV6_2292DSTOPTS                 = 0x4
    +    IPV6_2292HOPLIMIT                = 0x8
    +    IPV6_2292HOPOPTS                 = 0x3
    +    IPV6_2292PKTINFO                 = 0x2
    +    IPV6_2292PKTOPTIONS              = 0x6
    +    IPV6_2292RTHDR                   = 0x5
    +    IPV6_ADDRFORM                    = 0x1
    +    IPV6_ADD_MEMBERSHIP              = 0x14
    +    IPV6_AUTHHDR                     = 0xa
    +    IPV6_CHECKSUM                    = 0x7
    +    IPV6_DROP_MEMBERSHIP             = 0x15
    +    IPV6_DSTOPTS                     = 0x3b
    +    IPV6_HOPLIMIT                    = 0x34
    +    IPV6_HOPOPTS                     = 0x36
    +    IPV6_IPSEC_POLICY                = 0x22
    +    IPV6_JOIN_ANYCAST                = 0x1b
    +    IPV6_JOIN_GROUP                  = 0x14
    +    IPV6_LEAVE_ANYCAST               = 0x1c
    +    IPV6_LEAVE_GROUP                 = 0x15
    +    IPV6_MTU                         = 0x18
    +    IPV6_MTU_DISCOVER                = 0x17
    +    IPV6_MULTICAST_HOPS              = 0x12
    +    IPV6_MULTICAST_IF                = 0x11
    +    IPV6_MULTICAST_LOOP              = 0x13
    +    IPV6_NEXTHOP                     = 0x9
    +    IPV6_PKTINFO                     = 0x32
    +    IPV6_PMTUDISC_DO                 = 0x2
    +    IPV6_PMTUDISC_DONT               = 0x0
    +    IPV6_PMTUDISC_PROBE              = 0x3
    +    IPV6_PMTUDISC_WANT               = 0x1
    +    IPV6_RECVDSTOPTS                 = 0x3a
    +    IPV6_RECVERR                     = 0x19
    +    IPV6_RECVHOPLIMIT                = 0x33
    +    IPV6_RECVHOPOPTS                 = 0x35
    +    IPV6_RECVPKTINFO                 = 0x31
    +    IPV6_RECVRTHDR                   = 0x38
    +    IPV6_RECVTCLASS                  = 0x42
    +    IPV6_ROUTER_ALERT                = 0x16
    +    IPV6_RTHDR                       = 0x39
    +    IPV6_RTHDRDSTOPTS                = 0x37
    +    IPV6_RTHDR_LOOSE                 = 0x0
    +    IPV6_RTHDR_STRICT                = 0x1
    +    IPV6_RTHDR_TYPE_0                = 0x0
    +    IPV6_RXDSTOPTS                   = 0x3b
    +    IPV6_RXHOPOPTS                   = 0x36
    +    IPV6_TCLASS                      = 0x43
    +    IPV6_UNICAST_HOPS                = 0x10
    +    IPV6_V6ONLY                      = 0x1a
    +    IPV6_XFRM_POLICY                 = 0x23
    +    IP_ADD_MEMBERSHIP                = 0x23
    +    IP_ADD_SOURCE_MEMBERSHIP         = 0x27
    +    IP_BLOCK_SOURCE                  = 0x26
    +    IP_DEFAULT_MULTICAST_LOOP        = 0x1
    +    IP_DEFAULT_MULTICAST_TTL         = 0x1
    +    IP_DF                            = 0x4000
    +    IP_DROP_MEMBERSHIP               = 0x24
    +    IP_DROP_SOURCE_MEMBERSHIP        = 0x28
    +    IP_FREEBIND                      = 0xf
    +    IP_HDRINCL                       = 0x3
    +    IP_IPSEC_POLICY                  = 0x10
    +    IP_MAXPACKET                     = 0xffff
    +    IP_MAX_MEMBERSHIPS               = 0x14
    +    IP_MF                            = 0x2000
    +    IP_MINTTL                        = 0x15
    +    IP_MSFILTER                      = 0x29
    +    IP_MSS                           = 0x240
    +    IP_MTU                           = 0xe
    +    IP_MTU_DISCOVER                  = 0xa
    +    IP_MULTICAST_IF                  = 0x20
    +    IP_MULTICAST_LOOP                = 0x22
    +    IP_MULTICAST_TTL                 = 0x21
    +    IP_OFFMASK                       = 0x1fff
    +    IP_OPTIONS                       = 0x4
    +    IP_ORIGDSTADDR                   = 0x14
    +    IP_PASSSEC                       = 0x12
    +    IP_PKTINFO                       = 0x8
    +    IP_PKTOPTIONS                    = 0x9
    +    IP_PMTUDISC                      = 0xa
    +    IP_PMTUDISC_DO                   = 0x2
    +    IP_PMTUDISC_DONT                 = 0x0
    +    IP_PMTUDISC_PROBE                = 0x3
    +    IP_PMTUDISC_WANT                 = 0x1
    +    IP_RECVERR                       = 0xb
    +    IP_RECVOPTS                      = 0x6
    +    IP_RECVORIGDSTADDR               = 0x14
    +    IP_RECVRETOPTS                   = 0x7
    +    IP_RECVTOS                       = 0xd
    +    IP_RECVTTL                       = 0xc
    +    IP_RETOPTS                       = 0x7
    +    IP_RF                            = 0x8000
    +    IP_ROUTER_ALERT                  = 0x5
    +    IP_TOS                           = 0x1
    +    IP_TRANSPARENT                   = 0x13
    +    IP_TTL                           = 0x2
    +    IP_UNBLOCK_SOURCE                = 0x25
    +    IP_XFRM_POLICY                   = 0x11
    +    LINUX_REBOOT_CMD_CAD_OFF         = 0x0
    +    LINUX_REBOOT_CMD_CAD_ON          = 0x89abcdef
    +    LINUX_REBOOT_CMD_HALT            = 0xcdef0123
    +    LINUX_REBOOT_CMD_KEXEC           = 0x45584543
    +    LINUX_REBOOT_CMD_POWER_OFF       = 0x4321fedc
    +    LINUX_REBOOT_CMD_RESTART         = 0x1234567
    +    LINUX_REBOOT_CMD_RESTART2        = 0xa1b2c3d4
    +    LINUX_REBOOT_CMD_SW_SUSPEND      = 0xd000fce2
    +    LINUX_REBOOT_MAGIC1              = 0xfee1dead
    +    LINUX_REBOOT_MAGIC2              = 0x28121969
    +    LOCK_EX                          = 0x2
    +    LOCK_NB                          = 0x4
    +    LOCK_SH                          = 0x1
    +    LOCK_UN                          = 0x8
    +    MADV_DOFORK                      = 0xb
    +    MADV_DONTFORK                    = 0xa
    +    MADV_DONTNEED                    = 0x4
    +    MADV_HUGEPAGE                    = 0xe
    +    MADV_HWPOISON                    = 0x64
    +    MADV_MERGEABLE                   = 0xc
    +    MADV_NOHUGEPAGE                  = 0xf
    +    MADV_NORMAL                      = 0x0
    +    MADV_RANDOM                      = 0x1
    +    MADV_REMOVE                      = 0x9
    +    MADV_SEQUENTIAL                  = 0x2
    +    MADV_UNMERGEABLE                 = 0xd
    +    MADV_WILLNEED                    = 0x3
    +    MAP_32BIT                        = 0x40
    +    MAP_ANON                         = 0x20
    +    MAP_ANONYMOUS                    = 0x20
    +    MAP_DENYWRITE                    = 0x800
    +    MAP_EXECUTABLE                   = 0x1000
    +    MAP_FILE                         = 0x0
    +    MAP_FIXED                        = 0x10
    +    MAP_GROWSDOWN                    = 0x100
    +    MAP_HUGETLB                      = 0x40000
    +    MAP_LOCKED                       = 0x2000
    +    MAP_NONBLOCK                     = 0x10000
    +    MAP_NORESERVE                    = 0x4000
    +    MAP_POPULATE                     = 0x8000
    +    MAP_PRIVATE                      = 0x2
    +    MAP_SHARED                       = 0x1
    +    MAP_STACK                        = 0x20000
    +    MAP_TYPE                         = 0xf
    +    MCL_CURRENT                      = 0x1
    +    MCL_FUTURE                       = 0x2
    +    MNT_DETACH                       = 0x2
    +    MNT_EXPIRE                       = 0x4
    +    MNT_FORCE                        = 0x1
    +    MSG_CMSG_CLOEXEC                 = 0x40000000
    +    MSG_CONFIRM                      = 0x800
    +    MSG_CTRUNC                       = 0x8
    +    MSG_DONTROUTE                    = 0x4
    +    MSG_DONTWAIT                     = 0x40
    +    MSG_EOR                          = 0x80
    +    MSG_ERRQUEUE                     = 0x2000
    +    MSG_FASTOPEN                     = 0x20000000
    +    MSG_FIN                          = 0x200
    +    MSG_MORE                         = 0x8000
    +    MSG_NOSIGNAL                     = 0x4000
    +    MSG_OOB                          = 0x1
    +    MSG_PEEK                         = 0x2
    +    MSG_PROXY                        = 0x10
    +    MSG_RST                          = 0x1000
    +    MSG_SYN                          = 0x400
    +    MSG_TRUNC                        = 0x20
    +    MSG_TRYHARD                      = 0x4
    +    MSG_WAITALL                      = 0x100
    +    MSG_WAITFORONE                   = 0x10000
    +    MS_ACTIVE                        = 0x40000000
    +    MS_ASYNC                         = 0x1
    +    MS_BIND                          = 0x1000
    +    MS_DIRSYNC                       = 0x80
    +    MS_INVALIDATE                    = 0x2
    +    MS_I_VERSION                     = 0x800000
    +    MS_KERNMOUNT                     = 0x400000
    +    MS_MANDLOCK                      = 0x40
    +    MS_MGC_MSK                       = 0xffff0000
    +    MS_MGC_VAL                       = 0xc0ed0000
    +    MS_MOVE                          = 0x2000
    +    MS_NOATIME                       = 0x400
    +    MS_NODEV                         = 0x4
    +    MS_NODIRATIME                    = 0x800
    +    MS_NOEXEC                        = 0x8
    +    MS_NOSUID                        = 0x2
    +    MS_NOUSER                        = -0x80000000
    +    MS_POSIXACL                      = 0x10000
    +    MS_PRIVATE                       = 0x40000
    +    MS_RDONLY                        = 0x1
    +    MS_REC                           = 0x4000
    +    MS_RELATIME                      = 0x200000
    +    MS_REMOUNT                       = 0x20
    +    MS_RMT_MASK                      = 0x800051
    +    MS_SHARED                        = 0x100000
    +    MS_SILENT                        = 0x8000
    +    MS_SLAVE                         = 0x80000
    +    MS_STRICTATIME                   = 0x1000000
    +    MS_SYNC                          = 0x4
    +    MS_SYNCHRONOUS                   = 0x10
    +    MS_UNBINDABLE                    = 0x20000
    +    NAME_MAX                         = 0xff
    +    NETLINK_ADD_MEMBERSHIP           = 0x1
    +    NETLINK_AUDIT                    = 0x9
    +    NETLINK_BROADCAST_ERROR          = 0x4
    +    NETLINK_CONNECTOR                = 0xb
    +    NETLINK_DNRTMSG                  = 0xe
    +    NETLINK_DROP_MEMBERSHIP          = 0x2
    +    NETLINK_ECRYPTFS                 = 0x13
    +    NETLINK_FIB_LOOKUP               = 0xa
    +    NETLINK_FIREWALL                 = 0x3
    +    NETLINK_GENERIC                  = 0x10
    +    NETLINK_INET_DIAG                = 0x4
    +    NETLINK_IP6_FW                   = 0xd
    +    NETLINK_ISCSI                    = 0x8
    +    NETLINK_KOBJECT_UEVENT           = 0xf
    +    NETLINK_NETFILTER                = 0xc
    +    NETLINK_NFLOG                    = 0x5
    +    NETLINK_NO_ENOBUFS               = 0x5
    +    NETLINK_PKTINFO                  = 0x3
    +    NETLINK_ROUTE                    = 0x0
    +    NETLINK_SCSITRANSPORT            = 0x12
    +    NETLINK_SELINUX                  = 0x7
    +    NETLINK_UNUSED                   = 0x1
    +    NETLINK_USERSOCK                 = 0x2
    +    NETLINK_XFRM                     = 0x6
    +    NLA_ALIGNTO                      = 0x4
    +    NLA_F_NESTED                     = 0x8000
    +    NLA_F_NET_BYTEORDER              = 0x4000
    +    NLA_HDRLEN                       = 0x4
    +    NLMSG_ALIGNTO                    = 0x4
    +    NLMSG_DONE                       = 0x3
    +    NLMSG_ERROR                      = 0x2
    +    NLMSG_HDRLEN                     = 0x10
    +    NLMSG_MIN_TYPE                   = 0x10
    +    NLMSG_NOOP                       = 0x1
    +    NLMSG_OVERRUN                    = 0x4
    +    NLM_F_ACK                        = 0x4
    +    NLM_F_APPEND                     = 0x800
    +    NLM_F_ATOMIC                     = 0x400
    +    NLM_F_CREATE                     = 0x400
    +    NLM_F_DUMP                       = 0x300
    +    NLM_F_ECHO                       = 0x8
    +    NLM_F_EXCL                       = 0x200
    +    NLM_F_MATCH                      = 0x200
    +    NLM_F_MULTI                      = 0x2
    +    NLM_F_REPLACE                    = 0x100
    +    NLM_F_REQUEST                    = 0x1
    +    NLM_F_ROOT                       = 0x100
    +    O_ACCMODE                        = 0x3
    +    O_APPEND                         = 0x400
    +    O_ASYNC                          = 0x2000
    +    O_CLOEXEC                        = 0x80000
    +    O_CREAT                          = 0x40
    +    O_DIRECT                         = 0x4000
    +    O_DIRECTORY                      = 0x10000
    +    O_DSYNC                          = 0x1000
    +    O_EXCL                           = 0x80
    +    O_FSYNC                          = 0x101000
    +    O_LARGEFILE                      = 0x0
    +    O_NDELAY                         = 0x800
    +    O_NOATIME                        = 0x40000
    +    O_NOCTTY                         = 0x100
    +    O_NOFOLLOW                       = 0x20000
    +    O_NONBLOCK                       = 0x800
    +    O_RDONLY                         = 0x0
    +    O_RDWR                           = 0x2
    +    O_RSYNC                          = 0x101000
    +    O_SYNC                           = 0x101000
    +    O_TRUNC                          = 0x200
    +    O_WRONLY                         = 0x1
    +    PACKET_ADD_MEMBERSHIP            = 0x1
    +    PACKET_BROADCAST                 = 0x1
    +    PACKET_DROP_MEMBERSHIP           = 0x2
    +    PACKET_FASTROUTE                 = 0x6
    +    PACKET_HOST                      = 0x0
    +    PACKET_LOOPBACK                  = 0x5
    +    PACKET_MR_ALLMULTI               = 0x2
    +    PACKET_MR_MULTICAST              = 0x0
    +    PACKET_MR_PROMISC                = 0x1
    +    PACKET_MULTICAST                 = 0x2
    +    PACKET_OTHERHOST                 = 0x3
    +    PACKET_OUTGOING                  = 0x4
    +    PACKET_RECV_OUTPUT               = 0x3
    +    PACKET_RX_RING                   = 0x5
    +    PACKET_STATISTICS                = 0x6
    +    PRIO_PGRP                        = 0x1
    +    PRIO_PROCESS                     = 0x0
    +    PRIO_USER                        = 0x2
    +    PROT_EXEC                        = 0x4
    +    PROT_GROWSDOWN                   = 0x1000000
    +    PROT_GROWSUP                     = 0x2000000
    +    PROT_NONE                        = 0x0
    +    PROT_READ                        = 0x1
    +    PROT_WRITE                       = 0x2
    +    PR_CAPBSET_DROP                  = 0x18
    +    PR_CAPBSET_READ                  = 0x17
    +    PR_ENDIAN_BIG                    = 0x0
    +    PR_ENDIAN_LITTLE                 = 0x1
    +    PR_ENDIAN_PPC_LITTLE             = 0x2
    +    PR_FPEMU_NOPRINT                 = 0x1
    +    PR_FPEMU_SIGFPE                  = 0x2
    +    PR_FP_EXC_ASYNC                  = 0x2
    +    PR_FP_EXC_DISABLED               = 0x0
    +    PR_FP_EXC_DIV                    = 0x10000
    +    PR_FP_EXC_INV                    = 0x100000
    +    PR_FP_EXC_NONRECOV               = 0x1
    +    PR_FP_EXC_OVF                    = 0x20000
    +    PR_FP_EXC_PRECISE                = 0x3
    +    PR_FP_EXC_RES                    = 0x80000
    +    PR_FP_EXC_SW_ENABLE              = 0x80
    +    PR_FP_EXC_UND                    = 0x40000
    +    PR_GET_DUMPABLE                  = 0x3
    +    PR_GET_ENDIAN                    = 0x13
    +    PR_GET_FPEMU                     = 0x9
    +    PR_GET_FPEXC                     = 0xb
    +    PR_GET_KEEPCAPS                  = 0x7
    +    PR_GET_NAME                      = 0x10
    +    PR_GET_PDEATHSIG                 = 0x2
    +    PR_GET_SECCOMP                   = 0x15
    +    PR_GET_SECUREBITS                = 0x1b
    +    PR_GET_TIMERSLACK                = 0x1e
    +    PR_GET_TIMING                    = 0xd
    +    PR_GET_TSC                       = 0x19
    +    PR_GET_UNALIGN                   = 0x5
    +    PR_MCE_KILL                      = 0x21
    +    PR_MCE_KILL_CLEAR                = 0x0
    +    PR_MCE_KILL_DEFAULT              = 0x2
    +    PR_MCE_KILL_EARLY                = 0x1
    +    PR_MCE_KILL_GET                  = 0x22
    +    PR_MCE_KILL_LATE                 = 0x0
    +    PR_MCE_KILL_SET                  = 0x1
    +    PR_SET_DUMPABLE                  = 0x4
    +    PR_SET_ENDIAN                    = 0x14
    +    PR_SET_FPEMU                     = 0xa
    +    PR_SET_FPEXC                     = 0xc
    +    PR_SET_KEEPCAPS                  = 0x8
    +    PR_SET_NAME                      = 0xf
    +    PR_SET_PDEATHSIG                 = 0x1
    +    PR_SET_PTRACER                   = 0x59616d61
    +    PR_SET_SECCOMP                   = 0x16
    +    PR_SET_SECUREBITS                = 0x1c
    +    PR_SET_TIMERSLACK                = 0x1d
    +    PR_SET_TIMING                    = 0xe
    +    PR_SET_TSC                       = 0x1a
    +    PR_SET_UNALIGN                   = 0x6
    +    PR_TASK_PERF_EVENTS_DISABLE      = 0x1f
    +    PR_TASK_PERF_EVENTS_ENABLE       = 0x20
    +    PR_TIMING_STATISTICAL            = 0x0
    +    PR_TIMING_TIMESTAMP              = 0x1
    +    PR_TSC_ENABLE                    = 0x1
    +    PR_TSC_SIGSEGV                   = 0x2
    +    PR_UNALIGN_NOPRINT               = 0x1
    +    PR_UNALIGN_SIGBUS                = 0x2
    +    PTRACE_ARCH_PRCTL                = 0x1e
    +    PTRACE_ATTACH                    = 0x10
    +    PTRACE_CONT                      = 0x7
    +    PTRACE_DETACH                    = 0x11
    +    PTRACE_EVENT_CLONE               = 0x3
    +    PTRACE_EVENT_EXEC                = 0x4
    +    PTRACE_EVENT_EXIT                = 0x6
    +    PTRACE_EVENT_FORK                = 0x1
    +    PTRACE_EVENT_VFORK               = 0x2
    +    PTRACE_EVENT_VFORK_DONE          = 0x5
    +    PTRACE_GETEVENTMSG               = 0x4201
    +    PTRACE_GETFPREGS                 = 0xe
    +    PTRACE_GETFPXREGS                = 0x12
    +    PTRACE_GETREGS                   = 0xc
    +    PTRACE_GETREGSET                 = 0x4204
    +    PTRACE_GETSIGINFO                = 0x4202
    +    PTRACE_GET_THREAD_AREA           = 0x19
    +    PTRACE_KILL                      = 0x8
    +    PTRACE_OLDSETOPTIONS             = 0x15
    +    PTRACE_O_MASK                    = 0x7f
    +    PTRACE_O_TRACECLONE              = 0x8
    +    PTRACE_O_TRACEEXEC               = 0x10
    +    PTRACE_O_TRACEEXIT               = 0x40
    +    PTRACE_O_TRACEFORK               = 0x2
    +    PTRACE_O_TRACESYSGOOD            = 0x1
    +    PTRACE_O_TRACEVFORK              = 0x4
    +    PTRACE_O_TRACEVFORKDONE          = 0x20
    +    PTRACE_PEEKDATA                  = 0x2
    +    PTRACE_PEEKTEXT                  = 0x1
    +    PTRACE_PEEKUSR                   = 0x3
    +    PTRACE_POKEDATA                  = 0x5
    +    PTRACE_POKETEXT                  = 0x4
    +    PTRACE_POKEUSR                   = 0x6
    +    PTRACE_SETFPREGS                 = 0xf
    +    PTRACE_SETFPXREGS                = 0x13
    +    PTRACE_SETOPTIONS                = 0x4200
    +    PTRACE_SETREGS                   = 0xd
    +    PTRACE_SETREGSET                 = 0x4205
    +    PTRACE_SETSIGINFO                = 0x4203
    +    PTRACE_SET_THREAD_AREA           = 0x1a
    +    PTRACE_SINGLEBLOCK               = 0x21
    +    PTRACE_SINGLESTEP                = 0x9
    +    PTRACE_SYSCALL                   = 0x18
    +    PTRACE_SYSEMU                    = 0x1f
    +    PTRACE_SYSEMU_SINGLESTEP         = 0x20
    +    PTRACE_TRACEME                   = 0x0
    +    RLIMIT_AS                        = 0x9
    +    RLIMIT_CORE                      = 0x4
    +    RLIMIT_CPU                       = 0x0
    +    RLIMIT_DATA                      = 0x2
    +    RLIMIT_FSIZE                     = 0x1
    +    RLIMIT_NOFILE                    = 0x7
    +    RLIMIT_STACK                     = 0x3
    +    RLIM_INFINITY                    = -0x1
    +    RTAX_ADVMSS                      = 0x8
    +    RTAX_CWND                        = 0x7
    +    RTAX_FEATURES                    = 0xc
    +    RTAX_FEATURE_ALLFRAG             = 0x8
    +    RTAX_FEATURE_ECN                 = 0x1
    +    RTAX_FEATURE_SACK                = 0x2
    +    RTAX_FEATURE_TIMESTAMP           = 0x4
    +    RTAX_HOPLIMIT                    = 0xa
    +    RTAX_INITCWND                    = 0xb
    +    RTAX_INITRWND                    = 0xe
    +    RTAX_LOCK                        = 0x1
    +    RTAX_MAX                         = 0xe
    +    RTAX_MTU                         = 0x2
    +    RTAX_REORDERING                  = 0x9
    +    RTAX_RTO_MIN                     = 0xd
    +    RTAX_RTT                         = 0x4
    +    RTAX_RTTVAR                      = 0x5
    +    RTAX_SSTHRESH                    = 0x6
    +    RTAX_UNSPEC                      = 0x0
    +    RTAX_WINDOW                      = 0x3
    +    RTA_ALIGNTO                      = 0x4
    +    RTA_MAX                          = 0x10
    +    RTCF_DIRECTSRC                   = 0x4000000
    +    RTCF_DOREDIRECT                  = 0x1000000
    +    RTCF_LOG                         = 0x2000000
    +    RTCF_MASQ                        = 0x400000
    +    RTCF_NAT                         = 0x800000
    +    RTCF_VALVE                       = 0x200000
    +    RTF_ADDRCLASSMASK                = 0xf8000000
    +    RTF_ADDRCONF                     = 0x40000
    +    RTF_ALLONLINK                    = 0x20000
    +    RTF_BROADCAST                    = 0x10000000
    +    RTF_CACHE                        = 0x1000000
    +    RTF_DEFAULT                      = 0x10000
    +    RTF_DYNAMIC                      = 0x10
    +    RTF_FLOW                         = 0x2000000
    +    RTF_GATEWAY                      = 0x2
    +    RTF_HOST                         = 0x4
    +    RTF_INTERFACE                    = 0x40000000
    +    RTF_IRTT                         = 0x100
    +    RTF_LINKRT                       = 0x100000
    +    RTF_LOCAL                        = 0x80000000
    +    RTF_MODIFIED                     = 0x20
    +    RTF_MSS                          = 0x40
    +    RTF_MTU                          = 0x40
    +    RTF_MULTICAST                    = 0x20000000
    +    RTF_NAT                          = 0x8000000
    +    RTF_NOFORWARD                    = 0x1000
    +    RTF_NONEXTHOP                    = 0x200000
    +    RTF_NOPMTUDISC                   = 0x4000
    +    RTF_POLICY                       = 0x4000000
    +    RTF_REINSTATE                    = 0x8
    +    RTF_REJECT                       = 0x200
    +    RTF_STATIC                       = 0x400
    +    RTF_THROW                        = 0x2000
    +    RTF_UP                           = 0x1
    +    RTF_WINDOW                       = 0x80
    +    RTF_XRESOLVE                     = 0x800
    +    RTM_BASE                         = 0x10
    +    RTM_DELACTION                    = 0x31
    +    RTM_DELADDR                      = 0x15
    +    RTM_DELADDRLABEL                 = 0x49
    +    RTM_DELLINK                      = 0x11
    +    RTM_DELNEIGH                     = 0x1d
    +    RTM_DELQDISC                     = 0x25
    +    RTM_DELROUTE                     = 0x19
    +    RTM_DELRULE                      = 0x21
    +    RTM_DELTCLASS                    = 0x29
    +    RTM_DELTFILTER                   = 0x2d
    +    RTM_F_CLONED                     = 0x200
    +    RTM_F_EQUALIZE                   = 0x400
    +    RTM_F_NOTIFY                     = 0x100
    +    RTM_F_PREFIX                     = 0x800
    +    RTM_GETACTION                    = 0x32
    +    RTM_GETADDR                      = 0x16
    +    RTM_GETADDRLABEL                 = 0x4a
    +    RTM_GETANYCAST                   = 0x3e
    +    RTM_GETDCB                       = 0x4e
    +    RTM_GETLINK                      = 0x12
    +    RTM_GETMULTICAST                 = 0x3a
    +    RTM_GETNEIGH                     = 0x1e
    +    RTM_GETNEIGHTBL                  = 0x42
    +    RTM_GETQDISC                     = 0x26
    +    RTM_GETROUTE                     = 0x1a
    +    RTM_GETRULE                      = 0x22
    +    RTM_GETTCLASS                    = 0x2a
    +    RTM_GETTFILTER                   = 0x2e
    +    RTM_MAX                          = 0x4f
    +    RTM_NEWACTION                    = 0x30
    +    RTM_NEWADDR                      = 0x14
    +    RTM_NEWADDRLABEL                 = 0x48
    +    RTM_NEWLINK                      = 0x10
    +    RTM_NEWNDUSEROPT                 = 0x44
    +    RTM_NEWNEIGH                     = 0x1c
    +    RTM_NEWNEIGHTBL                  = 0x40
    +    RTM_NEWPREFIX                    = 0x34
    +    RTM_NEWQDISC                     = 0x24
    +    RTM_NEWROUTE                     = 0x18
    +    RTM_NEWRULE                      = 0x20
    +    RTM_NEWTCLASS                    = 0x28
    +    RTM_NEWTFILTER                   = 0x2c
    +    RTM_NR_FAMILIES                  = 0x10
    +    RTM_NR_MSGTYPES                  = 0x40
    +    RTM_SETDCB                       = 0x4f
    +    RTM_SETLINK                      = 0x13
    +    RTM_SETNEIGHTBL                  = 0x43
    +    RTNH_ALIGNTO                     = 0x4
    +    RTNH_F_DEAD                      = 0x1
    +    RTNH_F_ONLINK                    = 0x4
    +    RTNH_F_PERVASIVE                 = 0x2
    +    RTN_MAX                          = 0xb
    +    RTPROT_BIRD                      = 0xc
    +    RTPROT_BOOT                      = 0x3
    +    RTPROT_DHCP                      = 0x10
    +    RTPROT_DNROUTED                  = 0xd
    +    RTPROT_GATED                     = 0x8
    +    RTPROT_KERNEL                    = 0x2
    +    RTPROT_MRT                       = 0xa
    +    RTPROT_NTK                       = 0xf
    +    RTPROT_RA                        = 0x9
    +    RTPROT_REDIRECT                  = 0x1
    +    RTPROT_STATIC                    = 0x4
    +    RTPROT_UNSPEC                    = 0x0
    +    RTPROT_XORP                      = 0xe
    +    RTPROT_ZEBRA                     = 0xb
    +    RT_CLASS_DEFAULT                 = 0xfd
    +    RT_CLASS_LOCAL                   = 0xff
    +    RT_CLASS_MAIN                    = 0xfe
    +    RT_CLASS_MAX                     = 0xff
    +    RT_CLASS_UNSPEC                  = 0x0
    +    RUSAGE_CHILDREN                  = -0x1
    +    RUSAGE_SELF                      = 0x0
    +    RUSAGE_THREAD                    = 0x1
    +    SCM_CREDENTIALS                  = 0x2
    +    SCM_RIGHTS                       = 0x1
    +    SCM_TIMESTAMP                    = 0x1d
    +    SCM_TIMESTAMPING                 = 0x25
    +    SCM_TIMESTAMPNS                  = 0x23
    +    SHUT_RD                          = 0x0
    +    SHUT_RDWR                        = 0x2
    +    SHUT_WR                          = 0x1
    +    SIOCADDDLCI                      = 0x8980
    +    SIOCADDMULTI                     = 0x8931
    +    SIOCADDRT                        = 0x890b
    +    SIOCATMARK                       = 0x8905
    +    SIOCDARP                         = 0x8953
    +    SIOCDELDLCI                      = 0x8981
    +    SIOCDELMULTI                     = 0x8932
    +    SIOCDELRT                        = 0x890c
    +    SIOCDEVPRIVATE                   = 0x89f0
    +    SIOCDIFADDR                      = 0x8936
    +    SIOCDRARP                        = 0x8960
    +    SIOCGARP                         = 0x8954
    +    SIOCGIFADDR                      = 0x8915
    +    SIOCGIFBR                        = 0x8940
    +    SIOCGIFBRDADDR                   = 0x8919
    +    SIOCGIFCONF                      = 0x8912
    +    SIOCGIFCOUNT                     = 0x8938
    +    SIOCGIFDSTADDR                   = 0x8917
    +    SIOCGIFENCAP                     = 0x8925
    +    SIOCGIFFLAGS                     = 0x8913
    +    SIOCGIFHWADDR                    = 0x8927
    +    SIOCGIFINDEX                     = 0x8933
    +    SIOCGIFMAP                       = 0x8970
    +    SIOCGIFMEM                       = 0x891f
    +    SIOCGIFMETRIC                    = 0x891d
    +    SIOCGIFMTU                       = 0x8921
    +    SIOCGIFNAME                      = 0x8910
    +    SIOCGIFNETMASK                   = 0x891b
    +    SIOCGIFPFLAGS                    = 0x8935
    +    SIOCGIFSLAVE                     = 0x8929
    +    SIOCGIFTXQLEN                    = 0x8942
    +    SIOCGPGRP                        = 0x8904
    +    SIOCGRARP                        = 0x8961
    +    SIOCGSTAMP                       = 0x8906
    +    SIOCGSTAMPNS                     = 0x8907
    +    SIOCPROTOPRIVATE                 = 0x89e0
    +    SIOCRTMSG                        = 0x890d
    +    SIOCSARP                         = 0x8955
    +    SIOCSIFADDR                      = 0x8916
    +    SIOCSIFBR                        = 0x8941
    +    SIOCSIFBRDADDR                   = 0x891a
    +    SIOCSIFDSTADDR                   = 0x8918
    +    SIOCSIFENCAP                     = 0x8926
    +    SIOCSIFFLAGS                     = 0x8914
    +    SIOCSIFHWADDR                    = 0x8924
    +    SIOCSIFHWBROADCAST               = 0x8937
    +    SIOCSIFLINK                      = 0x8911
    +    SIOCSIFMAP                       = 0x8971
    +    SIOCSIFMEM                       = 0x8920
    +    SIOCSIFMETRIC                    = 0x891e
    +    SIOCSIFMTU                       = 0x8922
    +    SIOCSIFNAME                      = 0x8923
    +    SIOCSIFNETMASK                   = 0x891c
    +    SIOCSIFPFLAGS                    = 0x8934
    +    SIOCSIFSLAVE                     = 0x8930
    +    SIOCSIFTXQLEN                    = 0x8943
    +    SIOCSPGRP                        = 0x8902
    +    SIOCSRARP                        = 0x8962
    +    SOCK_CLOEXEC                     = 0x80000
    +    SOCK_DCCP                        = 0x6
    +    SOCK_DGRAM                       = 0x2
    +    SOCK_NONBLOCK                    = 0x800
    +    SOCK_PACKET                      = 0xa
    +    SOCK_RAW                         = 0x3
    +    SOCK_RDM                         = 0x4
    +    SOCK_SEQPACKET                   = 0x5
    +    SOCK_STREAM                      = 0x1
    +    SOL_AAL                          = 0x109
    +    SOL_ATM                          = 0x108
    +    SOL_DECNET                       = 0x105
    +    SOL_ICMPV6                       = 0x3a
    +    SOL_IP                           = 0x0
    +    SOL_IPV6                         = 0x29
    +    SOL_IRDA                         = 0x10a
    +    SOL_PACKET                       = 0x107
    +    SOL_RAW                          = 0xff
    +    SOL_SOCKET                       = 0x1
    +    SOL_TCP                          = 0x6
    +    SOL_X25                          = 0x106
    +    SOMAXCONN                        = 0x80
    +    SO_ACCEPTCONN                    = 0x1e
    +    SO_ATTACH_FILTER                 = 0x1a
    +    SO_BINDTODEVICE                  = 0x19
    +    SO_BROADCAST                     = 0x6
    +    SO_BSDCOMPAT                     = 0xe
    +    SO_DEBUG                         = 0x1
    +    SO_DETACH_FILTER                 = 0x1b
    +    SO_DOMAIN                        = 0x27
    +    SO_DONTROUTE                     = 0x5
    +    SO_ERROR                         = 0x4
    +    SO_KEEPALIVE                     = 0x9
    +    SO_LINGER                        = 0xd
    +    SO_MARK                          = 0x24
    +    SO_NO_CHECK                      = 0xb
    +    SO_OOBINLINE                     = 0xa
    +    SO_PASSCRED                      = 0x10
    +    SO_PASSSEC                       = 0x22
    +    SO_PEERCRED                      = 0x11
    +    SO_PEERNAME                      = 0x1c
    +    SO_PEERSEC                       = 0x1f
    +    SO_PRIORITY                      = 0xc
    +    SO_PROTOCOL                      = 0x26
    +    SO_RCVBUF                        = 0x8
    +    SO_RCVBUFFORCE                   = 0x21
    +    SO_RCVLOWAT                      = 0x12
    +    SO_RCVTIMEO                      = 0x14
    +    SO_REUSEADDR                     = 0x2
    +    SO_RXQ_OVFL                      = 0x28
    +    SO_SECURITY_AUTHENTICATION       = 0x16
    +    SO_SECURITY_ENCRYPTION_NETWORK   = 0x18
    +    SO_SECURITY_ENCRYPTION_TRANSPORT = 0x17
    +    SO_SNDBUF                        = 0x7
    +    SO_SNDBUFFORCE                   = 0x20
    +    SO_SNDLOWAT                      = 0x13
    +    SO_SNDTIMEO                      = 0x15
    +    SO_TIMESTAMP                     = 0x1d
    +    SO_TIMESTAMPING                  = 0x25
    +    SO_TIMESTAMPNS                   = 0x23
    +    SO_TYPE                          = 0x3
    +    S_BLKSIZE                        = 0x200
    +    S_IEXEC                          = 0x40
    +    S_IFBLK                          = 0x6000
    +    S_IFCHR                          = 0x2000
    +    S_IFDIR                          = 0x4000
    +    S_IFIFO                          = 0x1000
    +    S_IFLNK                          = 0xa000
    +    S_IFMT                           = 0xf000
    +    S_IFREG                          = 0x8000
    +    S_IFSOCK                         = 0xc000
    +    S_IREAD                          = 0x100
    +    S_IRGRP                          = 0x20
    +    S_IROTH                          = 0x4
    +    S_IRUSR                          = 0x100
    +    S_IRWXG                          = 0x38
    +    S_IRWXO                          = 0x7
    +    S_IRWXU                          = 0x1c0
    +    S_ISGID                          = 0x400
    +    S_ISUID                          = 0x800
    +    S_ISVTX                          = 0x200
    +    S_IWGRP                          = 0x10
    +    S_IWOTH                          = 0x2
    +    S_IWRITE                         = 0x80
    +    S_IWUSR                          = 0x80
    +    S_IXGRP                          = 0x8
    +    S_IXOTH                          = 0x1
    +    S_IXUSR                          = 0x40
    +    TCIFLUSH                         = 0x0
    +    TCIOFLUSH                        = 0x2
    +    TCOFLUSH                         = 0x1
    +    TCP_CONGESTION                   = 0xd
    +    TCP_CORK                         = 0x3
    +    TCP_DEFER_ACCEPT                 = 0x9
    +    TCP_INFO                         = 0xb
    +    TCP_KEEPCNT                      = 0x6
    +    TCP_KEEPIDLE                     = 0x4
    +    TCP_KEEPINTVL                    = 0x5
    +    TCP_LINGER2                      = 0x8
    +    TCP_MAXSEG                       = 0x2
    +    TCP_MAXWIN                       = 0xffff
    +    TCP_MAX_WINSHIFT                 = 0xe
    +    TCP_MD5SIG                       = 0xe
    +    TCP_MD5SIG_MAXKEYLEN             = 0x50
    +    TCP_MSS                          = 0x200
    +    TCP_NODELAY                      = 0x1
    +    TCP_QUICKACK                     = 0xc
    +    TCP_SYNCNT                       = 0x7
    +    TCP_WINDOW_CLAMP                 = 0xa
    +    TIOCCBRK                         = 0x5428
    +    TIOCCONS                         = 0x541d
    +    TIOCEXCL                         = 0x540c
    +    TIOCGDEV                         = 0x80045432
    +    TIOCGETD                         = 0x5424
    +    TIOCGICOUNT                      = 0x545d
    +    TIOCGLCKTRMIOS                   = 0x5456
    +    TIOCGPGRP                        = 0x540f
    +    TIOCGPTN                         = 0x80045430
    +    TIOCGRS485                       = 0x542e
    +    TIOCGSERIAL                      = 0x541e
    +    TIOCGSID                         = 0x5429
    +    TIOCGSOFTCAR                     = 0x5419
    +    TIOCGWINSZ                       = 0x5413
    +    TIOCINQ                          = 0x541b
    +    TIOCLINUX                        = 0x541c
    +    TIOCMBIC                         = 0x5417
    +    TIOCMBIS                         = 0x5416
    +    TIOCMGET                         = 0x5415
    +    TIOCMIWAIT                       = 0x545c
    +    TIOCMSET                         = 0x5418
    +    TIOCM_CAR                        = 0x40
    +    TIOCM_CD                         = 0x40
    +    TIOCM_CTS                        = 0x20
    +    TIOCM_DSR                        = 0x100
    +    TIOCM_DTR                        = 0x2
    +    TIOCM_LE                         = 0x1
    +    TIOCM_RI                         = 0x80
    +    TIOCM_RNG                        = 0x80
    +    TIOCM_RTS                        = 0x4
    +    TIOCM_SR                         = 0x10
    +    TIOCM_ST                         = 0x8
    +    TIOCNOTTY                        = 0x5422
    +    TIOCNXCL                         = 0x540d
    +    TIOCOUTQ                         = 0x5411
    +    TIOCPKT                          = 0x5420
    +    TIOCPKT_DATA                     = 0x0
    +    TIOCPKT_DOSTOP                   = 0x20
    +    TIOCPKT_FLUSHREAD                = 0x1
    +    TIOCPKT_FLUSHWRITE               = 0x2
    +    TIOCPKT_IOCTL                    = 0x40
    +    TIOCPKT_NOSTOP                   = 0x10
    +    TIOCPKT_START                    = 0x8
    +    TIOCPKT_STOP                     = 0x4
    +    TIOCSBRK                         = 0x5427
    +    TIOCSCTTY                        = 0x540e
    +    TIOCSERCONFIG                    = 0x5453
    +    TIOCSERGETLSR                    = 0x5459
    +    TIOCSERGETMULTI                  = 0x545a
    +    TIOCSERGSTRUCT                   = 0x5458
    +    TIOCSERGWILD                     = 0x5454
    +    TIOCSERSETMULTI                  = 0x545b
    +    TIOCSERSWILD                     = 0x5455
    +    TIOCSER_TEMT                     = 0x1
    +    TIOCSETD                         = 0x5423
    +    TIOCSIG                          = 0x40045436
    +    TIOCSLCKTRMIOS                   = 0x5457
    +    TIOCSPGRP                        = 0x5410
    +    TIOCSPTLCK                       = 0x40045431
    +    TIOCSRS485                       = 0x542f
    +    TIOCSSERIAL                      = 0x541f
    +    TIOCSSOFTCAR                     = 0x541a
    +    TIOCSTI                          = 0x5412
    +    TIOCSWINSZ                       = 0x5414
    +    TUNATTACHFILTER                  = 0x401054d5
    +    TUNDETACHFILTER                  = 0x401054d6
    +    TUNGETFEATURES                   = 0x800454cf
    +    TUNGETIFF                        = 0x800454d2
    +    TUNGETSNDBUF                     = 0x800454d3
    +    TUNGETVNETHDRSZ                  = 0x800454d7
    +    TUNSETDEBUG                      = 0x400454c9
    +    TUNSETGROUP                      = 0x400454ce
    +    TUNSETIFF                        = 0x400454ca
    +    TUNSETLINK                       = 0x400454cd
    +    TUNSETNOCSUM                     = 0x400454c8
    +    TUNSETOFFLOAD                    = 0x400454d0
    +    TUNSETOWNER                      = 0x400454cc
    +    TUNSETPERSIST                    = 0x400454cb
    +    TUNSETSNDBUF                     = 0x400454d4
    +    TUNSETTXFILTER                   = 0x400454d1
    +    TUNSETVNETHDRSZ                  = 0x400454d8
    +    WALL                             = 0x40000000
    +    WCLONE                           = 0x80000000
    +    WCONTINUED                       = 0x8
    +    WEXITED                          = 0x4
    +    WNOHANG                          = 0x1
    +    WNOTHREAD                        = 0x20000000
    +    WNOWAIT                          = 0x1000000
    +    WORDSIZE                         = 0x40
    +    WSTOPPED                         = 0x2
    +    WUNTRACED                        = 0x2
    +)
    + + +
    const (
    +    E2BIG           = Errno(0x7)
    +    EACCES          = Errno(0xd)
    +    EADDRINUSE      = Errno(0x62)
    +    EADDRNOTAVAIL   = Errno(0x63)
    +    EADV            = Errno(0x44)
    +    EAFNOSUPPORT    = Errno(0x61)
    +    EAGAIN          = Errno(0xb)
    +    EALREADY        = Errno(0x72)
    +    EBADE           = Errno(0x34)
    +    EBADF           = Errno(0x9)
    +    EBADFD          = Errno(0x4d)
    +    EBADMSG         = Errno(0x4a)
    +    EBADR           = Errno(0x35)
    +    EBADRQC         = Errno(0x38)
    +    EBADSLT         = Errno(0x39)
    +    EBFONT          = Errno(0x3b)
    +    EBUSY           = Errno(0x10)
    +    ECANCELED       = Errno(0x7d)
    +    ECHILD          = Errno(0xa)
    +    ECHRNG          = Errno(0x2c)
    +    ECOMM           = Errno(0x46)
    +    ECONNABORTED    = Errno(0x67)
    +    ECONNREFUSED    = Errno(0x6f)
    +    ECONNRESET      = Errno(0x68)
    +    EDEADLK         = Errno(0x23)
    +    EDEADLOCK       = Errno(0x23)
    +    EDESTADDRREQ    = Errno(0x59)
    +    EDOM            = Errno(0x21)
    +    EDOTDOT         = Errno(0x49)
    +    EDQUOT          = Errno(0x7a)
    +    EEXIST          = Errno(0x11)
    +    EFAULT          = Errno(0xe)
    +    EFBIG           = Errno(0x1b)
    +    EHOSTDOWN       = Errno(0x70)
    +    EHOSTUNREACH    = Errno(0x71)
    +    EIDRM           = Errno(0x2b)
    +    EILSEQ          = Errno(0x54)
    +    EINPROGRESS     = Errno(0x73)
    +    EINTR           = Errno(0x4)
    +    EINVAL          = Errno(0x16)
    +    EIO             = Errno(0x5)
    +    EISCONN         = Errno(0x6a)
    +    EISDIR          = Errno(0x15)
    +    EISNAM          = Errno(0x78)
    +    EKEYEXPIRED     = Errno(0x7f)
    +    EKEYREJECTED    = Errno(0x81)
    +    EKEYREVOKED     = Errno(0x80)
    +    EL2HLT          = Errno(0x33)
    +    EL2NSYNC        = Errno(0x2d)
    +    EL3HLT          = Errno(0x2e)
    +    EL3RST          = Errno(0x2f)
    +    ELIBACC         = Errno(0x4f)
    +    ELIBBAD         = Errno(0x50)
    +    ELIBEXEC        = Errno(0x53)
    +    ELIBMAX         = Errno(0x52)
    +    ELIBSCN         = Errno(0x51)
    +    ELNRNG          = Errno(0x30)
    +    ELOOP           = Errno(0x28)
    +    EMEDIUMTYPE     = Errno(0x7c)
    +    EMFILE          = Errno(0x18)
    +    EMLINK          = Errno(0x1f)
    +    EMSGSIZE        = Errno(0x5a)
    +    EMULTIHOP       = Errno(0x48)
    +    ENAMETOOLONG    = Errno(0x24)
    +    ENAVAIL         = Errno(0x77)
    +    ENETDOWN        = Errno(0x64)
    +    ENETRESET       = Errno(0x66)
    +    ENETUNREACH     = Errno(0x65)
    +    ENFILE          = Errno(0x17)
    +    ENOANO          = Errno(0x37)
    +    ENOBUFS         = Errno(0x69)
    +    ENOCSI          = Errno(0x32)
    +    ENODATA         = Errno(0x3d)
    +    ENODEV          = Errno(0x13)
    +    ENOENT          = Errno(0x2)
    +    ENOEXEC         = Errno(0x8)
    +    ENOKEY          = Errno(0x7e)
    +    ENOLCK          = Errno(0x25)
    +    ENOLINK         = Errno(0x43)
    +    ENOMEDIUM       = Errno(0x7b)
    +    ENOMEM          = Errno(0xc)
    +    ENOMSG          = Errno(0x2a)
    +    ENONET          = Errno(0x40)
    +    ENOPKG          = Errno(0x41)
    +    ENOPROTOOPT     = Errno(0x5c)
    +    ENOSPC          = Errno(0x1c)
    +    ENOSR           = Errno(0x3f)
    +    ENOSTR          = Errno(0x3c)
    +    ENOSYS          = Errno(0x26)
    +    ENOTBLK         = Errno(0xf)
    +    ENOTCONN        = Errno(0x6b)
    +    ENOTDIR         = Errno(0x14)
    +    ENOTEMPTY       = Errno(0x27)
    +    ENOTNAM         = Errno(0x76)
    +    ENOTRECOVERABLE = Errno(0x83)
    +    ENOTSOCK        = Errno(0x58)
    +    ENOTSUP         = Errno(0x5f)
    +    ENOTTY          = Errno(0x19)
    +    ENOTUNIQ        = Errno(0x4c)
    +    ENXIO           = Errno(0x6)
    +    EOPNOTSUPP      = Errno(0x5f)
    +    EOVERFLOW       = Errno(0x4b)
    +    EOWNERDEAD      = Errno(0x82)
    +    EPERM           = Errno(0x1)
    +    EPFNOSUPPORT    = Errno(0x60)
    +    EPIPE           = Errno(0x20)
    +    EPROTO          = Errno(0x47)
    +    EPROTONOSUPPORT = Errno(0x5d)
    +    EPROTOTYPE      = Errno(0x5b)
    +    ERANGE          = Errno(0x22)
    +    EREMCHG         = Errno(0x4e)
    +    EREMOTE         = Errno(0x42)
    +    EREMOTEIO       = Errno(0x79)
    +    ERESTART        = Errno(0x55)
    +    ERFKILL         = Errno(0x84)
    +    EROFS           = Errno(0x1e)
    +    ESHUTDOWN       = Errno(0x6c)
    +    ESOCKTNOSUPPORT = Errno(0x5e)
    +    ESPIPE          = Errno(0x1d)
    +    ESRCH           = Errno(0x3)
    +    ESRMNT          = Errno(0x45)
    +    ESTALE          = Errno(0x74)
    +    ESTRPIPE        = Errno(0x56)
    +    ETIME           = Errno(0x3e)
    +    ETIMEDOUT       = Errno(0x6e)
    +    ETOOMANYREFS    = Errno(0x6d)
    +    ETXTBSY         = Errno(0x1a)
    +    EUCLEAN         = Errno(0x75)
    +    EUNATCH         = Errno(0x31)
    +    EUSERS          = Errno(0x57)
    +    EWOULDBLOCK     = Errno(0xb)
    +    EXDEV           = Errno(0x12)
    +    EXFULL          = Errno(0x36)
    +)
    +

    +Errors +

    + + +
    const (
    +    SIGABRT   = Signal(0x6)
    +    SIGALRM   = Signal(0xe)
    +    SIGBUS    = Signal(0x7)
    +    SIGCHLD   = Signal(0x11)
    +    SIGCLD    = Signal(0x11)
    +    SIGCONT   = Signal(0x12)
    +    SIGFPE    = Signal(0x8)
    +    SIGHUP    = Signal(0x1)
    +    SIGILL    = Signal(0x4)
    +    SIGINT    = Signal(0x2)
    +    SIGIO     = Signal(0x1d)
    +    SIGIOT    = Signal(0x6)
    +    SIGKILL   = Signal(0x9)
    +    SIGPIPE   = Signal(0xd)
    +    SIGPOLL   = Signal(0x1d)
    +    SIGPROF   = Signal(0x1b)
    +    SIGPWR    = Signal(0x1e)
    +    SIGQUIT   = Signal(0x3)
    +    SIGSEGV   = Signal(0xb)
    +    SIGSTKFLT = Signal(0x10)
    +    SIGSTOP   = Signal(0x13)
    +    SIGSYS    = Signal(0x1f)
    +    SIGTERM   = Signal(0xf)
    +    SIGTRAP   = Signal(0x5)
    +    SIGTSTP   = Signal(0x14)
    +    SIGTTIN   = Signal(0x15)
    +    SIGTTOU   = Signal(0x16)
    +    SIGUNUSED = Signal(0x1f)
    +    SIGURG    = Signal(0x17)
    +    SIGUSR1   = Signal(0xa)
    +    SIGUSR2   = Signal(0xc)
    +    SIGVTALRM = Signal(0x1a)
    +    SIGWINCH  = Signal(0x1c)
    +    SIGXCPU   = Signal(0x18)
    +    SIGXFSZ   = Signal(0x19)
    +)
    +

    +Signals +

    + + +
    const (
    +    SYS_READ                   = 0
    +    SYS_WRITE                  = 1
    +    SYS_OPEN                   = 2
    +    SYS_CLOSE                  = 3
    +    SYS_STAT                   = 4
    +    SYS_FSTAT                  = 5
    +    SYS_LSTAT                  = 6
    +    SYS_POLL                   = 7
    +    SYS_LSEEK                  = 8
    +    SYS_MMAP                   = 9
    +    SYS_MPROTECT               = 10
    +    SYS_MUNMAP                 = 11
    +    SYS_BRK                    = 12
    +    SYS_RT_SIGACTION           = 13
    +    SYS_RT_SIGPROCMASK         = 14
    +    SYS_RT_SIGRETURN           = 15
    +    SYS_IOCTL                  = 16
    +    SYS_PREAD64                = 17
    +    SYS_PWRITE64               = 18
    +    SYS_READV                  = 19
    +    SYS_WRITEV                 = 20
    +    SYS_ACCESS                 = 21
    +    SYS_PIPE                   = 22
    +    SYS_SELECT                 = 23
    +    SYS_SCHED_YIELD            = 24
    +    SYS_MREMAP                 = 25
    +    SYS_MSYNC                  = 26
    +    SYS_MINCORE                = 27
    +    SYS_MADVISE                = 28
    +    SYS_SHMGET                 = 29
    +    SYS_SHMAT                  = 30
    +    SYS_SHMCTL                 = 31
    +    SYS_DUP                    = 32
    +    SYS_DUP2                   = 33
    +    SYS_PAUSE                  = 34
    +    SYS_NANOSLEEP              = 35
    +    SYS_GETITIMER              = 36
    +    SYS_ALARM                  = 37
    +    SYS_SETITIMER              = 38
    +    SYS_GETPID                 = 39
    +    SYS_SENDFILE               = 40
    +    SYS_SOCKET                 = 41
    +    SYS_CONNECT                = 42
    +    SYS_ACCEPT                 = 43
    +    SYS_SENDTO                 = 44
    +    SYS_RECVFROM               = 45
    +    SYS_SENDMSG                = 46
    +    SYS_RECVMSG                = 47
    +    SYS_SHUTDOWN               = 48
    +    SYS_BIND                   = 49
    +    SYS_LISTEN                 = 50
    +    SYS_GETSOCKNAME            = 51
    +    SYS_GETPEERNAME            = 52
    +    SYS_SOCKETPAIR             = 53
    +    SYS_SETSOCKOPT             = 54
    +    SYS_GETSOCKOPT             = 55
    +    SYS_CLONE                  = 56
    +    SYS_FORK                   = 57
    +    SYS_VFORK                  = 58
    +    SYS_EXECVE                 = 59
    +    SYS_EXIT                   = 60
    +    SYS_WAIT4                  = 61
    +    SYS_KILL                   = 62
    +    SYS_UNAME                  = 63
    +    SYS_SEMGET                 = 64
    +    SYS_SEMOP                  = 65
    +    SYS_SEMCTL                 = 66
    +    SYS_SHMDT                  = 67
    +    SYS_MSGGET                 = 68
    +    SYS_MSGSND                 = 69
    +    SYS_MSGRCV                 = 70
    +    SYS_MSGCTL                 = 71
    +    SYS_FCNTL                  = 72
    +    SYS_FLOCK                  = 73
    +    SYS_FSYNC                  = 74
    +    SYS_FDATASYNC              = 75
    +    SYS_TRUNCATE               = 76
    +    SYS_FTRUNCATE              = 77
    +    SYS_GETDENTS               = 78
    +    SYS_GETCWD                 = 79
    +    SYS_CHDIR                  = 80
    +    SYS_FCHDIR                 = 81
    +    SYS_RENAME                 = 82
    +    SYS_MKDIR                  = 83
    +    SYS_RMDIR                  = 84
    +    SYS_CREAT                  = 85
    +    SYS_LINK                   = 86
    +    SYS_UNLINK                 = 87
    +    SYS_SYMLINK                = 88
    +    SYS_READLINK               = 89
    +    SYS_CHMOD                  = 90
    +    SYS_FCHMOD                 = 91
    +    SYS_CHOWN                  = 92
    +    SYS_FCHOWN                 = 93
    +    SYS_LCHOWN                 = 94
    +    SYS_UMASK                  = 95
    +    SYS_GETTIMEOFDAY           = 96
    +    SYS_GETRLIMIT              = 97
    +    SYS_GETRUSAGE              = 98
    +    SYS_SYSINFO                = 99
    +    SYS_TIMES                  = 100
    +    SYS_PTRACE                 = 101
    +    SYS_GETUID                 = 102
    +    SYS_SYSLOG                 = 103
    +    SYS_GETGID                 = 104
    +    SYS_SETUID                 = 105
    +    SYS_SETGID                 = 106
    +    SYS_GETEUID                = 107
    +    SYS_GETEGID                = 108
    +    SYS_SETPGID                = 109
    +    SYS_GETPPID                = 110
    +    SYS_GETPGRP                = 111
    +    SYS_SETSID                 = 112
    +    SYS_SETREUID               = 113
    +    SYS_SETREGID               = 114
    +    SYS_GETGROUPS              = 115
    +    SYS_SETGROUPS              = 116
    +    SYS_SETRESUID              = 117
    +    SYS_GETRESUID              = 118
    +    SYS_SETRESGID              = 119
    +    SYS_GETRESGID              = 120
    +    SYS_GETPGID                = 121
    +    SYS_SETFSUID               = 122
    +    SYS_SETFSGID               = 123
    +    SYS_GETSID                 = 124
    +    SYS_CAPGET                 = 125
    +    SYS_CAPSET                 = 126
    +    SYS_RT_SIGPENDING          = 127
    +    SYS_RT_SIGTIMEDWAIT        = 128
    +    SYS_RT_SIGQUEUEINFO        = 129
    +    SYS_RT_SIGSUSPEND          = 130
    +    SYS_SIGALTSTACK            = 131
    +    SYS_UTIME                  = 132
    +    SYS_MKNOD                  = 133
    +    SYS_USELIB                 = 134
    +    SYS_PERSONALITY            = 135
    +    SYS_USTAT                  = 136
    +    SYS_STATFS                 = 137
    +    SYS_FSTATFS                = 138
    +    SYS_SYSFS                  = 139
    +    SYS_GETPRIORITY            = 140
    +    SYS_SETPRIORITY            = 141
    +    SYS_SCHED_SETPARAM         = 142
    +    SYS_SCHED_GETPARAM         = 143
    +    SYS_SCHED_SETSCHEDULER     = 144
    +    SYS_SCHED_GETSCHEDULER     = 145
    +    SYS_SCHED_GET_PRIORITY_MAX = 146
    +    SYS_SCHED_GET_PRIORITY_MIN = 147
    +    SYS_SCHED_RR_GET_INTERVAL  = 148
    +    SYS_MLOCK                  = 149
    +    SYS_MUNLOCK                = 150
    +    SYS_MLOCKALL               = 151
    +    SYS_MUNLOCKALL             = 152
    +    SYS_VHANGUP                = 153
    +    SYS_MODIFY_LDT             = 154
    +    SYS_PIVOT_ROOT             = 155
    +    SYS__SYSCTL                = 156
    +    SYS_PRCTL                  = 157
    +    SYS_ARCH_PRCTL             = 158
    +    SYS_ADJTIMEX               = 159
    +    SYS_SETRLIMIT              = 160
    +    SYS_CHROOT                 = 161
    +    SYS_SYNC                   = 162
    +    SYS_ACCT                   = 163
    +    SYS_SETTIMEOFDAY           = 164
    +    SYS_MOUNT                  = 165
    +    SYS_UMOUNT2                = 166
    +    SYS_SWAPON                 = 167
    +    SYS_SWAPOFF                = 168
    +    SYS_REBOOT                 = 169
    +    SYS_SETHOSTNAME            = 170
    +    SYS_SETDOMAINNAME          = 171
    +    SYS_IOPL                   = 172
    +    SYS_IOPERM                 = 173
    +    SYS_CREATE_MODULE          = 174
    +    SYS_INIT_MODULE            = 175
    +    SYS_DELETE_MODULE          = 176
    +    SYS_GET_KERNEL_SYMS        = 177
    +    SYS_QUERY_MODULE           = 178
    +    SYS_QUOTACTL               = 179
    +    SYS_NFSSERVCTL             = 180
    +    SYS_GETPMSG                = 181
    +    SYS_PUTPMSG                = 182
    +    SYS_AFS_SYSCALL            = 183
    +    SYS_TUXCALL                = 184
    +    SYS_SECURITY               = 185
    +    SYS_GETTID                 = 186
    +    SYS_READAHEAD              = 187
    +    SYS_SETXATTR               = 188
    +    SYS_LSETXATTR              = 189
    +    SYS_FSETXATTR              = 190
    +    SYS_GETXATTR               = 191
    +    SYS_LGETXATTR              = 192
    +    SYS_FGETXATTR              = 193
    +    SYS_LISTXATTR              = 194
    +    SYS_LLISTXATTR             = 195
    +    SYS_FLISTXATTR             = 196
    +    SYS_REMOVEXATTR            = 197
    +    SYS_LREMOVEXATTR           = 198
    +    SYS_FREMOVEXATTR           = 199
    +    SYS_TKILL                  = 200
    +    SYS_TIME                   = 201
    +    SYS_FUTEX                  = 202
    +    SYS_SCHED_SETAFFINITY      = 203
    +    SYS_SCHED_GETAFFINITY      = 204
    +    SYS_SET_THREAD_AREA        = 205
    +    SYS_IO_SETUP               = 206
    +    SYS_IO_DESTROY             = 207
    +    SYS_IO_GETEVENTS           = 208
    +    SYS_IO_SUBMIT              = 209
    +    SYS_IO_CANCEL              = 210
    +    SYS_GET_THREAD_AREA        = 211
    +    SYS_LOOKUP_DCOOKIE         = 212
    +    SYS_EPOLL_CREATE           = 213
    +    SYS_EPOLL_CTL_OLD          = 214
    +    SYS_EPOLL_WAIT_OLD         = 215
    +    SYS_REMAP_FILE_PAGES       = 216
    +    SYS_GETDENTS64             = 217
    +    SYS_SET_TID_ADDRESS        = 218
    +    SYS_RESTART_SYSCALL        = 219
    +    SYS_SEMTIMEDOP             = 220
    +    SYS_FADVISE64              = 221
    +    SYS_TIMER_CREATE           = 222
    +    SYS_TIMER_SETTIME          = 223
    +    SYS_TIMER_GETTIME          = 224
    +    SYS_TIMER_GETOVERRUN       = 225
    +    SYS_TIMER_DELETE           = 226
    +    SYS_CLOCK_SETTIME          = 227
    +    SYS_CLOCK_GETTIME          = 228
    +    SYS_CLOCK_GETRES           = 229
    +    SYS_CLOCK_NANOSLEEP        = 230
    +    SYS_EXIT_GROUP             = 231
    +    SYS_EPOLL_WAIT             = 232
    +    SYS_EPOLL_CTL              = 233
    +    SYS_TGKILL                 = 234
    +    SYS_UTIMES                 = 235
    +    SYS_VSERVER                = 236
    +    SYS_MBIND                  = 237
    +    SYS_SET_MEMPOLICY          = 238
    +    SYS_GET_MEMPOLICY          = 239
    +    SYS_MQ_OPEN                = 240
    +    SYS_MQ_UNLINK              = 241
    +    SYS_MQ_TIMEDSEND           = 242
    +    SYS_MQ_TIMEDRECEIVE        = 243
    +    SYS_MQ_NOTIFY              = 244
    +    SYS_MQ_GETSETATTR          = 245
    +    SYS_KEXEC_LOAD             = 246
    +    SYS_WAITID                 = 247
    +    SYS_ADD_KEY                = 248
    +    SYS_REQUEST_KEY            = 249
    +    SYS_KEYCTL                 = 250
    +    SYS_IOPRIO_SET             = 251
    +    SYS_IOPRIO_GET             = 252
    +    SYS_INOTIFY_INIT           = 253
    +    SYS_INOTIFY_ADD_WATCH      = 254
    +    SYS_INOTIFY_RM_WATCH       = 255
    +    SYS_MIGRATE_PAGES          = 256
    +    SYS_OPENAT                 = 257
    +    SYS_MKDIRAT                = 258
    +    SYS_MKNODAT                = 259
    +    SYS_FCHOWNAT               = 260
    +    SYS_FUTIMESAT              = 261
    +    SYS_NEWFSTATAT             = 262
    +    SYS_UNLINKAT               = 263
    +    SYS_RENAMEAT               = 264
    +    SYS_LINKAT                 = 265
    +    SYS_SYMLINKAT              = 266
    +    SYS_READLINKAT             = 267
    +    SYS_FCHMODAT               = 268
    +    SYS_FACCESSAT              = 269
    +    SYS_PSELECT6               = 270
    +    SYS_PPOLL                  = 271
    +    SYS_UNSHARE                = 272
    +    SYS_SET_ROBUST_LIST        = 273
    +    SYS_GET_ROBUST_LIST        = 274
    +    SYS_SPLICE                 = 275
    +    SYS_TEE                    = 276
    +    SYS_SYNC_FILE_RANGE        = 277
    +    SYS_VMSPLICE               = 278
    +    SYS_MOVE_PAGES             = 279
    +    SYS_UTIMENSAT              = 280
    +    SYS_EPOLL_PWAIT            = 281
    +    SYS_SIGNALFD               = 282
    +    SYS_TIMERFD_CREATE         = 283
    +    SYS_EVENTFD                = 284
    +    SYS_FALLOCATE              = 285
    +    SYS_TIMERFD_SETTIME        = 286
    +    SYS_TIMERFD_GETTIME        = 287
    +    SYS_ACCEPT4                = 288
    +    SYS_SIGNALFD4              = 289
    +    SYS_EVENTFD2               = 290
    +    SYS_EPOLL_CREATE1          = 291
    +    SYS_DUP3                   = 292
    +    SYS_PIPE2                  = 293
    +    SYS_INOTIFY_INIT1          = 294
    +    SYS_PREADV                 = 295
    +    SYS_PWRITEV                = 296
    +    SYS_RT_TGSIGQUEUEINFO      = 297
    +    SYS_PERF_EVENT_OPEN        = 298
    +    SYS_RECVMMSG               = 299
    +    SYS_FANOTIFY_INIT          = 300
    +    SYS_FANOTIFY_MARK          = 301
    +    SYS_PRLIMIT64              = 302
    +)
    + + +
    const (
    +    SizeofSockaddrInet4     = 0x10
    +    SizeofSockaddrInet6     = 0x1c
    +    SizeofSockaddrAny       = 0x70
    +    SizeofSockaddrUnix      = 0x6e
    +    SizeofSockaddrLinklayer = 0x14
    +    SizeofSockaddrNetlink   = 0xc
    +    SizeofLinger            = 0x8
    +    SizeofIPMreq            = 0x8
    +    SizeofIPMreqn           = 0xc
    +    SizeofIPv6Mreq          = 0x14
    +    SizeofMsghdr            = 0x38
    +    SizeofCmsghdr           = 0x10
    +    SizeofInet4Pktinfo      = 0xc
    +    SizeofInet6Pktinfo      = 0x14
    +    SizeofIPv6MTUInfo       = 0x20
    +    SizeofICMPv6Filter      = 0x20
    +    SizeofUcred             = 0xc
    +    SizeofTCPInfo           = 0x68
    +)
    + + +
    const (
    +    IFA_UNSPEC          = 0x0
    +    IFA_ADDRESS         = 0x1
    +    IFA_LOCAL           = 0x2
    +    IFA_LABEL           = 0x3
    +    IFA_BROADCAST       = 0x4
    +    IFA_ANYCAST         = 0x5
    +    IFA_CACHEINFO       = 0x6
    +    IFA_MULTICAST       = 0x7
    +    IFLA_UNSPEC         = 0x0
    +    IFLA_ADDRESS        = 0x1
    +    IFLA_BROADCAST      = 0x2
    +    IFLA_IFNAME         = 0x3
    +    IFLA_MTU            = 0x4
    +    IFLA_LINK           = 0x5
    +    IFLA_QDISC          = 0x6
    +    IFLA_STATS          = 0x7
    +    IFLA_COST           = 0x8
    +    IFLA_PRIORITY       = 0x9
    +    IFLA_MASTER         = 0xa
    +    IFLA_WIRELESS       = 0xb
    +    IFLA_PROTINFO       = 0xc
    +    IFLA_TXQLEN         = 0xd
    +    IFLA_MAP            = 0xe
    +    IFLA_WEIGHT         = 0xf
    +    IFLA_OPERSTATE      = 0x10
    +    IFLA_LINKMODE       = 0x11
    +    IFLA_LINKINFO       = 0x12
    +    IFLA_NET_NS_PID     = 0x13
    +    IFLA_IFALIAS        = 0x14
    +    IFLA_MAX            = 0x1d
    +    RT_SCOPE_UNIVERSE   = 0x0
    +    RT_SCOPE_SITE       = 0xc8
    +    RT_SCOPE_LINK       = 0xfd
    +    RT_SCOPE_HOST       = 0xfe
    +    RT_SCOPE_NOWHERE    = 0xff
    +    RT_TABLE_UNSPEC     = 0x0
    +    RT_TABLE_COMPAT     = 0xfc
    +    RT_TABLE_DEFAULT    = 0xfd
    +    RT_TABLE_MAIN       = 0xfe
    +    RT_TABLE_LOCAL      = 0xff
    +    RT_TABLE_MAX        = 0xffffffff
    +    RTA_UNSPEC          = 0x0
    +    RTA_DST             = 0x1
    +    RTA_SRC             = 0x2
    +    RTA_IIF             = 0x3
    +    RTA_OIF             = 0x4
    +    RTA_GATEWAY         = 0x5
    +    RTA_PRIORITY        = 0x6
    +    RTA_PREFSRC         = 0x7
    +    RTA_METRICS         = 0x8
    +    RTA_MULTIPATH       = 0x9
    +    RTA_FLOW            = 0xb
    +    RTA_CACHEINFO       = 0xc
    +    RTA_TABLE           = 0xf
    +    RTN_UNSPEC          = 0x0
    +    RTN_UNICAST         = 0x1
    +    RTN_LOCAL           = 0x2
    +    RTN_BROADCAST       = 0x3
    +    RTN_ANYCAST         = 0x4
    +    RTN_MULTICAST       = 0x5
    +    RTN_BLACKHOLE       = 0x6
    +    RTN_UNREACHABLE     = 0x7
    +    RTN_PROHIBIT        = 0x8
    +    RTN_THROW           = 0x9
    +    RTN_NAT             = 0xa
    +    RTN_XRESOLVE        = 0xb
    +    RTNLGRP_NONE        = 0x0
    +    RTNLGRP_LINK        = 0x1
    +    RTNLGRP_NOTIFY      = 0x2
    +    RTNLGRP_NEIGH       = 0x3
    +    RTNLGRP_TC          = 0x4
    +    RTNLGRP_IPV4_IFADDR = 0x5
    +    RTNLGRP_IPV4_MROUTE = 0x6
    +    RTNLGRP_IPV4_ROUTE  = 0x7
    +    RTNLGRP_IPV4_RULE   = 0x8
    +    RTNLGRP_IPV6_IFADDR = 0x9
    +    RTNLGRP_IPV6_MROUTE = 0xa
    +    RTNLGRP_IPV6_ROUTE  = 0xb
    +    RTNLGRP_IPV6_IFINFO = 0xc
    +    RTNLGRP_IPV6_PREFIX = 0x12
    +    RTNLGRP_IPV6_RULE   = 0x13
    +    RTNLGRP_ND_USEROPT  = 0x14
    +    SizeofNlMsghdr      = 0x10
    +    SizeofNlMsgerr      = 0x14
    +    SizeofRtGenmsg      = 0x1
    +    SizeofNlAttr        = 0x4
    +    SizeofRtAttr        = 0x4
    +    SizeofIfInfomsg     = 0x10
    +    SizeofIfAddrmsg     = 0x8
    +    SizeofRtMsg         = 0xc
    +    SizeofRtNexthop     = 0x8
    +)
    + + +
    const (
    +    SizeofSockFilter = 0x8
    +    SizeofSockFprog  = 0x10
    +)
    + + +
    const (
    +    VINTR    = 0x0
    +    VQUIT    = 0x1
    +    VERASE   = 0x2
    +    VKILL    = 0x3
    +    VEOF     = 0x4
    +    VTIME    = 0x5
    +    VMIN     = 0x6
    +    VSWTC    = 0x7
    +    VSTART   = 0x8
    +    VSTOP    = 0x9
    +    VSUSP    = 0xa
    +    VEOL     = 0xb
    +    VREPRINT = 0xc
    +    VDISCARD = 0xd
    +    VWERASE  = 0xe
    +    VLNEXT   = 0xf
    +    VEOL2    = 0x10
    +    IGNBRK   = 0x1
    +    BRKINT   = 0x2
    +    IGNPAR   = 0x4
    +    PARMRK   = 0x8
    +    INPCK    = 0x10
    +    ISTRIP   = 0x20
    +    INLCR    = 0x40
    +    IGNCR    = 0x80
    +    ICRNL    = 0x100
    +    IUCLC    = 0x200
    +    IXON     = 0x400
    +    IXANY    = 0x800
    +    IXOFF    = 0x1000
    +    IMAXBEL  = 0x2000
    +    IUTF8    = 0x4000
    +    OPOST    = 0x1
    +    OLCUC    = 0x2
    +    ONLCR    = 0x4
    +    OCRNL    = 0x8
    +    ONOCR    = 0x10
    +    ONLRET   = 0x20
    +    OFILL    = 0x40
    +    OFDEL    = 0x80
    +    B0       = 0x0
    +    B50      = 0x1
    +    B75      = 0x2
    +    B110     = 0x3
    +    B134     = 0x4
    +    B150     = 0x5
    +    B200     = 0x6
    +    B300     = 0x7
    +    B600     = 0x8
    +    B1200    = 0x9
    +    B1800    = 0xa
    +    B2400    = 0xb
    +    B4800    = 0xc
    +    B9600    = 0xd
    +    B19200   = 0xe
    +    B38400   = 0xf
    +    CSIZE    = 0x30
    +    CS5      = 0x0
    +    CS6      = 0x10
    +    CS7      = 0x20
    +    CS8      = 0x30
    +    CSTOPB   = 0x40
    +    CREAD    = 0x80
    +    PARENB   = 0x100
    +    PARODD   = 0x200
    +    HUPCL    = 0x400
    +    CLOCAL   = 0x800
    +    B57600   = 0x1001
    +    B115200  = 0x1002
    +    B230400  = 0x1003
    +    B460800  = 0x1004
    +    B500000  = 0x1005
    +    B576000  = 0x1006
    +    B921600  = 0x1007
    +    B1000000 = 0x1008
    +    B1152000 = 0x1009
    +    B1500000 = 0x100a
    +    B2000000 = 0x100b
    +    B2500000 = 0x100c
    +    B3000000 = 0x100d
    +    B3500000 = 0x100e
    +    B4000000 = 0x100f
    +    ISIG     = 0x1
    +    ICANON   = 0x2
    +    XCASE    = 0x4
    +    ECHO     = 0x8
    +    ECHOE    = 0x10
    +    ECHOK    = 0x20
    +    ECHONL   = 0x40
    +    NOFLSH   = 0x80
    +    TOSTOP   = 0x100
    +    ECHOCTL  = 0x200
    +    ECHOPRT  = 0x400
    +    ECHOKE   = 0x800
    +    FLUSHO   = 0x1000
    +    PENDIN   = 0x4000
    +    IEXTEN   = 0x8000
    +    TCGETS   = 0x5401
    +    TCSETS   = 0x5402
    +)
    + + +
    const ImplementsGetwd = true
    + + +
    const (
    +    PathMax = 0x1000
    +)
    + + +
    const SizeofInotifyEvent = 0x10
    + + + + +

    Variables

    + +
    var (
    +    Stdin  = 0
    +    Stdout = 1
    +    Stderr = 2
    +)
    + + +
    var ForkLock sync.RWMutex
    + + +
    var SocketDisableIPv6 bool
    +

    +For testing: clients can set this flag to force +creation of IPv6 sockets to return EAFNOSUPPORT. +

    + + + + + + +

    func Accept

    +
    func Accept(fd int) (nfd int, sa Sockaddr, err error)
    + + + + + + + +

    func Accept4

    +
    func Accept4(fd int, flags int) (nfd int, sa Sockaddr, err error)
    + + + + + + + +

    func Access

    +
    func Access(path string, mode uint32) (err error)
    + + + + + + + +

    func Acct

    +
    func Acct(path string) (err error)
    + + + + + + + +

    func Adjtimex

    +
    func Adjtimex(buf *Timex) (state int, err error)
    + + + + + + + +

    func AttachLsf

    +
    func AttachLsf(fd int, i []SockFilter) error
    + + + + + + + +

    func Bind

    +
    func Bind(fd int, sa Sockaddr) (err error)
    + + + + + + + +

    func BindToDevice

    +
    func BindToDevice(fd int, device string) (err error)
    +

    +BindToDevice binds the socket associated with fd to device. +

    + + + + + + + +

    func BytePtrFromString

    +
    func BytePtrFromString(s string) (*byte, error)
    +

    +BytePtrFromString returns a pointer to a NUL-terminated array of +bytes containing the text of s. If s contains a NUL byte at any +location, it returns (nil, EINVAL). +

    + + + + + + + +

    func ByteSliceFromString

    +
    func ByteSliceFromString(s string) ([]byte, error)
    +

    +ByteSliceFromString returns a NUL-terminated slice of bytes +containing the text of s. If s contains a NUL byte at any +location, it returns (nil, EINVAL). +

    + + + + + + + +

    func Chdir

    +
    func Chdir(path string) (err error)
    + + + + + + + +

    func Chmod

    +
    func Chmod(path string, mode uint32) (err error)
    + + + + + + + +

    func Chown

    +
    func Chown(path string, uid int, gid int) (err error)
    + + + + + + + +

    func Chroot

    +
    func Chroot(path string) (err error)
    + + + + + + + +

    func Clearenv

    +
    func Clearenv()
    + + + + + + + +

    func Close

    +
    func Close(fd int) (err error)
    + + + + + + + +

    func CloseOnExec

    +
    func CloseOnExec(fd int)
    + + + + + + + +

    func CmsgLen

    +
    func CmsgLen(datalen int) int
    +

    +CmsgLen returns the value to store in the Len field of the Cmsghdr +structure, taking into account any necessary alignment. +

    + + + + + + + +

    func CmsgSpace

    +
    func CmsgSpace(datalen int) int
    +

    +CmsgSpace returns the number of bytes an ancillary element with +payload of the passed data length occupies. +

    + + + + + + + +

    func Connect

    +
    func Connect(fd int, sa Sockaddr) (err error)
    + + + + + + + +

    func Creat

    +
    func Creat(path string, mode uint32) (fd int, err error)
    + + + + + + + +

    func DetachLsf

    +
    func DetachLsf(fd int) error
    + + + + + + + +

    func Dup

    +
    func Dup(oldfd int) (fd int, err error)
    + + + + + + + +

    func Dup2

    +
    func Dup2(oldfd int, newfd int) (err error)
    + + + + + + + +

    func Dup3

    +
    func Dup3(oldfd int, newfd int, flags int) (err error)
    + + + + + + + +

    func Environ

    +
    func Environ() []string
    + + + + + + + +

    func EpollCreate

    +
    func EpollCreate(size int) (fd int, err error)
    + + + + + + + +

    func EpollCreate1

    +
    func EpollCreate1(flag int) (fd int, err error)
    + + + + + + + +

    func EpollCtl

    +
    func EpollCtl(epfd int, op int, fd int, event *EpollEvent) (err error)
    + + + + + + + +

    func EpollWait

    +
    func EpollWait(epfd int, events []EpollEvent, msec int) (n int, err error)
    + + + + + + + +

    func Exec

    +
    func Exec(argv0 string, argv []string, envv []string) (err error)
    +

    +Ordinary exec. +

    + + + + + + + +

    func Exit

    +
    func Exit(code int)
    + + + + + + + +

    func Faccessat

    +
    func Faccessat(dirfd int, path string, mode uint32, flags int) (err error)
    + + + + + + + +

    func Fallocate

    +
    func Fallocate(fd int, mode uint32, off int64, len int64) (err error)
    + + + + + + + +

    func Fchdir

    +
    func Fchdir(fd int) (err error)
    + + + + + + + +

    func Fchmod

    +
    func Fchmod(fd int, mode uint32) (err error)
    + + + + + + + +

    func Fchmodat

    +
    func Fchmodat(dirfd int, path string, mode uint32, flags int) (err error)
    + + + + + + + +

    func Fchown

    +
    func Fchown(fd int, uid int, gid int) (err error)
    + + + + + + + +

    func Fchownat

    +
    func Fchownat(dirfd int, path string, uid int, gid int, flags int) (err error)
    + + + + + + + +

    func FcntlFlock

    +
    func FcntlFlock(fd uintptr, cmd int, lk *Flock_t) error
    +

    +FcntlFlock performs a fcntl syscall for the F_GETLK, F_SETLK or F_SETLKW command. +

    + + + + + + + +

    func Fdatasync

    +
    func Fdatasync(fd int) (err error)
    + + + + + + + +

    func Flock

    +
    func Flock(fd int, how int) (err error)
    + + + + + + + +

    func ForkExec

    +
    func ForkExec(argv0 string, argv []string, attr *ProcAttr) (pid int, err error)
    +

    +Combination of fork and exec, careful to be thread safe. +

    + + + + + + + +

    func Fstat

    +
    func Fstat(fd int, stat *Stat_t) (err error)
    + + + + + + + +

    func Fstatfs

    +
    func Fstatfs(fd int, buf *Statfs_t) (err error)
    + + + + + + + +

    func Fsync

    +
    func Fsync(fd int) (err error)
    + + + + + + + +

    func Ftruncate

    +
    func Ftruncate(fd int, length int64) (err error)
    + + + + + + + +

    func Futimes

    +
    func Futimes(fd int, tv []Timeval) (err error)
    + + + + + + + +

    func Futimesat

    +
    func Futimesat(dirfd int, path string, tv []Timeval) (err error)
    + + + + + + + +

    func Getcwd

    +
    func Getcwd(buf []byte) (n int, err error)
    + + + + + + + +

    func Getdents

    +
    func Getdents(fd int, buf []byte) (n int, err error)
    + + + + + + + +

    func Getegid

    +
    func Getegid() (egid int)
    + + + + + + + +

    func Getenv

    +
    func Getenv(key string) (value string, found bool)
    + + + + + + + +

    func Geteuid

    +
    func Geteuid() (euid int)
    + + + + + + + +

    func Getgid

    +
    func Getgid() (gid int)
    + + + + + + + +

    func Getgroups

    +
    func Getgroups() (gids []int, err error)
    + + + + + + + +

    func Getpagesize

    +
    func Getpagesize() int
    + + + + + + + +

    func Getpgid

    +
    func Getpgid(pid int) (pgid int, err error)
    + + + + + + + +

    func Getpgrp

    +
    func Getpgrp() (pid int)
    + + + + + + + +

    func Getpid

    +
    func Getpid() (pid int)
    + + + + + + + +

    func Getppid

    +
    func Getppid() (ppid int)
    + + + + + + + +

    func Getpriority

    +
    func Getpriority(which int, who int) (prio int, err error)
    + + + + + + + +

    func Getrlimit

    +
    func Getrlimit(resource int, rlim *Rlimit) (err error)
    + + + + + + + +

    func Getrusage

    +
    func Getrusage(who int, rusage *Rusage) (err error)
    + + + + + + + +

    func GetsockoptInet4Addr

    +
    func GetsockoptInet4Addr(fd, level, opt int) (value [4]byte, err error)
    + + + + + + + +

    func GetsockoptInt

    +
    func GetsockoptInt(fd, level, opt int) (value int, err error)
    + + + + + + + +

    func Gettid

    +
    func Gettid() (tid int)
    + + + + + + + +

    func Gettimeofday

    +
    func Gettimeofday(tv *Timeval) (err error)
    + + + + + + + +

    func Getuid

    +
    func Getuid() (uid int)
    + + + + + + + +

    func Getwd

    +
    func Getwd() (wd string, err error)
    + + + + + + + +

    func Getxattr

    +
    func Getxattr(path string, attr string, dest []byte) (sz int, err error)
    + + + + + + + +

    func InotifyAddWatch

    +
    func InotifyAddWatch(fd int, pathname string, mask uint32) (watchdesc int, err error)
    + + + + + + + +

    func InotifyInit

    +
    func InotifyInit() (fd int, err error)
    + + + + + + + +

    func InotifyInit1

    +
    func InotifyInit1(flags int) (fd int, err error)
    + + + + + + + +

    func InotifyRmWatch

    +
    func InotifyRmWatch(fd int, watchdesc uint32) (success int, err error)
    + + + + + + + +

    func Ioperm

    +
    func Ioperm(from int, num int, on int) (err error)
    + + + + + + + +

    func Iopl

    +
    func Iopl(level int) (err error)
    + + + + + + + +

    func Kill

    +
    func Kill(pid int, sig Signal) (err error)
    + + + + + + + +

    func Klogctl

    +
    func Klogctl(typ int, buf []byte) (n int, err error)
    + + + + + + + +

    func Lchown

    +
    func Lchown(path string, uid int, gid int) (err error)
    + + + + + + + + +
    func Link(oldpath string, newpath string) (err error)
    + + + + + + + +

    func Listen

    +
    func Listen(s int, n int) (err error)
    + + + + + + + +

    func Listxattr

    +
    func Listxattr(path string, dest []byte) (sz int, err error)
    + + + + + + + +

    func LsfSocket

    +
    func LsfSocket(ifindex, proto int) (int, error)
    + + + + + + + +

    func Lstat

    +
    func Lstat(path string, stat *Stat_t) (err error)
    + + + + + + + +

    func Madvise

    +
    func Madvise(b []byte, advice int) (err error)
    + + + + + + + +

    func Mkdir

    +
    func Mkdir(path string, mode uint32) (err error)
    + + + + + + + +

    func Mkdirat

    +
    func Mkdirat(dirfd int, path string, mode uint32) (err error)
    + + + + + + + +

    func Mkfifo

    +
    func Mkfifo(path string, mode uint32) (err error)
    + + + + + + + +

    func Mknod

    +
    func Mknod(path string, mode uint32, dev int) (err error)
    + + + + + + + +

    func Mknodat

    +
    func Mknodat(dirfd int, path string, mode uint32, dev int) (err error)
    + + + + + + + +

    func Mlock

    +
    func Mlock(b []byte) (err error)
    + + + + + + + +

    func Mlockall

    +
    func Mlockall(flags int) (err error)
    + + + + + + + +

    func Mmap

    +
    func Mmap(fd int, offset int64, length int, prot int, flags int) (data []byte, err error)
    + + + + + + + +

    func Mount

    +
    func Mount(source string, target string, fstype string, flags uintptr, data string) (err error)
    + + + + + + + +

    func Mprotect

    +
    func Mprotect(b []byte, prot int) (err error)
    + + + + + + + +

    func Munlock

    +
    func Munlock(b []byte) (err error)
    + + + + + + + +

    func Munlockall

    +
    func Munlockall() (err error)
    + + + + + + + +

    func Munmap

    +
    func Munmap(b []byte) (err error)
    + + + + + + + +

    func Nanosleep

    +
    func Nanosleep(time *Timespec, leftover *Timespec) (err error)
    + + + + + + + +

    func NetlinkRIB

    +
    func NetlinkRIB(proto, family int) ([]byte, error)
    +

    +NetlinkRIB returns routing information base, as known as RIB, which +consists of network facility information, states and parameters. +

    + + + + + + + +

    func Open

    +
    func Open(path string, mode int, perm uint32) (fd int, err error)
    + + + + + + + +

    func Openat

    +
    func Openat(dirfd int, path string, flags int, mode uint32) (fd int, err error)
    + + + + + + + +

    func ParseDirent

    +
    func ParseDirent(buf []byte, max int, names []string) (consumed int, count int, newnames []string)
    + + + + + + + +

    func ParseNetlinkMessage

    +
    func ParseNetlinkMessage(b []byte) ([]NetlinkMessage, error)
    +

    +ParseNetlinkMessage parses b as an array of netlink messages and +returns the slice containing the NetlinkMessage structures. +

    + + + + + + + +

    func ParseNetlinkRouteAttr

    +
    func ParseNetlinkRouteAttr(m *NetlinkMessage) ([]NetlinkRouteAttr, error)
    +

    +ParseNetlinkRouteAttr parses m's payload as an array of netlink +route attributes and returns the slice containing the +NetlinkRouteAttr structures. +

    + + + + + + + +

    func ParseSocketControlMessage

    +
    func ParseSocketControlMessage(b []byte) ([]SocketControlMessage, error)
    +

    +ParseSocketControlMessage parses b as an array of socket control +messages. +

    + + + + + + + +

    func ParseUnixRights

    +
    func ParseUnixRights(m *SocketControlMessage) ([]int, error)
    +

    +ParseUnixRights decodes a socket control message that contains an +integer array of open file descriptors from another process. +

    + + + + + + + +

    func Pause

    +
    func Pause() (err error)
    + + + + + + + +

    func Pipe

    +
    func Pipe(p []int) (err error)
    + + + + + + + +

    func Pipe2

    +
    func Pipe2(p []int, flags int) (err error)
    + + + + + + + +

    func PivotRoot

    +
    func PivotRoot(newroot string, putold string) (err error)
    + + + + + + + +

    func Pread

    +
    func Pread(fd int, p []byte, offset int64) (n int, err error)
    + + + + + + + +

    func PtraceAttach

    +
    func PtraceAttach(pid int) (err error)
    + + + + + + + +

    func PtraceCont

    +
    func PtraceCont(pid int, signal int) (err error)
    + + + + + + + +

    func PtraceDetach

    +
    func PtraceDetach(pid int) (err error)
    + + + + + + + +

    func PtraceGetEventMsg

    +
    func PtraceGetEventMsg(pid int) (msg uint, err error)
    + + + + + + + +

    func PtraceGetRegs

    +
    func PtraceGetRegs(pid int, regsout *PtraceRegs) (err error)
    + + + + + + + +

    func PtracePeekData

    +
    func PtracePeekData(pid int, addr uintptr, out []byte) (count int, err error)
    + + + + + + + +

    func PtracePeekText

    +
    func PtracePeekText(pid int, addr uintptr, out []byte) (count int, err error)
    + + + + + + + +

    func PtracePokeData

    +
    func PtracePokeData(pid int, addr uintptr, data []byte) (count int, err error)
    + + + + + + + +

    func PtracePokeText

    +
    func PtracePokeText(pid int, addr uintptr, data []byte) (count int, err error)
    + + + + + + + +

    func PtraceSetOptions

    +
    func PtraceSetOptions(pid int, options int) (err error)
    + + + + + + + +

    func PtraceSetRegs

    +
    func PtraceSetRegs(pid int, regs *PtraceRegs) (err error)
    + + + + + + + +

    func PtraceSingleStep

    +
    func PtraceSingleStep(pid int) (err error)
    + + + + + + + +

    func PtraceSyscall

    +
    func PtraceSyscall(pid int, signal int) (err error)
    + + + + + + + +

    func Pwrite

    +
    func Pwrite(fd int, p []byte, offset int64) (n int, err error)
    + + + + + + + +

    func RawSyscall

    +
    func RawSyscall(trap, a1, a2, a3 uintptr) (r1, r2 uintptr, err Errno)
    + + + + + + + +

    func RawSyscall6

    +
    func RawSyscall6(trap, a1, a2, a3, a4, a5, a6 uintptr) (r1, r2 uintptr, err Errno)
    + + + + + + + +

    func Read

    +
    func Read(fd int, p []byte) (n int, err error)
    + + + + + + + +

    func ReadDirent

    +
    func ReadDirent(fd int, buf []byte) (n int, err error)
    + + + + + + + + +
    func Readlink(path string, buf []byte) (n int, err error)
    + + + + + + + +

    func Reboot

    +
    func Reboot(cmd int) (err error)
    + + + + + + + +

    func Recvfrom

    +
    func Recvfrom(fd int, p []byte, flags int) (n int, from Sockaddr, err error)
    + + + + + + + +

    func Recvmsg

    +
    func Recvmsg(fd int, p, oob []byte, flags int) (n, oobn int, recvflags int, from Sockaddr, err error)
    + + + + + + + +

    func Removexattr

    +
    func Removexattr(path string, attr string) (err error)
    + + + + + + + +

    func Rename

    +
    func Rename(oldpath string, newpath string) (err error)
    + + + + + + + +

    func Renameat

    +
    func Renameat(olddirfd int, oldpath string, newdirfd int, newpath string) (err error)
    + + + + + + + +

    func Rmdir

    +
    func Rmdir(path string) error
    + + + + + + + +

    func Seek

    +
    func Seek(fd int, offset int64, whence int) (off int64, err error)
    + + + + + + + +

    func Select

    +
    func Select(nfd int, r *FdSet, w *FdSet, e *FdSet, timeout *Timeval) (n int, err error)
    + + + + + + + +

    func Sendfile

    +
    func Sendfile(outfd int, infd int, offset *int64, count int) (written int, err error)
    + + + + + + + +

    func Sendmsg

    +
    func Sendmsg(fd int, p, oob []byte, to Sockaddr, flags int) (err error)
    + + + + + + + +

    func SendmsgN

    +
    func SendmsgN(fd int, p, oob []byte, to Sockaddr, flags int) (n int, err error)
    + + + + + + + +

    func Sendto

    +
    func Sendto(fd int, p []byte, flags int, to Sockaddr) (err error)
    + + + + + + + +

    func SetLsfPromisc

    +
    func SetLsfPromisc(name string, m bool) error
    + + + + + + + +

    func SetNonblock

    +
    func SetNonblock(fd int, nonblocking bool) (err error)
    + + + + + + + +

    func Setdomainname

    +
    func Setdomainname(p []byte) (err error)
    + + + + + + + +

    func Setenv

    +
    func Setenv(key, value string) error
    + + + + + + + +

    func Setfsgid

    +
    func Setfsgid(gid int) (err error)
    + + + + + + + +

    func Setfsuid

    +
    func Setfsuid(uid int) (err error)
    + + + + + + + +

    func Setgid

    +
    func Setgid(gid int) (err error)
    + + + + + + + +

    func Setgroups

    +
    func Setgroups(gids []int) (err error)
    + + + + + + + +

    func Sethostname

    +
    func Sethostname(p []byte) (err error)
    + + + + + + + +

    func Setpgid

    +
    func Setpgid(pid int, pgid int) (err error)
    + + + + + + + +

    func Setpriority

    +
    func Setpriority(which int, who int, prio int) (err error)
    + + + + + + + +

    func Setregid

    +
    func Setregid(rgid int, egid int) (err error)
    + + + + + + + +

    func Setresgid

    +
    func Setresgid(rgid int, egid int, sgid int) (err error)
    + + + + + + + +

    func Setresuid

    +
    func Setresuid(ruid int, euid int, suid int) (err error)
    + + + + + + + +

    func Setreuid

    +
    func Setreuid(ruid int, euid int) (err error)
    + + + + + + + +

    func Setrlimit

    +
    func Setrlimit(resource int, rlim *Rlimit) (err error)
    + + + + + + + +

    func Setsid

    +
    func Setsid() (pid int, err error)
    + + + + + + + +

    func SetsockoptByte

    +
    func SetsockoptByte(fd, level, opt int, value byte) (err error)
    + + + + + + + +

    func SetsockoptICMPv6Filter

    +
    func SetsockoptICMPv6Filter(fd, level, opt int, filter *ICMPv6Filter) error
    + + + + + + + +

    func SetsockoptIPMreq

    +
    func SetsockoptIPMreq(fd, level, opt int, mreq *IPMreq) (err error)
    + + + + + + + +

    func SetsockoptIPMreqn

    +
    func SetsockoptIPMreqn(fd, level, opt int, mreq *IPMreqn) (err error)
    + + + + + + + +

    func SetsockoptIPv6Mreq

    +
    func SetsockoptIPv6Mreq(fd, level, opt int, mreq *IPv6Mreq) (err error)
    + + + + + + + +

    func SetsockoptInet4Addr

    +
    func SetsockoptInet4Addr(fd, level, opt int, value [4]byte) (err error)
    + + + + + + + +

    func SetsockoptInt

    +
    func SetsockoptInt(fd, level, opt int, value int) (err error)
    + + + + + + + +

    func SetsockoptLinger

    +
    func SetsockoptLinger(fd, level, opt int, l *Linger) (err error)
    + + + + + + + +

    func SetsockoptString

    +
    func SetsockoptString(fd, level, opt int, s string) (err error)
    + + + + + + + +

    func SetsockoptTimeval

    +
    func SetsockoptTimeval(fd, level, opt int, tv *Timeval) (err error)
    + + + + + + + +

    func Settimeofday

    +
    func Settimeofday(tv *Timeval) (err error)
    + + + + + + + +

    func Setuid

    +
    func Setuid(uid int) (err error)
    + + + + + + + +

    func Setxattr

    +
    func Setxattr(path string, attr string, data []byte, flags int) (err error)
    + + + + + + + +

    func Shutdown

    +
    func Shutdown(fd int, how int) (err error)
    + + + + + + + +

    func SlicePtrFromStrings

    +
    func SlicePtrFromStrings(ss []string) ([]*byte, error)
    +

    +SlicePtrFromStrings converts a slice of strings to a slice of +pointers to NUL-terminated byte arrays. If any string contains +a NUL byte, it returns (nil, EINVAL). +

    + + + + + + + +

    func Socket

    +
    func Socket(domain, typ, proto int) (fd int, err error)
    + + + + + + + +

    func Socketpair

    +
    func Socketpair(domain, typ, proto int) (fd [2]int, err error)
    + + + + + + + +

    func Splice

    +
    func Splice(rfd int, roff *int64, wfd int, woff *int64, len int, flags int) (n int64, err error)
    + + + + + + + +

    func StartProcess

    +
    func StartProcess(argv0 string, argv []string, attr *ProcAttr) (pid int, handle uintptr, err error)
    +

    +StartProcess wraps ForkExec for package os. +

    + + + + + + + +

    func Stat

    +
    func Stat(path string, stat *Stat_t) (err error)
    + + + + + + + +

    func Statfs

    +
    func Statfs(path string, buf *Statfs_t) (err error)
    + + + + + + + +

    func StringBytePtr

    +
    func StringBytePtr(s string) *byte
    +

    +StringBytePtr returns a pointer to a NUL-terminated array of bytes. +If s contains a NUL byte this function panics instead of returning +an error. +

    +

    +Deprecated: Use BytePtrFromString instead. +

    + + + + + + + +

    func StringByteSlice

    +
    func StringByteSlice(s string) []byte
    +

    +StringByteSlice converts a string to a NUL-terminated []byte, +If s contains a NUL byte this function panics instead of +returning an error. +

    +

    +Deprecated: Use ByteSliceFromString instead. +

    + + + + + + + +

    func StringSlicePtr

    +
    func StringSlicePtr(ss []string) []*byte
    +

    +StringSlicePtr converts a slice of strings to a slice of pointers +to NUL-terminated byte arrays. If any string contains a NUL byte +this function panics instead of returning an error. +

    +

    +Deprecated: Use SlicePtrFromStrings instead. +

    + + + + + + + + +
    func Symlink(oldpath string, newpath string) (err error)
    + + + + + + + +

    func Sync

    +
    func Sync()
    + + + + + + + +

    func SyncFileRange

    +
    func SyncFileRange(fd int, off int64, n int64, flags int) (err error)
    + + + + + + + +

    func Syscall

    +
    func Syscall(trap, a1, a2, a3 uintptr) (r1, r2 uintptr, err Errno)
    + + + + + + + +

    func Syscall6

    +
    func Syscall6(trap, a1, a2, a3, a4, a5, a6 uintptr) (r1, r2 uintptr, err Errno)
    + + + + + + + +

    func Sysinfo

    +
    func Sysinfo(info *Sysinfo_t) (err error)
    + + + + + + + +

    func Tee

    +
    func Tee(rfd int, wfd int, len int, flags int) (n int64, err error)
    + + + + + + + +

    func Tgkill

    +
    func Tgkill(tgid int, tid int, sig Signal) (err error)
    + + + + + + + +

    func Times

    +
    func Times(tms *Tms) (ticks uintptr, err error)
    + + + + + + + +

    func TimespecToNsec

    +
    func TimespecToNsec(ts Timespec) int64
    + + + + + + + +

    func TimevalToNsec

    +
    func TimevalToNsec(tv Timeval) int64
    + + + + + + + +

    func Truncate

    +
    func Truncate(path string, length int64) (err error)
    + + + + + + + +

    func Umask

    +
    func Umask(mask int) (oldmask int)
    + + + + + + + +

    func Uname

    +
    func Uname(buf *Utsname) (err error)
    + + + + + + + +

    func UnixCredentials

    +
    func UnixCredentials(ucred *Ucred) []byte
    +

    +UnixCredentials encodes credentials into a socket control message +for sending to another process. This can be used for +authentication. +

    + + + + + + + +

    func UnixRights

    +
    func UnixRights(fds ...int) []byte
    +

    +UnixRights encodes a set of open file descriptors into a socket +control message for sending to another process. +

    + + + + + + + + +
    func Unlink(path string) error
    + + + + + + + +

    func Unlinkat

    +
    func Unlinkat(dirfd int, path string) error
    + + + + + + + +

    func Unmount

    +
    func Unmount(target string, flags int) (err error)
    + + + + + + + +

    func Unsetenv

    +
    func Unsetenv(key string) error
    + + + + + + + +

    func Unshare

    +
    func Unshare(flags int) (err error)
    + + + + + + + +

    func Ustat

    +
    func Ustat(dev int, ubuf *Ustat_t) (err error)
    + + + + + + + +

    func Utime

    +
    func Utime(path string, buf *Utimbuf) (err error)
    + + + + + + + +

    func Utimes

    +
    func Utimes(path string, tv []Timeval) (err error)
    + + + + + + + +

    func UtimesNano

    +
    func UtimesNano(path string, ts []Timespec) (err error)
    + + + + + + + +

    func Wait4

    +
    func Wait4(pid int, wstatus *WaitStatus, options int, rusage *Rusage) (wpid int, err error)
    + + + + + + + +

    func Write

    +
    func Write(fd int, p []byte) (n int, err error)
    + + + + + + + + +

    type Cmsghdr

    +
    type Cmsghdr struct {
    +    Len          uint64
    +    Level        int32
    +    Type         int32
    +    X__cmsg_data [0]uint8
    +}
    + + + + + + + + + + + + + + +

    func (*Cmsghdr) SetLen

    +
    func (cmsg *Cmsghdr) SetLen(length int)
    + + + + + + + + +

    type Credential

    +
    type Credential struct {
    +    Uid    uint32   // User ID.
    +    Gid    uint32   // Group ID.
    +    Groups []uint32 // Supplementary group IDs.
    +}
    +

    +Credential holds user and group identities to be assumed +by a child process started by StartProcess. +

    + + + + + + + + + + + + + + + + +

    type Dirent

    +
    type Dirent struct {
    +    Ino       uint64
    +    Off       int64
    +    Reclen    uint16
    +    Type      uint8
    +    Name      [256]int8
    +    Pad_cgo_0 [5]byte
    +}
    + + + + + + + + + + + + + + + + +

    type EpollEvent

    +
    type EpollEvent struct {
    +    Events uint32
    +    Fd     int32
    +    Pad    int32
    +}
    + + + + + + + + + + + + + + + + +

    type Errno

    +
    type Errno uintptr
    +

    +An Errno is an unsigned number describing an error condition. +It implements the error interface. The zero Errno is by convention +a non-error, so code to convert from Errno to error should use: +

    +
    err = nil
    +if errno != 0 {
    +	err = errno
    +}
    +
    + + + + + + + + + + + + + + +

    func (Errno) Error

    +
    func (e Errno) Error() string
    + + + + + + +

    func (Errno) Temporary

    +
    func (e Errno) Temporary() bool
    + + + + + + +

    func (Errno) Timeout

    +
    func (e Errno) Timeout() bool
    + + + + + + + + +

    type FdSet

    +
    type FdSet struct {
    +    Bits [16]int64
    +}
    + + + + + + + + + + + + + + + + +

    type Flock_t

    +
    type Flock_t struct {
    +    Type      int16
    +    Whence    int16
    +    Pad_cgo_0 [4]byte
    +    Start     int64
    +    Len       int64
    +    Pid       int32
    +    Pad_cgo_1 [4]byte
    +}
    + + + + + + + + + + + + + + + + +

    type Fsid

    +
    type Fsid struct {
    +    X__val [2]int32
    +}
    + + + + + + + + + + + + + + + + +

    type ICMPv6Filter

    +
    type ICMPv6Filter struct {
    +    Data [8]uint32
    +}
    + + + + + + + + + + + + +

    func GetsockoptICMPv6Filter

    +
    func GetsockoptICMPv6Filter(fd, level, opt int) (*ICMPv6Filter, error)
    + + + + + + + + + +

    type IPMreq

    +
    type IPMreq struct {
    +    Multiaddr [4]byte /* in_addr */
    +    Interface [4]byte /* in_addr */
    +}
    + + + + + + + + + + + + +

    func GetsockoptIPMreq

    +
    func GetsockoptIPMreq(fd, level, opt int) (*IPMreq, error)
    + + + + + + + + + +

    type IPMreqn

    +
    type IPMreqn struct {
    +    Multiaddr [4]byte /* in_addr */
    +    Address   [4]byte /* in_addr */
    +    Ifindex   int32
    +}
    + + + + + + + + + + + + +

    func GetsockoptIPMreqn

    +
    func GetsockoptIPMreqn(fd, level, opt int) (*IPMreqn, error)
    + + + + + + + + + +

    type IPv6MTUInfo

    +
    type IPv6MTUInfo struct {
    +    Addr RawSockaddrInet6
    +    Mtu  uint32
    +}
    + + + + + + + + + + + + +

    func GetsockoptIPv6MTUInfo

    +
    func GetsockoptIPv6MTUInfo(fd, level, opt int) (*IPv6MTUInfo, error)
    + + + + + + + + + +

    type IPv6Mreq

    +
    type IPv6Mreq struct {
    +    Multiaddr [16]byte /* in6_addr */
    +    Interface uint32
    +}
    + + + + + + + + + + + + +

    func GetsockoptIPv6Mreq

    +
    func GetsockoptIPv6Mreq(fd, level, opt int) (*IPv6Mreq, error)
    + + + + + + + + + +

    type IfAddrmsg

    +
    type IfAddrmsg struct {
    +    Family    uint8
    +    Prefixlen uint8
    +    Flags     uint8
    +    Scope     uint8
    +    Index     uint32
    +}
    + + + + + + + + + + + + + + + + +

    type IfInfomsg

    +
    type IfInfomsg struct {
    +    Family     uint8
    +    X__ifi_pad uint8
    +    Type       uint16
    +    Index      int32
    +    Flags      uint32
    +    Change     uint32
    +}
    + + + + + + + + + + + + + + + + +

    type Inet4Pktinfo

    +
    type Inet4Pktinfo struct {
    +    Ifindex  int32
    +    Spec_dst [4]byte /* in_addr */
    +    Addr     [4]byte /* in_addr */
    +}
    + + + + + + + + + + + + + + + + +

    type Inet6Pktinfo

    +
    type Inet6Pktinfo struct {
    +    Addr    [16]byte /* in6_addr */
    +    Ifindex uint32
    +}
    + + + + + + + + + + + + + + + + +

    type InotifyEvent

    +
    type InotifyEvent struct {
    +    Wd     int32
    +    Mask   uint32
    +    Cookie uint32
    +    Len    uint32
    +    Name   [0]uint8
    +}
    + + + + + + + + + + + + + + + + +

    type Iovec

    +
    type Iovec struct {
    +    Base *byte
    +    Len  uint64
    +}
    + + + + + + + + + + + + + + +

    func (*Iovec) SetLen

    +
    func (iov *Iovec) SetLen(length int)
    + + + + + + + + +

    type Linger

    +
    type Linger struct {
    +    Onoff  int32
    +    Linger int32
    +}
    + + + + + + + + + + + + + + + + +

    type Msghdr

    +
    type Msghdr struct {
    +    Name       *byte
    +    Namelen    uint32
    +    Pad_cgo_0  [4]byte
    +    Iov        *Iovec
    +    Iovlen     uint64
    +    Control    *byte
    +    Controllen uint64
    +    Flags      int32
    +    Pad_cgo_1  [4]byte
    +}
    + + + + + + + + + + + + + + +

    func (*Msghdr) SetControllen

    +
    func (msghdr *Msghdr) SetControllen(length int)
    + + + + + + + + +

    type NetlinkMessage

    +
    type NetlinkMessage struct {
    +    Header NlMsghdr
    +    Data   []byte
    +}
    +

    +NetlinkMessage represents a netlink message. +

    + + + + + + + + + + + + + + + + +

    type NetlinkRouteAttr

    +
    type NetlinkRouteAttr struct {
    +    Attr  RtAttr
    +    Value []byte
    +}
    +

    +NetlinkRouteAttr represents a netlink route attribute. +

    + + + + + + + + + + + + + + + + +

    type NetlinkRouteRequest

    +
    type NetlinkRouteRequest struct {
    +    Header NlMsghdr
    +    Data   RtGenmsg
    +}
    +

    +NetlinkRouteRequest represents a request message to receive routing +and link states from the kernel. +

    + + + + + + + + + + + + + + + + +

    type NlAttr

    +
    type NlAttr struct {
    +    Len  uint16
    +    Type uint16
    +}
    + + + + + + + + + + + + + + + + +

    type NlMsgerr

    +
    type NlMsgerr struct {
    +    Error int32
    +    Msg   NlMsghdr
    +}
    + + + + + + + + + + + + + + + + +

    type NlMsghdr

    +
    type NlMsghdr struct {
    +    Len   uint32
    +    Type  uint16
    +    Flags uint16
    +    Seq   uint32
    +    Pid   uint32
    +}
    + + + + + + + + + + + + + + + + +

    type ProcAttr

    +
    type ProcAttr struct {
    +    Dir   string    // Current working directory.
    +    Env   []string  // Environment.
    +    Files []uintptr // File descriptors.
    +    Sys   *SysProcAttr
    +}
    +

    +ProcAttr holds attributes that will be applied to a new process started +by StartProcess. +

    + + + + + + + + + + + + + + + + +

    type PtraceRegs

    +
    type PtraceRegs struct {
    +    R15      uint64
    +    R14      uint64
    +    R13      uint64
    +    R12      uint64
    +    Rbp      uint64
    +    Rbx      uint64
    +    R11      uint64
    +    R10      uint64
    +    R9       uint64
    +    R8       uint64
    +    Rax      uint64
    +    Rcx      uint64
    +    Rdx      uint64
    +    Rsi      uint64
    +    Rdi      uint64
    +    Orig_rax uint64
    +    Rip      uint64
    +    Cs       uint64
    +    Eflags   uint64
    +    Rsp      uint64
    +    Ss       uint64
    +    Fs_base  uint64
    +    Gs_base  uint64
    +    Ds       uint64
    +    Es       uint64
    +    Fs       uint64
    +    Gs       uint64
    +}
    + + + + + + + + + + + + + + +

    func (*PtraceRegs) PC

    +
    func (r *PtraceRegs) PC() uint64
    + + + + + + +

    func (*PtraceRegs) SetPC

    +
    func (r *PtraceRegs) SetPC(pc uint64)
    + + + + + + + + +

    type RawSockaddr

    +
    type RawSockaddr struct {
    +    Family uint16
    +    Data   [14]int8
    +}
    + + + + + + + + + + + + + + + + +

    type RawSockaddrAny

    +
    type RawSockaddrAny struct {
    +    Addr RawSockaddr
    +    Pad  [96]int8
    +}
    + + + + + + + + + + + + + + + + +

    type RawSockaddrInet4

    +
    type RawSockaddrInet4 struct {
    +    Family uint16
    +    Port   uint16
    +    Addr   [4]byte /* in_addr */
    +    Zero   [8]uint8
    +}
    + + + + + + + + + + + + + + + + +

    type RawSockaddrInet6

    +
    type RawSockaddrInet6 struct {
    +    Family   uint16
    +    Port     uint16
    +    Flowinfo uint32
    +    Addr     [16]byte /* in6_addr */
    +    Scope_id uint32
    +}
    + + + + + + + + + + + + + + + + +

    type RawSockaddrLinklayer

    +
    type RawSockaddrLinklayer struct {
    +    Family   uint16
    +    Protocol uint16
    +    Ifindex  int32
    +    Hatype   uint16
    +    Pkttype  uint8
    +    Halen    uint8
    +    Addr     [8]uint8
    +}
    + + + + + + + + + + + + + + + + + +
    type RawSockaddrNetlink struct {
    +    Family uint16
    +    Pad    uint16
    +    Pid    uint32
    +    Groups uint32
    +}
    + + + + + + + + + + + + + + + + +

    type RawSockaddrUnix

    +
    type RawSockaddrUnix struct {
    +    Family uint16
    +    Path   [108]int8
    +}
    + + + + + + + + + + + + + + + + +

    type Rlimit

    +
    type Rlimit struct {
    +    Cur uint64
    +    Max uint64
    +}
    + + + + + + + + + + + + + + + + +

    type RtAttr

    +
    type RtAttr struct {
    +    Len  uint16
    +    Type uint16
    +}
    + + + + + + + + + + + + + + + + +

    type RtGenmsg

    +
    type RtGenmsg struct {
    +    Family uint8
    +}
    + + + + + + + + + + + + + + + + +

    type RtMsg

    +
    type RtMsg struct {
    +    Family   uint8
    +    Dst_len  uint8
    +    Src_len  uint8
    +    Tos      uint8
    +    Table    uint8
    +    Protocol uint8
    +    Scope    uint8
    +    Type     uint8
    +    Flags    uint32
    +}
    + + + + + + + + + + + + + + + + +

    type RtNexthop

    +
    type RtNexthop struct {
    +    Len     uint16
    +    Flags   uint8
    +    Hops    uint8
    +    Ifindex int32
    +}
    + + + + + + + + + + + + + + + + +

    type Rusage

    +
    type Rusage struct {
    +    Utime    Timeval
    +    Stime    Timeval
    +    Maxrss   int64
    +    Ixrss    int64
    +    Idrss    int64
    +    Isrss    int64
    +    Minflt   int64
    +    Majflt   int64
    +    Nswap    int64
    +    Inblock  int64
    +    Oublock  int64
    +    Msgsnd   int64
    +    Msgrcv   int64
    +    Nsignals int64
    +    Nvcsw    int64
    +    Nivcsw   int64
    +}
    + + + + + + + + + + + + + + + + +

    type Signal

    +
    type Signal int
    +

    +A Signal is a number describing a process signal. +It implements the os.Signal interface. +

    + + + + + + + + + + + + + + +

    func (Signal) Signal

    +
    func (s Signal) Signal()
    + + + + + + +

    func (Signal) String

    +
    func (s Signal) String() string
    + + + + + + + + +

    type SockFilter

    +
    type SockFilter struct {
    +    Code uint16
    +    Jt   uint8
    +    Jf   uint8
    +    K    uint32
    +}
    + + + + + + + + + + + + +

    func LsfJump

    +
    func LsfJump(code, k, jt, jf int) *SockFilter
    + + + + + +

    func LsfStmt

    +
    func LsfStmt(code, k int) *SockFilter
    + + + + + + + + + +

    type SockFprog

    +
    type SockFprog struct {
    +    Len       uint16
    +    Pad_cgo_0 [6]byte
    +    Filter    *SockFilter
    +}
    + + + + + + + + + + + + + + + + +

    type Sockaddr

    +
    type Sockaddr interface {
    +    // contains filtered or unexported methods
    +}
    + + + + + + + + + + + + +

    func Getpeername

    +
    func Getpeername(fd int) (sa Sockaddr, err error)
    + + + + + +

    func Getsockname

    +
    func Getsockname(fd int) (sa Sockaddr, err error)
    + + + + + + + + + +

    type SockaddrInet4

    +
    type SockaddrInet4 struct {
    +    Port int
    +    Addr [4]byte
    +    // contains filtered or unexported fields
    +}
    + + + + + + + + + + + + + + + + +

    type SockaddrInet6

    +
    type SockaddrInet6 struct {
    +    Port   int
    +    ZoneId uint32
    +    Addr   [16]byte
    +    // contains filtered or unexported fields
    +}
    + + + + + + + + + + + + + + + + +

    type SockaddrLinklayer

    +
    type SockaddrLinklayer struct {
    +    Protocol uint16
    +    Ifindex  int
    +    Hatype   uint16
    +    Pkttype  uint8
    +    Halen    uint8
    +    Addr     [8]byte
    +    // contains filtered or unexported fields
    +}
    + + + + + + + + + + + + + + + + + +
    type SockaddrNetlink struct {
    +    Family uint16
    +    Pad    uint16
    +    Pid    uint32
    +    Groups uint32
    +    // contains filtered or unexported fields
    +}
    + + + + + + + + + + + + + + + + +

    type SockaddrUnix

    +
    type SockaddrUnix struct {
    +    Name string
    +    // contains filtered or unexported fields
    +}
    + + + + + + + + + + + + + + + + +

    type SocketControlMessage

    +
    type SocketControlMessage struct {
    +    Header Cmsghdr
    +    Data   []byte
    +}
    +

    +SocketControlMessage represents a socket control message. +

    + + + + + + + + + + + + + + + + +

    type Stat_t

    +
    type Stat_t struct {
    +    Dev       uint64
    +    Ino       uint64
    +    Nlink     uint64
    +    Mode      uint32
    +    Uid       uint32
    +    Gid       uint32
    +    X__pad0   int32
    +    Rdev      uint64
    +    Size      int64
    +    Blksize   int64
    +    Blocks    int64
    +    Atim      Timespec
    +    Mtim      Timespec
    +    Ctim      Timespec
    +    X__unused [3]int64
    +}
    + + + + + + + + + + + + + + + + +

    type Statfs_t

    +
    type Statfs_t struct {
    +    Type    int64
    +    Bsize   int64
    +    Blocks  uint64
    +    Bfree   uint64
    +    Bavail  uint64
    +    Files   uint64
    +    Ffree   uint64
    +    Fsid    Fsid
    +    Namelen int64
    +    Frsize  int64
    +    Flags   int64
    +    Spare   [4]int64
    +}
    + + + + + + + + + + + + + + + + +

    type SysProcAttr

    +
    type SysProcAttr struct {
    +    Chroot      string         // Chroot.
    +    Credential  *Credential    // Credential.
    +    Ptrace      bool           // Enable tracing.
    +    Setsid      bool           // Create session.
    +    Setpgid     bool           // Set process group ID to Pgid, or, if Pgid == 0, to new pid.
    +    Setctty     bool           // Set controlling terminal to fd Ctty (only meaningful if Setsid is set)
    +    Noctty      bool           // Detach fd 0 from controlling terminal
    +    Ctty        int            // Controlling TTY fd
    +    Foreground  bool           // Place child's process group in foreground. (Implies Setpgid. Uses Ctty as fd of controlling TTY)
    +    Pgid        int            // Child's process group ID if Setpgid.
    +    Pdeathsig   Signal         // Signal that the process will get when its parent dies (Linux only)
    +    Cloneflags  uintptr        // Flags for clone calls (Linux only)
    +    UidMappings []SysProcIDMap // User ID mappings for user namespaces.
    +    GidMappings []SysProcIDMap // Group ID mappings for user namespaces.
    +    // GidMappingsEnableSetgroups enabling setgroups syscall.
    +    // If false, then setgroups syscall will be disabled for the child process.
    +    // This parameter is no-op if GidMappings == nil. Otherwise for unprivileged
    +    // users this should be set to false for mappings work.
    +    GidMappingsEnableSetgroups bool
    +}
    + + + + + + + + + + + + + + + + +

    type SysProcIDMap

    +
    type SysProcIDMap struct {
    +    ContainerID int // Container ID.
    +    HostID      int // Host ID.
    +    Size        int // Size.
    +}
    +

    +SysProcIDMap holds Container ID to Host ID mappings used for User Namespaces in Linux. +See user_namespaces(7). +

    + + + + + + + + + + + + + + + + +

    type Sysinfo_t

    +
    type Sysinfo_t struct {
    +    Uptime    int64
    +    Loads     [3]uint64
    +    Totalram  uint64
    +    Freeram   uint64
    +    Sharedram uint64
    +    Bufferram uint64
    +    Totalswap uint64
    +    Freeswap  uint64
    +    Procs     uint16
    +    Pad       uint16
    +    Pad_cgo_0 [4]byte
    +    Totalhigh uint64
    +    Freehigh  uint64
    +    Unit      uint32
    +    X_f       [0]byte
    +    Pad_cgo_1 [4]byte
    +}
    + + + + + + + + + + + + + + + + +

    type TCPInfo

    +
    type TCPInfo struct {
    +    State          uint8
    +    Ca_state       uint8
    +    Retransmits    uint8
    +    Probes         uint8
    +    Backoff        uint8
    +    Options        uint8
    +    Pad_cgo_0      [2]byte
    +    Rto            uint32
    +    Ato            uint32
    +    Snd_mss        uint32
    +    Rcv_mss        uint32
    +    Unacked        uint32
    +    Sacked         uint32
    +    Lost           uint32
    +    Retrans        uint32
    +    Fackets        uint32
    +    Last_data_sent uint32
    +    Last_ack_sent  uint32
    +    Last_data_recv uint32
    +    Last_ack_recv  uint32
    +    Pmtu           uint32
    +    Rcv_ssthresh   uint32
    +    Rtt            uint32
    +    Rttvar         uint32
    +    Snd_ssthresh   uint32
    +    Snd_cwnd       uint32
    +    Advmss         uint32
    +    Reordering     uint32
    +    Rcv_rtt        uint32
    +    Rcv_space      uint32
    +    Total_retrans  uint32
    +}
    + + + + + + + + + + + + + + + + +

    type Termios

    +
    type Termios struct {
    +    Iflag     uint32
    +    Oflag     uint32
    +    Cflag     uint32
    +    Lflag     uint32
    +    Line      uint8
    +    Cc        [32]uint8
    +    Pad_cgo_0 [3]byte
    +    Ispeed    uint32
    +    Ospeed    uint32
    +}
    + + + + + + + + + + + + + + + + +

    type Time_t

    +
    type Time_t int64
    + + + + + + + + + + + + +

    func Time

    +
    func Time(t *Time_t) (tt Time_t, err error)
    + + + + + + + + + +

    type Timespec

    +
    type Timespec struct {
    +    Sec  int64
    +    Nsec int64
    +}
    + + + + + + + + + + + + +

    func NsecToTimespec

    +
    func NsecToTimespec(nsec int64) (ts Timespec)
    + + + + + + + +

    func (*Timespec) Nano

    +
    func (ts *Timespec) Nano() int64
    + + + + + + +

    func (*Timespec) Unix

    +
    func (ts *Timespec) Unix() (sec int64, nsec int64)
    + + + + + + + + +

    type Timeval

    +
    type Timeval struct {
    +    Sec  int64
    +    Usec int64
    +}
    + + + + + + + + + + + + +

    func NsecToTimeval

    +
    func NsecToTimeval(nsec int64) (tv Timeval)
    + + + + + + + +

    func (*Timeval) Nano

    +
    func (tv *Timeval) Nano() int64
    + + + + + + +

    func (*Timeval) Unix

    +
    func (tv *Timeval) Unix() (sec int64, nsec int64)
    + + + + + + + + +

    type Timex

    +
    type Timex struct {
    +    Modes     uint32
    +    Pad_cgo_0 [4]byte
    +    Offset    int64
    +    Freq      int64
    +    Maxerror  int64
    +    Esterror  int64
    +    Status    int32
    +    Pad_cgo_1 [4]byte
    +    Constant  int64
    +    Precision int64
    +    Tolerance int64
    +    Time      Timeval
    +    Tick      int64
    +    Ppsfreq   int64
    +    Jitter    int64
    +    Shift     int32
    +    Pad_cgo_2 [4]byte
    +    Stabil    int64
    +    Jitcnt    int64
    +    Calcnt    int64
    +    Errcnt    int64
    +    Stbcnt    int64
    +    Tai       int32
    +    Pad_cgo_3 [44]byte
    +}
    + + + + + + + + + + + + + + + + +

    type Tms

    +
    type Tms struct {
    +    Utime  int64
    +    Stime  int64
    +    Cutime int64
    +    Cstime int64
    +}
    + + + + + + + + + + + + + + + + +

    type Ucred

    +
    type Ucred struct {
    +    Pid int32
    +    Uid uint32
    +    Gid uint32
    +}
    + + + + + + + + + + + + +

    func GetsockoptUcred

    +
    func GetsockoptUcred(fd, level, opt int) (*Ucred, error)
    + + + + + +

    func ParseUnixCredentials

    +
    func ParseUnixCredentials(m *SocketControlMessage) (*Ucred, error)
    +

    +ParseUnixCredentials decodes a socket control message that contains +credentials in a Ucred structure. To receive such a message, the +SO_PASSCRED option must be enabled on the socket. +

    + + + + + + + + + +

    type Ustat_t

    +
    type Ustat_t struct {
    +    Tfree     int32
    +    Pad_cgo_0 [4]byte
    +    Tinode    uint64
    +    Fname     [6]int8
    +    Fpack     [6]int8
    +    Pad_cgo_1 [4]byte
    +}
    + + + + + + + + + + + + + + + + +

    type Utimbuf

    +
    type Utimbuf struct {
    +    Actime  int64
    +    Modtime int64
    +}
    + + + + + + + + + + + + + + + + +

    type Utsname

    +
    type Utsname struct {
    +    Sysname    [65]int8
    +    Nodename   [65]int8
    +    Release    [65]int8
    +    Version    [65]int8
    +    Machine    [65]int8
    +    Domainname [65]int8
    +}
    + + + + + + + + + + + + + + + + +

    type WaitStatus

    +
    type WaitStatus uint32
    + + + + + + + + + + + + + + +

    func (WaitStatus) Continued

    +
    func (w WaitStatus) Continued() bool
    + + + + + + +

    func (WaitStatus) CoreDump

    +
    func (w WaitStatus) CoreDump() bool
    + + + + + + +

    func (WaitStatus) ExitStatus

    +
    func (w WaitStatus) ExitStatus() int
    + + + + + + +

    func (WaitStatus) Exited

    +
    func (w WaitStatus) Exited() bool
    + + + + + + +

    func (WaitStatus) Signal

    +
    func (w WaitStatus) Signal() Signal
    + + + + + + +

    func (WaitStatus) Signaled

    +
    func (w WaitStatus) Signaled() bool
    + + + + + + +

    func (WaitStatus) StopSignal

    +
    func (w WaitStatus) StopSignal() Signal
    + + + + + + +

    func (WaitStatus) Stopped

    +
    func (w WaitStatus) Stopped() bool
    + + + + + + +

    func (WaitStatus) TrapCause

    +
    func (w WaitStatus) TrapCause() int
    + + + + + + + + + + + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/testing/index.html b/pkg/testing/index.html new file mode 100644 index 0000000..a408773 --- /dev/null +++ b/pkg/testing/index.html @@ -0,0 +1,1622 @@ + + + + + + + + testing - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Package testing

    + + + + + + + + + + + + + + +
    +
    +
    import "testing"
    +
    +
    +
    Overview
    +
    Index
    + +
    Examples
    + + +
    Subdirectories
    + +
    +
    + +
    + +
    +

    Overview ▾

    +

    +Package testing provides support for automated testing of Go packages. +It is intended to be used in concert with the “go test” command, which automates +execution of any function of the form +

    +
    func TestXxx(*testing.T)
    +
    +

    +where Xxx can be any alphanumeric string (but the first letter must not be in +[a-z]) and serves to identify the test routine. +

    +

    +Within these functions, use the Error, Fail or related methods to signal failure. +

    +

    +To write a new test suite, create a file whose name ends _test.go that +contains the TestXxx functions as described here. Put the file in the same +package as the one being tested. The file will be excluded from regular +package builds but will be included when the “go test” command is run. +For more detail, run “go help test” and “go help testflag”. +

    +

    +Tests and benchmarks may be skipped if not applicable with a call to +the Skip method of *T and *B: +

    +
    func TestTimeConsuming(t *testing.T) {
    +    if testing.Short() {
    +        t.Skip("skipping test in short mode.")
    +    }
    +    ...
    +}
    +
    +

    Benchmarks

    +

    +Functions of the form +

    +
    func BenchmarkXxx(*testing.B)
    +
    +

    +are considered benchmarks, and are executed by the "go test" command when +its -bench flag is provided. Benchmarks are run sequentially. +

    +

    +For a description of the testing flags, see +https://golang.org/cmd/go/#hdr-Description_of_testing_flags. +

    +

    +A sample benchmark function looks like this: +

    +
    func BenchmarkHello(b *testing.B) {
    +    for i := 0; i < b.N; i++ {
    +        fmt.Sprintf("hello")
    +    }
    +}
    +
    +

    +The benchmark function must run the target code b.N times. +During benchmark execution, b.N is adjusted until the benchmark function lasts +long enough to be timed reliably. The output +

    +
    BenchmarkHello    10000000    282 ns/op
    +
    +

    +means that the loop ran 10000000 times at a speed of 282 ns per loop. +

    +

    +If a benchmark needs some expensive setup before running, the timer +may be reset: +

    +
    func BenchmarkBigLen(b *testing.B) {
    +    big := NewBig()
    +    b.ResetTimer()
    +    for i := 0; i < b.N; i++ {
    +        big.Len()
    +    }
    +}
    +
    +

    +If a benchmark needs to test performance in a parallel setting, it may use +the RunParallel helper function; such benchmarks are intended to be used with +the go test -cpu flag: +

    +
    func BenchmarkTemplateParallel(b *testing.B) {
    +    templ := template.Must(template.New("test").Parse("Hello, {{.}}!"))
    +    b.RunParallel(func(pb *testing.PB) {
    +        var buf bytes.Buffer
    +        for pb.Next() {
    +            buf.Reset()
    +            templ.Execute(&buf, "World")
    +        }
    +    })
    +}
    +
    +

    Examples

    +

    +The package also runs and verifies example code. Example functions may +include a concluding line comment that begins with "Output:" and is compared with +the standard output of the function when the tests are run. (The comparison +ignores leading and trailing space.) These are examples of an example: +

    +
    func ExampleHello() {
    +        fmt.Println("hello")
    +        // Output: hello
    +}
    +
    +func ExampleSalutations() {
    +        fmt.Println("hello, and")
    +        fmt.Println("goodbye")
    +        // Output:
    +        // hello, and
    +        // goodbye
    +}
    +
    +

    +Example functions without output comments are compiled but not executed. +

    +

    +The naming convention to declare examples for the package, a function F, a type T and +method M on type T are: +

    +
    func Example() { ... }
    +func ExampleF() { ... }
    +func ExampleT() { ... }
    +func ExampleT_M() { ... }
    +
    +

    +Multiple example functions for a package/type/function/method may be provided by +appending a distinct suffix to the name. The suffix must start with a +lower-case letter. +

    +
    func Example_suffix() { ... }
    +func ExampleF_suffix() { ... }
    +func ExampleT_suffix() { ... }
    +func ExampleT_M_suffix() { ... }
    +
    +

    +The entire test file is presented as the example when it contains a single +example function, at least one other function, type, variable, or constant +declaration, and no test or benchmark functions. +

    +

    Main

    +

    +It is sometimes necessary for a test program to do extra setup or teardown +before or after testing. It is also sometimes necessary for a test to control +which code runs on the main thread. To support these and other cases, +if a test file contains a function: +

    +
    func TestMain(m *testing.M)
    +
    +

    +then the generated test will call TestMain(m) instead of running the tests +directly. TestMain runs in the main goroutine and can do whatever setup +and teardown is necessary around a call to m.Run. It should then call +os.Exit with the result of m.Run. When TestMain is called, flag.Parse has +not been run. If TestMain depends on command-line flags, including those +of the testing package, it should call flag.Parse explicitly. +

    +

    +A simple implementation of TestMain is: +

    +
    func TestMain(m *testing.M) {
    +	flag.Parse()
    +	os.Exit(m.Run())
    +}
    +
    + +
    +
    + + +
    + +
    +

    Index ▾

    + + +
    +
    + + + + +
    func AllocsPerRun(runs int, f func()) (avg float64)
    + + +
    func Coverage() float64
    + + +
    func Main(matchString func(pat, str string) (bool, error), tests []InternalTest, benchmarks []InternalBenchmark, examples []InternalExample)
    + + +
    func RegisterCover(c Cover)
    + + +
    func RunBenchmarks(matchString func(pat, str string) (bool, error), benchmarks []InternalBenchmark)
    + + +
    func RunExamples(matchString func(pat, str string) (bool, error), examples []InternalExample) (ok bool)
    + + +
    func RunTests(matchString func(pat, str string) (bool, error), tests []InternalTest) (ok bool)
    + + +
    func Short() bool
    + + +
    func Verbose() bool
    + + + +
    type B
    + + + +
        func (c *B) Error(args ...interface{})
    + + +
        func (c *B) Errorf(format string, args ...interface{})
    + + +
        func (c *B) Fail()
    + + +
        func (c *B) FailNow()
    + + +
        func (c *B) Failed() bool
    + + +
        func (c *B) Fatal(args ...interface{})
    + + +
        func (c *B) Fatalf(format string, args ...interface{})
    + + +
        func (c *B) Log(args ...interface{})
    + + +
        func (c *B) Logf(format string, args ...interface{})
    + + +
        func (b *B) ReportAllocs()
    + + +
        func (b *B) ResetTimer()
    + + +
        func (b *B) RunParallel(body func(*PB))
    + + +
        func (b *B) SetBytes(n int64)
    + + +
        func (b *B) SetParallelism(p int)
    + + +
        func (c *B) Skip(args ...interface{})
    + + +
        func (c *B) SkipNow()
    + + +
        func (c *B) Skipf(format string, args ...interface{})
    + + +
        func (c *B) Skipped() bool
    + + +
        func (b *B) StartTimer()
    + + +
        func (b *B) StopTimer()
    + + + +
    type BenchmarkResult
    + + +
        func Benchmark(f func(b *B)) BenchmarkResult
    + + + +
        func (r BenchmarkResult) AllocedBytesPerOp() int64
    + + +
        func (r BenchmarkResult) AllocsPerOp() int64
    + + +
        func (r BenchmarkResult) MemString() string
    + + +
        func (r BenchmarkResult) NsPerOp() int64
    + + +
        func (r BenchmarkResult) String() string
    + + + +
    type Cover
    + + + + +
    type CoverBlock
    + + + + +
    type InternalBenchmark
    + + + + +
    type InternalExample
    + + + + +
    type InternalTest
    + + + + +
    type M
    + + +
        func MainStart(matchString func(pat, str string) (bool, error), tests []InternalTest, benchmarks []InternalBenchmark, examples []InternalExample) *M
    + + + +
        func (m *M) Run() int
    + + + +
    type PB
    + + + +
        func (pb *PB) Next() bool
    + + + +
    type T
    + + + +
        func (c *T) Error(args ...interface{})
    + + +
        func (c *T) Errorf(format string, args ...interface{})
    + + +
        func (c *T) Fail()
    + + +
        func (c *T) FailNow()
    + + +
        func (c *T) Failed() bool
    + + +
        func (c *T) Fatal(args ...interface{})
    + + +
        func (c *T) Fatalf(format string, args ...interface{})
    + + +
        func (c *T) Log(args ...interface{})
    + + +
        func (c *T) Logf(format string, args ...interface{})
    + + +
        func (t *T) Parallel()
    + + +
        func (c *T) Skip(args ...interface{})
    + + +
        func (c *T) SkipNow()
    + + +
        func (c *T) Skipf(format string, args ...interface{})
    + + +
        func (c *T) Skipped() bool
    + + + +
    type TB
    + + + + +
    +
    + + +
    +

    Examples

    +
    + +
    B.RunParallel
    + +
    +
    + + + +

    Package files

    +

    + + + allocs.go + + benchmark.go + + cover.go + + example.go + + testing.go + + +

    + +
    +
    + + + + + + + + +

    func AllocsPerRun

    +
    func AllocsPerRun(runs int, f func()) (avg float64)
    +

    +AllocsPerRun returns the average number of allocations during calls to f. +Although the return value has type float64, it will always be an integral value. +

    +

    +To compute the number of allocations, the function will first be run once as +a warm-up. The average number of allocations over the specified number of +runs will then be measured and returned. +

    +

    +AllocsPerRun sets GOMAXPROCS to 1 during its measurement and will restore +it before returning. +

    + + + + + + + +

    func Coverage

    +
    func Coverage() float64
    +

    +Coverage reports the current code coverage as a fraction in the range [0, 1]. +If coverage is not enabled, Coverage returns 0. +

    +

    +When running a large set of sequential test cases, checking Coverage after each one +can be useful for identifying which test cases exercise new code paths. +It is not a replacement for the reports generated by 'go test -cover' and +'go tool cover'. +

    + + + + + + + +

    func Main

    +
    func Main(matchString func(pat, str string) (bool, error), tests []InternalTest, benchmarks []InternalBenchmark, examples []InternalExample)
    +

    +An internal function but exported because it is cross-package; part of the implementation +of the "go test" command. +

    + + + + + + + +

    func RegisterCover

    +
    func RegisterCover(c Cover)
    +

    +RegisterCover records the coverage data accumulators for the tests. +NOTE: This function is internal to the testing infrastructure and may change. +It is not covered (yet) by the Go 1 compatibility guidelines. +

    + + + + + + + +

    func RunBenchmarks

    +
    func RunBenchmarks(matchString func(pat, str string) (bool, error), benchmarks []InternalBenchmark)
    +

    +An internal function but exported because it is cross-package; part of the implementation +of the "go test" command. +

    + + + + + + + +

    func RunExamples

    +
    func RunExamples(matchString func(pat, str string) (bool, error), examples []InternalExample) (ok bool)
    + + + + + + + +

    func RunTests

    +
    func RunTests(matchString func(pat, str string) (bool, error), tests []InternalTest) (ok bool)
    + + + + + + + +

    func Short

    +
    func Short() bool
    +

    +Short reports whether the -test.short flag is set. +

    + + + + + + + +

    func Verbose

    +
    func Verbose() bool
    +

    +Verbose reports whether the -test.v flag is set. +

    + + + + + + + + +

    type B

    +
    type B struct {
    +    N int
    +    // contains filtered or unexported fields
    +}
    +

    +B is a type passed to Benchmark functions to manage benchmark +timing and to specify the number of iterations to run. +

    +

    +A benchmark ends when its Benchmark function returns or calls any of the methods +FailNow, Fatal, Fatalf, SkipNow, Skip, or Skipf. Those methods must be called +only from the goroutine running the Benchmark function. +The other reporting methods, such as the variations of Log and Error, +may be called simultaneously from multiple goroutines. +

    +

    +Like in tests, benchmark logs are accumulated during execution +and dumped to standard error when done. Unlike in tests, benchmark logs +are always printed, so as not to hide output whose existence may be +affecting benchmark results. +

    + + + + + + + + + + + + + + +

    func (*B) Error

    +
    func (c *B) Error(args ...interface{})
    +

    +Error is equivalent to Log followed by Fail. +

    + + + + + + +

    func (*B) Errorf

    +
    func (c *B) Errorf(format string, args ...interface{})
    +

    +Errorf is equivalent to Logf followed by Fail. +

    + + + + + + +

    func (*B) Fail

    +
    func (c *B) Fail()
    +

    +Fail marks the function as having failed but continues execution. +

    + + + + + + +

    func (*B) FailNow

    +
    func (c *B) FailNow()
    +

    +FailNow marks the function as having failed and stops its execution. +Execution will continue at the next test or benchmark. +FailNow must be called from the goroutine running the +test or benchmark function, not from other goroutines +created during the test. Calling FailNow does not stop +those other goroutines. +

    + + + + + + +

    func (*B) Failed

    +
    func (c *B) Failed() bool
    +

    +Failed reports whether the function has failed. +

    + + + + + + +

    func (*B) Fatal

    +
    func (c *B) Fatal(args ...interface{})
    +

    +Fatal is equivalent to Log followed by FailNow. +

    + + + + + + +

    func (*B) Fatalf

    +
    func (c *B) Fatalf(format string, args ...interface{})
    +

    +Fatalf is equivalent to Logf followed by FailNow. +

    + + + + + + +

    func (*B) Log

    +
    func (c *B) Log(args ...interface{})
    +

    +Log formats its arguments using default formatting, analogous to Println, +and records the text in the error log. For tests, the text will be printed only if +the test fails or the -test.v flag is set. For benchmarks, the text is always +printed to avoid having performance depend on the value of the -test.v flag. +

    + + + + + + +

    func (*B) Logf

    +
    func (c *B) Logf(format string, args ...interface{})
    +

    +Logf formats its arguments according to the format, analogous to Printf, +and records the text in the error log. For tests, the text will be printed only if +the test fails or the -test.v flag is set. For benchmarks, the text is always +printed to avoid having performance depend on the value of the -test.v flag. +

    + + + + + + +

    func (*B) ReportAllocs

    +
    func (b *B) ReportAllocs()
    +

    +ReportAllocs enables malloc statistics for this benchmark. +It is equivalent to setting -test.benchmem, but it only affects the +benchmark function that calls ReportAllocs. +

    + + + + + + +

    func (*B) ResetTimer

    +
    func (b *B) ResetTimer()
    +

    +ResetTimer zeros the elapsed benchmark time and memory allocation counters. +It does not affect whether the timer is running. +

    + + + + + + +

    func (*B) RunParallel

    +
    func (b *B) RunParallel(body func(*PB))
    +

    +RunParallel runs a benchmark in parallel. +It creates multiple goroutines and distributes b.N iterations among them. +The number of goroutines defaults to GOMAXPROCS. To increase parallelism for +non-CPU-bound benchmarks, call SetParallelism before RunParallel. +RunParallel is usually used with the go test -cpu flag. +

    +

    +The body function will be run in each goroutine. It should set up any +goroutine-local state and then iterate until pb.Next returns false. +It should not use the StartTimer, StopTimer, or ResetTimer functions, +because they have global effect. +

    + + +
    + +
    +

    Example

    + + + +

    Code:

    +
    +// Parallel benchmark for text/template.Template.Execute on a single object.
    +testing.Benchmark(func(b *testing.B) {
    +    templ := template.Must(template.New("test").Parse("Hello, {{.}}!"))
    +    // RunParallel will create GOMAXPROCS goroutines
    +    // and distribute work among them.
    +    b.RunParallel(func(pb *testing.PB) {
    +        // Each goroutine has its own bytes.Buffer.
    +        var buf bytes.Buffer
    +        for pb.Next() {
    +            // The loop body is executed b.N times total across all goroutines.
    +            buf.Reset()
    +            templ.Execute(&buf, "World")
    +        }
    +    })
    +})
    +
    + + +
    +
    + + + + +

    func (*B) SetBytes

    +
    func (b *B) SetBytes(n int64)
    +

    +SetBytes records the number of bytes processed in a single operation. +If this is called, the benchmark will report ns/op and MB/s. +

    + + + + + + +

    func (*B) SetParallelism

    +
    func (b *B) SetParallelism(p int)
    +

    +SetParallelism sets the number of goroutines used by RunParallel to p*GOMAXPROCS. +There is usually no need to call SetParallelism for CPU-bound benchmarks. +If p is less than 1, this call will have no effect. +

    + + + + + + +

    func (*B) Skip

    +
    func (c *B) Skip(args ...interface{})
    +

    +Skip is equivalent to Log followed by SkipNow. +

    + + + + + + +

    func (*B) SkipNow

    +
    func (c *B) SkipNow()
    +

    +SkipNow marks the test as having been skipped and stops its execution. +Execution will continue at the next test or benchmark. See also FailNow. +SkipNow must be called from the goroutine running the test, not from +other goroutines created during the test. Calling SkipNow does not stop +those other goroutines. +

    + + + + + + +

    func (*B) Skipf

    +
    func (c *B) Skipf(format string, args ...interface{})
    +

    +Skipf is equivalent to Logf followed by SkipNow. +

    + + + + + + +

    func (*B) Skipped

    +
    func (c *B) Skipped() bool
    +

    +Skipped reports whether the test was skipped. +

    + + + + + + +

    func (*B) StartTimer

    +
    func (b *B) StartTimer()
    +

    +StartTimer starts timing a test. This function is called automatically +before a benchmark starts, but it can also used to resume timing after +a call to StopTimer. +

    + + + + + + +

    func (*B) StopTimer

    +
    func (b *B) StopTimer()
    +

    +StopTimer stops timing a test. This can be used to pause the timer +while performing complex initialization that you don't +want to measure. +

    + + + + + + + + +

    type BenchmarkResult

    +
    type BenchmarkResult struct {
    +    N         int           // The number of iterations.
    +    T         time.Duration // The total time taken.
    +    Bytes     int64         // Bytes processed in one iteration.
    +    MemAllocs uint64        // The total number of memory allocations.
    +    MemBytes  uint64        // The total number of bytes allocated.
    +}
    +

    +The results of a benchmark run. +

    + + + + + + + + + + + + +

    func Benchmark

    +
    func Benchmark(f func(b *B)) BenchmarkResult
    +

    +Benchmark benchmarks a single function. Useful for creating +custom benchmarks that do not use the "go test" command. +

    + + + + + + + +

    func (BenchmarkResult) AllocedBytesPerOp

    +
    func (r BenchmarkResult) AllocedBytesPerOp() int64
    + + + + + + +

    func (BenchmarkResult) AllocsPerOp

    +
    func (r BenchmarkResult) AllocsPerOp() int64
    + + + + + + +

    func (BenchmarkResult) MemString

    +
    func (r BenchmarkResult) MemString() string
    + + + + + + +

    func (BenchmarkResult) NsPerOp

    +
    func (r BenchmarkResult) NsPerOp() int64
    + + + + + + +

    func (BenchmarkResult) String

    +
    func (r BenchmarkResult) String() string
    + + + + + + + + +

    type Cover

    +
    type Cover struct {
    +    Mode            string
    +    Counters        map[string][]uint32
    +    Blocks          map[string][]CoverBlock
    +    CoveredPackages string
    +}
    +

    +Cover records information about test coverage checking. +NOTE: This struct is internal to the testing infrastructure and may change. +It is not covered (yet) by the Go 1 compatibility guidelines. +

    + + + + + + + + + + + + + + + + +

    type CoverBlock

    +
    type CoverBlock struct {
    +    Line0 uint32
    +    Col0  uint16
    +    Line1 uint32
    +    Col1  uint16
    +    Stmts uint16
    +}
    +

    +CoverBlock records the coverage data for a single basic block. +NOTE: This struct is internal to the testing infrastructure and may change. +It is not covered (yet) by the Go 1 compatibility guidelines. +

    + + + + + + + + + + + + + + + + +

    type InternalBenchmark

    +
    type InternalBenchmark struct {
    +    Name string
    +    F    func(b *B)
    +}
    +

    +An internal type but exported because it is cross-package; part of the implementation +of the "go test" command. +

    + + + + + + + + + + + + + + + + +

    type InternalExample

    +
    type InternalExample struct {
    +    Name   string
    +    F      func()
    +    Output string
    +}
    + + + + + + + + + + + + + + + + +

    type InternalTest

    +
    type InternalTest struct {
    +    Name string
    +    F    func(*T)
    +}
    +

    +An internal type but exported because it is cross-package; part of the implementation +of the "go test" command. +

    + + + + + + + + + + + + + + + + +

    type M

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

    +M is a type passed to a TestMain function to run the actual tests. +

    + + + + + + + + + + + + +

    func MainStart

    +
    func MainStart(matchString func(pat, str string) (bool, error), tests []InternalTest, benchmarks []InternalBenchmark, examples []InternalExample) *M
    +

    +MainStart is meant for use by tests generated by 'go test'. +It is not meant to be called directly and is not subject to the Go 1 compatibility document. +It may change signature from release to release. +

    + + + + + + + +

    func (*M) Run

    +
    func (m *M) Run() int
    +

    +Run runs the tests. It returns an exit code to pass to os.Exit. +

    + + + + + + + + +

    type PB

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

    +A PB is used by RunParallel for running parallel benchmarks. +

    + + + + + + + + + + + + + + +

    func (*PB) Next

    +
    func (pb *PB) Next() bool
    +

    +Next reports whether there are more iterations to execute. +

    + + + + + + + + +

    type T

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

    +T is a type passed to Test functions to manage test state and support formatted test logs. +Logs are accumulated during execution and dumped to standard error when done. +

    +

    +A test ends when its Test function returns or calls any of the methods +FailNow, Fatal, Fatalf, SkipNow, Skip, or Skipf. Those methods, as well as +the Parallel method, must be called only from the goroutine running the +Test function. +

    +

    +The other reporting methods, such as the variations of Log and Error, +may be called simultaneously from multiple goroutines. +

    + + + + + + + + + + + + + + +

    func (*T) Error

    +
    func (c *T) Error(args ...interface{})
    +

    +Error is equivalent to Log followed by Fail. +

    + + + + + + +

    func (*T) Errorf

    +
    func (c *T) Errorf(format string, args ...interface{})
    +

    +Errorf is equivalent to Logf followed by Fail. +

    + + + + + + +

    func (*T) Fail

    +
    func (c *T) Fail()
    +

    +Fail marks the function as having failed but continues execution. +

    + + + + + + +

    func (*T) FailNow

    +
    func (c *T) FailNow()
    +

    +FailNow marks the function as having failed and stops its execution. +Execution will continue at the next test or benchmark. +FailNow must be called from the goroutine running the +test or benchmark function, not from other goroutines +created during the test. Calling FailNow does not stop +those other goroutines. +

    + + + + + + +

    func (*T) Failed

    +
    func (c *T) Failed() bool
    +

    +Failed reports whether the function has failed. +

    + + + + + + +

    func (*T) Fatal

    +
    func (c *T) Fatal(args ...interface{})
    +

    +Fatal is equivalent to Log followed by FailNow. +

    + + + + + + +

    func (*T) Fatalf

    +
    func (c *T) Fatalf(format string, args ...interface{})
    +

    +Fatalf is equivalent to Logf followed by FailNow. +

    + + + + + + +

    func (*T) Log

    +
    func (c *T) Log(args ...interface{})
    +

    +Log formats its arguments using default formatting, analogous to Println, +and records the text in the error log. For tests, the text will be printed only if +the test fails or the -test.v flag is set. For benchmarks, the text is always +printed to avoid having performance depend on the value of the -test.v flag. +

    + + + + + + +

    func (*T) Logf

    +
    func (c *T) Logf(format string, args ...interface{})
    +

    +Logf formats its arguments according to the format, analogous to Printf, +and records the text in the error log. For tests, the text will be printed only if +the test fails or the -test.v flag is set. For benchmarks, the text is always +printed to avoid having performance depend on the value of the -test.v flag. +

    + + + + + + +

    func (*T) Parallel

    +
    func (t *T) Parallel()
    +

    +Parallel signals that this test is to be run in parallel with (and only with) +other parallel tests. +

    + + + + + + +

    func (*T) Skip

    +
    func (c *T) Skip(args ...interface{})
    +

    +Skip is equivalent to Log followed by SkipNow. +

    + + + + + + +

    func (*T) SkipNow

    +
    func (c *T) SkipNow()
    +

    +SkipNow marks the test as having been skipped and stops its execution. +Execution will continue at the next test or benchmark. See also FailNow. +SkipNow must be called from the goroutine running the test, not from +other goroutines created during the test. Calling SkipNow does not stop +those other goroutines. +

    + + + + + + +

    func (*T) Skipf

    +
    func (c *T) Skipf(format string, args ...interface{})
    +

    +Skipf is equivalent to Logf followed by SkipNow. +

    + + + + + + +

    func (*T) Skipped

    +
    func (c *T) Skipped() bool
    +

    +Skipped reports whether the test was skipped. +

    + + + + + + + + +

    type TB

    +
    type TB interface {
    +    Error(args ...interface{})
    +    Errorf(format string, args ...interface{})
    +    Fail()
    +    FailNow()
    +    Failed() bool
    +    Fatal(args ...interface{})
    +    Fatalf(format string, args ...interface{})
    +    Log(args ...interface{})
    +    Logf(format string, args ...interface{})
    +    Skip(args ...interface{})
    +    SkipNow()
    +    Skipf(format string, args ...interface{})
    +    Skipped() bool
    +    // contains filtered or unexported methods
    +}
    +

    +TB is the interface common to T and B. +

    + + + + + + + + + + + + + + + + + + + + + + + + +

    Subdirectories

    + + + + +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    NameSynopsis
    ..
    + iotest + + Package iotest implements Readers and Writers useful mainly for testing. +
    + quick + + Package quick implements utility functions to help with black box testing. +
    +
    + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/testing/iotest/index.html b/pkg/testing/iotest/index.html new file mode 100644 index 0000000..4614c29 --- /dev/null +++ b/pkg/testing/iotest/index.html @@ -0,0 +1,334 @@ + + + + + + + + iotest - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Package iotest

    + + + + + + + + + + + + + + +
    +
    +
    import "testing/iotest"
    +
    +
    +
    Overview
    +
    Index
    + + +
    +
    + +
    + +
    +

    Overview ▾

    +

    +Package iotest implements Readers and Writers useful mainly for testing. +

    + +
    +
    + + + + + + + + +

    Variables

    + +
    var ErrTimeout = errors.New("timeout")
    + + + + + + +

    func DataErrReader

    +
    func DataErrReader(r io.Reader) io.Reader
    +

    +DataErrReader changes the way errors are handled by a Reader. Normally, a +Reader returns an error (typically EOF) from the first Read call after the +last piece of data is read. DataErrReader wraps a Reader and changes its +behavior so the final error is returned along with the final data, instead +of in the first call after the final data. +

    + + + + + + + +

    func HalfReader

    +
    func HalfReader(r io.Reader) io.Reader
    +

    +HalfReader returns a Reader that implements Read +by reading half as many requested bytes from r. +

    + + + + + + + +

    func NewReadLogger

    +
    func NewReadLogger(prefix string, r io.Reader) io.Reader
    +

    +NewReadLogger returns a reader that behaves like r except +that it logs (using log.Print) each read to standard error, +printing the prefix and the hexadecimal data read. +

    + + + + + + + +

    func NewWriteLogger

    +
    func NewWriteLogger(prefix string, w io.Writer) io.Writer
    +

    +NewWriteLogger returns a writer that behaves like w except +that it logs (using log.Printf) each write to standard error, +printing the prefix and the hexadecimal data written. +

    + + + + + + + +

    func OneByteReader

    +
    func OneByteReader(r io.Reader) io.Reader
    +

    +OneByteReader returns a Reader that implements +each non-empty Read by reading one byte from r. +

    + + + + + + + +

    func TimeoutReader

    +
    func TimeoutReader(r io.Reader) io.Reader
    +

    +TimeoutReader returns ErrTimeout on the second read +with no data. Subsequent calls to read succeed. +

    + + + + + + + +

    func TruncateWriter

    +
    func TruncateWriter(w io.Writer, n int64) io.Writer
    +

    +TruncateWriter returns a Writer that writes to w +but stops silently after n bytes. +

    + + + + + + + + + + + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/testing/quick/index.html b/pkg/testing/quick/index.html new file mode 100644 index 0000000..34fa151 --- /dev/null +++ b/pkg/testing/quick/index.html @@ -0,0 +1,459 @@ + + + + + + + + quick - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Package quick

    + + + + + + + + + + + + + + +
    +
    +
    import "testing/quick"
    +
    +
    +
    Overview
    +
    Index
    + + +
    +
    + +
    + +
    +

    Overview ▾

    +

    +Package quick implements utility functions to help with black box testing. +

    + +
    +
    + + + + + + + + + + + +

    func Check

    +
    func Check(f interface{}, config *Config) (err error)
    +

    +Check looks for an input to f, any function that returns bool, +such that f returns false. It calls f repeatedly, with arbitrary +values for each argument. If f returns false on a given input, +Check returns that input as a *CheckError. +For example: +

    +
    func TestOddMultipleOfThree(t *testing.T) {
    +	f := func(x int) bool {
    +		y := OddMultipleOfThree(x)
    +		return y%2 == 1 && y%3 == 0
    +	}
    +	if err := quick.Check(f, nil); err != nil {
    +		t.Error(err)
    +	}
    +}
    +
    + + + + + + + +

    func CheckEqual

    +
    func CheckEqual(f, g interface{}, config *Config) (err error)
    +

    +CheckEqual looks for an input on which f and g return different results. +It calls f and g repeatedly with arbitrary values for each argument. +If f and g return different answers, CheckEqual returns a *CheckEqualError +describing the input and the outputs. +

    + + + + + + + +

    func Value

    +
    func Value(t reflect.Type, rand *rand.Rand) (value reflect.Value, ok bool)
    +

    +Value returns an arbitrary value of the given type. +If the type implements the Generator interface, that will be used. +Note: To create arbitrary values for structs, all the fields must be exported. +

    + + + + + + + + +

    type CheckEqualError

    +
    type CheckEqualError struct {
    +    CheckError
    +    Out1 []interface{}
    +    Out2 []interface{}
    +}
    +

    +A CheckEqualError is the result CheckEqual finding an error. +

    + + + + + + + + + + + + + + +

    func (*CheckEqualError) Error

    +
    func (s *CheckEqualError) Error() string
    + + + + + + + + +

    type CheckError

    +
    type CheckError struct {
    +    Count int
    +    In    []interface{}
    +}
    +

    +A CheckError is the result of Check finding an error. +

    + + + + + + + + + + + + + + +

    func (*CheckError) Error

    +
    func (s *CheckError) Error() string
    + + + + + + + + +

    type Config

    +
    type Config struct {
    +    // MaxCount sets the maximum number of iterations. If zero,
    +    // MaxCountScale is used.
    +    MaxCount int
    +    // MaxCountScale is a non-negative scale factor applied to the default
    +    // maximum. If zero, the default is unchanged.
    +    MaxCountScale float64
    +    // If non-nil, rand is a source of random numbers. Otherwise a default
    +    // pseudo-random source will be used.
    +    Rand *rand.Rand
    +    // If non-nil, the Values function generates a slice of arbitrary
    +    // reflect.Values that are congruent with the arguments to the function
    +    // being tested. Otherwise, the top-level Value function is used
    +    // to generate them.
    +    Values func([]reflect.Value, *rand.Rand)
    +}
    +

    +A Config structure contains options for running a test. +

    + + + + + + + + + + + + + + + + +

    type Generator

    +
    type Generator interface {
    +    // Generate returns a random instance of the type on which it is a
    +    // method using the size as a size hint.
    +    Generate(rand *rand.Rand, size int) reflect.Value
    +}
    +

    +A Generator can generate random values of its own type. +

    + + + + + + + + + + + + + + + + +

    type SetupError

    +
    type SetupError string
    +

    +A SetupError is the result of an error in the way that check is being +used, independent of the functions being tested. +

    + + + + + + + + + + + + + + +

    func (SetupError) Error

    +
    func (s SetupError) Error() string
    + + + + + + + + + + + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/time/index.html b/pkg/time/index.html new file mode 100644 index 0000000..e85d986 --- /dev/null +++ b/pkg/time/index.html @@ -0,0 +1,2170 @@ + + + + + + + + time - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Package time

    + + + + + + + + + + + + + + +
    +
    +
    import "time"
    +
    +
    +
    Overview
    +
    Index
    + +
    Examples
    + + +
    +
    + +
    + +
    +

    Overview ▾

    +

    +Package time provides functionality for measuring and displaying time. +

    +

    +The calendrical calculations always assume a Gregorian calendar. +

    + +
    +
    + + +
    + +
    +

    Index ▾

    + + +
    +
    + +
    Constants
    + + + + +
    func After(d Duration) <-chan Time
    + + +
    func Sleep(d Duration)
    + + +
    func Tick(d Duration) <-chan Time
    + + + +
    type Duration
    + + +
        func ParseDuration(s string) (Duration, error)
    + + +
        func Since(t Time) Duration
    + + + +
        func (d Duration) Hours() float64
    + + +
        func (d Duration) Minutes() float64
    + + +
        func (d Duration) Nanoseconds() int64
    + + +
        func (d Duration) Seconds() float64
    + + +
        func (d Duration) String() string
    + + + +
    type Location
    + + +
        func FixedZone(name string, offset int) *Location
    + + +
        func LoadLocation(name string) (*Location, error)
    + + + +
        func (l *Location) String() string
    + + + +
    type Month
    + + + +
        func (m Month) String() string
    + + + +
    type ParseError
    + + + +
        func (e *ParseError) Error() string
    + + + +
    type Ticker
    + + +
        func NewTicker(d Duration) *Ticker
    + + + +
        func (t *Ticker) Stop()
    + + + +
    type Time
    + + +
        func Date(year int, month Month, day, hour, min, sec, nsec int, loc *Location) Time
    + + +
        func Now() Time
    + + +
        func Parse(layout, value string) (Time, error)
    + + +
        func ParseInLocation(layout, value string, loc *Location) (Time, error)
    + + +
        func Unix(sec int64, nsec int64) Time
    + + + +
        func (t Time) Add(d Duration) Time
    + + +
        func (t Time) AddDate(years int, months int, days int) Time
    + + +
        func (t Time) After(u Time) bool
    + + +
        func (t Time) AppendFormat(b []byte, layout string) []byte
    + + +
        func (t Time) Before(u Time) bool
    + + +
        func (t Time) Clock() (hour, min, sec int)
    + + +
        func (t Time) Date() (year int, month Month, day int)
    + + +
        func (t Time) Day() int
    + + +
        func (t Time) Equal(u Time) bool
    + + +
        func (t Time) Format(layout string) string
    + + +
        func (t *Time) GobDecode(data []byte) error
    + + +
        func (t Time) GobEncode() ([]byte, error)
    + + +
        func (t Time) Hour() int
    + + +
        func (t Time) ISOWeek() (year, week int)
    + + +
        func (t Time) In(loc *Location) Time
    + + +
        func (t Time) IsZero() bool
    + + +
        func (t Time) Local() Time
    + + +
        func (t Time) Location() *Location
    + + +
        func (t Time) MarshalBinary() ([]byte, error)
    + + +
        func (t Time) MarshalJSON() ([]byte, error)
    + + +
        func (t Time) MarshalText() ([]byte, error)
    + + +
        func (t Time) Minute() int
    + + +
        func (t Time) Month() Month
    + + +
        func (t Time) Nanosecond() int
    + + +
        func (t Time) Round(d Duration) Time
    + + +
        func (t Time) Second() int
    + + +
        func (t Time) String() string
    + + +
        func (t Time) Sub(u Time) Duration
    + + +
        func (t Time) Truncate(d Duration) Time
    + + +
        func (t Time) UTC() Time
    + + +
        func (t Time) Unix() int64
    + + +
        func (t Time) UnixNano() int64
    + + +
        func (t *Time) UnmarshalBinary(data []byte) error
    + + +
        func (t *Time) UnmarshalJSON(data []byte) (err error)
    + + +
        func (t *Time) UnmarshalText(data []byte) (err error)
    + + +
        func (t Time) Weekday() Weekday
    + + +
        func (t Time) Year() int
    + + +
        func (t Time) YearDay() int
    + + +
        func (t Time) Zone() (name string, offset int)
    + + + +
    type Timer
    + + +
        func AfterFunc(d Duration, f func()) *Timer
    + + +
        func NewTimer(d Duration) *Timer
    + + + +
        func (t *Timer) Reset(d Duration) bool
    + + +
        func (t *Timer) Stop() bool
    + + + +
    type Weekday
    + + + +
        func (d Weekday) String() string
    + + + +
    +
    + + +
    +

    Examples

    +
    + +
    After
    + +
    Date
    + +
    Duration
    + +
    Month
    + +
    Parse
    + +
    ParseInLocation
    + +
    Sleep
    + +
    Tick
    + +
    Time.Format
    + +
    Time.Round
    + +
    Time.Truncate
    + +
    +
    + + + +

    Package files

    +

    + + + format.go + + sleep.go + + sys_unix.go + + tick.go + + time.go + + zoneinfo.go + + zoneinfo_read.go + + zoneinfo_unix.go + + +

    + +
    +
    + + + + +

    Constants

    + +
    const (
    +    ANSIC       = "Mon Jan _2 15:04:05 2006"
    +    UnixDate    = "Mon Jan _2 15:04:05 MST 2006"
    +    RubyDate    = "Mon Jan 02 15:04:05 -0700 2006"
    +    RFC822      = "02 Jan 06 15:04 MST"
    +    RFC822Z     = "02 Jan 06 15:04 -0700" // RFC822 with numeric zone
    +    RFC850      = "Monday, 02-Jan-06 15:04:05 MST"
    +    RFC1123     = "Mon, 02 Jan 2006 15:04:05 MST"
    +    RFC1123Z    = "Mon, 02 Jan 2006 15:04:05 -0700" // RFC1123 with numeric zone
    +    RFC3339     = "2006-01-02T15:04:05Z07:00"
    +    RFC3339Nano = "2006-01-02T15:04:05.999999999Z07:00"
    +    Kitchen     = "3:04PM"
    +    // Handy time stamps.
    +    Stamp      = "Jan _2 15:04:05"
    +    StampMilli = "Jan _2 15:04:05.000"
    +    StampMicro = "Jan _2 15:04:05.000000"
    +    StampNano  = "Jan _2 15:04:05.000000000"
    +)
    +

    +These are predefined layouts for use in Time.Format and Time.Parse. +The reference time used in the layouts is the specific time: +

    +
    Mon Jan 2 15:04:05 MST 2006
    +
    +

    +which is Unix time 1136239445. Since MST is GMT-0700, +the reference time can be thought of as +

    +
    01/02 03:04:05PM '06 -0700
    +
    +

    +To define your own format, write down what the reference time would look +like formatted your way; see the values of constants like ANSIC, +StampMicro or Kitchen for examples. The model is to demonstrate what the +reference time looks like so that the Format and Parse methods can apply +the same transformation to a general time value. +

    +

    +Within the format string, an underscore _ represents a space that may be +replaced by a digit if the following number (a day) has two digits; for +compatibility with fixed-width Unix time formats. +

    +

    +A decimal point followed by one or more zeros represents a fractional +second, printed to the given number of decimal places. A decimal point +followed by one or more nines represents a fractional second, printed to +the given number of decimal places, with trailing zeros removed. +When parsing (only), the input may contain a fractional second +field immediately after the seconds field, even if the layout does not +signify its presence. In that case a decimal point followed by a maximal +series of digits is parsed as a fractional second. +

    +

    +Numeric time zone offsets format as follows: +

    +
    -0700  ±hhmm
    +-07:00 ±hh:mm
    +-07    ±hh
    +
    +

    +Replacing the sign in the format with a Z triggers +the ISO 8601 behavior of printing Z instead of an +offset for the UTC zone. Thus: +

    +
    Z0700  Z or ±hhmm
    +Z07:00 Z or ±hh:mm
    +Z07    Z or ±hh
    +
    +

    +The executable example for time.Format demonstrates the working +of the layout string in detail and is a good reference. +

    +

    +Note that the RFC822, RFC850, and RFC1123 formats should be applied +only to local times. Applying them to UTC times will use "UTC" as the +time zone abbreviation, while strictly speaking those RFCs require the +use of "GMT" in that case. +In general RFC1123Z should be used instead of RFC1123 for servers +that insist on that format, and RFC3339 should be preferred for new protocols. +

    + + + + + + + +

    func After

    +
    func After(d Duration) <-chan Time
    +

    +After waits for the duration to elapse and then sends the current time +on the returned channel. +It is equivalent to NewTimer(d).C. +

    + +
    + +
    +

    Example

    + + + +

    Code:

    +
    +select {
    +case m := <-c:
    +    handle(m)
    +case <-time.After(5 * time.Minute):
    +    fmt.Println("timed out")
    +}
    +
    + + +
    +
    + + + + + + +

    func Sleep

    +
    func Sleep(d Duration)
    +

    +Sleep pauses the current goroutine for at least the duration d. +A negative or zero duration causes Sleep to return immediately. +

    + +
    + +
    +

    Example

    + + + +

    Code:

    +
    +time.Sleep(100 * time.Millisecond)
    +
    + + +
    +
    + + + + + + +

    func Tick

    +
    func Tick(d Duration) <-chan Time
    +

    +Tick is a convenience wrapper for NewTicker providing access to the ticking +channel only. While Tick is useful for clients that have no need to shut down +the Ticker, be aware that without a way to shut it down the underlying +Ticker cannot be recovered by the garbage collector; it "leaks". +

    + +
    + +
    +

    Example

    + + + +

    Code:

    +
    +c := time.Tick(1 * time.Minute)
    +for now := range c {
    +    fmt.Printf("%v %s\n", now, statusUpdate())
    +}
    +
    + + +
    +
    + + + + + + + +

    type Duration

    +
    type Duration int64
    +

    +A Duration represents the elapsed time between two instants +as an int64 nanosecond count. The representation limits the +largest representable duration to approximately 290 years. +

    + + + +
    const (
    +    Nanosecond  Duration = 1
    +    Microsecond          = 1000 * Nanosecond
    +    Millisecond          = 1000 * Microsecond
    +    Second               = 1000 * Millisecond
    +    Minute               = 60 * Second
    +    Hour                 = 60 * Minute
    +)
    +

    +Common durations. There is no definition for units of Day or larger +to avoid confusion across daylight savings time zone transitions. +

    +

    +To count the number of units in a Duration, divide: +

    +
    second := time.Second
    +fmt.Print(int64(second/time.Millisecond)) // prints 1000
    +
    +

    +To convert an integer number of units to a Duration, multiply: +

    +
    seconds := 10
    +fmt.Print(time.Duration(seconds)*time.Second) // prints 10s
    +
    + + + + + +
    + +
    +

    Example

    + + + +

    Code:

    +
    +t0 := time.Now()
    +expensiveCall()
    +t1 := time.Now()
    +fmt.Printf("The call took %v to run.\n", t1.Sub(t0))
    +
    + + +
    +
    + + + + + + +

    func ParseDuration

    +
    func ParseDuration(s string) (Duration, error)
    +

    +ParseDuration parses a duration string. +A duration string is a possibly signed sequence of +decimal numbers, each with optional fraction and a unit suffix, +such as "300ms", "-1.5h" or "2h45m". +Valid time units are "ns", "us" (or "µs"), "ms", "s", "m", "h". +

    + + + + + +

    func Since

    +
    func Since(t Time) Duration
    +

    +Since returns the time elapsed since t. +It is shorthand for time.Now().Sub(t). +

    + + + + + + + +

    func (Duration) Hours

    +
    func (d Duration) Hours() float64
    +

    +Hours returns the duration as a floating point number of hours. +

    + + + + + + +

    func (Duration) Minutes

    +
    func (d Duration) Minutes() float64
    +

    +Minutes returns the duration as a floating point number of minutes. +

    + + + + + + +

    func (Duration) Nanoseconds

    +
    func (d Duration) Nanoseconds() int64
    +

    +Nanoseconds returns the duration as an integer nanosecond count. +

    + + + + + + +

    func (Duration) Seconds

    +
    func (d Duration) Seconds() float64
    +

    +Seconds returns the duration as a floating point number of seconds. +

    + + + + + + +

    func (Duration) String

    +
    func (d Duration) String() string
    +

    +String returns a string representing the duration in the form "72h3m0.5s". +Leading zero units are omitted. As a special case, durations less than one +second format use a smaller unit (milli-, micro-, or nanoseconds) to ensure +that the leading digit is non-zero. The zero duration formats as 0, +with no unit. +

    + + + + + + + + +

    type Location

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

    +A Location maps time instants to the zone in use at that time. +Typically, the Location represents the collection of time offsets +in use in a geographical area, such as CEST and CET for central Europe. +

    + + + + + +
    var Local *Location = &localLoc
    +

    +Local represents the system's local time zone. +

    + + +
    var UTC *Location = &utcLoc
    +

    +UTC represents Universal Coordinated Time (UTC). +

    + + + + + + + + + +

    func FixedZone

    +
    func FixedZone(name string, offset int) *Location
    +

    +FixedZone returns a Location that always uses +the given zone name and offset (seconds east of UTC). +

    + + + + + +

    func LoadLocation

    +
    func LoadLocation(name string) (*Location, error)
    +

    +LoadLocation returns the Location with the given name. +

    +

    +If the name is "" or "UTC", LoadLocation returns UTC. +If the name is "Local", LoadLocation returns Local. +

    +

    +Otherwise, the name is taken to be a location name corresponding to a file +in the IANA Time Zone database, such as "America/New_York". +

    +

    +The time zone database needed by LoadLocation may not be +present on all systems, especially non-Unix systems. +LoadLocation looks in the directory or uncompressed zip file +named by the ZONEINFO environment variable, if any, then looks in +known installation locations on Unix systems, +and finally looks in $GOROOT/lib/time/zoneinfo.zip. +

    + + + + + + + +

    func (*Location) String

    +
    func (l *Location) String() string
    +

    +String returns a descriptive name for the time zone information, +corresponding to the argument to LoadLocation. +

    + + + + + + + + +

    type Month

    +
    type Month int
    +

    +A Month specifies a month of the year (January = 1, ...). +

    + + + +
    const (
    +    January Month = 1 + iota
    +    February
    +    March
    +    April
    +    May
    +    June
    +    July
    +    August
    +    September
    +    October
    +    November
    +    December
    +)
    + + + + + +
    + +
    +

    Example

    + + + +

    Code:

    +
    +_, month, day := time.Now().Date()
    +if month == time.November && day == 10 {
    +    fmt.Println("Happy Go day!")
    +}
    +
    + + +
    +
    + + + + + + + + +

    func (Month) String

    +
    func (m Month) String() string
    +

    +String returns the English name of the month ("January", "February", ...). +

    + + + + + + + + +

    type ParseError

    +
    type ParseError struct {
    +    Layout     string
    +    Value      string
    +    LayoutElem string
    +    ValueElem  string
    +    Message    string
    +}
    +

    +ParseError describes a problem parsing a time string. +

    + + + + + + + + + + + + + + +

    func (*ParseError) Error

    +
    func (e *ParseError) Error() string
    +

    +Error returns the string representation of a ParseError. +

    + + + + + + + + +

    type Ticker

    +
    type Ticker struct {
    +    C <-chan Time // The channel on which the ticks are delivered.
    +    // contains filtered or unexported fields
    +}
    +

    +A Ticker holds a channel that delivers `ticks' of a clock +at intervals. +

    + + + + + + + + + + + + +

    func NewTicker

    +
    func NewTicker(d Duration) *Ticker
    +

    +NewTicker returns a new Ticker containing a channel that will send the +time with a period specified by the duration argument. +It adjusts the intervals or drops ticks to make up for slow receivers. +The duration d must be greater than zero; if not, NewTicker will panic. +Stop the ticker to release associated resources. +

    + + + + + + + +

    func (*Ticker) Stop

    +
    func (t *Ticker) Stop()
    +

    +Stop turns off a ticker. After Stop, no more ticks will be sent. +Stop does not close the channel, to prevent a read from the channel succeeding +incorrectly. +

    + + + + + + + + +

    type Time

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

    +A Time represents an instant in time with nanosecond precision. +

    +

    +Programs using times should typically store and pass them as values, +not pointers. That is, time variables and struct fields should be of +type time.Time, not *time.Time. A Time value can be used by +multiple goroutines simultaneously. +

    +

    +Time instants can be compared using the Before, After, and Equal methods. +The Sub method subtracts two instants, producing a Duration. +The Add method adds a Time and a Duration, producing a Time. +

    +

    +The zero value of type Time is January 1, year 1, 00:00:00.000000000 UTC. +As this time is unlikely to come up in practice, the IsZero method gives +a simple way of detecting a time that has not been initialized explicitly. +

    +

    +Each Time has associated with it a Location, consulted when computing the +presentation form of the time, such as in the Format, Hour, and Year methods. +The methods Local, UTC, and In return a Time with a specific location. +Changing the location in this way changes only the presentation; it does not +change the instant in time being denoted and therefore does not affect the +computations described in earlier paragraphs. +

    +

    +Note that the Go == operator compares not just the time instant but also the +Location. Therefore, Time values should not be used as map or database keys +without first guaranteeing that the identical Location has been set for all +values, which can be achieved through use of the UTC or Local method. +

    + + + + + + + + + + + + +

    func Date

    +
    func Date(year int, month Month, day, hour, min, sec, nsec int, loc *Location) Time
    +

    +Date returns the Time corresponding to +

    +
    yyyy-mm-dd hh:mm:ss + nsec nanoseconds
    +
    +

    +in the appropriate zone for that time in the given location. +

    +

    +The month, day, hour, min, sec, and nsec values may be outside +their usual ranges and will be normalized during the conversion. +For example, October 32 converts to November 1. +

    +

    +A daylight savings time transition skips or repeats times. +For example, in the United States, March 13, 2011 2:15am never occurred, +while November 6, 2011 1:15am occurred twice. In such cases, the +choice of time zone, and therefore the time, is not well-defined. +Date returns a time that is correct in one of the two zones involved +in the transition, but it does not guarantee which. +

    +

    +Date panics if loc is nil. +

    + +
    + +
    +

    Example

    + + + +

    Code:

    +
    t := time.Date(2009, time.November, 10, 23, 0, 0, 0, time.UTC)
    +fmt.Printf("Go launched at %s\n", t.Local())
    +
    + +

    Output:

    +
    Go launched at 2009-11-10 15:00:00 -0800 PST
    +
    + + +
    +
    + + + + +

    func Now

    +
    func Now() Time
    +

    +Now returns the current local time. +

    + + + + + +

    func Parse

    +
    func Parse(layout, value string) (Time, error)
    +

    +Parse parses a formatted string and returns the time value it represents. +The layout defines the format by showing how the reference time, +defined to be +

    +
    Mon Jan 2 15:04:05 -0700 MST 2006
    +
    +

    +would be interpreted if it were the value; it serves as an example of +the input format. The same interpretation will then be made to the +input string. +

    +

    +Predefined layouts ANSIC, UnixDate, RFC3339 and others describe standard +and convenient representations of the reference time. For more information +about the formats and the definition of the reference time, see the +documentation for ANSIC and the other constants defined by this package. +Also, the executable example for time.Format demonstrates the working +of the layout string in detail and is a good reference. +

    +

    +Elements omitted from the value are assumed to be zero or, when +zero is impossible, one, so parsing "3:04pm" returns the time +corresponding to Jan 1, year 0, 15:04:00 UTC (note that because the year is +0, this time is before the zero Time). +Years must be in the range 0000..9999. The day of the week is checked +for syntax but it is otherwise ignored. +

    +

    +In the absence of a time zone indicator, Parse returns a time in UTC. +

    +

    +When parsing a time with a zone offset like -0700, if the offset corresponds +to a time zone used by the current location (Local), then Parse uses that +location and zone in the returned time. Otherwise it records the time as +being in a fabricated location with time fixed at the given zone offset. +

    +

    +No checking is done that the day of the month is within the month's +valid dates; any one- or two-digit value is accepted. For example +February 31 and even February 99 are valid dates, specifying dates +in March and May. This behavior is consistent with time.Date. +

    +

    +When parsing a time with a zone abbreviation like MST, if the zone abbreviation +has a defined offset in the current location, then that offset is used. +The zone abbreviation "UTC" is recognized as UTC regardless of location. +If the zone abbreviation is unknown, Parse records the time as being +in a fabricated location with the given zone abbreviation and a zero offset. +This choice means that such a time can be parsed and reformatted with the +same layout losslessly, but the exact instant used in the representation will +differ by the actual zone offset. To avoid such problems, prefer time layouts +that use a numeric zone offset, or use ParseInLocation. +

    + +
    + +
    +

    Example

    + + + +

    Code:

    +
    // See the example for time.Format for a thorough description of how
    +// to define the layout string to parse a time.Time value; Parse and
    +// Format use the same model to describe their input and output.
    +
    +// longForm shows by example how the reference time would be represented in
    +// the desired layout.
    +const longForm = "Jan 2, 2006 at 3:04pm (MST)"
    +t, _ := time.Parse(longForm, "Feb 3, 2013 at 7:54pm (PST)")
    +fmt.Println(t)
    +
    +// shortForm is another way the reference time would be represented
    +// in the desired layout; it has no time zone present.
    +// Note: without explicit zone, returns time in UTC.
    +const shortForm = "2006-Jan-02"
    +t, _ = time.Parse(shortForm, "2013-Feb-03")
    +fmt.Println(t)
    +
    +
    + +

    Output:

    +
    2013-02-03 19:54:00 -0800 PST
    +2013-02-03 00:00:00 +0000 UTC
    +
    + + +
    +
    + + + + +

    func ParseInLocation

    +
    func ParseInLocation(layout, value string, loc *Location) (Time, error)
    +

    +ParseInLocation is like Parse but differs in two important ways. +First, in the absence of time zone information, Parse interprets a time as UTC; +ParseInLocation interprets the time as in the given location. +Second, when given a zone offset or abbreviation, Parse tries to match it +against the Local location; ParseInLocation uses the given location. +

    + +
    + +
    +

    Example

    + + + +

    Code:

    +
    loc, _ := time.LoadLocation("Europe/Berlin")
    +
    +const longForm = "Jan 2, 2006 at 3:04pm (MST)"
    +t, _ := time.ParseInLocation(longForm, "Jul 9, 2012 at 5:02am (CEST)", loc)
    +fmt.Println(t)
    +
    +// Note: without explicit zone, returns time in given location.
    +const shortForm = "2006-Jan-02"
    +t, _ = time.ParseInLocation(shortForm, "2012-Jul-09", loc)
    +fmt.Println(t)
    +
    +
    + +

    Output:

    +
    2012-07-09 05:02:00 +0200 CEST
    +2012-07-09 00:00:00 +0200 CEST
    +
    + + +
    +
    + + + + +

    func Unix

    +
    func Unix(sec int64, nsec int64) Time
    +

    +Unix returns the local Time corresponding to the given Unix time, +sec seconds and nsec nanoseconds since January 1, 1970 UTC. +It is valid to pass nsec outside the range [0, 999999999]. +Not all sec values have a corresponding time value. One such +value is 1<<63-1 (the largest int64 value). +

    + + + + + + + +

    func (Time) Add

    +
    func (t Time) Add(d Duration) Time
    +

    +Add returns the time t+d. +

    + + + + + + +

    func (Time) AddDate

    +
    func (t Time) AddDate(years int, months int, days int) Time
    +

    +AddDate returns the time corresponding to adding the +given number of years, months, and days to t. +For example, AddDate(-1, 2, 3) applied to January 1, 2011 +returns March 4, 2010. +

    +

    +AddDate normalizes its result in the same way that Date does, +so, for example, adding one month to October 31 yields +December 1, the normalized form for November 31. +

    + + + + + + +

    func (Time) After

    +
    func (t Time) After(u Time) bool
    +

    +After reports whether the time instant t is after u. +

    + + + + + + +

    func (Time) AppendFormat

    +
    func (t Time) AppendFormat(b []byte, layout string) []byte
    +

    +AppendFormat is like Format but appends the textual +representation to b and returns the extended buffer. +

    + + + + + + +

    func (Time) Before

    +
    func (t Time) Before(u Time) bool
    +

    +Before reports whether the time instant t is before u. +

    + + + + + + +

    func (Time) Clock

    +
    func (t Time) Clock() (hour, min, sec int)
    +

    +Clock returns the hour, minute, and second within the day specified by t. +

    + + + + + + +

    func (Time) Date

    +
    func (t Time) Date() (year int, month Month, day int)
    +

    +Date returns the year, month, and day in which t occurs. +

    + + + + + + +

    func (Time) Day

    +
    func (t Time) Day() int
    +

    +Day returns the day of the month specified by t. +

    + + + + + + +

    func (Time) Equal

    +
    func (t Time) Equal(u Time) bool
    +

    +Equal reports whether t and u represent the same time instant. +Two times can be equal even if they are in different locations. +For example, 6:00 +0200 CEST and 4:00 UTC are Equal. +This comparison is different from using t == u, which also compares +the locations. +

    + + + + + + +

    func (Time) Format

    +
    func (t Time) Format(layout string) string
    +

    +Format returns a textual representation of the time value formatted +according to layout, which defines the format by showing how the reference +time, defined to be +

    +
    Mon Jan 2 15:04:05 -0700 MST 2006
    +
    +

    +would be displayed if it were the value; it serves as an example of the +desired output. The same display rules will then be applied to the time +value. +

    +

    +A fractional second is represented by adding a period and zeros +to the end of the seconds section of layout string, as in "15:04:05.000" +to format a time stamp with millisecond precision. +

    +

    +Predefined layouts ANSIC, UnixDate, RFC3339 and others describe standard +and convenient representations of the reference time. For more information +about the formats and the definition of the reference time, see the +documentation for ANSIC and the other constants defined by this package. +

    + + +
    + +
    +

    Example

    + + + +

    Code:

    +
    // Parse a time value from a string in the standard Unix format.
    +t, err := time.Parse(time.UnixDate, "Sat Mar  7 11:06:39 PST 2015")
    +if err != nil { // Always check errors even if they should not happen.
    +    panic(err)
    +}
    +
    +// time.Time's Stringer method is useful without any format.
    +fmt.Println("default format:", t)
    +
    +// Predefined constants in the package implement common layouts.
    +fmt.Println("Unix format:", t.Format(time.UnixDate))
    +
    +// The time zone attached to the time value affects its output.
    +fmt.Println("Same, in UTC:", t.UTC().Format(time.UnixDate))
    +
    +// The rest of this function demonstrates the properties of the
    +// layout string used in the format.
    +
    +// The layout string used by the Parse function and Format method
    +// shows by example how the reference time should be represented.
    +// We stress that one must show how the reference time is formatted,
    +// not a time of the user's choosing. Thus each layout string is a
    +// representation of the time stamp,
    +//	Jan 2 15:04:05 2006 MST
    +// An easy way to remember this value is that it holds, when presented
    +// in this order, the values (lined up with the elements above):
    +//	  1 2  3  4  5    6  -7
    +// There are some wrinkles illustrated below.
    +
    +// Most uses of Format and Parse use constant layout strings such as
    +// the ones defined in this package, but the interface is flexible,
    +// as these examples show.
    +
    +// Define a helper function to make the examples' output look nice.
    +do := func(name, layout, want string) {
    +    got := t.Format(layout)
    +    if want != got {
    +        fmt.Printf("error: for %q got %q; expected %q\n", layout, got, want)
    +        return
    +    }
    +    fmt.Printf("%-15s %q gives %q\n", name, layout, got)
    +}
    +
    +// Print a header in our output.
    +fmt.Printf("\nFormats:\n\n")
    +
    +// A simple starter example.
    +do("Basic", "Mon Jan 2 15:04:05 MST 2006", "Sat Mar 7 11:06:39 PST 2015")
    +
    +// For fixed-width printing of values, such as the date, that may be one or
    +// two characters (7 vs. 07), use an _ instead of a space in the layout string.
    +// Here we print just the day, which is 2 in our layout string and 7 in our
    +// value.
    +do("No pad", "<2>", "<7>")
    +
    +// An underscore represents a zero pad, if required.
    +do("Spaces", "<_2>", "< 7>")
    +
    +// Similarly, a 0 indicates zero padding.
    +do("Zeros", "<02>", "<07>")
    +
    +// If the value is already the right width, padding is not used.
    +// For instance, the second (05 in the reference time) in our value is 39,
    +// so it doesn't need padding, but the minutes (04, 06) does.
    +do("Suppressed pad", "04:05", "06:39")
    +
    +// The predefined constant Unix uses an underscore to pad the day.
    +// Compare with our simple starter example.
    +do("Unix", time.UnixDate, "Sat Mar  7 11:06:39 PST 2015")
    +
    +// The hour of the reference time is 15, or 3PM. The layout can express
    +// it either way, and since our value is the morning we should see it as
    +// an AM time. We show both in one format string. Lower case too.
    +do("AM/PM", "3PM==3pm==15h", "11AM==11am==11h")
    +
    +// When parsing, if the seconds value is followed by a decimal point
    +// and some digits, that is taken as a fraction of a second even if
    +// the layout string does not represent the fractional second.
    +// Here we add a fractional second to our time value used above.
    +t, err = time.Parse(time.UnixDate, "Sat Mar  7 11:06:39.1234 PST 2015")
    +if err != nil {
    +    panic(err)
    +}
    +// It does not appear in the output if the layout string does not contain
    +// a representation of the fractional second.
    +do("No fraction", time.UnixDate, "Sat Mar  7 11:06:39 PST 2015")
    +
    +// Fractional seconds can be printed by adding a run of 0s or 9s after
    +// a decimal point in the seconds value in the layout string.
    +// If the layout digits are 0s, the fractional second is of the specified
    +// width. Note that the output has a trailing zero.
    +do("0s for fraction", "15:04:05.00000", "11:06:39.12340")
    +
    +// If the fraction in the layout is 9s, trailing zeros are dropped.
    +do("9s for fraction", "15:04:05.99999999", "11:06:39.1234")
    +
    +
    + +

    Output:

    +
    default format: 2015-03-07 11:06:39 -0800 PST
    +Unix format: Sat Mar  7 11:06:39 PST 2015
    +Same, in UTC: Sat Mar  7 19:06:39 UTC 2015
    +
    +Formats:
    +
    +Basic           "Mon Jan 2 15:04:05 MST 2006" gives "Sat Mar 7 11:06:39 PST 2015"
    +No pad          "<2>" gives "<7>"
    +Spaces          "<_2>" gives "< 7>"
    +Zeros           "<02>" gives "<07>"
    +Suppressed pad  "04:05" gives "06:39"
    +Unix            "Mon Jan _2 15:04:05 MST 2006" gives "Sat Mar  7 11:06:39 PST 2015"
    +AM/PM           "3PM==3pm==15h" gives "11AM==11am==11h"
    +No fraction     "Mon Jan _2 15:04:05 MST 2006" gives "Sat Mar  7 11:06:39 PST 2015"
    +0s for fraction "15:04:05.00000" gives "11:06:39.12340"
    +9s for fraction "15:04:05.99999999" gives "11:06:39.1234"
    +
    + + +
    +
    + + + + +

    func (*Time) GobDecode

    +
    func (t *Time) GobDecode(data []byte) error
    +

    +GobDecode implements the gob.GobDecoder interface. +

    + + + + + + +

    func (Time) GobEncode

    +
    func (t Time) GobEncode() ([]byte, error)
    +

    +GobEncode implements the gob.GobEncoder interface. +

    + + + + + + +

    func (Time) Hour

    +
    func (t Time) Hour() int
    +

    +Hour returns the hour within the day specified by t, in the range [0, 23]. +

    + + + + + + +

    func (Time) ISOWeek

    +
    func (t Time) ISOWeek() (year, week int)
    +

    +ISOWeek returns the ISO 8601 year and week number in which t occurs. +Week ranges from 1 to 53. Jan 01 to Jan 03 of year n might belong to +week 52 or 53 of year n-1, and Dec 29 to Dec 31 might belong to week 1 +of year n+1. +

    + + + + + + +

    func (Time) In

    +
    func (t Time) In(loc *Location) Time
    +

    +In returns t with the location information set to loc. +

    +

    +In panics if loc is nil. +

    + + + + + + +

    func (Time) IsZero

    +
    func (t Time) IsZero() bool
    +

    +IsZero reports whether t represents the zero time instant, +January 1, year 1, 00:00:00 UTC. +

    + + + + + + +

    func (Time) Local

    +
    func (t Time) Local() Time
    +

    +Local returns t with the location set to local time. +

    + + + + + + +

    func (Time) Location

    +
    func (t Time) Location() *Location
    +

    +Location returns the time zone information associated with t. +

    + + + + + + +

    func (Time) MarshalBinary

    +
    func (t Time) MarshalBinary() ([]byte, error)
    +

    +MarshalBinary implements the encoding.BinaryMarshaler interface. +

    + + + + + + +

    func (Time) MarshalJSON

    +
    func (t Time) MarshalJSON() ([]byte, error)
    +

    +MarshalJSON implements the json.Marshaler interface. +The time is a quoted string in RFC 3339 format, with sub-second precision added if present. +

    + + + + + + +

    func (Time) MarshalText

    +
    func (t Time) MarshalText() ([]byte, error)
    +

    +MarshalText implements the encoding.TextMarshaler interface. +The time is formatted in RFC 3339 format, with sub-second precision added if present. +

    + + + + + + +

    func (Time) Minute

    +
    func (t Time) Minute() int
    +

    +Minute returns the minute offset within the hour specified by t, in the range [0, 59]. +

    + + + + + + +

    func (Time) Month

    +
    func (t Time) Month() Month
    +

    +Month returns the month of the year specified by t. +

    + + + + + + +

    func (Time) Nanosecond

    +
    func (t Time) Nanosecond() int
    +

    +Nanosecond returns the nanosecond offset within the second specified by t, +in the range [0, 999999999]. +

    + + + + + + +

    func (Time) Round

    +
    func (t Time) Round(d Duration) Time
    +

    +Round returns the result of rounding t to the nearest multiple of d (since the zero time). +The rounding behavior for halfway values is to round up. +If d <= 0, Round returns t unchanged. +

    + + +
    + +
    +

    Example

    + + + +

    Code:

    +
    t := time.Date(0, 0, 0, 12, 15, 30, 918273645, time.UTC)
    +round := []time.Duration{
    +    time.Nanosecond,
    +    time.Microsecond,
    +    time.Millisecond,
    +    time.Second,
    +    2 * time.Second,
    +    time.Minute,
    +    10 * time.Minute,
    +    time.Hour,
    +}
    +
    +for _, d := range round {
    +    fmt.Printf("t.Round(%6s) = %s\n", d, t.Round(d).Format("15:04:05.999999999"))
    +}
    +
    + +

    Output:

    +
    t.Round(   1ns) = 12:15:30.918273645
    +t.Round(   1µs) = 12:15:30.918274
    +t.Round(   1ms) = 12:15:30.918
    +t.Round(    1s) = 12:15:31
    +t.Round(    2s) = 12:15:30
    +t.Round(  1m0s) = 12:16:00
    +t.Round( 10m0s) = 12:20:00
    +t.Round(1h0m0s) = 12:00:00
    +
    + + +
    +
    + + + + +

    func (Time) Second

    +
    func (t Time) Second() int
    +

    +Second returns the second offset within the minute specified by t, in the range [0, 59]. +

    + + + + + + +

    func (Time) String

    +
    func (t Time) String() string
    +

    +String returns the time formatted using the format string +

    +
    "2006-01-02 15:04:05.999999999 -0700 MST"
    +
    + + + + + + +

    func (Time) Sub

    +
    func (t Time) Sub(u Time) Duration
    +

    +Sub returns the duration t-u. If the result exceeds the maximum (or minimum) +value that can be stored in a Duration, the maximum (or minimum) duration +will be returned. +To compute t-d for a duration d, use t.Add(-d). +

    + + + + + + +

    func (Time) Truncate

    +
    func (t Time) Truncate(d Duration) Time
    +

    +Truncate returns the result of rounding t down to a multiple of d (since the zero time). +If d <= 0, Truncate returns t unchanged. +

    + + +
    + +
    +

    Example

    + + + +

    Code:

    +
    t, _ := time.Parse("2006 Jan 02 15:04:05", "2012 Dec 07 12:15:30.918273645")
    +trunc := []time.Duration{
    +    time.Nanosecond,
    +    time.Microsecond,
    +    time.Millisecond,
    +    time.Second,
    +    2 * time.Second,
    +    time.Minute,
    +    10 * time.Minute,
    +    time.Hour,
    +}
    +
    +for _, d := range trunc {
    +    fmt.Printf("t.Truncate(%6s) = %s\n", d, t.Truncate(d).Format("15:04:05.999999999"))
    +}
    +
    +
    + +

    Output:

    +
    t.Truncate(   1ns) = 12:15:30.918273645
    +t.Truncate(   1µs) = 12:15:30.918273
    +t.Truncate(   1ms) = 12:15:30.918
    +t.Truncate(    1s) = 12:15:30
    +t.Truncate(    2s) = 12:15:30
    +t.Truncate(  1m0s) = 12:15:00
    +t.Truncate( 10m0s) = 12:10:00
    +t.Truncate(1h0m0s) = 12:00:00
    +
    + + +
    +
    + + + + +

    func (Time) UTC

    +
    func (t Time) UTC() Time
    +

    +UTC returns t with the location set to UTC. +

    + + + + + + +

    func (Time) Unix

    +
    func (t Time) Unix() int64
    +

    +Unix returns t as a Unix time, the number of seconds elapsed +since January 1, 1970 UTC. +

    + + + + + + +

    func (Time) UnixNano

    +
    func (t Time) UnixNano() int64
    +

    +UnixNano returns t as a Unix time, the number of nanoseconds elapsed +since January 1, 1970 UTC. The result is undefined if the Unix time +in nanoseconds cannot be represented by an int64. Note that this +means the result of calling UnixNano on the zero Time is undefined. +

    + + + + + + +

    func (*Time) UnmarshalBinary

    +
    func (t *Time) UnmarshalBinary(data []byte) error
    +

    +UnmarshalBinary implements the encoding.BinaryUnmarshaler interface. +

    + + + + + + +

    func (*Time) UnmarshalJSON

    +
    func (t *Time) UnmarshalJSON(data []byte) (err error)
    +

    +UnmarshalJSON implements the json.Unmarshaler interface. +The time is expected to be a quoted string in RFC 3339 format. +

    + + + + + + +

    func (*Time) UnmarshalText

    +
    func (t *Time) UnmarshalText(data []byte) (err error)
    +

    +UnmarshalText implements the encoding.TextUnmarshaler interface. +The time is expected to be in RFC 3339 format. +

    + + + + + + +

    func (Time) Weekday

    +
    func (t Time) Weekday() Weekday
    +

    +Weekday returns the day of the week specified by t. +

    + + + + + + +

    func (Time) Year

    +
    func (t Time) Year() int
    +

    +Year returns the year in which t occurs. +

    + + + + + + +

    func (Time) YearDay

    +
    func (t Time) YearDay() int
    +

    +YearDay returns the day of the year specified by t, in the range [1,365] for non-leap years, +and [1,366] in leap years. +

    + + + + + + +

    func (Time) Zone

    +
    func (t Time) Zone() (name string, offset int)
    +

    +Zone computes the time zone in effect at time t, returning the abbreviated +name of the zone (such as "CET") and its offset in seconds east of UTC. +

    + + + + + + + + +

    type Timer

    +
    type Timer struct {
    +    C <-chan Time
    +    // contains filtered or unexported fields
    +}
    +

    +The Timer type represents a single event. +When the Timer expires, the current time will be sent on C, +unless the Timer was created by AfterFunc. +A Timer must be created with NewTimer or AfterFunc. +

    + + + + + + + + + + + + +

    func AfterFunc

    +
    func AfterFunc(d Duration, f func()) *Timer
    +

    +AfterFunc waits for the duration to elapse and then calls f +in its own goroutine. It returns a Timer that can +be used to cancel the call using its Stop method. +

    + + + + + +

    func NewTimer

    +
    func NewTimer(d Duration) *Timer
    +

    +NewTimer creates a new Timer that will send +the current time on its channel after at least duration d. +

    + + + + + + + +

    func (*Timer) Reset

    +
    func (t *Timer) Reset(d Duration) bool
    +

    +Reset changes the timer to expire after duration d. +It returns true if the timer had been active, false if the timer had +expired or been stopped. +

    + + + + + + +

    func (*Timer) Stop

    +
    func (t *Timer) Stop() bool
    +

    +Stop prevents the Timer from firing. +It returns true if the call stops the timer, false if the timer has already +expired or been stopped. +Stop does not close the channel, to prevent a read from the channel succeeding +incorrectly. +

    + + + + + + + + +

    type Weekday

    +
    type Weekday int
    +

    +A Weekday specifies a day of the week (Sunday = 0, ...). +

    + + + +
    const (
    +    Sunday Weekday = iota
    +    Monday
    +    Tuesday
    +    Wednesday
    +    Thursday
    +    Friday
    +    Saturday
    +)
    + + + + + + + + + + + + + +

    func (Weekday) String

    +
    func (d Weekday) String() string
    +

    +String returns the English name of the day ("Sunday", "Monday", ...). +

    + + + + + + + + + + + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/unicode/index.html b/pkg/unicode/index.html new file mode 100644 index 0000000..508f591 --- /dev/null +++ b/pkg/unicode/index.html @@ -0,0 +1,1697 @@ + + + + + + + + unicode - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Package unicode

    + + + + + + + + + + + + + + +
    +
    +
    import "unicode"
    +
    +
    +
    Overview
    +
    Index
    + +
    Examples
    + + +
    Subdirectories
    + +
    +
    + +
    + +
    +

    Overview ▾

    +

    +Package unicode provides data and functions to test some properties of +Unicode code points. +

    + +
    +
    +
    + +
    +

    Example (Is)

    +

    Functions starting with "Is" can be used to inspect which table of range a +rune belongs to. Note that runes may fit into more than one range. +

    + + +

    Code:

    +
    // constant with mixed type runes
    +const mixed = "\b5Ὂg̀9! ℃ᾭG"
    +for _, c := range mixed {
    +    fmt.Printf("For %q:\n", c)
    +    if unicode.IsControl(c) {
    +        fmt.Println("\tis control rune")
    +    }
    +    if unicode.IsDigit(c) {
    +        fmt.Println("\tis digit rune")
    +    }
    +    if unicode.IsGraphic(c) {
    +        fmt.Println("\tis graphic rune")
    +    }
    +    if unicode.IsLetter(c) {
    +        fmt.Println("\tis letter rune")
    +    }
    +    if unicode.IsLower(c) {
    +        fmt.Println("\tis lower case rune")
    +    }
    +    if unicode.IsMark(c) {
    +        fmt.Println("\tis mark rune")
    +    }
    +    if unicode.IsNumber(c) {
    +        fmt.Println("\tis number rune")
    +    }
    +    if unicode.IsPrint(c) {
    +        fmt.Println("\tis printable rune")
    +    }
    +    if !unicode.IsPrint(c) {
    +        fmt.Println("\tis not printable rune")
    +    }
    +    if unicode.IsPunct(c) {
    +        fmt.Println("\tis punct rune")
    +    }
    +    if unicode.IsSpace(c) {
    +        fmt.Println("\tis space rune")
    +    }
    +    if unicode.IsSymbol(c) {
    +        fmt.Println("\tis symbol rune")
    +    }
    +    if unicode.IsTitle(c) {
    +        fmt.Println("\tis title case rune")
    +    }
    +    if unicode.IsUpper(c) {
    +        fmt.Println("\tis upper case rune")
    +    }
    +}
    +
    +
    + +

    Output:

    +
    For '\b':
    +	is control rune
    +	is not printable rune
    +For '5':
    +	is digit rune
    +	is graphic rune
    +	is number rune
    +	is printable rune
    +For 'Ὂ':
    +	is graphic rune
    +	is letter rune
    +	is printable rune
    +	is upper case rune
    +For 'g':
    +	is graphic rune
    +	is letter rune
    +	is lower case rune
    +	is printable rune
    +For '̀':
    +	is graphic rune
    +	is mark rune
    +	is printable rune
    +For '9':
    +	is digit rune
    +	is graphic rune
    +	is number rune
    +	is printable rune
    +For '!':
    +	is graphic rune
    +	is printable rune
    +	is punct rune
    +For ' ':
    +	is graphic rune
    +	is printable rune
    +	is space rune
    +For '℃':
    +	is graphic rune
    +	is printable rune
    +	is symbol rune
    +For 'ᾭ':
    +	is graphic rune
    +	is letter rune
    +	is printable rune
    +	is title case rune
    +For 'G':
    +	is graphic rune
    +	is letter rune
    +	is printable rune
    +	is upper case rune
    +
    + + +
    +
    + + + + + + + +

    Constants

    + +
    const (
    +    MaxRune         = '\U0010FFFF' // Maximum valid Unicode code point.
    +    ReplacementChar = '\uFFFD'     // Represents invalid code points.
    +    MaxASCII        = '\u007F'     // maximum ASCII value.
    +    MaxLatin1       = '\u00FF'     // maximum Latin-1 value.
    +)
    + + +
    const (
    +    UpperCase = iota
    +    LowerCase
    +    TitleCase
    +    MaxCase
    +)
    +

    +Indices into the Delta arrays inside CaseRanges for case mapping. +

    + + +
    const (
    +    UpperLower = MaxRune + 1 // (Cannot be a valid delta.)
    +)
    +

    +If the Delta field of a CaseRange is UpperLower, it means +this CaseRange represents a sequence of the form (say) +Upper Lower Upper Lower. +

    + + +
    const Version = "8.0.0"
    +

    +Version is the Unicode edition from which the tables are derived. +

    + + + + +

    Variables

    + +
    var (
    +    Cc     = _Cc // Cc is the set of Unicode characters in category Cc.
    +    Cf     = _Cf // Cf is the set of Unicode characters in category Cf.
    +    Co     = _Co // Co is the set of Unicode characters in category Co.
    +    Cs     = _Cs // Cs is the set of Unicode characters in category Cs.
    +    Digit  = _Nd // Digit is the set of Unicode characters with the "decimal digit" property.
    +    Nd     = _Nd // Nd is the set of Unicode characters in category Nd.
    +    Letter = _L  // Letter/L is the set of Unicode letters, category L.
    +    L      = _L
    +    Lm     = _Lm // Lm is the set of Unicode characters in category Lm.
    +    Lo     = _Lo // Lo is the set of Unicode characters in category Lo.
    +    Lower  = _Ll // Lower is the set of Unicode lower case letters.
    +    Ll     = _Ll // Ll is the set of Unicode characters in category Ll.
    +    Mark   = _M  // Mark/M is the set of Unicode mark characters, category M.
    +    M      = _M
    +    Mc     = _Mc // Mc is the set of Unicode characters in category Mc.
    +    Me     = _Me // Me is the set of Unicode characters in category Me.
    +    Mn     = _Mn // Mn is the set of Unicode characters in category Mn.
    +    Nl     = _Nl // Nl is the set of Unicode characters in category Nl.
    +    No     = _No // No is the set of Unicode characters in category No.
    +    Number = _N  // Number/N is the set of Unicode number characters, category N.
    +    N      = _N
    +    Other  = _C // Other/C is the set of Unicode control and special characters, category C.
    +    C      = _C
    +    Pc     = _Pc // Pc is the set of Unicode characters in category Pc.
    +    Pd     = _Pd // Pd is the set of Unicode characters in category Pd.
    +    Pe     = _Pe // Pe is the set of Unicode characters in category Pe.
    +    Pf     = _Pf // Pf is the set of Unicode characters in category Pf.
    +    Pi     = _Pi // Pi is the set of Unicode characters in category Pi.
    +    Po     = _Po // Po is the set of Unicode characters in category Po.
    +    Ps     = _Ps // Ps is the set of Unicode characters in category Ps.
    +    Punct  = _P  // Punct/P is the set of Unicode punctuation characters, category P.
    +    P      = _P
    +    Sc     = _Sc // Sc is the set of Unicode characters in category Sc.
    +    Sk     = _Sk // Sk is the set of Unicode characters in category Sk.
    +    Sm     = _Sm // Sm is the set of Unicode characters in category Sm.
    +    So     = _So // So is the set of Unicode characters in category So.
    +    Space  = _Z  // Space/Z is the set of Unicode space characters, category Z.
    +    Z      = _Z
    +    Symbol = _S // Symbol/S is the set of Unicode symbol characters, category S.
    +    S      = _S
    +    Title  = _Lt // Title is the set of Unicode title case letters.
    +    Lt     = _Lt // Lt is the set of Unicode characters in category Lt.
    +    Upper  = _Lu // Upper is the set of Unicode upper case letters.
    +    Lu     = _Lu // Lu is the set of Unicode characters in category Lu.
    +    Zl     = _Zl // Zl is the set of Unicode characters in category Zl.
    +    Zp     = _Zp // Zp is the set of Unicode characters in category Zp.
    +    Zs     = _Zs // Zs is the set of Unicode characters in category Zs.
    +)
    +

    +These variables have type *RangeTable. +

    + + +
    var (
    +    Ahom                   = _Ahom                   // Ahom is the set of Unicode characters in script Ahom.
    +    Anatolian_Hieroglyphs  = _Anatolian_Hieroglyphs  // Anatolian_Hieroglyphs is the set of Unicode characters in script Anatolian_Hieroglyphs.
    +    Arabic                 = _Arabic                 // Arabic is the set of Unicode characters in script Arabic.
    +    Armenian               = _Armenian               // Armenian is the set of Unicode characters in script Armenian.
    +    Avestan                = _Avestan                // Avestan is the set of Unicode characters in script Avestan.
    +    Balinese               = _Balinese               // Balinese is the set of Unicode characters in script Balinese.
    +    Bamum                  = _Bamum                  // Bamum is the set of Unicode characters in script Bamum.
    +    Bassa_Vah              = _Bassa_Vah              // Bassa_Vah is the set of Unicode characters in script Bassa_Vah.
    +    Batak                  = _Batak                  // Batak is the set of Unicode characters in script Batak.
    +    Bengali                = _Bengali                // Bengali is the set of Unicode characters in script Bengali.
    +    Bopomofo               = _Bopomofo               // Bopomofo is the set of Unicode characters in script Bopomofo.
    +    Brahmi                 = _Brahmi                 // Brahmi is the set of Unicode characters in script Brahmi.
    +    Braille                = _Braille                // Braille is the set of Unicode characters in script Braille.
    +    Buginese               = _Buginese               // Buginese is the set of Unicode characters in script Buginese.
    +    Buhid                  = _Buhid                  // Buhid is the set of Unicode characters in script Buhid.
    +    Canadian_Aboriginal    = _Canadian_Aboriginal    // Canadian_Aboriginal is the set of Unicode characters in script Canadian_Aboriginal.
    +    Carian                 = _Carian                 // Carian is the set of Unicode characters in script Carian.
    +    Caucasian_Albanian     = _Caucasian_Albanian     // Caucasian_Albanian is the set of Unicode characters in script Caucasian_Albanian.
    +    Chakma                 = _Chakma                 // Chakma is the set of Unicode characters in script Chakma.
    +    Cham                   = _Cham                   // Cham is the set of Unicode characters in script Cham.
    +    Cherokee               = _Cherokee               // Cherokee is the set of Unicode characters in script Cherokee.
    +    Common                 = _Common                 // Common is the set of Unicode characters in script Common.
    +    Coptic                 = _Coptic                 // Coptic is the set of Unicode characters in script Coptic.
    +    Cuneiform              = _Cuneiform              // Cuneiform is the set of Unicode characters in script Cuneiform.
    +    Cypriot                = _Cypriot                // Cypriot is the set of Unicode characters in script Cypriot.
    +    Cyrillic               = _Cyrillic               // Cyrillic is the set of Unicode characters in script Cyrillic.
    +    Deseret                = _Deseret                // Deseret is the set of Unicode characters in script Deseret.
    +    Devanagari             = _Devanagari             // Devanagari is the set of Unicode characters in script Devanagari.
    +    Duployan               = _Duployan               // Duployan is the set of Unicode characters in script Duployan.
    +    Egyptian_Hieroglyphs   = _Egyptian_Hieroglyphs   // Egyptian_Hieroglyphs is the set of Unicode characters in script Egyptian_Hieroglyphs.
    +    Elbasan                = _Elbasan                // Elbasan is the set of Unicode characters in script Elbasan.
    +    Ethiopic               = _Ethiopic               // Ethiopic is the set of Unicode characters in script Ethiopic.
    +    Georgian               = _Georgian               // Georgian is the set of Unicode characters in script Georgian.
    +    Glagolitic             = _Glagolitic             // Glagolitic is the set of Unicode characters in script Glagolitic.
    +    Gothic                 = _Gothic                 // Gothic is the set of Unicode characters in script Gothic.
    +    Grantha                = _Grantha                // Grantha is the set of Unicode characters in script Grantha.
    +    Greek                  = _Greek                  // Greek is the set of Unicode characters in script Greek.
    +    Gujarati               = _Gujarati               // Gujarati is the set of Unicode characters in script Gujarati.
    +    Gurmukhi               = _Gurmukhi               // Gurmukhi is the set of Unicode characters in script Gurmukhi.
    +    Han                    = _Han                    // Han is the set of Unicode characters in script Han.
    +    Hangul                 = _Hangul                 // Hangul is the set of Unicode characters in script Hangul.
    +    Hanunoo                = _Hanunoo                // Hanunoo is the set of Unicode characters in script Hanunoo.
    +    Hatran                 = _Hatran                 // Hatran is the set of Unicode characters in script Hatran.
    +    Hebrew                 = _Hebrew                 // Hebrew is the set of Unicode characters in script Hebrew.
    +    Hiragana               = _Hiragana               // Hiragana is the set of Unicode characters in script Hiragana.
    +    Imperial_Aramaic       = _Imperial_Aramaic       // Imperial_Aramaic is the set of Unicode characters in script Imperial_Aramaic.
    +    Inherited              = _Inherited              // Inherited is the set of Unicode characters in script Inherited.
    +    Inscriptional_Pahlavi  = _Inscriptional_Pahlavi  // Inscriptional_Pahlavi is the set of Unicode characters in script Inscriptional_Pahlavi.
    +    Inscriptional_Parthian = _Inscriptional_Parthian // Inscriptional_Parthian is the set of Unicode characters in script Inscriptional_Parthian.
    +    Javanese               = _Javanese               // Javanese is the set of Unicode characters in script Javanese.
    +    Kaithi                 = _Kaithi                 // Kaithi is the set of Unicode characters in script Kaithi.
    +    Kannada                = _Kannada                // Kannada is the set of Unicode characters in script Kannada.
    +    Katakana               = _Katakana               // Katakana is the set of Unicode characters in script Katakana.
    +    Kayah_Li               = _Kayah_Li               // Kayah_Li is the set of Unicode characters in script Kayah_Li.
    +    Kharoshthi             = _Kharoshthi             // Kharoshthi is the set of Unicode characters in script Kharoshthi.
    +    Khmer                  = _Khmer                  // Khmer is the set of Unicode characters in script Khmer.
    +    Khojki                 = _Khojki                 // Khojki is the set of Unicode characters in script Khojki.
    +    Khudawadi              = _Khudawadi              // Khudawadi is the set of Unicode characters in script Khudawadi.
    +    Lao                    = _Lao                    // Lao is the set of Unicode characters in script Lao.
    +    Latin                  = _Latin                  // Latin is the set of Unicode characters in script Latin.
    +    Lepcha                 = _Lepcha                 // Lepcha is the set of Unicode characters in script Lepcha.
    +    Limbu                  = _Limbu                  // Limbu is the set of Unicode characters in script Limbu.
    +    Linear_A               = _Linear_A               // Linear_A is the set of Unicode characters in script Linear_A.
    +    Linear_B               = _Linear_B               // Linear_B is the set of Unicode characters in script Linear_B.
    +    Lisu                   = _Lisu                   // Lisu is the set of Unicode characters in script Lisu.
    +    Lycian                 = _Lycian                 // Lycian is the set of Unicode characters in script Lycian.
    +    Lydian                 = _Lydian                 // Lydian is the set of Unicode characters in script Lydian.
    +    Mahajani               = _Mahajani               // Mahajani is the set of Unicode characters in script Mahajani.
    +    Malayalam              = _Malayalam              // Malayalam is the set of Unicode characters in script Malayalam.
    +    Mandaic                = _Mandaic                // Mandaic is the set of Unicode characters in script Mandaic.
    +    Manichaean             = _Manichaean             // Manichaean is the set of Unicode characters in script Manichaean.
    +    Meetei_Mayek           = _Meetei_Mayek           // Meetei_Mayek is the set of Unicode characters in script Meetei_Mayek.
    +    Mende_Kikakui          = _Mende_Kikakui          // Mende_Kikakui is the set of Unicode characters in script Mende_Kikakui.
    +    Meroitic_Cursive       = _Meroitic_Cursive       // Meroitic_Cursive is the set of Unicode characters in script Meroitic_Cursive.
    +    Meroitic_Hieroglyphs   = _Meroitic_Hieroglyphs   // Meroitic_Hieroglyphs is the set of Unicode characters in script Meroitic_Hieroglyphs.
    +    Miao                   = _Miao                   // Miao is the set of Unicode characters in script Miao.
    +    Modi                   = _Modi                   // Modi is the set of Unicode characters in script Modi.
    +    Mongolian              = _Mongolian              // Mongolian is the set of Unicode characters in script Mongolian.
    +    Mro                    = _Mro                    // Mro is the set of Unicode characters in script Mro.
    +    Multani                = _Multani                // Multani is the set of Unicode characters in script Multani.
    +    Myanmar                = _Myanmar                // Myanmar is the set of Unicode characters in script Myanmar.
    +    Nabataean              = _Nabataean              // Nabataean is the set of Unicode characters in script Nabataean.
    +    New_Tai_Lue            = _New_Tai_Lue            // New_Tai_Lue is the set of Unicode characters in script New_Tai_Lue.
    +    Nko                    = _Nko                    // Nko is the set of Unicode characters in script Nko.
    +    Ogham                  = _Ogham                  // Ogham is the set of Unicode characters in script Ogham.
    +    Ol_Chiki               = _Ol_Chiki               // Ol_Chiki is the set of Unicode characters in script Ol_Chiki.
    +    Old_Hungarian          = _Old_Hungarian          // Old_Hungarian is the set of Unicode characters in script Old_Hungarian.
    +    Old_Italic             = _Old_Italic             // Old_Italic is the set of Unicode characters in script Old_Italic.
    +    Old_North_Arabian      = _Old_North_Arabian      // Old_North_Arabian is the set of Unicode characters in script Old_North_Arabian.
    +    Old_Permic             = _Old_Permic             // Old_Permic is the set of Unicode characters in script Old_Permic.
    +    Old_Persian            = _Old_Persian            // Old_Persian is the set of Unicode characters in script Old_Persian.
    +    Old_South_Arabian      = _Old_South_Arabian      // Old_South_Arabian is the set of Unicode characters in script Old_South_Arabian.
    +    Old_Turkic             = _Old_Turkic             // Old_Turkic is the set of Unicode characters in script Old_Turkic.
    +    Oriya                  = _Oriya                  // Oriya is the set of Unicode characters in script Oriya.
    +    Osmanya                = _Osmanya                // Osmanya is the set of Unicode characters in script Osmanya.
    +    Pahawh_Hmong           = _Pahawh_Hmong           // Pahawh_Hmong is the set of Unicode characters in script Pahawh_Hmong.
    +    Palmyrene              = _Palmyrene              // Palmyrene is the set of Unicode characters in script Palmyrene.
    +    Pau_Cin_Hau            = _Pau_Cin_Hau            // Pau_Cin_Hau is the set of Unicode characters in script Pau_Cin_Hau.
    +    Phags_Pa               = _Phags_Pa               // Phags_Pa is the set of Unicode characters in script Phags_Pa.
    +    Phoenician             = _Phoenician             // Phoenician is the set of Unicode characters in script Phoenician.
    +    Psalter_Pahlavi        = _Psalter_Pahlavi        // Psalter_Pahlavi is the set of Unicode characters in script Psalter_Pahlavi.
    +    Rejang                 = _Rejang                 // Rejang is the set of Unicode characters in script Rejang.
    +    Runic                  = _Runic                  // Runic is the set of Unicode characters in script Runic.
    +    Samaritan              = _Samaritan              // Samaritan is the set of Unicode characters in script Samaritan.
    +    Saurashtra             = _Saurashtra             // Saurashtra is the set of Unicode characters in script Saurashtra.
    +    Sharada                = _Sharada                // Sharada is the set of Unicode characters in script Sharada.
    +    Shavian                = _Shavian                // Shavian is the set of Unicode characters in script Shavian.
    +    Siddham                = _Siddham                // Siddham is the set of Unicode characters in script Siddham.
    +    SignWriting            = _SignWriting            // SignWriting is the set of Unicode characters in script SignWriting.
    +    Sinhala                = _Sinhala                // Sinhala is the set of Unicode characters in script Sinhala.
    +    Sora_Sompeng           = _Sora_Sompeng           // Sora_Sompeng is the set of Unicode characters in script Sora_Sompeng.
    +    Sundanese              = _Sundanese              // Sundanese is the set of Unicode characters in script Sundanese.
    +    Syloti_Nagri           = _Syloti_Nagri           // Syloti_Nagri is the set of Unicode characters in script Syloti_Nagri.
    +    Syriac                 = _Syriac                 // Syriac is the set of Unicode characters in script Syriac.
    +    Tagalog                = _Tagalog                // Tagalog is the set of Unicode characters in script Tagalog.
    +    Tagbanwa               = _Tagbanwa               // Tagbanwa is the set of Unicode characters in script Tagbanwa.
    +    Tai_Le                 = _Tai_Le                 // Tai_Le is the set of Unicode characters in script Tai_Le.
    +    Tai_Tham               = _Tai_Tham               // Tai_Tham is the set of Unicode characters in script Tai_Tham.
    +    Tai_Viet               = _Tai_Viet               // Tai_Viet is the set of Unicode characters in script Tai_Viet.
    +    Takri                  = _Takri                  // Takri is the set of Unicode characters in script Takri.
    +    Tamil                  = _Tamil                  // Tamil is the set of Unicode characters in script Tamil.
    +    Telugu                 = _Telugu                 // Telugu is the set of Unicode characters in script Telugu.
    +    Thaana                 = _Thaana                 // Thaana is the set of Unicode characters in script Thaana.
    +    Thai                   = _Thai                   // Thai is the set of Unicode characters in script Thai.
    +    Tibetan                = _Tibetan                // Tibetan is the set of Unicode characters in script Tibetan.
    +    Tifinagh               = _Tifinagh               // Tifinagh is the set of Unicode characters in script Tifinagh.
    +    Tirhuta                = _Tirhuta                // Tirhuta is the set of Unicode characters in script Tirhuta.
    +    Ugaritic               = _Ugaritic               // Ugaritic is the set of Unicode characters in script Ugaritic.
    +    Vai                    = _Vai                    // Vai is the set of Unicode characters in script Vai.
    +    Warang_Citi            = _Warang_Citi            // Warang_Citi is the set of Unicode characters in script Warang_Citi.
    +    Yi                     = _Yi                     // Yi is the set of Unicode characters in script Yi.
    +)
    +

    +These variables have type *RangeTable. +

    + + +
    var (
    +    ASCII_Hex_Digit                    = _ASCII_Hex_Digit                    // ASCII_Hex_Digit is the set of Unicode characters with property ASCII_Hex_Digit.
    +    Bidi_Control                       = _Bidi_Control                       // Bidi_Control is the set of Unicode characters with property Bidi_Control.
    +    Dash                               = _Dash                               // Dash is the set of Unicode characters with property Dash.
    +    Deprecated                         = _Deprecated                         // Deprecated is the set of Unicode characters with property Deprecated.
    +    Diacritic                          = _Diacritic                          // Diacritic is the set of Unicode characters with property Diacritic.
    +    Extender                           = _Extender                           // Extender is the set of Unicode characters with property Extender.
    +    Hex_Digit                          = _Hex_Digit                          // Hex_Digit is the set of Unicode characters with property Hex_Digit.
    +    Hyphen                             = _Hyphen                             // Hyphen is the set of Unicode characters with property Hyphen.
    +    IDS_Binary_Operator                = _IDS_Binary_Operator                // IDS_Binary_Operator is the set of Unicode characters with property IDS_Binary_Operator.
    +    IDS_Trinary_Operator               = _IDS_Trinary_Operator               // IDS_Trinary_Operator is the set of Unicode characters with property IDS_Trinary_Operator.
    +    Ideographic                        = _Ideographic                        // Ideographic is the set of Unicode characters with property Ideographic.
    +    Join_Control                       = _Join_Control                       // Join_Control is the set of Unicode characters with property Join_Control.
    +    Logical_Order_Exception            = _Logical_Order_Exception            // Logical_Order_Exception is the set of Unicode characters with property Logical_Order_Exception.
    +    Noncharacter_Code_Point            = _Noncharacter_Code_Point            // Noncharacter_Code_Point is the set of Unicode characters with property Noncharacter_Code_Point.
    +    Other_Alphabetic                   = _Other_Alphabetic                   // Other_Alphabetic is the set of Unicode characters with property Other_Alphabetic.
    +    Other_Default_Ignorable_Code_Point = _Other_Default_Ignorable_Code_Point // Other_Default_Ignorable_Code_Point is the set of Unicode characters with property Other_Default_Ignorable_Code_Point.
    +    Other_Grapheme_Extend              = _Other_Grapheme_Extend              // Other_Grapheme_Extend is the set of Unicode characters with property Other_Grapheme_Extend.
    +    Other_ID_Continue                  = _Other_ID_Continue                  // Other_ID_Continue is the set of Unicode characters with property Other_ID_Continue.
    +    Other_ID_Start                     = _Other_ID_Start                     // Other_ID_Start is the set of Unicode characters with property Other_ID_Start.
    +    Other_Lowercase                    = _Other_Lowercase                    // Other_Lowercase is the set of Unicode characters with property Other_Lowercase.
    +    Other_Math                         = _Other_Math                         // Other_Math is the set of Unicode characters with property Other_Math.
    +    Other_Uppercase                    = _Other_Uppercase                    // Other_Uppercase is the set of Unicode characters with property Other_Uppercase.
    +    Pattern_Syntax                     = _Pattern_Syntax                     // Pattern_Syntax is the set of Unicode characters with property Pattern_Syntax.
    +    Pattern_White_Space                = _Pattern_White_Space                // Pattern_White_Space is the set of Unicode characters with property Pattern_White_Space.
    +    Quotation_Mark                     = _Quotation_Mark                     // Quotation_Mark is the set of Unicode characters with property Quotation_Mark.
    +    Radical                            = _Radical                            // Radical is the set of Unicode characters with property Radical.
    +    STerm                              = _STerm                              // STerm is the set of Unicode characters with property STerm.
    +    Soft_Dotted                        = _Soft_Dotted                        // Soft_Dotted is the set of Unicode characters with property Soft_Dotted.
    +    Terminal_Punctuation               = _Terminal_Punctuation               // Terminal_Punctuation is the set of Unicode characters with property Terminal_Punctuation.
    +    Unified_Ideograph                  = _Unified_Ideograph                  // Unified_Ideograph is the set of Unicode characters with property Unified_Ideograph.
    +    Variation_Selector                 = _Variation_Selector                 // Variation_Selector is the set of Unicode characters with property Variation_Selector.
    +    White_Space                        = _White_Space                        // White_Space is the set of Unicode characters with property White_Space.
    +)
    +

    +These variables have type *RangeTable. +

    + + +
    var CaseRanges = _CaseRanges
    +

    +CaseRanges is the table describing case mappings for all letters with +non-self mappings. +

    + + +
    var Categories = map[string]*RangeTable{
    +    "C":  C,
    +    "Cc": Cc,
    +    "Cf": Cf,
    +    "Co": Co,
    +    "Cs": Cs,
    +    "L":  L,
    +    "Ll": Ll,
    +    "Lm": Lm,
    +    "Lo": Lo,
    +    "Lt": Lt,
    +    "Lu": Lu,
    +    "M":  M,
    +    "Mc": Mc,
    +    "Me": Me,
    +    "Mn": Mn,
    +    "N":  N,
    +    "Nd": Nd,
    +    "Nl": Nl,
    +    "No": No,
    +    "P":  P,
    +    "Pc": Pc,
    +    "Pd": Pd,
    +    "Pe": Pe,
    +    "Pf": Pf,
    +    "Pi": Pi,
    +    "Po": Po,
    +    "Ps": Ps,
    +    "S":  S,
    +    "Sc": Sc,
    +    "Sk": Sk,
    +    "Sm": Sm,
    +    "So": So,
    +    "Z":  Z,
    +    "Zl": Zl,
    +    "Zp": Zp,
    +    "Zs": Zs,
    +}
    +

    +Categories is the set of Unicode category tables. +

    + + +
    var FoldCategory = map[string]*RangeTable{
    +    "Common":    foldCommon,
    +    "Greek":     foldGreek,
    +    "Inherited": foldInherited,
    +    "L":         foldL,
    +    "Ll":        foldLl,
    +    "Lt":        foldLt,
    +    "Lu":        foldLu,
    +    "M":         foldM,
    +    "Mn":        foldMn,
    +}
    +

    +FoldCategory maps a category name to a table of +code points outside the category that are equivalent under +simple case folding to code points inside the category. +If there is no entry for a category name, there are no such points. +

    + + +
    var FoldScript = map[string]*RangeTable{}
    +

    +FoldScript maps a script name to a table of +code points outside the script that are equivalent under +simple case folding to code points inside the script. +If there is no entry for a script name, there are no such points. +

    + + +
    var GraphicRanges = []*RangeTable{
    +    L, M, N, P, S, Zs,
    +}
    +

    +GraphicRanges defines the set of graphic characters according to Unicode. +

    + + +
    var PrintRanges = []*RangeTable{
    +    L, M, N, P, S,
    +}
    +

    +PrintRanges defines the set of printable characters according to Go. +ASCII space, U+0020, is handled separately. +

    + + +
    var Properties = map[string]*RangeTable{
    +    "ASCII_Hex_Digit":                    ASCII_Hex_Digit,
    +    "Bidi_Control":                       Bidi_Control,
    +    "Dash":                               Dash,
    +    "Deprecated":                         Deprecated,
    +    "Diacritic":                          Diacritic,
    +    "Extender":                           Extender,
    +    "Hex_Digit":                          Hex_Digit,
    +    "Hyphen":                             Hyphen,
    +    "IDS_Binary_Operator":                IDS_Binary_Operator,
    +    "IDS_Trinary_Operator":               IDS_Trinary_Operator,
    +    "Ideographic":                        Ideographic,
    +    "Join_Control":                       Join_Control,
    +    "Logical_Order_Exception":            Logical_Order_Exception,
    +    "Noncharacter_Code_Point":            Noncharacter_Code_Point,
    +    "Other_Alphabetic":                   Other_Alphabetic,
    +    "Other_Default_Ignorable_Code_Point": Other_Default_Ignorable_Code_Point,
    +    "Other_Grapheme_Extend":              Other_Grapheme_Extend,
    +    "Other_ID_Continue":                  Other_ID_Continue,
    +    "Other_ID_Start":                     Other_ID_Start,
    +    "Other_Lowercase":                    Other_Lowercase,
    +    "Other_Math":                         Other_Math,
    +    "Other_Uppercase":                    Other_Uppercase,
    +    "Pattern_Syntax":                     Pattern_Syntax,
    +    "Pattern_White_Space":                Pattern_White_Space,
    +    "Quotation_Mark":                     Quotation_Mark,
    +    "Radical":                            Radical,
    +    "STerm":                              STerm,
    +    "Soft_Dotted":                        Soft_Dotted,
    +    "Terminal_Punctuation":               Terminal_Punctuation,
    +    "Unified_Ideograph":                  Unified_Ideograph,
    +    "Variation_Selector":                 Variation_Selector,
    +    "White_Space":                        White_Space,
    +}
    +

    +Properties is the set of Unicode property tables. +

    + + +
    var Scripts = map[string]*RangeTable{
    +    "Ahom":                   Ahom,
    +    "Anatolian_Hieroglyphs":  Anatolian_Hieroglyphs,
    +    "Arabic":                 Arabic,
    +    "Armenian":               Armenian,
    +    "Avestan":                Avestan,
    +    "Balinese":               Balinese,
    +    "Bamum":                  Bamum,
    +    "Bassa_Vah":              Bassa_Vah,
    +    "Batak":                  Batak,
    +    "Bengali":                Bengali,
    +    "Bopomofo":               Bopomofo,
    +    "Brahmi":                 Brahmi,
    +    "Braille":                Braille,
    +    "Buginese":               Buginese,
    +    "Buhid":                  Buhid,
    +    "Canadian_Aboriginal":    Canadian_Aboriginal,
    +    "Carian":                 Carian,
    +    "Caucasian_Albanian":     Caucasian_Albanian,
    +    "Chakma":                 Chakma,
    +    "Cham":                   Cham,
    +    "Cherokee":               Cherokee,
    +    "Common":                 Common,
    +    "Coptic":                 Coptic,
    +    "Cuneiform":              Cuneiform,
    +    "Cypriot":                Cypriot,
    +    "Cyrillic":               Cyrillic,
    +    "Deseret":                Deseret,
    +    "Devanagari":             Devanagari,
    +    "Duployan":               Duployan,
    +    "Egyptian_Hieroglyphs":   Egyptian_Hieroglyphs,
    +    "Elbasan":                Elbasan,
    +    "Ethiopic":               Ethiopic,
    +    "Georgian":               Georgian,
    +    "Glagolitic":             Glagolitic,
    +    "Gothic":                 Gothic,
    +    "Grantha":                Grantha,
    +    "Greek":                  Greek,
    +    "Gujarati":               Gujarati,
    +    "Gurmukhi":               Gurmukhi,
    +    "Han":                    Han,
    +    "Hangul":                 Hangul,
    +    "Hanunoo":                Hanunoo,
    +    "Hatran":                 Hatran,
    +    "Hebrew":                 Hebrew,
    +    "Hiragana":               Hiragana,
    +    "Imperial_Aramaic":       Imperial_Aramaic,
    +    "Inherited":              Inherited,
    +    "Inscriptional_Pahlavi":  Inscriptional_Pahlavi,
    +    "Inscriptional_Parthian": Inscriptional_Parthian,
    +    "Javanese":               Javanese,
    +    "Kaithi":                 Kaithi,
    +    "Kannada":                Kannada,
    +    "Katakana":               Katakana,
    +    "Kayah_Li":               Kayah_Li,
    +    "Kharoshthi":             Kharoshthi,
    +    "Khmer":                  Khmer,
    +    "Khojki":                 Khojki,
    +    "Khudawadi":              Khudawadi,
    +    "Lao":                    Lao,
    +    "Latin":                  Latin,
    +    "Lepcha":                 Lepcha,
    +    "Limbu":                  Limbu,
    +    "Linear_A":               Linear_A,
    +    "Linear_B":               Linear_B,
    +    "Lisu":                   Lisu,
    +    "Lycian":                 Lycian,
    +    "Lydian":                 Lydian,
    +    "Mahajani":               Mahajani,
    +    "Malayalam":              Malayalam,
    +    "Mandaic":                Mandaic,
    +    "Manichaean":             Manichaean,
    +    "Meetei_Mayek":           Meetei_Mayek,
    +    "Mende_Kikakui":          Mende_Kikakui,
    +    "Meroitic_Cursive":       Meroitic_Cursive,
    +    "Meroitic_Hieroglyphs":   Meroitic_Hieroglyphs,
    +    "Miao":                   Miao,
    +    "Modi":                   Modi,
    +    "Mongolian":              Mongolian,
    +    "Mro":                    Mro,
    +    "Multani":                Multani,
    +    "Myanmar":                Myanmar,
    +    "Nabataean":              Nabataean,
    +    "New_Tai_Lue":            New_Tai_Lue,
    +    "Nko":                    Nko,
    +    "Ogham":                  Ogham,
    +    "Ol_Chiki":               Ol_Chiki,
    +    "Old_Hungarian":          Old_Hungarian,
    +    "Old_Italic":             Old_Italic,
    +    "Old_North_Arabian":      Old_North_Arabian,
    +    "Old_Permic":             Old_Permic,
    +    "Old_Persian":            Old_Persian,
    +    "Old_South_Arabian":      Old_South_Arabian,
    +    "Old_Turkic":             Old_Turkic,
    +    "Oriya":                  Oriya,
    +    "Osmanya":                Osmanya,
    +    "Pahawh_Hmong":           Pahawh_Hmong,
    +    "Palmyrene":              Palmyrene,
    +    "Pau_Cin_Hau":            Pau_Cin_Hau,
    +    "Phags_Pa":               Phags_Pa,
    +    "Phoenician":             Phoenician,
    +    "Psalter_Pahlavi":        Psalter_Pahlavi,
    +    "Rejang":                 Rejang,
    +    "Runic":                  Runic,
    +    "Samaritan":              Samaritan,
    +    "Saurashtra":             Saurashtra,
    +    "Sharada":                Sharada,
    +    "Shavian":                Shavian,
    +    "Siddham":                Siddham,
    +    "SignWriting":            SignWriting,
    +    "Sinhala":                Sinhala,
    +    "Sora_Sompeng":           Sora_Sompeng,
    +    "Sundanese":              Sundanese,
    +    "Syloti_Nagri":           Syloti_Nagri,
    +    "Syriac":                 Syriac,
    +    "Tagalog":                Tagalog,
    +    "Tagbanwa":               Tagbanwa,
    +    "Tai_Le":                 Tai_Le,
    +    "Tai_Tham":               Tai_Tham,
    +    "Tai_Viet":               Tai_Viet,
    +    "Takri":                  Takri,
    +    "Tamil":                  Tamil,
    +    "Telugu":                 Telugu,
    +    "Thaana":                 Thaana,
    +    "Thai":                   Thai,
    +    "Tibetan":                Tibetan,
    +    "Tifinagh":               Tifinagh,
    +    "Tirhuta":                Tirhuta,
    +    "Ugaritic":               Ugaritic,
    +    "Vai":                    Vai,
    +    "Warang_Citi":            Warang_Citi,
    +    "Yi":                     Yi,
    +}
    +

    +Scripts is the set of Unicode script tables. +

    + + + + + + +

    func In

    +
    func In(r rune, ranges ...*RangeTable) bool
    +

    +In reports whether the rune is a member of one of the ranges. +

    + + + + + + + +

    func Is

    +
    func Is(rangeTab *RangeTable, r rune) bool
    +

    +Is reports whether the rune is in the specified table of ranges. +

    + + + + + + + +

    func IsControl

    +
    func IsControl(r rune) bool
    +

    +IsControl reports whether the rune is a control character. +The C (Other) Unicode category includes more code points +such as surrogates; use Is(C, r) to test for them. +

    + + + + + + + +

    func IsDigit

    +
    func IsDigit(r rune) bool
    +

    +IsDigit reports whether the rune is a decimal digit. +

    + + + + + + + +

    func IsGraphic

    +
    func IsGraphic(r rune) bool
    +

    +IsGraphic reports whether the rune is defined as a Graphic by Unicode. +Such characters include letters, marks, numbers, punctuation, symbols, and +spaces, from categories L, M, N, P, S, Zs. +

    + + + + + + + +

    func IsLetter

    +
    func IsLetter(r rune) bool
    +

    +IsLetter reports whether the rune is a letter (category L). +

    + + + + + + + +

    func IsLower

    +
    func IsLower(r rune) bool
    +

    +IsLower reports whether the rune is a lower case letter. +

    + + + + + + + +

    func IsMark

    +
    func IsMark(r rune) bool
    +

    +IsMark reports whether the rune is a mark character (category M). +

    + + + + + + + +

    func IsNumber

    +
    func IsNumber(r rune) bool
    +

    +IsNumber reports whether the rune is a number (category N). +

    + + + + + + + +

    func IsOneOf

    +
    func IsOneOf(ranges []*RangeTable, r rune) bool
    +

    +IsOneOf reports whether the rune is a member of one of the ranges. +The function "In" provides a nicer signature and should be used in preference to IsOneOf. +

    + + + + + + + +

    func IsPrint

    +
    func IsPrint(r rune) bool
    +

    +IsPrint reports whether the rune is defined as printable by Go. Such +characters include letters, marks, numbers, punctuation, symbols, and the +ASCII space character, from categories L, M, N, P, S and the ASCII space +character. This categorization is the same as IsGraphic except that the +only spacing character is ASCII space, U+0020. +

    + + + + + + + +

    func IsPunct

    +
    func IsPunct(r rune) bool
    +

    +IsPunct reports whether the rune is a Unicode punctuation character +(category P). +

    + + + + + + + +

    func IsSpace

    +
    func IsSpace(r rune) bool
    +

    +IsSpace reports whether the rune is a space character as defined +by Unicode's White Space property; in the Latin-1 space +this is +

    +
    '\t', '\n', '\v', '\f', '\r', ' ', U+0085 (NEL), U+00A0 (NBSP).
    +
    +

    +Other definitions of spacing characters are set by category +Z and property Pattern_White_Space. +

    + + + + + + + +

    func IsSymbol

    +
    func IsSymbol(r rune) bool
    +

    +IsSymbol reports whether the rune is a symbolic character. +

    + + + + + + + +

    func IsTitle

    +
    func IsTitle(r rune) bool
    +

    +IsTitle reports whether the rune is a title case letter. +

    + + + + + + + +

    func IsUpper

    +
    func IsUpper(r rune) bool
    +

    +IsUpper reports whether the rune is an upper case letter. +

    + + + + + + + +

    func SimpleFold

    +
    func SimpleFold(r rune) rune
    +

    +SimpleFold iterates over Unicode code points equivalent under +the Unicode-defined simple case folding. Among the code points +equivalent to rune (including rune itself), SimpleFold returns the +smallest rune > r if one exists, or else the smallest rune >= 0. +

    +

    +For example: +

    +
    SimpleFold('A') = 'a'
    +SimpleFold('a') = 'A'
    +
    +SimpleFold('K') = 'k'
    +SimpleFold('k') = '\u212A' (Kelvin symbol, K)
    +SimpleFold('\u212A') = 'K'
    +
    +SimpleFold('1') = '1'
    +
    + +
    + +
    +

    Example

    + + + +

    Code:

    +
    fmt.Printf("%#U\n", unicode.SimpleFold('A'))      // 'a'
    +fmt.Printf("%#U\n", unicode.SimpleFold('a'))      // 'A'
    +fmt.Printf("%#U\n", unicode.SimpleFold('K'))      // 'k'
    +fmt.Printf("%#U\n", unicode.SimpleFold('k'))      // '\u212A' (Kelvin symbol, K)
    +fmt.Printf("%#U\n", unicode.SimpleFold('\u212A')) // 'K'
    +fmt.Printf("%#U\n", unicode.SimpleFold('1'))      // '1'
    +
    +
    + +

    Output:

    +
    U+0061 'a'
    +U+0041 'A'
    +U+006B 'k'
    +U+212A 'K'
    +U+004B 'K'
    +U+0031 '1'
    +
    + + +
    +
    + + + + + + +

    func To

    +
    func To(_case int, r rune) rune
    +

    +To maps the rune to the specified case: UpperCase, LowerCase, or TitleCase. +

    + +
    + +
    +

    Example

    + + + +

    Code:

    +
    const lcG = 'g'
    +fmt.Printf("%#U\n", unicode.To(unicode.UpperCase, lcG))
    +fmt.Printf("%#U\n", unicode.To(unicode.LowerCase, lcG))
    +fmt.Printf("%#U\n", unicode.To(unicode.TitleCase, lcG))
    +
    +const ucG = 'G'
    +fmt.Printf("%#U\n", unicode.To(unicode.UpperCase, ucG))
    +fmt.Printf("%#U\n", unicode.To(unicode.LowerCase, ucG))
    +fmt.Printf("%#U\n", unicode.To(unicode.TitleCase, ucG))
    +
    +
    + +

    Output:

    +
    U+0047 'G'
    +U+0067 'g'
    +U+0047 'G'
    +U+0047 'G'
    +U+0067 'g'
    +U+0047 'G'
    +
    + + +
    +
    + + + + + + +

    func ToLower

    +
    func ToLower(r rune) rune
    +

    +ToLower maps the rune to lower case. +

    + +
    + +
    +

    Example

    + + + +

    Code:

    +
    const ucG = 'G'
    +fmt.Printf("%#U\n", unicode.ToLower(ucG))
    +
    +
    + +

    Output:

    +
    U+0067 'g'
    +
    + + +
    +
    + + + + + + +

    func ToTitle

    +
    func ToTitle(r rune) rune
    +

    +ToTitle maps the rune to title case. +

    + +
    + +
    +

    Example

    + + + +

    Code:

    +
    const ucG = 'g'
    +fmt.Printf("%#U\n", unicode.ToTitle(ucG))
    +
    +
    + +

    Output:

    +
    U+0047 'G'
    +
    + + +
    +
    + + + + + + +

    func ToUpper

    +
    func ToUpper(r rune) rune
    +

    +ToUpper maps the rune to upper case. +

    + +
    + +
    +

    Example

    + + + +

    Code:

    +
    const ucG = 'g'
    +fmt.Printf("%#U\n", unicode.ToUpper(ucG))
    +
    +
    + +

    Output:

    +
    U+0047 'G'
    +
    + + +
    +
    + + + + + + + +

    type CaseRange

    +
    type CaseRange struct {
    +    Lo    uint32
    +    Hi    uint32
    +    Delta d
    +}
    +

    +CaseRange represents a range of Unicode code points for simple (one +code point to one code point) case conversion. +The range runs from Lo to Hi inclusive, with a fixed stride of 1. Deltas +are the number to add to the code point to reach the code point for a +different case for that character. They may be negative. If zero, it +means the character is in the corresponding case. There is a special +case representing sequences of alternating corresponding Upper and Lower +pairs. It appears with a fixed Delta of +

    +
    {UpperLower, UpperLower, UpperLower}
    +
    +

    +The constant UpperLower has an otherwise impossible delta value. +

    + + + + + + + + + + + + + + + + +

    type Range16

    +
    type Range16 struct {
    +    Lo     uint16
    +    Hi     uint16
    +    Stride uint16
    +}
    +

    +Range16 represents of a range of 16-bit Unicode code points. The range runs from Lo to Hi +inclusive and has the specified stride. +

    + + + + + + + + + + + + + + + + +

    type Range32

    +
    type Range32 struct {
    +    Lo     uint32
    +    Hi     uint32
    +    Stride uint32
    +}
    +

    +Range32 represents of a range of Unicode code points and is used when one or +more of the values will not fit in 16 bits. The range runs from Lo to Hi +inclusive and has the specified stride. Lo and Hi must always be >= 1<<16. +

    + + + + + + + + + + + + + + + + +

    type RangeTable

    +
    type RangeTable struct {
    +    R16         []Range16
    +    R32         []Range32
    +    LatinOffset int // number of entries in R16 with Hi <= MaxLatin1
    +}
    +

    +RangeTable defines a set of Unicode code points by listing the ranges of +code points within the set. The ranges are listed in two slices +to save space: a slice of 16-bit ranges and a slice of 32-bit ranges. +The two slices must be in sorted order and non-overlapping. +Also, R32 should contain only values >= 0x10000 (1<<16). +

    + + + + + + + + + + + + + + + + +

    type SpecialCase

    +
    type SpecialCase []CaseRange
    +

    +SpecialCase represents language-specific case mappings such as Turkish. +Methods of SpecialCase customize (by overriding) the standard mappings. +

    + + + + + +
    var AzeriCase SpecialCase = _TurkishCase
    + + +
    var TurkishCase SpecialCase = _TurkishCase
    + + + +
    + +
    +

    Example

    + + + +

    Code:

    +
    t := unicode.TurkishCase
    +
    +const lci = 'i'
    +fmt.Printf("%#U\n", t.ToLower(lci))
    +fmt.Printf("%#U\n", t.ToTitle(lci))
    +fmt.Printf("%#U\n", t.ToUpper(lci))
    +
    +const uci = 'İ'
    +fmt.Printf("%#U\n", t.ToLower(uci))
    +fmt.Printf("%#U\n", t.ToTitle(uci))
    +fmt.Printf("%#U\n", t.ToUpper(uci))
    +
    +
    + +

    Output:

    +
    U+0069 'i'
    +U+0130 'İ'
    +U+0130 'İ'
    +U+0069 'i'
    +U+0130 'İ'
    +U+0130 'İ'
    +
    + + +
    +
    + + + + + + + + +

    func (SpecialCase) ToLower

    +
    func (special SpecialCase) ToLower(r rune) rune
    +

    +ToLower maps the rune to lower case giving priority to the special mapping. +

    + + + + + + +

    func (SpecialCase) ToTitle

    +
    func (special SpecialCase) ToTitle(r rune) rune
    +

    +ToTitle maps the rune to title case giving priority to the special mapping. +

    + + + + + + +

    func (SpecialCase) ToUpper

    +
    func (special SpecialCase) ToUpper(r rune) rune
    +

    +ToUpper maps the rune to upper case giving priority to the special mapping. +

    + + + + + + + + + + +

    Bugs

    +
      + +
    • There is no mechanism for full case folding, that is, for +characters that involve multiple runes in the input or output. +
    • + +
    + + + + + + + + + +

    Subdirectories

    + + + + +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    NameSynopsis
    ..
    + utf16 + + Package utf16 implements encoding and decoding of UTF-16 sequences. +
    + utf8 + + Package utf8 implements functions and constants to support text encoded in UTF-8. +
    +
    + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/unicode/utf16/index.html b/pkg/unicode/utf16/index.html new file mode 100644 index 0000000..9bdaf46 --- /dev/null +++ b/pkg/unicode/utf16/index.html @@ -0,0 +1,286 @@ + + + + + + + + utf16 - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Package utf16

    + + + + + + + + + + + + + + +
    +
    +
    import "unicode/utf16"
    +
    +
    +
    Overview
    +
    Index
    + + +
    +
    + +
    + +
    +

    Overview ▾

    +

    +Package utf16 implements encoding and decoding of UTF-16 sequences. +

    + +
    +
    + + +
    + +
    +

    Index ▾

    + + + + + + + +

    Package files

    +

    + + + utf16.go + + +

    + +
    +
    + + + + + + + + +

    func Decode

    +
    func Decode(s []uint16) []rune
    +

    +Decode returns the Unicode code point sequence represented +by the UTF-16 encoding s. +

    + + + + + + + +

    func DecodeRune

    +
    func DecodeRune(r1, r2 rune) rune
    +

    +DecodeRune returns the UTF-16 decoding of a surrogate pair. +If the pair is not a valid UTF-16 surrogate pair, DecodeRune returns +the Unicode replacement code point U+FFFD. +

    + + + + + + + +

    func Encode

    +
    func Encode(s []rune) []uint16
    +

    +Encode returns the UTF-16 encoding of the Unicode code point sequence s. +

    + + + + + + + +

    func EncodeRune

    +
    func EncodeRune(r rune) (r1, r2 rune)
    +

    +EncodeRune returns the UTF-16 surrogate pair r1, r2 for the given rune. +If the rune is not a valid Unicode code point or does not need encoding, +EncodeRune returns U+FFFD, U+FFFD. +

    + + + + + + + +

    func IsSurrogate

    +
    func IsSurrogate(r rune) bool
    +

    +IsSurrogate reports whether the specified Unicode code point +can appear in a surrogate pair. +

    + + + + + + + + + + + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/unicode/utf8/index.html b/pkg/unicode/utf8/index.html new file mode 100644 index 0000000..41ed24c --- /dev/null +++ b/pkg/unicode/utf8/index.html @@ -0,0 +1,889 @@ + + + + + + + + utf8 - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Package utf8

    + + + + + + + + + + + + + + +
    +
    +
    import "unicode/utf8"
    +
    +
    +
    Overview
    +
    Index
    + +
    Examples
    + + +
    +
    + +
    + +
    +

    Overview ▾

    +

    +Package utf8 implements functions and constants to support text encoded in +UTF-8. It includes functions to translate between runes and UTF-8 byte sequences. +

    + +
    +
    + + + + + + + +

    Constants

    + +
    const (
    +    RuneError = '\uFFFD'     // the "error" Rune or "Unicode replacement character"
    +    RuneSelf  = 0x80         // characters below Runeself are represented as themselves in a single byte.
    +    MaxRune   = '\U0010FFFF' // Maximum valid Unicode code point.
    +    UTFMax    = 4            // maximum number of bytes of a UTF-8 encoded Unicode character.
    +)
    +

    +Numbers fundamental to the encoding. +

    + + + + + + + +

    func DecodeLastRune

    +
    func DecodeLastRune(p []byte) (r rune, size int)
    +

    +DecodeLastRune unpacks the last UTF-8 encoding in p and returns the rune and +its width in bytes. If p is empty it returns (RuneError, 0). Otherwise, if +the encoding is invalid, it returns (RuneError, 1). Both are impossible +results for correct, non-empty UTF-8. +

    +

    +An encoding is invalid if it is incorrect UTF-8, encodes a rune that is +out of range, or is not the shortest possible UTF-8 encoding for the +value. No other validation is performed. +

    + +
    + +
    +

    Example

    + + + +

    Code:

    +
    b := []byte("Hello, 世界")
    +
    +for len(b) > 0 {
    +    r, size := utf8.DecodeLastRune(b)
    +    fmt.Printf("%c %v\n", r, size)
    +
    +    b = b[:len(b)-size]
    +}
    +
    + +

    Output:

    +
    界 3
    +世 3
    +  1
    +, 1
    +o 1
    +l 1
    +l 1
    +e 1
    +H 1
    +
    + + +
    +
    + + + + + + +

    func DecodeLastRuneInString

    +
    func DecodeLastRuneInString(s string) (r rune, size int)
    +

    +DecodeLastRuneInString is like DecodeLastRune but its input is a string. If +s is empty it returns (RuneError, 0). Otherwise, if the encoding is invalid, +it returns (RuneError, 1). Both are impossible results for correct, +non-empty UTF-8. +

    +

    +An encoding is invalid if it is incorrect UTF-8, encodes a rune that is +out of range, or is not the shortest possible UTF-8 encoding for the +value. No other validation is performed. +

    + +
    + +
    +

    Example

    + + + +

    Code:

    +
    str := "Hello, 世界"
    +
    +for len(str) > 0 {
    +    r, size := utf8.DecodeLastRuneInString(str)
    +    fmt.Printf("%c %v\n", r, size)
    +
    +    str = str[:len(str)-size]
    +}
    +
    + +

    Output:

    +
    界 3
    +世 3
    +  1
    +, 1
    +o 1
    +l 1
    +l 1
    +e 1
    +H 1
    +
    + + +
    +
    + + + + + + +

    func DecodeRune

    +
    func DecodeRune(p []byte) (r rune, size int)
    +

    +DecodeRune unpacks the first UTF-8 encoding in p and returns the rune and +its width in bytes. If p is empty it returns (RuneError, 0). Otherwise, if +the encoding is invalid, it returns (RuneError, 1). Both are impossible +results for correct, non-empty UTF-8. +

    +

    +An encoding is invalid if it is incorrect UTF-8, encodes a rune that is +out of range, or is not the shortest possible UTF-8 encoding for the +value. No other validation is performed. +

    + +
    + +
    +

    Example

    + + + +

    Code:

    +
    b := []byte("Hello, 世界")
    +
    +for len(b) > 0 {
    +    r, size := utf8.DecodeRune(b)
    +    fmt.Printf("%c %v\n", r, size)
    +
    +    b = b[size:]
    +}
    +
    + +

    Output:

    +
    H 1
    +e 1
    +l 1
    +l 1
    +o 1
    +, 1
    +  1
    +世 3
    +界 3
    +
    + + +
    +
    + + + + + + +

    func DecodeRuneInString

    +
    func DecodeRuneInString(s string) (r rune, size int)
    +

    +DecodeRuneInString is like DecodeRune but its input is a string. If s is +empty it returns (RuneError, 0). Otherwise, if the encoding is invalid, it +returns (RuneError, 1). Both are impossible results for correct, non-empty +UTF-8. +

    +

    +An encoding is invalid if it is incorrect UTF-8, encodes a rune that is +out of range, or is not the shortest possible UTF-8 encoding for the +value. No other validation is performed. +

    + +
    + +
    +

    Example

    + + + +

    Code:

    +
    str := "Hello, 世界"
    +
    +for len(str) > 0 {
    +    r, size := utf8.DecodeRuneInString(str)
    +    fmt.Printf("%c %v\n", r, size)
    +
    +    str = str[size:]
    +}
    +
    + +

    Output:

    +
    H 1
    +e 1
    +l 1
    +l 1
    +o 1
    +, 1
    +  1
    +世 3
    +界 3
    +
    + + +
    +
    + + + + + + +

    func EncodeRune

    +
    func EncodeRune(p []byte, r rune) int
    +

    +EncodeRune writes into p (which must be large enough) the UTF-8 encoding of the rune. +It returns the number of bytes written. +

    + +
    + +
    +

    Example

    + + + +

    Code:

    +
    r := '世'
    +buf := make([]byte, 3)
    +
    +n := utf8.EncodeRune(buf, r)
    +
    +fmt.Println(buf)
    +fmt.Println(n)
    +
    + +

    Output:

    +
    [228 184 150]
    +3
    +
    + + +
    +
    + + + + + + +

    func FullRune

    +
    func FullRune(p []byte) bool
    +

    +FullRune reports whether the bytes in p begin with a full UTF-8 encoding of a rune. +An invalid encoding is considered a full Rune since it will convert as a width-1 error rune. +

    + +
    + +
    +

    Example

    + + + +

    Code:

    +
    buf := []byte{228, 184, 150} // 世
    +fmt.Println(utf8.FullRune(buf))
    +fmt.Println(utf8.FullRune(buf[:2]))
    +
    + +

    Output:

    +
    true
    +false
    +
    + + +
    +
    + + + + + + +

    func FullRuneInString

    +
    func FullRuneInString(s string) bool
    +

    +FullRuneInString is like FullRune but its input is a string. +

    + +
    + +
    +

    Example

    + + + +

    Code:

    +
    str := "世"
    +fmt.Println(utf8.FullRuneInString(str))
    +fmt.Println(utf8.FullRuneInString(str[:2]))
    +
    + +

    Output:

    +
    true
    +false
    +
    + + +
    +
    + + + + + + +

    func RuneCount

    +
    func RuneCount(p []byte) int
    +

    +RuneCount returns the number of runes in p. Erroneous and short +encodings are treated as single runes of width 1 byte. +

    + +
    + +
    +

    Example

    + + + +

    Code:

    +
    buf := []byte("Hello, 世界")
    +fmt.Println("bytes =", len(buf))
    +fmt.Println("runes =", utf8.RuneCount(buf))
    +
    + +

    Output:

    +
    bytes = 13
    +runes = 9
    +
    + + +
    +
    + + + + + + +

    func RuneCountInString

    +
    func RuneCountInString(s string) (n int)
    +

    +RuneCountInString is like RuneCount but its input is a string. +

    + +
    + +
    +

    Example

    + + + +

    Code:

    +
    str := "Hello, 世界"
    +fmt.Println("bytes =", len(str))
    +fmt.Println("runes =", utf8.RuneCountInString(str))
    +
    + +

    Output:

    +
    bytes = 13
    +runes = 9
    +
    + + +
    +
    + + + + + + +

    func RuneLen

    +
    func RuneLen(r rune) int
    +

    +RuneLen returns the number of bytes required to encode the rune. +It returns -1 if the rune is not a valid value to encode in UTF-8. +

    + +
    + +
    +

    Example

    + + + +

    Code:

    +
    fmt.Println(utf8.RuneLen('a'))
    +fmt.Println(utf8.RuneLen('界'))
    +
    + +

    Output:

    +
    1
    +3
    +
    + + +
    +
    + + + + + + +

    func RuneStart

    +
    func RuneStart(b byte) bool
    +

    +RuneStart reports whether the byte could be the first byte of an encoded, +possibly invalid rune. Second and subsequent bytes always have the top two +bits set to 10. +

    + +
    + +
    +

    Example

    + + + +

    Code:

    +
    buf := []byte("a界")
    +fmt.Println(utf8.RuneStart(buf[0]))
    +fmt.Println(utf8.RuneStart(buf[1]))
    +fmt.Println(utf8.RuneStart(buf[2]))
    +
    + +

    Output:

    +
    true
    +true
    +false
    +
    + + +
    +
    + + + + + + +

    func Valid

    +
    func Valid(p []byte) bool
    +

    +Valid reports whether p consists entirely of valid UTF-8-encoded runes. +

    + +
    + +
    +

    Example

    + + + +

    Code:

    +
    valid := []byte("Hello, 世界")
    +invalid := []byte{0xff, 0xfe, 0xfd}
    +
    +fmt.Println(utf8.Valid(valid))
    +fmt.Println(utf8.Valid(invalid))
    +
    + +

    Output:

    +
    true
    +false
    +
    + + +
    +
    + + + + + + +

    func ValidRune

    +
    func ValidRune(r rune) bool
    +

    +ValidRune reports whether r can be legally encoded as UTF-8. +Code points that are out of range or a surrogate half are illegal. +

    + +
    + +
    +

    Example

    + + + +

    Code:

    +
    valid := 'a'
    +invalid := rune(0xfffffff)
    +
    +fmt.Println(utf8.ValidRune(valid))
    +fmt.Println(utf8.ValidRune(invalid))
    +
    + +

    Output:

    +
    true
    +false
    +
    + + +
    +
    + + + + + + +

    func ValidString

    +
    func ValidString(s string) bool
    +

    +ValidString reports whether s consists entirely of valid UTF-8-encoded runes. +

    + +
    + +
    +

    Example

    + + + +

    Code:

    +
    valid := "Hello, 世界"
    +invalid := string([]byte{0xff, 0xfe, 0xfd})
    +
    +fmt.Println(utf8.ValidString(valid))
    +fmt.Println(utf8.ValidString(invalid))
    +
    + +

    Output:

    +
    true
    +false
    +
    + + +
    +
    + + + + + + + + + + + + + + + + + +
    +
    + + + + + + + + + + + + diff --git a/pkg/unsafe/index.html b/pkg/unsafe/index.html new file mode 100644 index 0000000..4682015 --- /dev/null +++ b/pkg/unsafe/index.html @@ -0,0 +1,502 @@ + + + + + + + + unsafe - The Go Programming Language + + + + + + + + +
    +... +
    + + + + + +
    +
    + + +

    Package unsafe

    + + + + + + + + + + + + + + +
    +
    +
    import "unsafe"
    +
    +
    +
    Overview
    +
    Index
    + + +
    +
    + +
    + +
    +

    Overview ▾

    +

    +Package unsafe contains operations that step around the type safety of Go programs. +

    +

    +Packages that import unsafe may be non-portable and are not protected by the +Go 1 compatibility guidelines. +

    + +
    +
    + + +
    + +
    +

    Index ▾

    + + + + + + + +

    Package files

    +

    + + + unsafe.go + + +

    + +
    +
    + + + + + + + + +

    func Alignof

    +
    func Alignof(x ArbitraryType) uintptr
    +

    +Alignof takes an expression x of any type and returns the required alignment +of a hypothetical variable v as if v was declared via var v = x. +It is the largest value m such that the address of v is always zero mod m. +It is the same as the value returned by reflect.TypeOf(x).Align(). +As a special case, if a variable s is of struct type and f is a field +within that struct, then Alignof(s.f) will return the required alignment +of a field of that type within a struct. This case is the same as the +value returned by reflect.TypeOf(s.f).FieldAlign(). +

    + + + + + + + +

    func Offsetof

    +
    func Offsetof(x ArbitraryType) uintptr
    +

    +Offsetof returns the offset within the struct of the field represented by x, +which must be of the form structValue.field. In other words, it returns the +number of bytes between the start of the struct and the start of the field. +

    + + + + + + + +

    func Sizeof

    +
    func Sizeof(x ArbitraryType) uintptr
    +

    +Sizeof takes an expression x of any type and returns the size in bytes +of a hypothetical variable v as if v was declared via var v = x. +The size does not include any memory possibly referenced by x. +For instance, if x is a slice, Sizeof returns the size of the slice +descriptor, not the size of the memory referenced by the slice. +

    + + + + + + + + +

    type ArbitraryType

    +
    type ArbitraryType int
    +

    +ArbitraryType is here for the purposes of documentation only and is not actually +part of the unsafe package. It represents the type of an arbitrary Go expression. +

    + + + + + + + + + + + + + + + + +

    type Pointer

    +
    type Pointer *ArbitraryType
    +

    +Pointer represents a pointer to an arbitrary type. There are four special operations +available for type Pointer that are not available for other types: +

    +
    - A pointer value of any type can be converted to a Pointer.
    +- A Pointer can be converted to a pointer value of any type.
    +- A uintptr can be converted to a Pointer.
    +- A Pointer can be converted to a uintptr.
    +
    +

    +Pointer therefore allows a program to defeat the type system and read and write +arbitrary memory. It should be used with extreme care. +

    +

    +The following patterns involving Pointer are valid. +Code not using these patterns is likely to be invalid today +or to become invalid in the future. +Even the valid patterns below come with important caveats. +

    +

    +Running "go vet" can help find uses of Pointer that do not conform to these patterns, +but silence from "go vet" is not a guarantee that the code is valid. +

    +

    +(1) Conversion of a *T1 to Pointer to *T2. +

    +

    +Provided that T2 is no larger than T1 and that the two share an equivalent +memory layout, this conversion allows reinterpreting data of one type as +data of another type. An example is the implementation of +math.Float64bits: +

    +
    func Float64bits(f float64) uint64 {
    +	return *(*uint64)(unsafe.Pointer(&f))
    +}
    +
    +

    +(2) Conversion of a Pointer to a uintptr (but not back to Pointer). +

    +

    +Converting a Pointer to a uintptr produces the memory address of the value +pointed at, as an integer. The usual use for such a uintptr is to print it. +

    +

    +Conversion of a uintptr back to Pointer is not valid in general. +

    +

    +A uintptr is an integer, not a reference. +Converting a Pointer to a uintptr creates an integer value +with no pointer semantics. +Even if a uintptr holds the address of some object, +the garbage collector will not update that uintptr's value +if the object moves, nor will that uintptr keep the object +from being reclaimed. +

    +

    +The remaining patterns enumerate the only valid conversions +from uintptr to Pointer. +

    +

    +(3) Conversion of a Pointer to a uintptr and back, with arithmetic. +

    +

    +If p points into an allocated object, it can be advanced through the object +by conversion to uintptr, addition of an offset, and conversion back to Pointer. +

    +
    p = unsafe.Pointer(uintptr(p) + offset)
    +
    +

    +The most common use of this pattern is to access fields in a struct +or elements of an array: +

    +
    // equivalent to f := unsafe.Pointer(&s.f)
    +f := unsafe.Pointer(uintptr(unsafe.Pointer(&s)) + unsafe.Offsetof(s.f))
    +
    +// equivalent to e := unsafe.Pointer(&x[i])
    +e := unsafe.Pointer(uintptr(unsafe.Pointer(&x[0])) + i*unsafe.Sizeof(x[0]))
    +
    +

    +It is valid both to add and to subtract offsets from a pointer in this way, +but the result must continue to point into the original allocated object. +Unlike in C, it is not valid to advance a pointer just beyond the end of +its original allocation: +

    +
    // INVALID: end points outside allocated space.
    +var s thing
    +end = unsafe.Pointer(uintptr(unsafe.Pointer(&s)) + unsafe.Sizeof(s))
    +
    +// INVALID: end points outside allocated space.
    +b := make([]byte, n)
    +end = unsafe.Pointer(uintptr(unsafe.Pointer(&b[0])) + uintptr(n))
    +
    +

    +Note that both conversions must appear in the same expression, with only +the intervening arithmetic between them: +

    +
    // INVALID: uintptr cannot be stored in variable
    +// before conversion back to Pointer.
    +u := uintptr(p)
    +p = unsafe.Pointer(u + offset)
    +
    +

    +(4) Conversion of a Pointer to a uintptr when calling syscall.Syscall. +

    +

    +The Syscall functions in package syscall pass their uintptr arguments directly +to the operating system, which then may, depending on the details of the call, +reinterpret some of them as pointers. +That is, the system call implementation is implicitly converting certain arguments +back from uintptr to pointer. +

    +

    +If a pointer argument must be converted to uintptr for use as an argument, +that conversion must appear in the call expression itself: +

    +
    syscall.Syscall(SYS_READ, uintptr(fd), uintptr(unsafe.Pointer(p)), uintptr(n))
    +
    +

    +The compiler handles a Pointer converted to a uintptr in the argument list of +a call to a function implemented in assembly by arranging that the referenced +allocated object, if any, is retained and not moved until the call completes, +even though from the types alone it would appear that the object is no longer +needed during the call. +

    +

    +For the compiler to recognize this pattern, +the conversion must appear in the argument list: +

    +
    // INVALID: uintptr cannot be stored in variable
    +// before implicit conversion back to Pointer during system call.
    +u := uintptr(unsafe.Pointer(p))
    +syscall.Syscall(SYS_READ, uintptr(fd), u, uintptr(n))
    +
    +

    +(5) Conversion of the result of reflect.Value.Pointer or reflect.Value.UnsafeAddr +from uintptr to Pointer. +

    +

    +Package reflect's Value methods named Pointer and UnsafeAddr return type uintptr +instead of unsafe.Pointer to keep callers from changing the result to an arbitrary +type without first importing "unsafe". However, this means that the result is +fragile and must be converted to Pointer immediately after making the call, +in the same expression: +

    +
    p := (*int)(unsafe.Pointer(reflect.ValueOf(new(int)).Pointer()))
    +
    +

    +As in the cases above, it is invalid to store the result before the conversion: +

    +
    // INVALID: uintptr cannot be stored in variable
    +// before conversion back to Pointer.
    +u := reflect.ValueOf(new(int)).Pointer()
    +p := (*int)(unsafe.Pointer(u))
    +
    +

    +(6) Conversion of a reflect.SliceHeader or reflect.StringHeader Data field to or from Pointer. +

    +

    +As in the previous case, the reflect data structures SliceHeader and StringHeader +declare the field Data as a uintptr to keep callers from changing the result to +an arbitrary type without first importing "unsafe". However, this means that +SliceHeader and StringHeader are only valid when interpreting the content +of an actual slice or string value. +

    +
    var s string
    +hdr := (*reflect.StringHeader)(unsafe.Pointer(&s)) // case 1
    +hdr.Data = uintptr(unsafe.Pointer(p))              // case 6 (this case)
    +hdr.Len = uintptr(n)
    +
    +

    +In this usage hdr.Data is really an alternate way to refer to the underlying +pointer in the slice header, not a uintptr variable itself. +

    +

    +In general, reflect.SliceHeader and reflect.StringHeader should be used +only as *reflect.SliceHeader and *reflect.StringHeader pointing at actual +slices or strings, never as plain structs. +A program should not declare or allocate variables of these struct types. +

    +
    // INVALID: a directly-declared header will not hold Data as a reference.
    +var hdr reflect.StringHeader
    +hdr.Data = uintptr(unsafe.Pointer(p))
    +hdr.Len = uintptr(n)
    +s := *(*string)(unsafe.Pointer(&hdr)) // p possibly already lost
    +
    + + + + + + + + + + + + + + + + + + + + + + + + + + +
    +
    + + + + + + + + + + + +