You are on page 1of 649

The Go Programming Language

The Go Memory Model


Introduction Happens Before Synchronization Initialization Goroutine creation Channel communication Locks Once Incorrect synchronization

Introduction
The Go memory model specifies the conditions under which reads of a variable in one goroutine can be guaranteed to observe values produced by writes to the same variable in a different goroutine.

Happens Before
Within a single goroutine, reads and writes must behave as if they executed in the order specified by the program. That is, compilers and processors may reorder the reads and writes executed within a single goroutine only when the reordering does not change the behavior within that goroutine as defined by the language specification. Because of this reordering, the execution order observed by one goroutine may differ from the order perceived by another. For example, if one goroutine executes a = 1; b = 2;, another might observe the updated value of b before the updated value of a. To specify the requirements of reads and writes, we define happens before, a partial order on the execution of memory operations in a Go program. If event e 1 happens before event e 2, then we say that e 2 happens after e 1. Also, if e 1 does not happen before e 2 and does not happen after e 2, then we say that e 1 and e 2 happen concurrently. Within a single goroutine, the happens before order is the order expressed by the program. A read r of a variable v is allowed to observe a write w to v if both of the following hold: 1. w happens before r. 2. There is no other write w' to v that happens after w but before r. To guarantee that a read r of a variable v observes a particular write w to v, ensure that w is the only write r is allowed to observe. That is, r is guaranteed to observe w if both of the following hold: 1. w happens before r. 2. Any other write to the shared variable v either happens before w or after r. This pair of conditions is stronger than the first pair; it requires that there are no other writes happening

concurrently with w or r. Within a single goroutine, there is no concurrency, so the two definitions are equivalent: a read r observes the value written by the most recent write w to v. When multiple goroutines access a shared variable v, they must use synchronization events to establish happens-before conditions that ensure reads observe the desired writes. The initialization of variable v with the zero value for v's type behaves as a write in the memory model. Reads and writes of values larger than a single machine word behave as multiple machine-word-sized operations in an unspecified order.

Synchronization
Initialization
Program initialization runs in a single goroutine and new goroutines created during initialization do not start running until initialization ends. If a package p imports package q, the completion of q's init functions happens before the start of any of p's. The start of the function main.main happens after all init functions have finished. The execution of any goroutines created during init functions happens after all init functions have finished.

Goroutine creation
The go statement that starts a new goroutine happens before the goroutine's execution begins. For example, in this program:
var a string; func f() { print(a); } func hello() { a = "hello, world"; go f(); }

calling hello will print "hello, world" at some point in the future (perhaps after hello has returned).

Channel com m unication


Channel communication is the main method of synchronization between goroutines. Each send on a particular channel is matched to a corresponding receive from that channel, usually in a different goroutine. A send on a channel happens before the corresponding receive from that channel completes. This program:

var c = make(chan int, 10) var a string func f() { a = "hello, world"; c <- 0; } func main() { go f(); <-c; print(a); }

is guaranteed to print "hello, world". The write to a happens before the send on c, which happens before the corresponding receive on c completes, which happens before the print. A receive from an unbuffered channel happens before the send on that channel completes. This program (as above, but with the send and receive statements swapped and using an unbuffered channel):
var c = make(chan int) var a string func f() { a = "hello, world"; <-c; }

func main() { go f(); c <- 0; print(a); }

is also guaranteed to print "hello, world". The write to a happens before the receive on c, which happens before the corresponding send on c completes, which happens before the print. If the channel were buffered (e.g., c = make(chan int, 1)) then the program would not be guaranteed to print "hello, world". (It might print the empty string; it cannot print "goodbye, universe", nor can it crash.)

Locks
The sync package implements two lock data types, sync.Mutex and sync.RWMutex. For any sync.Mutex or sync.RWMutex variable l and n < m, the n'th call to l.Unlock() happens before the m'th call to l.Lock() returns. This program:

var l sync.Mutex var a string func f() { a = "hello, world"; l.Unlock(); } func main() { l.Lock(); go f(); l.Lock(); print(a); }

is guaranteed to print "hello, world". The first call to l.Unlock() (in f) happens before the second call to l.Lock() (in main) returns, which happens before the print. For any call to l.RLock on a sync.RWMutex variable l, there is an n such that the l.RLock happens (returns) after the n'th call to l.Unlock and the matching l.RUnlock happens before the n+1'th call to l.Lock.

Once
The once package provides a safe mechanism for initialization in the presence of multiple goroutines. Multiple threads can execute once.Do(f) for a particular f, but only one will run f(), and the other calls block until f() has returned. A single call of f() from once.Do(f) happens (returns) before any call of once.Do(f) returns. In this program:
var a string func setup() { a = "hello, world"; } func doprint() { once.Do(setup); print(a); } func twoprint() { go doprint(); go doprint(); }

calling twoprint causes "hello, world" to be printed twice. The first call to twoprint runs setup once.

Incorrect synchronization
Note that a read r may observe the value written by a write w that happens concurrently with r. Even if this occurs, it does not imply that reads happening after r will observe writes that happened before w. In this program:

var a, b int func f() { a = 1; b = 2; } func g() { print(b); print(a); } func main() { go f(); g(); }

it can happen that g prints 2 and then 0. This fact invalidates a few common idioms. Double-checked locking is an attempt to avoid the overhead of synchronization. For example, the twoprint program might be incorrectly written as:
var a string var done bool func setup() { a = "hello, world"; done = true; } func doprint() { if !done { once.Do(setup); } print(a); } func twoprint() { go doprint(); go doprint(); }

but there is no guarantee that, in doprint, observing the write to done implies observing the write to a. This version can (incorrectly) print an empty string instead of "hello, world". Another incorrect idiom is busy waiting for a value, as in:

var a string var done bool func setup() { a = "hello, world"; done = true; } func main() { go setup(); for !done { } print(a); }

As before, there is no guarantee that, in main, observing the write to done implies observing the write to a, so this program could print an empty string too. Worse, there is no guarantee that the write to done will ever be observed by main, since there are no synchronization events between the two threads. The loop in main is not guaranteed to finish. There are subtler variants on this theme, such as this program.
type T struct { msg string; } var g *T func setup() { t := new(T); t.msg = "hello, world"; g = t; } func main() { go setup(); for g == nil { } print(g.msg); }

Even if main observes g != nil and exits its loop, there is no guarantee that it will observe the initialized value for g.msg. In all these examples, the solution is the same: use explicit synchronization.

Except as noted, this content is licensed under Creative Commons Attribution 3.0.

The Go Programming Language

Go For C++ Programmers


Conceptual Differences Syntax Constants Slices Making values Interfaces Goroutines Channels Go is a systems programming language intended to be a general-purpose systems language, like C++. These are some notes on Go for experienced C++ programmers. This document discusses the differences between Go and C++, and says little to nothing about the similarities. For a more general introduction to Go, see the Go tutorial and Effective Go. For a detailed description of the Go language, see the Go spec.

Conceptual Differences
Go does not have classes with constructors or destructors. Instead of class methods, a class inheritance hierarchy, and virtual functions, Go provides interfaces, which are discussed in more detail below. Interfaces are also used where C++ uses templates. Go uses garbage collection. It is not necessary (or possible) to release memory explicitly. The garbage collection is (intended to be) incremental and highly efficient on modern processors. Go has pointers but not pointer arithmetic. You cannot use a pointer variable to walk through the bytes of a string. Arrays in Go are first class values. When an array is used as a function parameter, the function receives a copy of the array, not a pointer to it. However, in practice functions often use slices for parameters; slices hold pointers to underlying arrays. Slices are discussed further below. Strings are provided by the language. They may not be changed once they have been created. Hash tables are provided by the language. They are called maps. Separate threads of execution, and communication channels between them, are provided by the language. This is discussed further below. Certain types (maps and channels, described further below) are passed by reference, not by value. That is, passing a map to a function does not copy the map, and if the function changes the map the change will be seen by the caller. In C++ terms, one can think of these as being reference types. Go does not use header files. Instead, each source file is part of a defined package. When a package defines an object (type, constant, variable, function) with a name starting with an upper case letter, that object is visible to any other file which imports that package. Go does not support implicit type conversion. Operations that mix different types require casts (called conversions in Go).

Go does not support function overloading and does not support user defined operators. Go does not support const or volatile qualifiers. Go uses nil for invalid pointers, where C++ uses NULL or simply 0.

Syntax
The declaration syntax is reversed compared to C++. You write the name followed by the type. Unlike in C++, the syntax for a type does not match the way in which the variable is used. Type declarations may be read easily from left to right.
Go var var var var var var var var C++ int v1; const std::string v2; (approximately) int v3[10]; int* v4; (approximately) struct { int f; } v5; int* v6; (but no pointer arithmetic) unordered_map<string, int>* v7; (approximately) int (*v8)(int a);

v1 v2 v3 v4 v5 v6 v7 v8

int string [10]int []int struct { f int } *int map[string]int func(a int) int

// // // // // // // //

Declarations generally take the form of a keyword followed by the name of the object being declared. The keyword is one of var, func, const, or type. Method declarations are a minor exception in that the receiver appears before the name of the object being declared; see the discussion of interfaces. You can also use a keyword followed by a series of declarations in parentheses.
var ( i int m float )

When declaring a function, you must either provide a name for each parameter or not provide a name for any parameter; you can't omit some names and provide others. You may group several names with the same type:
func f(i, j, k int, s, t string)

A variable may be initialized when it is declared. When this is done, specifying the type is permitted but not required. When the type is not specified, the type of the variable is the type of the initialization expression.
var v = *p

See also the discussion of constants, below. If a variable is not initialized explicitly, the type must be specified. In that case it will be implicitly initialized to the type's zero value (0, nil, etc.). There are no uninitialized variables in Go. Within a function, a short declaration syntax is available with := .
v1 := v2

This is equivalent to

var v1 = v2

Go permits multiple assignments, which are done in parallel.


i, j = j, i // Swap i and j.

Functions may have multiple return values, indicated by a list in parentheses. The returned values can be stored by assignment to a list of variables.
func f() (i int, j int) { ... } v1, v2 = f()

Go code uses very few semicolons in practice. Technically, all Go statements are terminated by a semicolon. However, Go treats the end of a non-blank line as a semicolon unless the line is clearly incomplete (the exact rules are in the language specification). A consequence of this is that in some cases Go does not permit you to use a line break. For example, you may not write
func g() { }

// INVALID

A semicolon will be inserted after g(), causing it to be a function declaration rather than a function definition. Similarly, you may not write
if x { } else { }

// INVALID

A semicolon will be inserted after the } preceding the else, causing a syntax error. Since semicolons do end statements, you may continue using them as in C++. However, that is not the recommended style. Idiomatic Go code omits unnecessary semicolons, which in practice is all of them other than the initial loop clause and cases where you want several short statements on a single line. While we're on the topic, we recommend that rather than worry about semicolons and brace placement, you format your code with the gofmt program. That will produce a single standard Go style, and let you worry about your code rather than your formatting. While the style may initially seem odd, it is as good as any other style, and familiarity will lead to comfort. When using a pointer to a struct, you use . instead of ->. Thus syntactically speaking a structure and a pointer to a structure are used in the same way.
type myStruct struct { i int } var v9 myStruct // v9 has structure type var p9 *myStruct // p9 is a pointer to a structure f(v9.i, p9.i)

Go does not require parentheses around the condition of a if statement, or the expressions of a for statement, or the value of a switch statement. On the other hand, it does require curly braces around the body of an if or for statement.

if a < b { f() } if (a < b) { f() } if (a < b) f() for i = 0; i < 10; i++ {} for (i = 0; i < 10; i++) {}

// // // // //

Valid Valid (condition is a parenthesized expression) INVALID Valid INVALID

Go does not have a while statement nor does it have a do/while statement. The for statement may be used with a single condition, which makes it equivalent to a while statement. Omitting the condition entirely is an endless loop. Go permits break and continue to specify a label. The label must refer to a for, switch, or select statement. In a switch statement, case labels do not fall through. You can make them fall through using the fallthrough keyword. This applies even to adjacent cases.
switch i { case 0: // empty case body case 1: f() // f is not called when i == 0! }

But a case can have multiple values.


switch i { case 0, 1: f() // f is called if i == 0 || i == 1. }

The values in a case need not be constantsor even integers; any type that supports the equality comparison operator, such as strings or pointers, can be usedand if the switch value is omitted it defaults to true.
switch { case i < 0: f1() case i == 0: f2() case i > 0: f3() }

The ++ and -- operators may only be used in statements, not in expressions. You cannot write c = *p++. *p++ is parsed as (*p)++. The defer statement may be used to call a function after the function containing the defer statement returns.
fd := open("filename") defer close(fd)

// fd will be closed when this function returns.

Constants

In Go constants may be untyped. This applies even to constants named with a const declaration, if no type is given in the declaration and the initializer expression uses only untyped constants. A value derived from an untyped constant becomes typed when it is used within a context that requires a typed value. This permits constants to be used relatively freely without requiring general implicit type conversion.
var a uint f(a + 1) // untyped numeric constant "1" becomes typed as uint

The language does not impose any limits on the size of an untyped numeric constant or constant expression. A limit is only applied when a constant is used where a type is required.
const huge = 1 << 100 f(huge >> 98)

Go does not support enums. Instead, you can use the special name iota in a single const declaration to get a series of increasing value. When an initialization expression is omitted for a const, it reuses the preceding expression.
const ( red = iota blue green )

// red == 0 // blue == 1 // green == 2

Slices
A slice is conceptually a struct with three fields: a pointer to an array, a length, and a capacity. Slices support the [] operator to access elements of the underlying array. The builtin len function returns the length of the slice. The builtin cap function returns the capacity. Given an array, or another slice, a new slice is created via a[I:J]. This creates a new slice which refers to a, starts at index I, and ends before index J. It has length J - I. The new slice refers to the same array to which a refers. That is, changes made using the new slice may be seen using a. The capacity of the new slice is simply the capacity of a minus I. The capacity of an array is the length of the array. You may also assign an array pointer to a variable of slice type; given var s []int; var a[10] int, the assignment s = &a is equivalent to s = a[0:len(a)]. What this means is that Go uses slices for some cases where C++ uses pointers. If you create a value of type [100]byte (an array of 100 bytes, perhaps a buffer) and you want to pass it to a function without copying it, you should declare the function parameter to have type []byte, and pass the address of the array. Unlike in C++, it is not necessary to pass the length of the buffer; it is efficiently accessible via len. The slice syntax may also be used with a string. It returns a new string, whose value is a substring of the original string. Because strings are immutable, string slices can be implemented without allocating new storage for the slices's contents.

Making values
Go has a builtin function new which takes a type and allocates space on the heap. The allocated space will be zero-initialized for the type. For example, new(int) allocates a new int on the heap, initializes it with the value 0, and returns its address, which has type *int. Unlike in C++, new is a function, not an operator;

new int is a syntax error. Map and channel values must be allocated using the builtin function make. A variable declared with map or channel type without an initializer will be automatically initialized to nil. Calling make(map[int]int) returns a newly allocated value of type map[int]int. Note that make returns a value, not a pointer. This is consistent with the fact that map and channel values are passed by reference. Calling make with a map type takes an optional argument which is the expected capacity of the map. Calling make with a channel type takes an optional argument which sets the buffering capacity of the channel; the default is 0 (unbuffered). The make function may also be used to allocate a slice. In this case it allocates memory for the underlying array and returns a slice referring to it. There is one required argument, which is the number of elements in the slice. A second, optional, argument is the capacity of the slice. For example, make([]int, 10, 20). This is identical to new([20]int)[0:10]. Since Go uses garbage collection, the newly allocated array will be discarded sometime after there are no references to the returned slice.

Interfaces
Where C++ provides classes, subclasses and templates, Go provides interfaces. A Go interface is similar to a C++ pure abstract class: a class with no data members, with methods which are all pure virtual. However, in Go, any type which provides the methods named in the interface may be treated as an implementation of the interface. No explicitly declared inheritance is required. The implementation of the interface is entirely separate from the interface itself. A method looks like an ordinary function definition, except that it has a receiver. The receiver is similar to the this pointer in a C++ class method.
type myType struct { i int } func (p *myType) get() int { return p.i }

This declares a method get associated with myType. The receiver is named p in the body of the function. Methods are defined on named types. If you convert the value to a different type, the new value will have the methods of the new type, not the old type. You may define methods on a builtin type by declaring a new named type derived from it. The new type is distinct from the builtin type.
type myInteger int func (p myInteger) get() int { return int(p) } // Conversion required. func f(i int) { } var v myInteger // f(v) is invalid. // f(int(v)) is valid; int(v) has no defined methods.

Given this interface:


type myInterface interface { get() int set(i int) }

we can make myType satisfy the interface by adding

func (p *myType) set(i int) { p.i = i }

Now any function which takes myInterface as a parameter will accept a variable of type *myType.
func getAndSet(x myInterface) {} func f1() { var p myType getAndSet(&p) }

In other words, if we view myInterface as a C++ pure abstract base class, defining set and get for *myType made *myType automatically inherit from myInterface. A type may satisfy multiple interfaces. An anonymous field may be used to implement something much like a C++ child class.
type myChildType struct { myType; j int } func (p *myChildType) get() int { p.j++; return p.myType.get() }

This effectively implements myChildType as a child of myType.


func f2() { var p myChildType getAndSet(&p) }

The set method is effectively inherited from myChildType, because methods associated with the anonymous field are promoted to become methods of the enclosing type. In this case, because myChildType has an anonymous field of type myType, the methods of myType also become methods of myChildType. In this example, the get method was overridden, and the set method was inherited. This is not precisely the same as a child class in C++. When a method of an anonymous field is called, its receiver is the field, not the surrounding struct. In other words, methods on anonymous fields are not virtual functions. When you want the equivalent of a virtual function, use an interface. A variable which has an interface type may be converted to have a different interface type using a special construct called a type assertion. This is implemented dynamically at runtime, like C++ dynamic_cast. Unlike dynamic_cast, there does not need to be any declared relationship between the two interfaces.
type myPrintInterface interface { print() } func f3(x myInterface) { x.(myPrintInterface).print() }

// type assertion to myPrintInterface

The conversion to myPrintInterface is entirely dynamic. It will work as long as the underlying type of x (the dynamic type) defines a print method. Because the conversion is dynamic, it may be used to implement generic programming similar to templates in C++. This is done by manipulating values of the minimal interface.
type Any interface { }

Containers may be written in terms of Any, but the caller must unbox using a type assertion to recover values of the contained type. As the typing is dynamic rather than static, there is no equivalent of the way that a C++ template may inline the relevant operations. The operations are fully type-checked at runtime, but all operations will involve a function call.
type iterator interface { get() Any set(v Any) increment() equal(arg *iterator) bool }

Goroutines
Go permits starting a new thread of execution (a goroutine) using the go statement. The go statement runs a function in a different, newly created, goroutine. All goroutines in a single program share the same address space. Internally, goroutines act like coroutines that are multiplexed among multiple operating system threads. You do not have to worry about these details.
func server(i int) { for { print(i) sys.sleep(10) } } go server(1) go server(2)

(Note that the for statement in the server function is equivalent to a C++ while (true) loop.) Goroutines are (intended to be) cheap. Function literals (which Go implements as closures) can be useful with the go statement.
var g int go func(i int) { s := 0 for j := 0; j < i; j++ { s += j } g = s }(1000) // Passes argument 1000 to the function literal.

Channels
Channels are used to communicate between goroutines. Any value may be sent over a channel. Channels are (intended to be) efficient and cheap. To send a value on a channel, use <- as a binary operator. To receive a value on a channel, use <- as a unary operator. When calling functions, channels are passed by reference. The Go library provides mutexes, but you can also use a single goroutine with a shared channel. Here is an example of using a manager function to control access to a single value.

type cmd struct { get bool; val int } func manager(ch chan cmd) { var val int = 0 for { c := <- ch if c.get { c.val = val ch <- c } else { val = c.val } } }

In that example the same channel is used for input and output. This is incorrect if there are multiple goroutines communicating with the manager at once: a goroutine waiting for a response from the manager might receive a request from another goroutine instead. A solution is to pass in a channel.
type cmd2 struct { get bool; val int; ch <- chan int } func manager2(ch chan cmd2) { var val int = 0 for { c := <- ch if c.get { c.ch <- val } else { val = c.val } } }

To use manager2, given a channel to it:


func f4(ch <- chan cmd2) int { myCh := make(chan int) c := cmd2{ true, 0, myCh } ch <- c return <-myCh }

// Composite literal syntax.

Except as noted, this content is licensed under Creative Commons Attribution 3.0.

The Go Programming Language

How to Write Go Code


Introduction Community resources Creating a new package Makefile Go source files Testing

Introduction
This document explains how to write a new package and how to test code. It assumes you have installed Go using the installation instructions. Before embarking on a change to an existing package or the creation of a new package, be sure to send mail to the mailing list to let people know what you are thinking of doing. Doing so helps avoid duplication of effort and enables discussions about design before any code has been written.

Community resources
For real-time help, there may be users or developers on #go-nuts on the Freenode IRC server. The official mailing list for discussion of the Go language is Go Nuts. Bugs can be reported using the Go issue tracker. For those who wish to keep up with development, there is another mailing list, golang-checkins, that receives a message summarizing each checkin to the Go repository.

Creating a new package


The source code for the package with import path x/y is, by convention, kept in the directory $GOROOT/src /pkg/x/y.

Makefile
It would be nice to have Go-specific tools that inspect the source files to determine what to build and in what order, but for now, Go uses GNU make. Thus, the first file to create in a new package directory is usually the Makefile. The basic form used in the Go source tree is illustrated by src/pkg/container/vector /Makefile:

include ../../../Make.$(GOARCH) TARG=container/vector GOFILES=\ intvector.go\ stringvector.go\ vector.go\ include ../../../Make.pkg

Outside the Go source tree (for personal packages), the standard form is
include $(GOROOT)/src/Make.$(GOARCH) TARG=mypackage GOFILES=\ my1.go\ my2.go\ include $(GOROOT)/src/Make.pkg

The first and last lines include standard definitions and rules. Packages maintained in the standard Go tree use a relative path (instead of $(GOROOT)/src) so that make will work correctly even if $(GOROOT) contains spaces. This makes it easy for programmers to try Go. TARG is the target install path for the package, the string that clients will use to import it. Inside the Go tree, this string should be the same as the directory in which the Makefile appears, with the $GOROOT/src/pkg/ prefix removed. Outside the Go tree, you can use any TARG you want that doesn't conflict with the standard Go package names. A common convention is to use an identifying top-level name to group your packages: myname/tree, myname/filter, etc. Note that even if you keep your package source outside the Go tree, running make install installs your package binaries in the standard location$GOROOT/pkgto make it easy to find them. GOFILES is a list of source files to compile to create the package. The trailing \ characters allow the list to be split onto multiple lines for easy sorting. If you create a new package directory in the Go tree, add it to the list in $GOROOT/src/pkg/Makefile so that it is included in the standard build. Then run:
cd $GOROOT/src/pkg ./deps.bash

to update the dependency file Make.deps. (This happens automatically each time you run make all or make build.) If you change the imports of an existing package, you do not need to edit $GOROOT/src/pkg/Makefile but you will still need to run deps.bash as above.

Go source files
The first statement in each of the source files listed in the Makefile should be package name, where name is the package's default name for imports. (All files in a package must use the same name.) Go's convention is that the package name is the last element of the import path: the package imported as "crypto/rot13" should be named rot13. At the moment, the Go tools impose a restriction that package names are unique across all packages linked into a single binary, but that restriction will be lifted soon.

Go compiles all the source files in a package at once, so one file can refer to constants, variables, types, and functions in another file without special arrangement or declarations. Writing clean, idiomatic Go code is beyond the scope of this document. Effective Go is an introduction to that topic.

Testing
Go has a lightweight test framework known as gotest. You write a test by creating a file with a name ending in _test.go that contains functions named TestXXX with signature func (t *testing.T). The test framework runs each such function; if the function calls a failure function such as t.Error or t.Fail, the test is considered to have failed. The gotest command documentation and the testing package documentation give more detail. The *_test.go files should not be listed in the Makefile. To run the test, run either make test or gotest (they are equivalent). To run only the tests in a single test file, for instance one_test.go, run gotest one_test.go. If your change affects performance, add a Benchmark function (see the gotest command documentation) and run it using gotest -benchmarks=.. Once your new code is tested and working, it's time to get it reviewed and submitted.

Except as noted, this content is licensed under Creative Commons Attribution 3.0.

The Go Programming Language

Directory src/pkg
Subdirectories

Subdirectories
Name .. archive tar asn1 big bignum bufio bytes compress flate gzip zlib container heap list ring vector crypto aes block blowfish hmac md4 md5 rc4 ripemd160 rsa sha1 Synopsis

The tar package implements access to tar archives. The asn1 package implements parsing of DER-encoded ASN.1 data structures, as defined in ITU-T Rec X.690. This package implements multi-precision arithmetic (big numbers). A package for arbitrary precision arithmethic. This package implements buffered I/O. The bytes package implements functions for the manipulation of byte slices. The flate package implements the DEFLATE compressed data format, described in RFC 1951. The gzip package implements reading and writing of gzip format compressed files, as specified in RFC 1952. The zlib package implements reading and writing of zlib format compressed data, as specified in RFC 1950. This package provides heap operations for any type that implements heap.Interface. The list package implements a doubly linked list. The ring package implements operations on circular lists. The vector package implements containers for managing sequences of elements. This package implements AES encryption (formerly Rijndael), as defined in U.S. Federal Information Processing Standards Publication 197. The block package implements standard block cipher modes that can be wrapped around low-level block cipher implementations. This package implements Bruce Schneier's Blowfish encryption algorithm. The hmac package implements the Keyed-Hash Message Authentication Code (HMAC) as defined in U.S. Federal Information Processing Standards Publication 198. This package implements the MD4 hash algorithm as defined in RFC 1320. This package implements the MD5 hash algorithm as defined in RFC 1321. This package implements RC4 encryption, as defined in Bruce Schneier's Applied Cryptography. This package implements the RIPEMD-160 hash algorithm. This package implements RSA encryption as specified in PKCS#1. This package implements the SHA1 hash algorithm as defined in RFC 3174.

sha256 sha512 subtle tls x509 xtea debug dwarf elf gosym macho proc ebnf encoding ascii85 base64 binary git85 hex pem exec exp 4s datafmt draw x11 eval exception iterable nacl av srpc ogle spacewar

This package implements the SHA224 and SHA256 hash algorithms as defined in FIPS 180-2. This package implements the SHA512 hash algorithm as defined in FIPS 180-2. This package implements functions that are often useful in cryptographic code but require careful thought to use correctly. This package partially implements the TLS 1.1 protocol, as specified in RFC 4346. This package parses X.509-encoded keys and certificates. This package implements XTEA encryption, as defined in Needham and Wheeler's 1997 technical report, "Tea extensions. This package provides access to DWARF debugging information loaded from executable files, as defined in the DWARF 2.0 Standard at http://dwarfstd.org/dwarf-2.0.0.pdf. Package elf implements access to ELF object files. Package gosym implements access to the Go symbol and line number tables embedded in Go binaries generated by the gc compilers. Package macho implements access to Mach-O object files, as defined by http://developer.apple.com/mac/library/documentation/DeveloperTools/Conceptual /MachORuntime/Reference/reference.html. Package ptrace provides a platform-independent interface for tracing and controlling running processes. A library for EBNF grammars. Package ascii85 implements the ascii85 data encoding as used in the btoa tool and Adobe's PostScript and PDF document formats. Package base64 implements base64 encoding as specified by RFC 4648. This package implements translation between unsigned integer values and byte sequences. Package git85 implements the radix 85 data encoding used in the Git version control system. This package implements hexadecimal encoding and decoding. This package implements the PEM data encoding, which originated in Privacy Enhanced Mail. The exec package runs external commands.

The datafmt package implements syntax-directed, type-driven formatting of arbitrary data structures. Package draw provides basic graphics and drawing primitives, in the style of the Plan 9 graphics library (see http://plan9.bell-labs.com/magic/man2html/2/draw) and the X Render extension. This package implements an X11 backend for the exp/draw package. This package is the beginning of an interpreter for Go. This package illustrates how basic try-catch exception handling can be emulated using goroutines, channels, and closures. The iterable package provides several traversal and searching methods. Package av implements audio and video access for Native Client binaries running standalone or embedded in a web browser window. This package implements Native Client's simple RPC (SRPC). Ogle is the beginning of a debugger for Go.

expvar flag fmt go ast doc parser printer scanner token gob hash adler32 crc32 crc64 http image jpeg png io ioutil json log math mime net netchan once os signal patch path rand reflect regexp rpc runtime

The expvar package provides a standardized interface to public variables, such as operation counters in servers. The flag package implements command-line flag parsing. Package fmt implements formatted I/O with functions analogous to C's printf. The AST package declares the types used to represent syntax trees for Go packages. The doc package extracts source code documentation from a Go AST. A parser for Go source files. The printer package implements printing of AST nodes. A scanner for Go source text. This package defines constants representing the lexical tokens of the Go programming language and basic operations on tokens (printing, predicates). The gob package manages streams of gobs - binary values exchanged between an Encoder (transmitter) and a Decoder (receiver). This package implements the Adler-32 checksum. This package implements the 32-bit cyclic redundancy check, or CRC-32, checksum. This package implements the 64-bit cyclic redundancy check, or CRC-64, checksum. The http package implements parsing of HTTP requests, replies, and URLs and provides an extensible HTTP server and a basic HTTP client. The image package implements a basic 2-D image library. The jpeg package implements a decoder for JPEG images, as defined in ITU-T T.81. The png package implements a PNG image decoder and encoder. This package provides basic interfaces to I/O primitives. The json package implements a simple parser and representation for JSON (JavaScript Object Notation), as defined at http://www.json.org/. Rudimentary logging package. The math package provides basic constants and mathematical functions. The mime package translates file name extensions to MIME types. The net package provides a portable interface to Unix networks sockets, including TCP/IP, UDP, domain name resolution, and Unix domain sockets. The netchan package implements type-safe networked channels: it allows the two ends of a channel to appear on different computers connected by a network. This package provides a single function, Do, to run a function exactly once, usually used as part of initialization. The os package provides a platform-independent interface to operating system functionality. Package signal implements operating system-independent signal handling. Package patch implements parsing and execution of the textual and binary patch descriptions used by version control tools such as CVS, Git, Mercurial, and Subversion. The path package implements utility routines for manipulating slash-separated filename paths. Package rand implements pseudo-random number generators. The reflect package implements run-time reflection, allowing a program to manipulate objects with arbitrary types. Package regexp implements a simple regular expression library. The rpc package provides access to the public methods of an object across a network or other I/O connection. The runtime package contains operations that interact with Go's runtime system, such as functions to control goroutines.

tiny scanner sort strconv strings sync syscall syslog tabwriter template testing iotest quick script time unicode unsafe utf8 websocket xgb xml

A general-purpose scanner for UTF-8 encoded text. The sort package provides primitives for sorting arrays and user-defined collections. The strconv package implements conversions to and from string representations of basic data types. A package of simple functions to manipulate strings. The sync package provides basic synchronization primitives such as mutual exclusion locks. This package contains an interface to the low-level operating system primitives. The syslog package provides a simple interface to the system log service. The tabwriter package implements a write filter (tabwriter.Writer) that translates tabbed columns in input into properly aligned text. Data-driven templates for generating textual output such as HTML. See http://code.google.com/p/json-template/wiki/Reference for full documentation of the template language. The testing package provides support for automated testing of Go packages. The iotest package implements Readers and Writers useful only for testing. This package implements utility functions to help with black box testing. This package aids in the testing of code that uses channels. The time package provides functionality for measuring and displaying time. This package provides data and functions to test some properties of Unicode code points. The unsafe package contains operations that step around the type safety of Go programs. Functions and constants to support text encoded in UTF-8. The websocket package implements a client and server for the Web Socket protocol. The XGB package implements the X11 core protocol. Package xml implements a simple XML 1.0 parser that understands XML name spaces.

Except as noted, this content is licensed under Creative Commons Attribution 3.0.

The Go Programming Language

Package tar
Constants Variables type Header type Reader func NewReader func (*Reader) Next func (*Reader) Read type Writer func NewWriter func (*Writer) Close func (*Writer) Flush func (*Writer) Write func (*Writer) WriteHeader import "archive/tar" The tar package implements access to tar archives. It aims to cover most of the variations, including those produced by GNU and BSD tars. References:
http://www.freebsd.org/cgi/man.cgi?query=tar&sektion=5 http://www.gnu.org/software/tar/manual/html_node/Standard.html

Package files
common.go reader.go writer.go

Constants
const (

// Types TypeReg TypeRegA TypeLink TypeSymlink TypeChar TypeBlock TypeDir TypeFifo TypeCont TypeXHeader TypeXGlobalHeader )

= = = = = = = = = = =

'0' '\x00' '1' '2' '3' '4' '5' '6' '7' 'x' 'g'

Variables
var ( ErrWriteTooLong = os.NewError("write too long") ErrFieldTooLong = os.NewError("header field too long") ErrWriteAfterClose = os.NewError("write after close") )

var ( HeaderError os.Error = os.ErrorString("invalid tar header") )

type Header
A Header represents a single header in a tar archive. Some fields may not be populated.
type Header struct { Name string Mode int64 Uid int64 Gid int64 Size int64 Mtime int64 Typeflag byte Linkname string Uname string Gname string Devmajor int64 Devminor int64 Atime int64 Ctime int64 }

type Reader
A Reader provides sequential access to the contents of a tar archive. A tar archive consists of a sequence of files. The Next method advances to the next file in the archive (including the first), and then it can be treated as an io.Reader to access the file's data. Example:

tr := tar.NewReader(r); for { hdr, err := tr.Next(); if err != nil { // handle error } if hdr == nil { // end of tar archive break } io.Copy(data, tr); }

type Reader struct { // contains unexported fields }

func New Reader


func NewReader(r io.Reader) *Reader NewReader creates a new Reader reading from r.

func (*Reader) Next


func (tr *Reader) Next() (*Header, os.Error) Next advances to the next entry in the tar archive.

func (*Reader) Read


func (tr *Reader) Read(b []byte) (n int, err os.Error) Read reads from the current entry in the tar archive. It returns 0, os.EOF when it reaches the end of that entry, until Next is called to advance to the next entry.

type Writer
A Writer provides sequential writing of a tar archive in POSIX.1 format. A tar archive consists of a sequence of files. Call WriteHeader to begin a new file, and then call Write to supply that file's data, writing at most hdr.Size bytes in total. Example:
tw := tar.NewWriter(w); hdr := new(Header); hdr.Size = length of data in bytes; // populate other hdr fields as desired if err := tw.WriteHeader(hdr); err != nil { // handle error } io.Copy(tw, data); tw.Close();

type Writer struct { // contains unexported fields }

func New Writer


func NewWriter(w io.Writer) *Writer NewWriter creates a new Writer writing to w.

func (*Writer) Close


func (tw *Writer) Close() os.Error Close closes the tar archive, flushing any unwritten data to the underlying writer.

func (*Writer) Flush


func (tw *Writer) Flush() os.Error Flush finishes writing the current file (optional).

func (*Writer) Write


func (tw *Writer) Write(b []byte) (n int, err os.Error) Write writes to the current entry in the tar archive. Write returns the error ErrWriteTooLong if more than hdr.Size bytes are written after WriteHeader.

func (*Writer) WriteHeader


func (tw *Writer) WriteHeader(hdr *Header) os.Error WriteHeader writes hdr and prepares to accept the file's contents. WriteHeader calls Flush if it is not the first header. Calling after a Close will return ErrWriteAfterClose.

Except as noted, this content is licensed under Creative Commons Attribution 3.0.

The Go Programming Language

Package asn1
func Marshal func MarshalToMemory func Unmarshal type BitString func (BitString) At func (BitString) RightAlign type ObjectIdentifier type RawContent type RawValue type StructuralError func (StructuralError) String type SyntaxError func (SyntaxError) String import "asn1" The asn1 package 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. Package files
asn1.go common.go marshal.go

func Marshal
func Marshal(out io.Writer, val interface{}) os.Error Marshal serialises val as an ASN.1 structure and writes the result to out. In the case of an error, no output is produced.

func MarshalToMemory
func MarshalToMemory(val interface{}) ([]byte, os.Error) MarshalToMemory performs the same actions as Marshal, but returns the result as a byte slice.

func Unmarshal
func Unmarshal(val interface{}, b []byte) (rest []byte, err os.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 or int64. 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 ST RING can be written to a []byte. An ASN.1 OBJECT IDENTIFIER can be written to an ObjectIdentifier. 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:
optional [explicit] tag:x default:x marks the field as ASN.1 OPTIONAL specifies the ASN.1 tag number; implies ASN.1 CONTEXT SPECIFIC sets the default value for optional integer fields

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. Other ASN.1 types are not supported; if it encounters them, Unmarshal returns a parse error.

type BitString
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.
type BitString struct { Bytes []byte // bits packed into bytes. BitLength int // length in bits. }

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 ObjectIdentifier
An ObjectIdentifier represents an ASN.1 OBJECT IDENTIFIER.
type ObjectIdentifier []int

type RawContent
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 RawContent []byte

type RawValue
A RawValue represents an undecoded ASN.1 object.
type RawValue struct { Class, Tag int IsCompound bool Bytes []byte }

type StructuralError
A StructuralError suggests that the ASN.1 data is valid, but the Go type which is receiving it doesn't match.
type StructuralError struct { Msg string }

func (StructuralError) String


func (e StructuralError) String() string

type SyntaxError
A SyntaxError suggests that the ASN.1 data is invalid.
type SyntaxError struct { Msg string }

func (SyntaxError) String


func (e SyntaxError) String() string

Except as noted, this content is licensed under Creative Commons Attribution 3.0.

The Go Programming Language

Package big
func GcdInt func ProbablyPrime type Int func NewInt func (*Int) Add func (*Int) Bytes func (*Int) Cmp func (*Int) Div func (*Int) Exp func (*Int) Len func (*Int) Mod func (*Int) Mul import "big" This package implements multi-precision arithmetic (big numbers). The following numeric types are supported:
- Int signed integers

func (*Int) Neg func (*Int) New func (*Int) Rsh func (*Int) Set func (*Int) SetBytes func (*Int) SetString func (*Int) String func (*Int) Sub type Word

All methods on Int take the result as the receiver; if it is one of the operands it may be overwritten (and its memory reused). To enable chaining of operations, the result is also returned. If possible, one should use big over bignum as the latter is headed for deprecation. Package files
arith.go int.go nat.go

func GcdInt
func GcdInt(d, x, y, a, b *Int) GcdInt sets d to the greatest common divisor of a and b, which must be positive numbers. If x and y are not nil, GcdInt sets x and y such that d = a*x + b*y. If either a or b is not positive, GcdInt sets d = x = y = 0.

func ProbablyPrime
func ProbablyPrime(z *Int, n int) bool ProbablyPrime performs n Miller-Rabin tests to check whether z is prime. If it returns true, z is prime with probability 1 - 1/4^n. If it returns false, z is not prime.

type Int
An Int represents a signed multi-precision integer. The zero value for an Int represents the value 0.
type Int struct { // contains unexported fields }

func New Int


func NewInt(x int64) *Int NewInt allocates and returns a new Int set to x.

func (*Int) Add


func (z *Int) Add(x, y *Int) *Int Add computes z = x+y.

func (*Int) Bytes


func (z *Int) Bytes() []byte Bytes returns the absolute value of x as a big-endian byte array.

func (*Int) Cm p
func (x *Int) Cmp(y *Int) (r int) Cmp compares x and y. The result is
-1 if x < y 0 if x == y +1 if x > y

func (*Int) Div


func (z *Int) Div(x, y *Int) (q, r *Int) Div calculates q = (x-r)/y where 0 <= r < y. The receiver is set to q.

func (*Int) Exp


func (z *Int) Exp(x, y, m *Int) *Int Exp sets z = x**y mod m. If m is nil, z = x**y. See Knuth, volume 2, section 4.6.3.

func (*Int) Len


func (z *Int) Len() int Len returns the length of the absolute value of x in bits. Zero is considered to have a length of one.

func (*Int) Mod


func (z *Int) Mod(x, y *Int) (r *Int)

Mod calculates q = (x-r)/y and returns r.

func (*Int) Mul


func (z *Int) Mul(x, y *Int) *Int Mul computes z = x*y.

func (*Int) Neg


func (z *Int) Neg(x *Int) *Int Neg computes z = -x.

func (*Int) New


func (z *Int) New(x int64) *Int New allocates and returns a new Int set to x.

func (*Int) Rsh


func (z *Int) Rsh(x *Int, n int) *Int Rsh sets z = x >> s and returns z.

func (*Int) Set


func (z *Int) Set(x *Int) *Int Set sets z to x.

func (*Int) SetBytes


func (z *Int) SetBytes(b []byte) *Int SetBytes interprets b as the bytes of a big-endian, unsigned integer and sets x to that value.

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. If base is 0 then SetString attempts to detect the base by at the prefix of s. '0x' implies base 16, '0' implies base 8. Otherwise base 10 is assumed.

func (*Int) String


func (z *Int) String() string

func (*Int) Sub


func (z *Int) Sub(x, y *Int) *Int Sub computes z = x-y.

type Word
type Word uintptr

Except as noted, this content is licensed under Creative Commons Attribution 3.0.

The Go Programming Language

Package bignum
func Div128 func Iadd func Iscale func Isub func Mul128 func MulAdd128 func Nadd func Nscale func Nsub type Integer func Int func IntFromString func MakeInt func (*Integer) Abs func (*Integer) Add func (*Integer) And func (*Integer) AndNot func (*Integer) Cmp func (*Integer) Div func (*Integer) DivMod func (*Integer) Format func (*Integer) IsEven func (*Integer) IsNeg func (*Integer) IsOdd func (*Integer) IsPos func (*Integer) IsZero func (*Integer) Mod func (*Integer) Mul func (*Integer) Mul1 func (*Integer) MulNat func (*Integer) Neg func (*Integer) Not func (*Integer) Or func (*Integer) Quo func (*Integer) QuoRem func (*Integer) Rem func (*Integer) Shl func (*Integer) Shr func (*Integer) String func (*Integer) Sub func (*Integer) ToString func (*Integer) Value func (*Integer) Xor type Natural func Binomial func Fact func Nat func NatFromString func (Natural) Add func (Natural) And func (Natural) AndNot func (Natural) Cmp func (Natural) Div func (Natural) DivMod func (Natural) Format func (Natural) Gcd func (Natural) IsEven func (Natural) IsOdd func (Natural) IsZero func (Natural) Log2 func (Natural) Mod func (Natural) Mul func (Natural) Mul1 func (Natural) Or func (Natural) Pop func (Natural) Pow func (Natural) Shl func (Natural) Shr func (Natural) String func (Natural) Sub func (Natural) ToString func (Natural) Value func (Natural) Xor type Rational func MakeRat func Rat func RatFromString func (*Rational) Add func (*Rational) Cmp func (*Rational) Format func (*Rational) IsInt func (*Rational) IsNeg func (*Rational) IsPos func (*Rational) IsZero func (*Rational) Mul func (*Rational) Neg func (*Rational) Quo func (*Rational) String func (*Rational) Sub func (*Rational) ToString func (*Rational) Value

func MulRange import "bignum" A package for arbitrary precision arithmethic. It implements the following numeric types:
- Natural - Integer - Rational unsigned integers signed integers rational numbers

This package has been designed for ease of use but the functions it provides are likely to be quite slow. It may be deprecated eventually. Use package big instead, if possible. Package files
arith.go bignum.go integer.go rational.go

func Div128
func Div128(x1, x0, y uint64) (q, r uint64) q = (x1<<64 + x0)/y + r

func Iadd
func Iadd(z, x, y *Integer) Iadd sets z to the sum x + y. z must exist and may be x or y.

func Iscale
func Iscale(z *Integer, d int64) Nscale sets *z to the scaled value (*z) * d.

func Isub
func Isub(z, x, y *Integer)

func Mul128
func Mul128(x, y uint64) (z1, z0 uint64) z1<<64 + z0 = x*y

func MulAdd128
func MulAdd128(x, y, c uint64) (z1, z0 uint64)

z1<<64 + z0 = x*y + c

func Nadd
func Nadd(zp *Natural, x, y Natural) Nadd sets *zp to the sum x + y. *zp may be x or y.

func Nscale
func Nscale(z *Natural, d uint64) Nscale sets *z to the scaled value (*z) * d.

func Nsub
func Nsub(zp *Natural, x, y Natural) Nsub sets *zp to the difference x - y for x >= y. If x < y, an underflow run-time error occurs (use Cmp to test if x >= y). *zp may be x or y.

type Integer
Integer represents a signed integer value of arbitrary precision.
type Integer struct { // contains unexported fields }

func Int
func Int(x int64) *Integer Int creates a small integer with value x.

func IntFrom String


func IntFromString(s string, base uint) (*Integer, uint, int) IntFromString returns the integer corresponding to the longest possible prefix of s representing an integer in a given conversion base, the actual conversion base used, and the prefix length. The syntax of integers follows the syntax of signed integer literals in Go. If the base argument 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. Otherwise the selected base is 10.

func MakeInt
func MakeInt(sign bool, mant Natural) *Integer MakeInt makes an integer given a sign and a mantissa. The number is positive (>= 0) if sign is false or the

mantissa is zero; it is negative otherwise.

func (*Integer) Abs


func (x *Integer) Abs() Natural Abs returns the absolute value of x.

func (*Integer) Add


func (x *Integer) Add(y *Integer) *Integer Add returns the sum x + y.

func (*Integer) And


func (x *Integer) And(y *Integer) *Integer And returns the bitwise and x & y for the 2's-complement representation of x and y.

func (*Integer) AndNot


func (x *Integer) AndNot(y *Integer) *Integer AndNot returns the bitwise clear x &^ y for the 2's-complement representation of x and y.

func (*Integer) Cm p
func (x *Integer) Cmp(y *Integer) int Cmp compares x and y. The result is an int value that is
< 0 if x < y == 0 if x == y > 0 if x > y

func (*Integer) Div


func (x *Integer) Div(y *Integer) *Integer Div returns the quotient q = x / y for y != 0. If y == 0, a division-by-zero run-time error occurs. Div and Mod implement Euclidian division and modulus:
q = x.Div(y) r = x.Mod(y) with: 0 <= r < |q| and: y = x*q + r

(Raymond T. Boute, The Euclidian 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.)

func (*Integer) DivMod


func (x *Integer) DivMod(y *Integer) (*Integer, *Integer) DivMod returns the pair (x.Div(y), x.Mod(y)).

func (*Integer) Form at


func (x *Integer) Format(h fmt.State, c int)

Format is a support routine for fmt.Formatter. It accepts the formats 'b' (binary), 'o' (octal), and 'x' (hexadecimal).

func (*Integer) IsEven


func (x *Integer) IsEven() bool IsEven returns true iff x is divisible by 2.

func (*Integer) IsNeg


func (x *Integer) IsNeg() bool IsNeg returns true iff x < 0.

func (*Integer) IsOdd


func (x *Integer) IsOdd() bool IsOdd returns true iff x is not divisible by 2.

func (*Integer) IsPos


func (x *Integer) IsPos() bool IsPos returns true iff x >= 0.

func (*Integer) IsZero


func (x *Integer) IsZero() bool IsZero returns true iff x == 0.

func (*Integer) Mod


func (x *Integer) Mod(y *Integer) *Integer Mod returns the modulus r of the division x / y for y != 0, with r = x - y*x.Div(y). r is always positive. If y == 0, a division-by-zero run-time error occurs.

func (*Integer) Mul


func (x *Integer) Mul(y *Integer) *Integer Mul returns the product x * y.

func (*Integer) Mul1


func (x *Integer) Mul1(d int64) *Integer Mul1 returns the product x * d.

func (*Integer) MulNat


func (x *Integer) MulNat(y Natural) *Integer MulNat returns the product x * y, where y is a (unsigned) natural number.

func (*Integer) Neg


func (x *Integer) Neg() *Integer

Neg returns the negated value of x.

func (*Integer) Not


func (x *Integer) Not() *Integer Not returns the bitwise not ^x for the 2's-complement representation of x.

func (*Integer) Or
func (x *Integer) Or(y *Integer) *Integer Or returns the bitwise or x | y for the 2's-complement representation of x and y.

func (*Integer) Quo


func (x *Integer) Quo(y *Integer) *Integer Quo returns the quotient q = x / y for y != 0. If y == 0, a division-by-zero run-time error occurs. Quo and Rem implement T-division and modulus (like C99):
q = x.Quo(y) = trunc(x/y) r = x.Rem(y) = x - y*q (truncation towards zero)

(Daan Leijen, Division and Modulus for Computer Scientists.)

func (*Integer) QuoRem


func (x *Integer) QuoRem(y *Integer) (*Integer, *Integer) QuoRem returns the pair (x.Quo(y), x.Rem(y)) for y != 0. If y == 0, a division-by-zero run-time error occurs.

func (*Integer) Rem


func (x *Integer) Rem(y *Integer) *Integer Rem returns the remainder r of the division x / y for y != 0, with r = x - y*x.Quo(y). Unless r is zero, its sign corresponds to the sign of x. If y == 0, a division-by-zero run-time error occurs.

func (*Integer) Shl


func (x *Integer) Shl(s uint) *Integer Shl implements shift left x << s. It returns x * 2^s.

func (*Integer) Shr


func (x *Integer) Shr(s uint) *Integer Shr implements shift right x >> s. It returns x / 2^s.

func (*Integer) String


func (x *Integer) String() string String converts x to its decimal string representation. x.String() is the same as x.ToString(10).

func (*Integer) Sub

func (x *Integer) Sub(y *Integer) *Integer Sub returns the difference x - y.

func (*Integer) ToString


func (x *Integer) ToString(base uint) string ToString converts x to a string for a given base, with 2 <= base <= 16.

func (*Integer) Value


func (x *Integer) Value() int64 Value returns the value of x, if x fits into an int64; otherwise the result is undefined.

func (*Integer) Xor


func (x *Integer) Xor(y *Integer) *Integer Xor returns the bitwise xor x | y for the 2's-complement representation of x and y.

type Natural
Natural represents an unsigned integer value of arbitrary precision.
type Natural []digit

func Binom ial


func Binomial(n, k uint) Natural Binomial computes the binomial coefficient of (n, k).

func Fact
func Fact(n uint) Natural Fact computes the factorial of n (Fact(n) == MulRange(2, n)).

func MulRange
func MulRange(a, b uint) Natural MulRange computes the product of all the unsigned integers in the range [a, b] inclusively.

func Nat
func Nat(x uint64) Natural Nat creates a small natural number with value x.

func NatFrom String


func NatFromString(s string, base uint) (Natural, uint, int) NatFromString returns the natural number corresponding to the longest possible prefix of s representing a natural number in a given conversion base, the actual conversion base used, and the prefix length. The

syntax of natural numbers follows the syntax of unsigned integer literals in Go. If the base argument 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. Otherwise the selected base is 10.

func (Natural) Add


func (x Natural) Add(y Natural) Natural Add returns the sum z = x + y.

func (Natural) And


func (x Natural) And(y Natural) Natural And returns the bitwise and x & y for the 2's-complement representation of x and y.

func (Natural) AndNot


func (x Natural) AndNot(y Natural) Natural AndNot returns the bitwise clear x &^ y for the 2's-complement representation of x and y.

func (Natural) Cm p
func (x Natural) Cmp(y Natural) int Cmp compares x and y. The result is an int value
< 0 if x < y == 0 if x == y > 0 if x > y

func (Natural) Div


func (x Natural) Div(y Natural) Natural Div returns the quotient q = x / y for y > 0, with x = y*q + r and 0 <= r < y. If y == 0, a division-by-zero run-time error occurs.

func (Natural) DivMod


func (x Natural) DivMod(y Natural) (Natural, Natural) DivMod returns the pair (x.Div(y), x.Mod(y)) for y > 0. If y == 0, a division-by-zero run-time error occurs.

func (Natural) Form at


func (x Natural) Format(h fmt.State, c int) Format is a support routine for fmt.Formatter. It accepts the formats 'b' (binary), 'o' (octal), and 'x' (hexadecimal).

func (Natural) Gcd


func (x Natural) Gcd(y Natural) Natural Gcd computes the gcd of x and y.

func (Natural) IsEven


func (x Natural) IsEven() bool IsEven returns true iff x is divisible by 2.

func (Natural) IsOdd


func (x Natural) IsOdd() bool IsOdd returns true iff x is not divisible by 2.

func (Natural) IsZero


func (x Natural) IsZero() bool IsZero returns true iff x == 0.

func (Natural) Log2


func (x Natural) Log2() uint Log2 computes the binary logarithm of x for x > 0. The result is the integer n for which 2^n <= x < 2^(n+1). If x == 0 a run-time error occurs.

func (Natural) Mod


func (x Natural) Mod(y Natural) Natural Mod returns the modulus r of the division x / y for y > 0, with x = y*q + r and 0 <= r < y. If y == 0, a divisionby-zero run-time error occurs.

func (Natural) Mul


func (x Natural) Mul(y Natural) Natural Mul returns the product x * y.

func (Natural) Mul1


func (x Natural) Mul1(d uint64) Natural Mul1 returns the product x * d.

func (Natural) Or
func (x Natural) Or(y Natural) Natural Or returns the bitwise or x | y for the 2's-complement representation of x and y.

func (Natural) Pop


func (x Natural) Pop() uint Pop computes the population count of (the number of 1 bits in) x.

func (Natural) Pow


func (xp Natural) Pow(n uint) Natural Pow computes x to the power of n.

func (Natural) Shl


func (x Natural) Shl(s uint) Natural Shl implements shift left x << s. It returns x * 2^s.

func (Natural) Shr


func (x Natural) Shr(s uint) Natural Shr implements shift right x >> s. It returns x / 2^s.

func (Natural) String


func (x Natural) String() string String converts x to its decimal string representation. x.String() is the same as x.ToString(10).

func (Natural) Sub


func (x Natural) Sub(y Natural) Natural Sub returns the difference x - y for x >= y. If x < y, an underflow run-time error occurs (use Cmp to test if x >= y).

func (Natural) ToString


func (x Natural) ToString(base uint) string ToString converts x to a string for a given base, with 2 <= base <= 16.

func (Natural) Value


func (x Natural) Value() uint64 Value returns the lowest 64bits of x.

func (Natural) Xor


func (x Natural) Xor(y Natural) Natural Xor returns the bitwise exclusive or x ^ y for the 2's-complement representation of x and y.

type Rational
Rational represents a quotient a/b of arbitrary precision.
type Rational struct { // contains unexported fields }

func MakeRat
func MakeRat(a *Integer, b Natural) *Rational MakeRat makes a rational number given a numerator a and a denominator b.

func Rat

func Rat(a0 int64, b0 int64) *Rational Rat creates a small rational number with value a0/b0.

func RatFrom String


func RatFromString(s string, base uint) (*Rational, uint, int) RatFromString returns the rational number corresponding to the longest possible prefix of s representing a rational number in a given conversion base, the actual conversion base used, and the prefix length. The syntax of a rational number is:
rational = mantissa [exponent] . mantissa = integer ('/' natural | '.' natural) . exponent = ('e'|'E') integer .

If the base argument is 0, the string prefix determines the actual conversion base for the mantissa. A prefix of 0x or 0X selects base 16; the 0 prefix selects base 8. Otherwise the selected base is 10. If the mantissa is represented via a division, both the numerator and denominator may have different base prefixes; in that case the base of of the numerator is returned. If the mantissa contains a decimal point, the base for the fractional part is the same as for the part before the decimal point and the fractional part does not accept a base prefix. The base for the exponent is always 10.

func (*Rational) Add


func (x *Rational) Add(y *Rational) *Rational Add returns the sum x + y.

func (*Rational) Cm p
func (x *Rational) Cmp(y *Rational) int Cmp compares x and y. The result is an int value
< 0 if x < y == 0 if x == y > 0 if x > y

func (*Rational) Form at


func (x *Rational) Format(h fmt.State, c int) Format is a support routine for fmt.Formatter. It accepts the formats 'b' (binary), 'o' (octal), and 'x' (hexadecimal).

func (*Rational) IsInt


func (x *Rational) IsInt() bool IsInt returns true iff x can be written with a denominator 1 in the form x == x'/1; i.e., if x is an integer value.

func (*Rational) IsNeg


func (x *Rational) IsNeg() bool IsNeg returns true iff x < 0.

func (*Rational) IsPos


func (x *Rational) IsPos() bool IsPos returns true iff x > 0.

func (*Rational) IsZero


func (x *Rational) IsZero() bool IsZero returns true iff x == 0.

func (*Rational) Mul


func (x *Rational) Mul(y *Rational) *Rational Mul returns the product x * y.

func (*Rational) Neg


func (x *Rational) Neg() *Rational Neg returns the negated value of x.

func (*Rational) Quo


func (x *Rational) Quo(y *Rational) *Rational Quo returns the quotient x / y for y != 0. If y == 0, a division-by-zero run-time error occurs.

func (*Rational) String


func (x *Rational) String() string String converts x to its decimal string representation. x.String() is the same as x.ToString(10).

func (*Rational) Sub


func (x *Rational) Sub(y *Rational) *Rational Sub returns the difference x - y.

func (*Rational) ToString


func (x *Rational) ToString(base uint) string ToString converts x to a string for a given base, with 2 <= base <= 16. The string representation is of the form "n" if x is an integer; otherwise it is of form "n/d".

func (*Rational) Value


func (x *Rational) Value() (numerator *Integer, denominator Natural) Value returns the numerator and denominator of x.

Except as noted, this content is licensed under Creative Commons Attribution 3.0.

The Go Programming Language

Package bufio
Variables type BufSizeError func (BufSizeError) String type Error type ReadWriter func NewReadWriter type Reader func NewReader func NewReaderSize func (*Reader) Buffered func (*Reader) Read func (*Reader) ReadByte func (*Reader) ReadBytes func (*Reader) ReadRune func (*Reader) ReadSlice import "bufio" This package 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. Package files
buf io.go

func (*Reader) ReadString func (*Reader) UnreadByte type Writer func NewWriter func NewWriterSize func (*Writer) Available func (*Writer) Buffered func (*Writer) Flush func (*Writer) Write func (*Writer) WriteByte func (*Writer) WriteRune func (*Writer) WriteString

Variables
var ( ErrInvalidUnreadByte os.Error = &Error{"bufio: invalid use of UnreadByte"} ErrBufferFull os.Error = &Error{"bufio: buffer full"} )

type BufSizeError
BufSizeError is the error representing an invalid buffer size.
type BufSizeError int

func (BufSizeError) String


func (b BufSizeError) String() string

type Error
Errors introduced by this package.
type Error struct { os.ErrorString }

type ReadWriter
ReadWriter stores pointers to a Reader and a Writer. It implements io.ReadWriter.
type ReadWriter struct { *Reader *Writer }

func New ReadWriter


func NewReadWriter(r *Reader, w *Writer) *ReadWriter NewReadWriter allocates a new ReadWriter that dispatches to r and w.

type Reader
Reader implements buffering for an io.Reader object.
type Reader struct { // contains unexported fields }

func New Reader


func NewReader(rd io.Reader) *Reader NewReader returns a new Reader whose buffer has the default size.

func New ReaderSize


func NewReaderSize(rd io.Reader, size int) (*Reader, os.Error) NewReaderSize creates a new Reader whose buffer has the specified size, which must be greater than zero. If the argument io.Reader is already a Reader with large enough size, it returns the underlying Reader. It returns the Reader and any error.

func (*Reader) Buffered


func (b *Reader) Buffered() int Buffered returns the number of bytes that can be read from the current buffer.

func (*Reader) Read

func (b *Reader) Read(p []byte) (nn int, err os.Error) Read reads data into p. It returns the number of bytes read into p. If nn < len(p), also returns an error explaining why the read is short. At EOF, the count will be zero and err will be os.EOF.

func (*Reader) ReadByte


func (b *Reader) ReadByte() (c byte, err os.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 os.Error) ReadBytes reads until the first occurrence of delim in the input, returning a string 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 os.EOF). ReadBytes returns err != nil if and only if line does not end in delim.

func (*Reader) ReadRune


func (b *Reader) ReadRune() (rune int, size int, err os.Error) ReadRune reads a single UTF-8 encoded Unicode character and returns the rune and its size in bytes.

func (*Reader) ReadSlice


func (b *Reader) ReadSlice(delim byte) (line []byte, err os.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 call. If ReadSlice encounters an error before finding a delimiter, it returns all the data in the buffer and the error itself (often os.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 os.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 os.EOF). ReadString returns err != nil if and only if line does not end in delim.

func (*Reader) UnreadByte


func (b *Reader) UnreadByte() os.Error UnreadByte unreads the last byte. Only the most recently read byte can be unread.

type Writer
Writer implements buffering for an io.Writer object.

type Writer struct { // contains unexported fields }

func New Writer


func NewWriter(wr io.Writer) *Writer NewWriter returns a new Writer whose buffer has the default size.

func New WriterSize


func NewWriterSize(wr io.Writer, size int) (*Writer, os.Error) NewWriterSize creates a new Writer whose buffer has the specified size, which must be greater than zero. If the argument io.Writer is already a Writer with large enough size, it returns the underlying Writer. It returns the Writer and any error.

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() os.Error Flush writes any buffered data to the underlying io.Writer.

func (*Writer) Write


func (b *Writer) Write(p []byte) (nn int, err os.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) os.Error WriteByte writes a single byte.

func (*Writer) WriteRune


func (b *Writer) WriteRune(rune int) (size int, err os.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, os.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.

Except as noted, this content is licensed under Creative Commons Attribution 3.0.

The Go Programming Language

Package bytes
Constants func Add func AddByte func Compare func Count func Equal func Fields func HasPrefix func HasSuffix func Index func IndexByte func Join func LastIndex func Map func Repeat func Runes func Split func SplitAfter func ToLower func ToTitle func ToUpper import "bytes" The bytes package implements functions for the manipulation of byte slices. Analagous to the facilities of the strings package. Package files
buf f er.go by tes.go

func TrimSpace type Buffer func NewBuffer func NewBufferString func (*Buffer) Bytes func (*Buffer) Len func (*Buffer) Read func (*Buffer) ReadByte func (*Buffer) ReadFrom func (*Buffer) ReadRune func (*Buffer) Reset func (*Buffer) String func (*Buffer) Truncate func (*Buffer) Write func (*Buffer) WriteByte func (*Buffer) WriteRune func (*Buffer) WriteString func (*Buffer) WriteTo

Constants
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.
const MinRead = 512

func Add
func Add(s, t []byte) []byte Add appends the contents of t to the end of s and returns the result. If s has enough capacity, it is extended

in place; otherwise a new array is allocated and returned.

func AddByte
func AddByte(s []byte, t byte) []byte AddByte appends byte b to the end of s and returns the result. If s has enough capacity, it is extended in place; otherwise a new array is allocated and returned.

func Compare
func Compare(a, b []byte) int Compare returns an integer comparing the two byte arrays lexicographically. The result will be 0 if a==b, -1 if a < b, and +1 if a > b

func Count
func Count(s, sep []byte) int Count counts the number of non-overlapping instances of sep in s.

func Equal
func Equal(a, b []byte) bool Equal returns a boolean reporting whether a == b.

func Fields
func Fields(s []byte) [][]byte Fields splits the array s around each instance of one or more consecutive white space characters, returning a slice of subarrays of s or an empty list if s contains only white space.

func HasPrefix
func HasPrefix(s, prefix []byte) bool HasPrefix tests whether the byte array s begins with prefix.

func HasSuffix
func HasSuffix(s, suffix []byte) bool HasSuffix tests whether the byte array 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 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 Join
func Join(a [][]byte, sep []byte) []byte Join concatenates the elements of a to create a single byte array. The separator sep is placed between elements in the resulting array.

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 Map
func Map(mapping func(rune int) int, s []byte) []byte Map returns a copy of the byte array 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.

func Repeat
func Repeat(b []byte, count int) []byte Repeat returns a new byte array consisting of count copies of b.

func Runes
func Runes(s []byte) []int Runes returns a slice of runes (Unicode code points) equivalent to s.

func Split
func Split(s, sep []byte, n int) [][]byte

Split splits the array s around each instance of sep, returning an array of subarrays of s. If sep is empty, Split splits s after each UTF-8 sequence. If n > 0, Split splits s into at most n subarrays; the last subarray will contain an unsplit remainder.

func SplitAfter
func SplitAfter(s, sep []byte, n int) [][]byte SplitAfter splits the array s after each instance of sep, returning an array of subarrays of s. If sep is empty, SplitAfter splits s after each UTF-8 sequence. If n > 0, SplitAfter splits s into at most n subarrays; the last subarray will contain an unsplit remainder.

func ToLower
func ToLower(s []byte) []byte ToUpper returns a copy of the byte array s with all Unicode letters mapped to their lower case.

func ToTitle
func ToTitle(s []byte) []byte ToTitle returns a copy of the byte array s with all Unicode letters mapped to their title case.

func ToUpper
func ToUpper(s []byte) []byte ToUpper returns a copy of the byte array s with all Unicode letters mapped to their upper case.

func TrimSpace
func TrimSpace(s []byte) []byte Trim returns a slice of the string s, with all leading and trailing white space removed, as defined by Unicode.

type Buffer
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.
type Buffer struct { // contains unexported fields }

func New Buffer

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 to size the internal buffer for writing. To do that, buf should have the desired capacity but a length of zero.

func New BufferString


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.

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) 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) Read


func (b *Buffer) Read(p []byte) (n int, err os.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 os.EOF even if len(p) is zero; otherwise it is nil.

func (*Buffer) ReadByte


func (b *Buffer) ReadByte() (c byte, err os.Error) ReadByte reads and returns the next byte from the buffer. If no byte is available, it returns error os.EOF.

func (*Buffer) ReadFrom


func (b *Buffer) ReadFrom(r io.Reader) (n int64, err os.Error) ReadFrom reads data from r until EOF and appends it to the buffer. The return value n is the number of bytes read. Any error except os.EOF encountered during the read is also returned.

func (*Buffer) ReadRune


func (b *Buffer) ReadRune() (r int, size int, err os.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 os.EOF. If the bytes are an erroneous UTF-8 encoding, it consumes one byte and returns U+FFFD, 1.

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 is an error to call b.Truncate(n) with n > b.Len().

func (*Buffer) Write


func (b *Buffer) Write(p []byte) (n int, err os.Error) Write appends the contents of p to the buffer. The return value n is the length of p; err is always nil.

func (*Buffer) WriteByte


func (b *Buffer) WriteByte(c byte) os.Error WriteByte appends the byte c to the buffer. T he returned error is always nil, but is included to match bufio.Writer's WriteByte.

func (*Buffer) WriteRune


func (b *Buffer) WriteRune(r int) (n int, err os.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.

func (*Buffer) WriteString


func (b *Buffer) WriteString(s string) (n int, err os.Error) WriteString appends the contents of s to the buffer. The return value n is the length of s; err is always nil.

func (*Buffer) WriteTo


func (b *Buffer) WriteTo(w io.Writer) (n int64, err os.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. Any error encountered during the write is also returned.

Except as noted, this content is licensed under Creative Commons Attribution 3.0.

The Go Programming Language

Package flate
Constants func NewDeflater func NewInflater type CorruptInputError func (CorruptInputError) String type InternalError func (InternalError) String type ReadError import "compress/flate" The flate package implements the DEFLATE compressed data format, described in RFC 1951. The gzip and zlib packages implement access to DEFLATE-based file formats. Package files
def late.go huf f man_bit_writer.go huf f man_code.go inf late.go rev erse_bits.go token.go util.go

func (*ReadError) String type Reader type WriteError func (*WriteError) String type WrongValueError func (WrongValueError) String

Constants
const ( NoCompression = 0 BestSpeed = 1 BestCompression = 9 DefaultCompression = -1 )

func NewDeflater
func NewDeflater(w io.Writer, level int) io.WriteCloser

func NewInflater
func NewInflater(r io.Reader) io.ReadCloser NewInflater returns a new ReadCloser that can be used to read the uncompressed version of r. It is the caller's responsibility to call Close on the ReadCloser when finished reading.

type CorruptInputError
A CorruptInputError reports the presence of corrupt input at a given offset.

type CorruptInputError int64

func (CorruptInputError) String


func (e CorruptInputError) String() string

type InternalError
An InternalError reports an error in the flate code itself.
type InternalError string

func (InternalError) String


func (e InternalError) String() string

type ReadError
A ReadError reports an error encountered while reading input.
type ReadError struct { Offset int64 // byte offset where error occurred Error os.Error // error returned by underlying Read }

func (*ReadError) String


func (e *ReadError) String() string

type Reader
The actual read interface needed by NewInflater. If the passed in io.Reader does not also have ReadByte, the NewInflater will introduce its own buffering.
type Reader interface { io.Reader ReadByte() (c byte, err os.Error) }

type WriteError
A WriteError reports an error encountered while writing output.

type WriteError struct { // byte offset where error occurred Offset int64 Error os.Error // error returned by underlying Read }

func (*WriteError) String


func (e *WriteError) String() string

type WrongValueError
type WrongValueError struct { // contains unexported fields }

func (WrongValueError) String


func (err WrongValueError) String() string

Except as noted, this content is licensed under Creative Commons Attribution 3.0.

The Go Programming Language

Package gzip
Constants Variables type Deflater func NewDeflater func NewDeflaterLevel func (*Deflater) Close func (*Deflater) Write type Header type Inflater func NewInflater func (*Inflater) Close func (*Inflater) Read Bugs import "compress/gzip" The gzip package implements reading and writing of gzip format compressed files, as specified in RFC 1952. Package files
gunzip.go gzip.go

Constants
These constants are copied from the flate package, so that code that imports "compress/gzip" does not also have to import "compress/flate".
const ( NoCompression BestSpeed BestCompression DefaultCompression )

= = = =

flate.NoCompression flate.BestSpeed flate.BestCompression flate.DefaultCompression

Variables
var ChecksumError os.Error = os.ErrorString("gzip checksum error")

var HeaderError os.Error = os.ErrorString("invalid gzip header")

type Deflater
A Deflater is an io.WriteCloser that satisfies writes by compressing data written to its wrapped io.Writer.
type Deflater struct { Header // contains unexported fields }

func New Deflater


func NewDeflater(w io.Writer) (*Deflater, os.Error) NewDeflater calls NewDeflaterLevel with the default compression level.

func New DeflaterLevel


func NewDeflaterLevel(w io.Writer, level int) (*Deflater, os.Error) NewDeflaterLevel creates a new Deflater writing to the given writer. Writes may be buffered and not flushed until Close. Callers that wish to set the fields in Deflater.Header must do so before the first call to Write or Close. It is the caller's responsibility to call Close on the WriteCloser when done. level is the compression level, which can be DefaultCompression, NoCompression, or any integer value between BestSpeed and BestCompression (inclusive).

func (*Deflater) Close


func (z *Deflater) Close() os.Error Calling Close does not close the wrapped io.Writer originally passed to NewDeflater.

func (*Deflater) Write


func (z *Deflater) Write(p []byte) (int, os.Error)

type Header
The gzip file stores a header giving metadata about the compressed file. That header is exposed as the fields of the Deflater and Inflater structs.
type Header Comment Extra Mtime Name OS } struct string []byte uint32 string byte { // // // // //

comment "extra data" modification time (seconds since January 1, 1970) file name operating system type

type Inflater
An Inflater is an io.Reader that can be read to retrieve uncompressed data from a gzip-format compressed file.

In general, a gzip file can be a concatenation of gzip files, each with its own header. Reads from the Inflater return the concatenation of the uncompressed data of each. Only the first header is recorded in the Inflater fields. Gzip files store a length and checksum of the uncompressed data. The Inflater will return a ChecksumError when Read reaches the end of the uncompressed data if it does not have the expected length or checksum. Clients should treat data returned by Read as tentative until they receive the successful (zero length, nil error) Read marking the end of the data.
type Inflater struct { Header // contains unexported fields }

func New Inflater


func NewInflater(r io.Reader) (*Inflater, os.Error) NewInflater creates a new Inflater reading the given reader. The implementation buffers input and may read more data than necessary from r. It is the caller's responsibility to call Close on the Inflater when done.

func (*Inflater) Close


func (z *Inflater) Close() os.Error Calling Close does not close the wrapped io.Reader originally passed to NewInflater.

func (*Inflater) Read


func (z *Inflater) Read(p []byte) (n int, err os.Error)

Bugs
Comments and Names don't properly map UTF-8 character codes outside of the 0x00-0x7f range to ISO 8859-1 (Latin-1).

Except as noted, this content is licensed under Creative Commons Attribution 3.0.

The Go Programming Language

Package zlib
Constants Variables func NewDeflater func NewDeflaterLevel func NewInflater Bugs import "compress/zlib" The zlib package implements reading and writing of zlib format compressed data, as specified in RFC 1950. The implementation provides filters that uncompress during reading and compress during writing. For example, to write compressed data to a buffer:
var b bytes.Buffer w, err := zlib.NewDeflater(&b) w.Write([]byte("hello, world\n")) w.Close()

and to read that data back:


r, err := zlib.NewInflater(&b) io.Copy(os.Stdout, r) r.Close()

Package files
reader.go writer.go

Constants
These constants are copied from the flate package, so that code that imports "compress/zlib" does not also have to import "compress/flate".
const ( NoCompression BestSpeed BestCompression DefaultCompression )

= = = =

flate.NoCompression flate.BestSpeed flate.BestCompression flate.DefaultCompression

Variables

var ChecksumError os.Error = os.ErrorString("zlib checksum error")

var HeaderError os.Error = os.ErrorString("invalid zlib header")

var UnsupportedError os.Error = os.ErrorString("unsupported zlib format")

func NewDeflater
func NewDeflater(w io.Writer) (io.WriteCloser, os.Error) NewDeflater calls NewDeflaterLevel with the default compression level.

func NewDeflaterLevel
func NewDeflaterLevel(w io.Writer, level int) (io.WriteCloser, os.Error) NewDeflaterLevel creates a new io.WriteCloser that satisfies writes by compressing data written to w. It is the caller's responsibility to call Close on the WriteCloser when done. level is the compression level, which can be DefaultCompression, NoCompression, or any integer value between BestSpeed and BestCompression (inclusive).

func NewInflater
func NewInflater(r io.Reader) (io.ReadCloser, os.Error) NewInflater creates a new io.ReadCloser that satisfies reads by decompressing data read from r. The implementation buffers input and may read more data than necessary from r. It is the caller's responsibility to call Close on the ReadCloser when done.

Bugs
The zlib package does not implement the FDICT flag.

Except as noted, this content is licensed under Creative Commons Attribution 3.0.

The Go Programming Language

Package heap
func Init func Pop func Push func Remove type Interface import "container/heap" This package provides heap operations for any type that implements heap.Interface. Package files
heap.go

func Init
func Init(h Interface) A heaper must be initialized before any of the heap operations can be used. Init is idempotent with respect to the heap invariants and may be called whenever the heap invariants may have been invalidated. Its complexity is O(n) where n = h.Len().

func Pop
func Pop(h Interface) interface{} Pop removes the minimum element (according to Less) from the heap and returns it. The complexity is O(log(n)) where n = h.Len(). Same as Remove(h, 0).

func Push
func Push(h Interface, x interface{}) Push pushes the element x onto the heap. The complexity is O(log(n)) where n = h.Len().

func Remove
func Remove(h Interface, i int) interface{} Remove removes the element at index i from the heap. The complexity is O(log(n)) where n = h.Len().

type Interface
Any type that implements heap.Interface may be used as a min-heap with the following invariants (established after Init has been called):
!h.Less(j, i) for 0 <= i < h.Len() and j = 2*i+1 or 2*i+2 and j < h.Len()

type Interface interface { sort.Interface Push(x interface{}) Pop() interface{} }

Except as noted, this content is licensed under Creative Commons Attribution 3.0.

The Go Programming Language

Package list
type Element func (*Element) Next func (*Element) Prev type List func New func (*List) Back func (*List) Front func (*List) Init func (*List) InsertAfter func (*List) InsertBefore func (*List) Iter import "container/list" The list package implements a doubly linked list. Package files
list.go

func (*List) Len func (*List) MoveToBack func (*List) MoveToFront func (*List) PushBack func (*List) PushBackList func (*List) PushFront func (*List) PushFrontList func (*List) Remove

type Element
Element is an element in the linked list.
type Element struct {

// The contents of this list element. Value interface{} // contains unexported fields }

func (*Elem ent) Next


func (e *Element) Next() *Element Next returns the next list element or nil.

func (*Elem ent) Prev


func (e *Element) Prev() *Element Prev returns the previous list element or nil.

type List

List represents a doubly linked list.


type List struct { // contains unexported fields }

func New
func New() *List New returns an initialized list.

func (*List) Back


func (l *List) Back() *Element Back returns the last element in the list.

func (*List) Front


func (l *List) Front() *Element Front returns the first element in the list.

func (*List) Init


func (l *List) Init() *List Init initializes or clears a List.

func (*List) InsertAfter


func (l *List) InsertAfter(value interface{}, mark *Element) *Element InsertAfter inserts the value immediately after mark and returns a new Element containing the value.

func (*List) InsertBefore


func (l *List) InsertBefore(value interface{}, mark *Element) *Element InsertBefore inserts the value immediately before mark and returns a new Element containing the value.

func (*List) Iter


func (l *List) Iter() <-chan interface{}

func (*List) Len


func (l *List) Len() int Len returns the number of elements in the list.

func (*List) MoveToBack


func (l *List) MoveToBack(e *Element) MoveToBack moves the element to the back of the list.

func (*List) MoveToFront

func (l *List) MoveToFront(e *Element) MoveToFront moves the element to the front of the list.

func (*List) PushBack


func (l *List) PushBack(value interface{}) *Element PushBack inserts the value at the back of the list and returns a new Element containing the value.

func (*List) PushBackList


func (l *List) PushBackList(ol *List) PushBackList inserts each element of ol at the back of the list.

func (*List) PushFront


func (l *List) PushFront(value interface{}) *Element PushFront inserts the value at the front of the list and returns a new Element containing the value.

func (*List) PushFrontList


func (l *List) PushFrontList(ol *List) PushFrontList inserts each element of ol at the front of the list. The ordering of the passed list is preserved.

func (*List) Rem ove


func (l *List) Remove(e *Element) Remove removes the element from the list.

Except as noted, this content is licensed under Creative Commons Attribution 3.0.

The Go Programming Language

Package ring
type Ring func New func (*Ring) Iter func (*Ring) Len func (*Ring) Link func (*Ring) Move func (*Ring) Next func (*Ring) Prev func (*Ring) Unlink import "container/ring" The ring package implements operations on circular lists. Package files
ring.go

type Ring
A Ring is an element of a circular list, or ring. Rings do not have a beginning or end; a pointer to any ring element serves as reference to the entire ring. Empty rings are represented as nil Ring pointers. The zero value for a Ring is a one-element ring with a nil Value.
type Ring struct { Value interface{} // for use by client; untouched by this library // contains unexported fields }

func New
func New(n int) *Ring New creates a ring of n elements.

func (*Ring) Iter


func (r *Ring) Iter() <-chan interface{}

func (*Ring) Len


func (r *Ring) Len() int Len computes the number of elements in ring r. It executes in time proportional to the number of elements.

func (*Ring) Link


func (r *Ring) Link(s *Ring) *Ring

Link connects ring r with with ring s such that r.Next() becomes s and returns the original value for r.Next(). r must not be empty. If r and s point to the same ring, linking them removes the elements between r and s from the ring. The removed elements form a subring and the result is a reference to that subring (if no elements were removed, the result is still the original value for r.Next(), and not nil). If r and s point to different rings, linking them creates a single ring with the elements of s inserted after r. The result points to the element following the last element of s after insertion.

func (*Ring) Move


func (r *Ring) Move(n int) *Ring Move moves n % r.Len() elements backward (n < 0) or forward (n >= 0) in the ring and returns that ring element. r must not be empty.

func (*Ring) Next


func (r *Ring) Next() *Ring Next returns the next ring element. r must not be empty.

func (*Ring) Prev


func (r *Ring) Prev() *Ring Prev returns the previous ring element. r must not be empty.

func (*Ring) Unlink


func (r *Ring) Unlink(n int) *Ring Unlink removes n % r.Len() elements from the ring r, starting at r.Next(). If n % r.Len() == 0, r remains unchanged. The result is the removed subring. r must not be empty.

Except as noted, this content is licensed under Creative Commons Attribution 3.0.

The Go Programming Language

Package vector
type IntVector func (*IntVector) AppendVector func (*IntVector) At func (*IntVector) Cap func (*IntVector) Cut func (*IntVector) Data func (*IntVector) Delete func (*IntVector) Do func (*IntVector) Expand func (*IntVector) Extend func (*IntVector) Insert func (*IntVector) InsertVector func (*IntVector) Iter func (*IntVector) Last func (*IntVector) Len func (*IntVector) Less func (*IntVector) Pop func (*IntVector) Push func (*IntVector) Resize func (*IntVector) Set func (*IntVector) Slice func (*IntVector) Swap type LessInterface type StringVector func (*StringVector) AppendVector func (*StringVector) At func (*StringVector) Cap func (*StringVector) Cut func (*StringVector) Data func (*StringVector) Delete func (*StringVector) Do func (*StringVector) Expand func (*StringVector) Extend func (*StringVector) Insert func (*StringVector) InsertVector import "container/vector" The vector package implements containers for managing sequences of elements. Vectors grow and shrink dynamically as necessary. Package files
def s.go intv ector.go stringv ector.go v ector.go

func (*StringVector) Iter func (*StringVector) Last func (*StringVector) Len func (*StringVector) Less func (*StringVector) Pop func (*StringVector) Push func (*StringVector) Resize func (*StringVector) Set func (*StringVector) Slice func (*StringVector) Swap type Vector func (*Vector) AppendVector func (*Vector) At func (*Vector) Cap func (*Vector) Cut func (*Vector) Data func (*Vector) Delete func (*Vector) Do func (*Vector) Expand func (*Vector) Extend func (*Vector) Insert func (*Vector) InsertVector func (*Vector) Iter func (*Vector) Last func (*Vector) Len func (*Vector) Less func (*Vector) Pop func (*Vector) Push func (*Vector) Resize func (*Vector) Set func (*Vector) Slice func (*Vector) Swap

type IntVector

IntVector is a container for numbered sequences of elements of type int. A vector's length and capacity adjusts automatically as necessary. The zero value for IntVector is an empty vector ready to use.
type IntVector []int

func (*IntVector) AppendVector


func (p *IntVector) AppendVector(x *IntVector) AppendVector appends the entire vector x to the end of this vector.

func (*IntVector) At
func (p *IntVector) At(i int) int At returns the i'th element of the vector.

func (*IntVector) Cap


func (p *IntVector) Cap() int Cap returns the capacity of the vector; that is, the maximum length the vector can grow without resizing. Same as cap(*p).

func (*IntVector) Cut


func (p *IntVector) Cut(i, j int) Cut deletes elements i through j-1, inclusive.

func (*IntVector) Data


func (p *IntVector) Data() []int Data returns all the elements as a slice.

func (*IntVector) Delete


func (p *IntVector) Delete(i int) Delete deletes the i'th element of the vector. The gap is closed so the old element at index i+1 has index i afterwards.

func (*IntVector) Do
func (p *IntVector) Do(f func(elem interface{})) Do calls function f for each element of the vector, in order. The behavior of Do is undefined if f changes *p.

func (*IntVector) Expand


func (p *IntVector) Expand(i, n int) Insert n elements at position i.

func (*IntVector) Extend


func (p *IntVector) Extend(n int)

Insert n elements at the end of a vector.

func (*IntVector) Insert


func (p *IntVector) Insert(i int, x int) Insert inserts into the vector an element of value x before the current element at index i.

func (*IntVector) InsertVector


func (p *IntVector) InsertVector(i int, x *IntVector) InsertVector inserts into the vector the contents of the vector x such that the 0th element of x appears at index i after insertion.

func (*IntVector) Iter


func (p *IntVector) Iter() <-chan int Channel iterator for range.

func (*IntVector) Last


func (p *IntVector) Last() int Last returns the element in the vector of highest index.

func (*IntVector) Len


func (p *IntVector) Len() int Len returns the number of elements in the vector. Same as len(*p).

func (*IntVector) Less


func (p *IntVector) Less(i, j int) bool Less returns a boolean denoting whether the i'th element is less than the j'th element.

func (*IntVector) Pop


func (p *IntVector) Pop() int Pop deletes the last element of the vector.

func (*IntVector) Push


func (p *IntVector) Push(x int) Push appends x to the end of the vector.

func (*IntVector) Resize


func (p *IntVector) Resize(length, capacity int) *IntVector Resize changes the length and capacity of a vector. If the new length is shorter than the current length, Resize discards trailing elements. If the new length is longer than the current length, Resize adds the respective zero values for the additional elements. The capacity parameter is ignored unless the new length or capacity is longer than the current capacity. The resized vector's capacity may be larger than the requested capacity.

func (*IntVector) Set


func (p *IntVector) Set(i int, x int) Set sets the i'th element of the vector to value x.

func (*IntVector) Slice


func (p *IntVector) Slice(i, j int) *IntVector Slice returns a new sub-vector by slicing the old one to extract slice [i:j]. The elements are copied. The original vector is unchanged.

func (*IntVector) Sw ap
func (p *IntVector) Swap(i, j int) Swap exchanges the elements at indexes i and j.

type LessInterface
LessInterface provides partial support of the sort.Interface.
type LessInterface interface { Less(y interface{}) bool }

type StringVector
StringVector is a container for numbered sequences of elements of type string. A vector's length and capacity adjusts automatically as necessary. The zero value for StringVector is an empty vector ready to use.
type StringVector []string

func (*StringVector) AppendVector


func (p *StringVector) AppendVector(x *StringVector) AppendVector appends the entire vector x to the end of this vector.

func (*StringVector) At
func (p *StringVector) At(i int) string At returns the i'th element of the vector.

func (*StringVector) Cap


func (p *StringVector) Cap() int Cap returns the capacity of the vector; that is, the maximum length the vector can grow without resizing. Same as cap(*p).

func (*StringVector) Cut

func (p *StringVector) Cut(i, j int) Cut deletes elements i through j-1, inclusive.

func (*StringVector) Data


func (p *StringVector) Data() []string Data returns all the elements as a slice.

func (*StringVector) Delete


func (p *StringVector) Delete(i int) Delete deletes the i'th element of the vector. The gap is closed so the old element at index i+1 has index i afterwards.

func (*StringVector) Do
func (p *StringVector) Do(f func(elem interface{})) Do calls function f for each element of the vector, in order. The behavior of Do is undefined if f changes *p.

func (*StringVector) Expand


func (p *StringVector) Expand(i, n int) Insert n elements at position i.

func (*StringVector) Extend


func (p *StringVector) Extend(n int) Insert n elements at the end of a vector.

func (*StringVector) Insert


func (p *StringVector) Insert(i int, x string) Insert inserts into the vector an element of value x before the current element at index i.

func (*StringVector) InsertVector


func (p *StringVector) InsertVector(i int, x *StringVector) InsertVector inserts into the vector the contents of the vector x such that the 0th element of x appears at index i after insertion.

func (*StringVector) Iter


func (p *StringVector) Iter() <-chan string Channel iterator for range.

func (*StringVector) Last


func (p *StringVector) Last() string Last returns the element in the vector of highest index.

func (*StringVector) Len

func (p *StringVector) Len() int Len returns the number of elements in the vector. Same as len(*p).

func (*StringVector) Less


func (p *StringVector) Less(i, j int) bool Less returns a boolean denoting whether the i'th element is less than the j'th element.

func (*StringVector) Pop


func (p *StringVector) Pop() string Pop deletes the last element of the vector.

func (*StringVector) Push


func (p *StringVector) Push(x string) Push appends x to the end of the vector.

func (*StringVector) Resize


func (p *StringVector) Resize(length, capacity int) *StringVector Resize changes the length and capacity of a vector. If the new length is shorter than the current length, Resize discards trailing elements. If the new length is longer than the current length, Resize adds the respective zero values for the additional elements. The capacity parameter is ignored unless the new length or capacity is longer than the current capacity. The resized vector's capacity may be larger than the requested capacity.

func (*StringVector) Set


func (p *StringVector) Set(i int, x string) Set sets the i'th element of the vector to value x.

func (*StringVector) Slice


func (p *StringVector) Slice(i, j int) *StringVector Slice returns a new sub-vector by slicing the old one to extract slice [i:j]. The elements are copied. The original vector is unchanged.

func (*StringVector) Sw ap
func (p *StringVector) Swap(i, j int) Swap exchanges the elements at indexes i and j.

type Vector
Vector is a container for numbered sequences of elements of type interface{}. A vector's length and capacity adjusts automatically as necessary. The zero value for Vector is an empty vector ready to use.
type Vector []interface{}

func (*Vector) AppendVector


func (p *Vector) AppendVector(x *Vector) AppendVector appends the entire vector x to the end of this vector.

func (*Vector) At
func (p *Vector) At(i int) interface{} At returns the i'th element of the vector.

func (*Vector) Cap


func (p *Vector) Cap() int Cap returns the capacity of the vector; that is, the maximum length the vector can grow without resizing. Same as cap(*p).

func (*Vector) Cut


func (p *Vector) Cut(i, j int) Cut deletes elements i through j-1, inclusive.

func (*Vector) Data


func (p *Vector) Data() []interface{} Data returns all the elements as a slice.

func (*Vector) Delete


func (p *Vector) Delete(i int) Delete deletes the i'th element of the vector. The gap is closed so the old element at index i+1 has index i afterwards.

func (*Vector) Do
func (p *Vector) Do(f func(elem interface{})) Do calls function f for each element of the vector, in order. The behavior of Do is undefined if f changes *p.

func (*Vector) Expand


func (p *Vector) Expand(i, n int) Insert n elements at position i.

func (*Vector) Extend


func (p *Vector) Extend(n int) Insert n elements at the end of a vector.

func (*Vector) Insert


func (p *Vector) Insert(i int, x interface{}) Insert inserts into the vector an element of value x before the current element at index i.

func (*Vector) InsertVector


func (p *Vector) InsertVector(i int, x *Vector) InsertVector inserts into the vector the contents of the vector x such that the 0th element of x appears at index i after insertion.

func (*Vector) Iter


func (p *Vector) Iter() <-chan interface{} Channel iterator for range.

func (*Vector) Last


func (p *Vector) Last() interface{} Last returns the element in the vector of highest index.

func (*Vector) Len


func (p *Vector) Len() int Len returns the number of elements in the vector. Same as len(*p).

func (*Vector) Less


func (p *Vector) Less(i, j int) bool Less returns a boolean denoting whether the i'th element is less than the j'th element.

func (*Vector) Pop


func (p *Vector) Pop() interface{} Pop deletes the last element of the vector.

func (*Vector) Push


func (p *Vector) Push(x interface{}) Push appends x to the end of the vector.

func (*Vector) Resize


func (p *Vector) Resize(length, capacity int) *Vector Resize changes the length and capacity of a vector. If the new length is shorter than the current length, Resize discards trailing elements. If the new length is longer than the current length, Resize adds the respective zero values for the additional elements. The capacity parameter is ignored unless the new length or capacity is longer than the current capacity. The resized vector's capacity may be larger than the requested capacity.

func (*Vector) Set


func (p *Vector) Set(i int, x interface{}) Set sets the i'th element of the vector to value x.

func (*Vector) Slice

func (p *Vector) Slice(i, j int) *Vector Slice returns a new sub-vector by slicing the old one to extract slice [i:j]. The elements are copied. The original vector is unchanged.

func (*Vector) Sw ap
func (p *Vector) Swap(i, j int) Swap exchanges the elements at indexes i and j.

Except as noted, this content is licensed under Creative Commons Attribution 3.0.

The Go Programming Language

Package aes
Constants type Cipher func NewCipher func (*Cipher) BlockSize func (*Cipher) Decrypt func (*Cipher) Encrypt func (*Cipher) Reset type KeySizeError func (KeySizeError) String import "crypto/aes" This package implements AES encryption (formerly Rijndael), as defined in U.S. Federal Information Processing Standards Publication 197. Package files
block.go cipher.go const.go

Constants
The AES block size in bytes.
const BlockSize = 16

type Cipher
A Cipher is an instance of AES encryption using a particular key.
type Cipher struct { // contains unexported fields }

func New Cipher


func NewCipher(key []byte) (*Cipher, os.Error) NewCipher creates and returns a new Cipher. The key argument should be the AES key, either 16, 24, or 32 bytes to select AES-128, AES-192, or AES-256.

func (*Cipher) BlockSize


func (c *Cipher) BlockSize() int

BlockSize returns the AES block size, 16 bytes. It is necessary to satisfy the Cipher interface in the package "crypto/block".

func (*Cipher) Decrypt


func (c *Cipher) Decrypt(src, dst []byte) Decrypt decrypts the 16-byte buffer src using the key k and stores the result in dst.

func (*Cipher) Encrypt


func (c *Cipher) Encrypt(src, dst []byte) Encrypt encrypts the 16-byte buffer src using the key k and stores the result in dst. Note that for amounts of data larger than a block, it is not safe to just call Encrypt on successive blocks; instead, use an encryption mode like CBC (see crypto/block/cbc.go).

func (*Cipher) Reset


func (c *Cipher) Reset() Reset zeros the key data, so that it will no longer appear in the process's memory.

type KeySizeError
type KeySizeError int

func (KeySizeError) String


func (k KeySizeError) String() string

Except as noted, this content is licensed under Creative Commons Attribution 3.0.

The Go Programming Language

Package block
func NewCBCDecrypter func NewCBCEncrypter func NewCFBDecrypter func NewCFBEncrypter func NewCMAC func NewCTRReader func NewCTRWriter func NewEAXDecrypter func NewEAXEncrypter import "crypto/block" The block package 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. Package files
cbc.go cf b.go cipher.go cmac.go ctr.go eax.go ecb.go of b.go xor.go

func NewECBDecrypter func NewECBEncrypter func NewOFBReader func NewOFBWriter type Cipher type EAXTagError func (*EAXTagError) String

func NewCBCDecrypter
func NewCBCDecrypter(c Cipher, iv []byte, r io.Reader) io.Reader NewCBCDecrypter returns a reader that reads data from r and decrypts it using c in cipher block chaining (CBC) mode with the initialization vector iv. The returned Reader does not buffer or read ahead except as required by the cipher's block size.

func NewCBCEncrypter
func NewCBCEncrypter(c Cipher, iv []byte, w io.Writer) io.Writer NewCBCEncrypter returns a writer that encrypts data using c in cipher block chaining (CBC) mode with the initialization vector iv and writes the encrypted data to w. The returned Writer does no buffering except as required by the cipher's block size, so there is no need for a Flush method.

func NewCFBDecrypter
func NewCFBDecrypter(c Cipher, s int, iv []byte, r io.Reader) io.Reader NewCFBDecrypter returns a reader that reads data from r and decrypts it using c in s-bit cipher feedback (CFB) mode with the initialization vector iv. The returned Reader does not buffer or read ahead except as required by the cipher's block size. Modes for s not a multiple of 8 are unimplemented.

func NewCFBEncrypter
func NewCFBEncrypter(c Cipher, s int, iv []byte, w io.Writer) io.Writer NewCFBEncrypter returns a writer that encrypts data using c in s-bit cipher feedback (CFB) mode with the initialization vector iv and writes the encrypted data to w. The returned Writer does no buffering except as required by the cipher's block size, so there is no need for a Flush method. Modes for s not a multiple of 8 are unimplemented.

func NewCMAC
func NewCMAC(c Cipher) hash.Hash NewCMAC returns a new instance of a CMAC message authentication code digest using the given Cipher.

func NewCTRReader
func NewCTRReader(c Cipher, iv []byte, r io.Reader) io.Reader NewCTRReader returns a reader that reads data from r, decrypts (or encrypts) it using c in counter (CTR) mode with the initialization vector iv. The returned Reader does not buffer and has no block size. In CTR mode, encryption and decryption are the same operation: a CTR reader applied to an encrypted stream produces a decrypted stream and vice versa.

func NewCTRWriter
func NewCTRWriter(c Cipher, iv []byte, w io.Writer) io.Writer NewCTRWriter returns a writer that encrypts (or decrypts) data using c in counter (CTR) mode with the initialization vector iv and writes the encrypted data to w. The returned Writer does not buffer and has no block size. In CTR mode, encryption and decryption are the same operation: a CTR writer applied to an decrypted stream produces an encrypted stream and vice versa.

func NewEAXDecrypter
func NewEAXDecrypter(c Cipher, iv []byte, hdr []byte, tagBytes int, r io.Reader) io.Reader NewEAXDecrypter creates and returns a new EAX decrypter using the given cipher c, initialization vector iv, associated data hdr, and tag length tagBytes. The encrypter's Read method decrypts and returns data read from r. At r's EOF, the encrypter checks the final authenticating tag and returns an EAXTagError if the tag is invalid. In that case, the message should be discarded. Note that the data stream returned from Read cannot be assumed to be valid, authenticated data until Read returns 0, nil to signal the end of the data.

func NewEAXEncrypter
func NewEAXEncrypter(c Cipher, iv []byte, hdr []byte, tagBytes int, w io.Writer) io.WriteCloser

NewEAXEncrypter creates and returns a new EAX encrypter using the given cipher c, initialization vector iv, associated data hdr, and tag length tagBytes. The encrypter's Write method encrypts the data it receives and writes that data to w. T he encrypter's Close method writes a final authenticating tag to w.

func NewECBDecrypter
func NewECBDecrypter(c Cipher, r io.Reader) io.Reader NewECBDecrypter returns a reader that reads data from r and decrypts it using c. It decrypts by calling c.Decrypt on each block in sequence; this mode is known as electronic codebook mode, or ECB. The returned Reader does not buffer or read ahead except as required by the cipher's block size.

func NewECBEncrypter
func NewECBEncrypter(c Cipher, w io.Writer) io.Writer NewECBEncrypter returns a writer that encrypts data using c and writes it to w. It encrypts by calling c.Encrypt on each block in sequence; this mode is known as electronic codebook mode, or ECB. The returned Writer does no buffering except as required by the cipher's block size, so there is no need for a Flush method.

func NewOFBReader
func NewOFBReader(c Cipher, iv []byte, r io.Reader) io.Reader NewOFBReader returns a reader that reads data from r, decrypts (or encrypts) it using c in output feedback (OFB) mode with the initialization vector iv. The returned Reader does not buffer and has no block size. In OFB mode, encryption and decryption are the same operation: an OFB reader applied to an encrypted stream produces a decrypted stream and vice versa.

func NewOFBWriter
func NewOFBWriter(c Cipher, iv []byte, w io.Writer) io.Writer NewOFBWriter returns a writer that encrypts (or decrypts) data using c in cipher feedback (OFB) mode with the initialization vector iv and writes the encrypted data to w. The returned Writer does not buffer and has no block size. In OFB mode, encryption and decryption are the same operation: an OFB writer applied to an decrypted stream produces an encrypted stream and vice versa.

type Cipher
A Cipher 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 Cipher interface { // BlockSize returns the cipher's block size. BlockSize() int // Encrypt encrypts the first block in src into dst. // Src and dst may point at the same memory. Encrypt(src, dst []byte) // Decrypt decrypts the first block in src into dst. // Src and dst may point at the same memory. Decrypt(src, dst []byte) }

type EAXTagError
An EAXTagError is returned when the message has failed to authenticate, because the tag at the end of the message stream (Read) does not match the tag computed from the message itself (Computed).
type EAXTagError struct { Read []byte Computed []byte }

func (*EAXTagError) String


func (e *EAXTagError) String() string

Except as noted, this content is licensed under Creative Commons Attribution 3.0.

The Go Programming Language

Package blowfish
Constants type Cipher func NewCipher func (*Cipher) BlockSize func (*Cipher) Decrypt func (*Cipher) Encrypt func (*Cipher) Reset type KeySizeError func (KeySizeError) String import "crypto/blowfish" This package implements Bruce Schneier's Blowfish encryption algorithm. Package files
block.go cipher.go const.go

Constants
The Blowfish block size in bytes.
const BlockSize = 8

type Cipher
A Cipher is an instance of Blowfish encryption using a particular key.
type Cipher struct { // contains unexported fields }

func New Cipher


func NewCipher(key []byte) (*Cipher, os.Error) NewCipher creates and returns a Cipher. The key argument should be the Blowfish key, 4 to 56 bytes.

func (*Cipher) BlockSize


func (c *Cipher) BlockSize() int BlockSize returns the Blowfish block size, 8 bytes. It is necessary to satisfy the Cipher interface in the package "crypto/block".

func (*Cipher) Decrypt


func (c *Cipher) Decrypt(src, dst []byte) Decrypt decrypts the 8-byte buffer src using the key k and stores the result in dst.

func (*Cipher) Encrypt


func (c *Cipher) Encrypt(src, dst []byte) Encrypt encrypts the 8-byte buffer src using the key k and stores the result in dst. Note that for amounts of data larger than a block, it is not safe to just call Encrypt on successive blocks; instead, use an encryption mode like CBC (see crypto/block/cbc.go).

func (*Cipher) Reset


func (c *Cipher) Reset() Reset zeros the key data, so that it will no longer appear in the process's memory.

type KeySizeError
type KeySizeError int

func (KeySizeError) String


func (k KeySizeError) String() string

Except as noted, this content is licensed under Creative Commons Attribution 3.0.

The Go Programming Language

Package hmac
func New func NewMD5 func NewSHA1 import "crypto/hmac" The hmac package 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. Package files
hmac.go

func New
func New(h hash.Hash, key []byte) hash.Hash New returns a new HMAC hash using the given hash and key.

func NewMD5
func NewMD5(key []byte) hash.Hash NewMD5 returns a new HMAC-MD5 hash using the given key.

func NewSHA1
func NewSHA1(key []byte) hash.Hash NewSHA1 returns a new HMAC-SHA1 hash using the given key.

Except as noted, this content is licensed under Creative Commons Attribution 3.0.

The Go Programming Language

Package md4
Constants func New import "crypto/md4" This package implements the MD4 hash algorithm as defined in RFC 1320. Package files
md4.go md4block.go

Constants
The size of an MD4 checksum in bytes.
const Size = 16

func New
func New() hash.Hash New returns a new hash.Hash computing the MD4 checksum.

Except as noted, this content is licensed under Creative Commons Attribution 3.0.

The Go Programming Language

Package md5
Constants func New import "crypto/md5" This package implements the MD5 hash algorithm as defined in RFC 1321. Package files
md5.go md5block.go

Constants
The size of an MD5 checksum in bytes.
const Size = 16

func New
func New() hash.Hash New returns a new hash.Hash computing the MD5 checksum.

Except as noted, this content is licensed under Creative Commons Attribution 3.0.

The Go Programming Language

Package rc4
type Cipher func NewCipher func (*Cipher) Reset func (*Cipher) XORKeyStream type KeySizeError func (KeySizeError) String Bugs import "crypto/rc4" This package implements RC4 encryption, as defined in Bruce Schneier's Applied Cryptography. Package files
rc4.go

type Cipher
A Cipher is an instance of RC4 using a particular key.
type Cipher struct { // contains unexported fields }

func New Cipher


func NewCipher(key []byte) (*Cipher, os.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(buf []byte) XORKeyStream will XOR each byte of the given buffer with a byte of the generated keystream.

type KeySizeError

type KeySizeError int

func (KeySizeError) String


func (k KeySizeError) String() string

Bugs
RC4 is in common use but has design weaknesses that make it a poor choice for new protocols.

Except as noted, this content is licensed under Creative Commons Attribution 3.0.

The Go Programming Language

Package ripemd160
Constants func New import "crypto/ripemd160" This package implements the RIPEMD-160 hash algorithm. Package files
ripemd160.go ripemd160block.go

Constants
The block size of the hash algorithm in bytes.
const BlockSize = 64

The size of the checksum in bytes.


const Size = 20

func New
func New() hash.Hash New returns a new hash.Hash computing the checksum.

Except as noted, this content is licensed under Creative Commons Attribution 3.0.

The Go Programming Language

Package rsa
func DecryptOAEP func DecryptPKCS1v15 func DecryptPKCS1v15SessionKey func EncryptOAEP func EncryptPKCS1v15 func SignPKCS1v15 func VerifyPKCS1v15 type DecryptionError func (DecryptionError) String type MessageTooLongError import "crypto/rsa" This package implements RSA encryption as specified in PKCS#1. Package files
pkcs1v 15.go rsa.go

type type

type type

func (MessageTooLongError) String PKCS1v15Hash PrivateKey func GenerateKey func (PrivateKey) Validate PublicKey VerificationError func (VerificationError) String

func DecryptOAEP
func DecryptOAEP(hash hash.Hash, rand io.Reader, priv *PrivateKey, ciphertext []byte, label []byte) (msg []byte, err os.Error) DecryptOAEP decrypts ciphertext using RSA-OAEP. If rand != nil, DecryptOAEP uses RSA blinding to avoid timing side-channel attacks.

func DecryptPKCS1v15
func DecryptPKCS1v15(rand io.Reader, priv *PrivateKey, ciphertext []byte) (out []byte, err os.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.

func DecryptPKCS1v15SessionKey
func DecryptPKCS1v15SessionKey(rand io.Reader, priv *PrivateKey, ciphertext []byte, key []byte) (err os.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),

func EncryptOAEP
func EncryptOAEP(hash hash.Hash, rand io.Reader, pub *PublicKey, msg []byte, label []byte) (out []byte, err os.Error) EncryptOAEP encrypts the given message with RSA-OAEP. The message must be no longer than the length of the public modulus less twice the hash length plus 2.

func EncryptPKCS1v15
func EncryptPKCS1v15(rand io.Reader, pub *PublicKey, msg []byte) (out []byte, err os.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. 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 PKCS1v15Hash, hashed []byte) (s []byte, err os.Error) SignPKCS1v15 calcuates the signature of hashed using RSASSA-PSS-SIGN from RSA PKCS#1 v1.5. Note that hashed must be the result of hashing the input message using the given hash function.

func VerifyPKCS1v15
func VerifyPKCS1v15(pub *PublicKey, hash PKCS1v15Hash, hashed []byte, sig []byte) (err os.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.

type DecryptionError
A DecryptionError represents a failure to decrypt a message. It is deliberately vague to avoid adaptive attacks.
type DecryptionError struct{}

func (DecryptionError) String


func (DecryptionError) String() string

type MessageTooLongError
MessageTooLongError is returned when attempting to encrypt a message which is too large for the size of the public key.
type MessageTooLongError struct{}

func (MessageTooLongError) String


func (MessageTooLongError) String() string

type PKCS1v15Hash
Due to the design of PKCS#1 v1.5, we need to know the exact hash function in use. A generic hash.Hash will not do.
type PKCS1v15Hash int

const ( HashMD5 PKCS1v15Hash = iota HashSHA1 HashSHA256 HashSHA384 HashSHA512 )

type PrivateKey
A PrivateKey represents an RSA key
type PrivateKey struct PublicKey D *big.Int P, Q *big.Int } { // public part. // private exponent // prime factors of N

func GenerateKey
func GenerateKey(rand io.Reader, bits int) (priv *PrivateKey, err os.Error) GenerateKeyPair generates an RSA keypair of the given bit size.

func (PrivateKey) Validate


func (priv PrivateKey) Validate() os.Error

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

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

type VerificationError
A VerificationError represents a failure to verify a signature. It is deliberately vague to avoid adaptive attacks.
type VerificationError struct{}

func (VerificationError) String


func (VerificationError) String() string

Except as noted, this content is licensed under Creative Commons Attribution 3.0.

The Go Programming Language

Package sha1
Constants func New import "crypto/sha1" This package implements the SHA1 hash algorithm as defined in RFC 3174. Package files
sha1.go sha1block.go

Constants
The size of a SHA1 checksum in bytes.
const Size = 20

func New
func New() hash.Hash New returns a new hash.Hash computing the SHA1 checksum.

Except as noted, this content is licensed under Creative Commons Attribution 3.0.

The Go Programming Language

Package sha256
Constants func New func New224 import "crypto/sha256" This package implements the SHA224 and SHA256 hash algorithms as defined in FIPS 180-2. Package files
sha256.go sha256block.go

Constants
The size of a SHA256 checksum in bytes.
const Size = 32

The size of a SHA224 checksum in bytes.


const Size224 = 28

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.

Except as noted, this content is licensed under Creative Commons Attribution 3.0.

The Go Programming Language

Package sha512
Constants func New import "crypto/sha512" This package implements the SHA512 hash algorithm as defined in FIPS 180-2. Package files
sha512.go sha512block.go

Constants
The size of a SHA512 checksum in bytes.
const Size = 64

func New
func New() hash.Hash New returns a new hash.Hash computing the SHA512 checksum.

Except as noted, this content is licensed under Creative Commons Attribution 3.0.

The Go Programming Language

Package subtle
func ConstantTimeByteEq func ConstantTimeCompare func ConstantTimeCopy func ConstantTimeEq func ConstantTimeSelect import "crypto/subtle" This package implements functions that are often useful in cryptographic code but require careful thought to use correctly. Package files
constant_time.go

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 equal length 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 iff 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 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.

Except as noted, this content is licensed under Creative Commons Attribution 3.0.

The Go Programming Language

Package tls
Variables type CASet func NewCASet func (*CASet) FindParent func (*CASet) SetFromPEM type Certificate type Config type Conn func Client func Server func (*Conn) Close func (*Conn) GetConnectionState func (*Conn) Read import "crypto/tls" This package partially implements the TLS 1.1 protocol, as specified in RFC 4346. Package files
alert.go ca_set.go common.go handshake_client.go handshake_messages.go handshake_serv er.go prf .go record_process.go record_read.go record_write.go tls.go

func (*Conn) SetReadTimeout func (*Conn) SetTimeout func (*Conn) SetWriteTimeout func (*Conn) WaitConnectionState func (*Conn) Write type ConnectionState type Listener func NewListener func (*Listener) Accept func (*Listener) Addr func (*Listener) Close

Variables
TLS cipher suites.
var ( TLS_RSA_WITH_RC4_128_SHA uint16 = 5 )

type CASet
A CASet is a set of certificates.
type CASet struct { // contains unexported fields }

func New CASet


func NewCASet() *CASet

func (*CASet) FindParent

func (s *CASet) FindParent(cert *x509.Certificate) (parent *x509.Certificate) FindParent attempts to find the certificate in s which signs the given certificate. If no such certificate can be found, it returns nil.

func (*CASet) SetFrom PEM


func (s *CASet) SetFromPEM(pemCerts []byte) (ok bool) SetFromPEM attempts to parse a series of PEM encoded root certificates. It appends any certificates found to s and returns true if any certificates were successfully parsed. On many Linux systems, /etc/ssl/cert.pem will contains the system wide set of root CAs in a format suitable for this function.

type Certificate
type Certificate struct { Certificate [][]byte PrivateKey *rsa.PrivateKey }

type Config
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.
type Config struct { // Rand provides the source of entropy for nonces and RSA blinding. Rand io.Reader // Time returns the current time as the number of seconds since the epoch. Time func() int64 Certificates []Certificate RootCAs *CASet // NextProtos is a list of supported, application level protocols. // Currently only server-side handling is supported. NextProtos []string }

type Conn
A Conn represents a secure connection.
type Conn struct { net.Conn // contains unexported fields }

func Client
func Client(conn net.Conn, config *Config) *Conn

func Server

func Server(conn net.Conn, config *Config) *Conn

func (*Conn) Close


func (tls *Conn) Close() os.Error

func (*Conn) GetConnectionState


func (tls *Conn) GetConnectionState() ConnectionState

func (*Conn) Read


func (tls *Conn) Read(p []byte) (int, os.Error)

func (*Conn) SetReadTim eout


func (tls *Conn) SetReadTimeout(nsec int64) os.Error

func (*Conn) SetTim eout


func (tls *Conn) SetTimeout(nsec int64) os.Error

func (*Conn) SetWriteTim eout


func (tls *Conn) SetWriteTimeout(nsec int64) os.Error

func (*Conn) WaitConnectionState


func (tls *Conn) WaitConnectionState() ConnectionState

func (*Conn) Write


func (tls *Conn) Write(p []byte) (int, os.Error)

type ConnectionState
type ConnectionState struct { HandshakeComplete bool CipherSuite string Error alertType NegotiatedProtocol string }

type Listener
type Listener struct { // contains unexported fields }

func New Listener


func NewListener(listener net.Listener, config *Config) (l *Listener) NewListener creates a Listener which accepts connections from an inner Listener and wraps each connection

with Server.

func (*Listener) Accept


func (l *Listener) Accept() (c net.Conn, err os.Error)

func (*Listener) Addr


func (l *Listener) Addr() net.Addr

func (*Listener) Close


func (l *Listener) Close() os.Error

Except as noted, this content is licensed under Creative Commons Attribution 3.0.

The Go Programming Language

Package x509
func CreateCertificate func MarshalPKCS1PrivateKey func ParseCertificates func ParsePKCS1PrivateKey type Certificate func ParseCertificate func (*Certificate) CheckSignatureFrom func (*Certificate) IsValidForHost type ConstraintViolationError func (ConstraintViolationError) String import "crypto/x509" This package parses X.509-encoded keys and certificates. Package files
x509.go

type type type type type

KeyUsage Name PublicKeyAlgorithm SignatureAlgorithm UnhandledCriticalExtension func (UnhandledCriticalExtension) String type UnsupportedAlgorithmError func (UnsupportedAlgorithmError) String

func CreateCertificate
func CreateCertificate(rand io.Reader, template, parent *Certificate, priv *rsa.PrivateKey) (cert []byte, err os.Error) CreateSelfSignedCertificate creates a new certificate based on a template. The following members of template are used: SerialNumber, Subject, NotBefore, NotAfter, KeyUsage, BasicConstraintsValid, IsCA, MaxPathLen, SubjectKeyId, DNSNames. The certificate is signed by parent. If parent is equal to template then the certificate is self-signed. The returned slice is the certificate in DER encoding.

func MarshalPKCS1PrivateKey
func MarshalPKCS1PrivateKey(key *rsa.PrivateKey) []byte MarshalPKCS1PrivateKey converts a private key to ASN.1 DER encoded form.

func ParseCertificates
func ParseCertificates(asn1Data []byte) ([]*Certificate, os.Error) ParseCertificates parses one or more certificates from the given ASN.1 DER data. The certificates must be concatenated with no intermediate padding.

func ParsePKCS1PrivateKey
func ParsePKCS1PrivateKey(der []byte) (key *rsa.PrivateKey, err os.Error) ParsePKCS1PrivateKey returns an RSA private key from its ASN.1 PKCS#1 DER encoded form.

type Certificate
A Certificate represents an X.509 certificate.
type Certificate struct { Raw []byte // Raw ASN.1 DER contents. Signature []byte SignatureAlgorithm SignatureAlgorithm PublicKeyAlgorithm PublicKeyAlgorithm PublicKey interface{} Version SerialNumber Issuer Subject NotBefore, NotAfter KeyUsage int []byte Name Name *time.Time // Validity bounds. KeyUsage

BasicConstraintsValid bool // if true then the next two fields are valid. IsCA bool MaxPathLen int SubjectKeyId []byte AuthorityKeyId []byte // Subject Alternate Name values DNSNames []string EmailAddresses []string }

func ParseCertificate
func ParseCertificate(asn1Data []byte) (*Certificate, os.Error) ParseCertificate parses a single certificate from the given ASN.1 DER data.

func (*Certificate) CheckSignatureFrom


func (c *Certificate) CheckSignatureFrom(parent *Certificate) (err os.Error) CheckSignatureFrom verifies that the signature on c is a valid signature from parent.

func (*Certificate) IsValidForHost


func (c *Certificate) IsValidForHost(h string) bool IsValidForHost returns true iff c is a valid certificate for the given host.

type ConstraintViolationError

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.
type ConstraintViolationError struct{}

func (ConstraintViolationError) String


func (ConstraintViolationError) String() string

type KeyUsage
KeyUsage represents the set of actions that are valid for a given key. It's a bitmap of the KeyUsage* constants.
type KeyUsage int

const ( KeyUsageDigitalSignature KeyUsage = 1 << iota KeyUsageContentCommitment KeyUsageKeyEncipherment KeyUsageDataEncipherment KeyUsageKeyAgreement KeyUsageCertSign KeyUsageCRLSign KeyUsageEncipherOnly KeyUsageDecipherOnly )

type Name
Name represents an X.509 distinguished name. This only includes the common elements of a DN. Additional elements in the name are ignored.
type Name struct { Country, Organization, OrganizationalUnit string CommonName, SerialNumber, Locality string Province, StreetAddress, PostalCode string }

type PublicKeyAlgorithm
type PublicKeyAlgorithm int

const ( UnknownPublicKeyAlgorithm PublicKeyAlgorithm = iota RSA )

type SignatureAlgorithm
type SignatureAlgorithm int

const ( UnknownSignatureAlgorithm SignatureAlgorithm = iota MD2WithRSA MD5WithRSA SHA1WithRSA SHA256WithRSA SHA384WithRSA SHA512WithRSA )

type UnhandledCriticalExtension
type UnhandledCriticalExtension struct{}

func (UnhandledCriticalExtension) String


func (h UnhandledCriticalExtension) String() string

type UnsupportedAlgorithmError
UnsupportedAlgorithmError results from attempting to perform an operation that involves algorithms that are not currently implemented.
type UnsupportedAlgorithmError struct{}

func (UnsupportedAlgorithm Error) String


func (UnsupportedAlgorithmError) String() string

Except as noted, this content is licensed under Creative Commons Attribution 3.0.

The Go Programming Language

Package xtea
Constants type Cipher func NewCipher func (*Cipher) BlockSize func (*Cipher) Decrypt func (*Cipher) Encrypt func (*Cipher) Reset type KeySizeError func (KeySizeError) String import "crypto/xtea" This package implements XTEA encryption, as defined in Needham and Wheeler's 1997 technical report, "Tea extensions." Package files
block.go cipher.go

Constants
The XTEA block size in bytes.
const BlockSize = 8

type Cipher
A Cipher is an instance of an XTEA cipher using a particular key. table contains a series of precalculated values that are used each round.
type Cipher struct { // contains unexported fields }

func New Cipher


func NewCipher(key []byte) (*Cipher, os.Error) NewCipher creates and returns a new Cipher. The key argument should be the XTEA key. XTEA only supports 128 bit (16 byte) keys.

func (*Cipher) BlockSize


func (c *Cipher) BlockSize() int

BlockSize returns the XTEA block size, 8 bytes. It is necessary to satisfy the Cipher interface in the package "crypto/block".

func (*Cipher) Decrypt


func (c *Cipher) Decrypt(src, dst []byte) Decrypt decrypts the 8 byte buffer src using the key k and stores the result in dst.

func (*Cipher) Encrypt


func (c *Cipher) Encrypt(src, dst []byte) Encrypt encrypts the 8 byte buffer src using the key and stores the result in dst. Note that for amounts of data larger than a block, it is not safe to just call Encrypt on successive blocks; instead, use an encryption mode like CBC (see crypto/block/cbc.go).

func (*Cipher) Reset


func (c *Cipher) Reset() Reset zeros the table, so that it will no longer appear in the process's memory.

type KeySizeError
type KeySizeError int

func (KeySizeError) String


func (k KeySizeError) String() string

Except as noted, this content is licensed under Creative Commons Attribution 3.0.

The Go Programming Language

Package dwarf
type AddrType type ArrayType func (*ArrayType) Size func (*ArrayType) String type Attr func (Attr) GoString func (Attr) String type BasicType func (*BasicType) Basic func (*BasicType) String type BoolType type CharType type CommonType func (*CommonType) Common func (*CommonType) Size type ComplexType type Data func New func (*Data) Reader func (*Data) Type type DecodeError func (DecodeError) String type DotDotDotType func (*DotDotDotType) String type Entry func (*Entry) Val type EnumType func (*EnumType) String type EnumValue type Field type FloatType import "debug/dwarf" This package provides access to DWARF debugging information loaded from executable files, as defined in the DWARF 2.0 Standard at http://dwarfstd.org/dwarf-2.0.0.pdf. Package files
buf .go const.go entry .go open.go ty pe.go unit.go

type FuncType func (*FuncType) String type IntType type Offset type PtrType func (*PtrType) String type QualType func (*QualType) Size func (*QualType) String type Reader func (*Reader) Next func (*Reader) Seek func (*Reader) SkipChildren type StructField type StructType func (*StructType) Defn func (*StructType) String type Tag func (Tag) GoString func (Tag) String type Type type TypedefType func (*TypedefType) Size func (*TypedefType) String type UcharType type UintType type VoidType func (*VoidType) String

type AddrType
An AddrType represents a machine address type.

type AddrType struct { BasicType }

type ArrayType
An ArrayType represents a fixed size array type.
type ArrayType struct { CommonType Type Type StrideBitSize int64 // if > 0, number of bits to hold each element Count int64 // if == -1, an incomplete array, like char x[]. }

func (*ArrayType) Size


func (t *ArrayType) Size() int64

func (*ArrayType) String


func (t *ArrayType) String() string

type Attr
An Attr identifies the attribute type in a DWARF Entry's Field.
type Attr uint32

const ( AttrSibling AttrLocation AttrName AttrOrdering AttrByteSize AttrBitOffset AttrBitSize AttrStmtList AttrLowpc AttrHighpc AttrLanguage AttrDiscr AttrDiscrValue AttrVisibility AttrImport AttrStringLength AttrCommonRef AttrCompDir AttrConstValue AttrContainingType AttrDefaultValue AttrInline AttrIsOptional AttrLowerBound AttrProducer AttrPrototyped AttrReturnAddr AttrStartScope AttrStrideSize AttrUpperBound AttrAbstractOrigin AttrAccessibility AttrAddrClass AttrArtificial AttrBaseTypes AttrCalling AttrCount AttrDataMemberLoc AttrDeclColumn AttrDeclFile AttrDeclLine AttrDeclaration AttrDiscrList AttrEncoding AttrExternal AttrFrameBase AttrFriend AttrIdentifierCase AttrMacroInfo AttrNamelistItem AttrPriority AttrSegment AttrSpecification AttrStaticLink AttrType AttrUseLocation AttrVarParam AttrVirtuality AttrVtableElemLoc AttrAllocated AttrAssociated AttrDataLocation AttrStride AttrEntrypc AttrUseUTF8

Attr Attr Attr Attr Attr Attr Attr Attr Attr Attr Attr Attr Attr Attr Attr Attr Attr Attr Attr Attr Attr Attr Attr Attr Attr Attr Attr Attr Attr Attr Attr Attr Attr Attr Attr Attr Attr Attr Attr Attr Attr Attr Attr Attr Attr Attr Attr Attr Attr Attr Attr Attr Attr Attr Attr Attr Attr Attr Attr Attr Attr Attr Attr Attr Attr

= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =

0x01 0x02 0x03 0x09 0x0B 0x0C 0x0D 0x10 0x11 0x12 0x13 0x15 0x16 0x17 0x18 0x19 0x1A 0x1B 0x1C 0x1D 0x1E 0x20 0x21 0x22 0x25 0x27 0x2A 0x2C 0x2E 0x2F 0x31 0x32 0x33 0x34 0x35 0x36 0x37 0x38 0x39 0x3A 0x3B 0x3C 0x3D 0x3E 0x3F 0x40 0x41 0x42 0x43 0x44 0x45 0x46 0x47 0x48 0x49 0x4A 0x4B 0x4C 0x4D 0x4E 0x4F 0x50 0x51 0x52 0x53

func (Attr) GoString


func (a Attr) GoString() string

func (Attr) String


func (a Attr) String() string

type BasicType
A BasicType holds fields common to all basic types.
type BasicType struct { CommonType BitSize int64 BitOffset int64 }

func (*BasicType) Basic


func (b *BasicType) Basic() *BasicType

func (*BasicType) String


func (t *BasicType) String() string

type BoolType
A BoolType represents a boolean type.
type BoolType struct { BasicType }

type CharType
A CharType represents a signed character type.
type CharType struct { BasicType }

type CommonType
A CommonType holds fields common to multiple types. If a field is not known or not applicable for a given type, the zero value is used.

type CommonType struct { ByteSize int64 // size of value of this type, in bytes Name string // name that can be used to refer to type }

func (*Com m onType) Com m on


func (c *CommonType) Common() *CommonType

func (*Com m onType) Size


func (c *CommonType) Size() int64

type ComplexType
A ComplexType represents a complex floating point type.
type ComplexType struct { BasicType }

type Data
Data represents the DWARF debugging information loaded from an executable file (for example, an ELF or Mach-O executable).
type Data struct { // contains unexported fields }

func New
func New(abbrev, aranges, frame, info, line, pubnames, ranges, str []byte) (*Data, os.Error) New returns a new Data object initialized from the given parameters. Clients should typically use [TODO(rsc): method to be named later] instead of calling New directly. The []byte arguments are the data from the corresponding debug section in the object file; for example, for an ELF object, abbrev is the contents of the ".debug_abbrev" section.

func (*Data) Reader


func (d *Data) Reader() *Reader Reader returns a new Reader for Data. The reader is positioned at byte offset 0 in the DWARF info section.

func (*Data) Type


func (d *Data) Type(off Offset) (Type, os.Error)

type DecodeError
type DecodeError struct { Name string Offset Offset Error string }

func (DecodeError) String


func (e DecodeError) String() string

type DotDotDotType
A DotDotDotType represents the variadic ... function parameter.
type DotDotDotType struct { CommonType }

func (*DotDotDotType) String


func (t *DotDotDotType) String() string

type Entry
An entry is a sequence of attribute/value pairs.
type Entry struct { Offset Offset // offset of Entry in DWARF info Tag Tag // tag (kind of Entry) Children bool // whether Entry is followed by children Field []Field }

func (*Entry) Val


func (e *Entry) Val(a Attr) interface{} Val returns the value associated with attribute Attr in Entry, or nil if there is no such attribute. A common idiom is to merge the check for nil return with the check that the value has the expected dynamic type, as in:
v, ok := e.Val(AttrSibling).(int64);

type EnumType
An EnumType represents an enumerated type. The only indication of its native integer type is its ByteSize

(inside CommonType).
type EnumType struct { CommonType EnumName string Val []*EnumValue }

func (*Enum Type) String


func (t *EnumType) String() string

type EnumValue
An EnumValue represents a single enumeration value.
type EnumValue struct { Name string Val int64 }

type Field
A Field is a single attribute/value pair in an Entry.
type Field struct { Attr Attr Val interface{} }

type FloatType
A FloatType represents a floating point type.
type FloatType struct { BasicType }

type FuncType
A FuncType represents a function type.
type FuncType struct { CommonType ReturnType Type ParamType []Type }

func (*FuncType) String


func (t *FuncType) String() string

type IntType
An IntType represents a signed integer type.
type IntType struct { BasicType }

type Offset
An Offset represents the location of an Entry within the DWARF info. (See Reader.Seek.)
type Offset uint32

type PtrType
A PtrType represents a pointer type.
type PtrType struct { CommonType Type Type }

func (*PtrType) String


func (t *PtrType) String() string

type QualType
A QualType represents a type that has the C/C++ "const", "restrict", or "volatile" qualifier.
type QualType struct { CommonType Qual string Type Type }

func (*QualType) Size


func (t *QualType) Size() int64

func (*QualType) String


func (t *QualType) String() string

type Reader
A Reader allows reading Entry structures from a DWARF info section. The Entry structures are arranged in a tree. The Reader's Next function return successive entries from a pre-order traversal of the tree. If an entry has children, its Children field will be true, and the children follow, terminated by an Entry with Tag 0.
type Reader struct { // contains unexported fields }

func (*Reader) Next


func (r *Reader) Next() (*Entry, os.Error) Next reads the next entry from the encoded entry stream. It returns nil, nil when it reaches the end of the section. It returns an error if the current offset is invalid or the data at the offset cannot be decoded as a valid Entry.

func (*Reader) Seek


func (r *Reader) Seek(off Offset) Seek positions the Reader at offset off in the encoded entry stream. Offset 0 can be used to denote the first entry.

func (*Reader) SkipChildren


func (r *Reader) SkipChildren() SkipChildren skips over the child entries associated with the last Entry returned by Next. If that Entry did not have children or Next has not been called, SkipChildren is a no-op.

type StructField
A StructField represents a field in a struct, union, or C++ class type.
type StructField struct { Name string Type Type ByteOffset int64 ByteSize int64 BitOffset int64 // within the ByteSize bytes at ByteOffset BitSize int64 // zero if not a bit field }

type StructType
A StructType represents a struct, union, or C++ class type.

type StructType struct { CommonType StructName string Kind string // "struct", "union", or "class". Field []*StructField Incomplete bool // if true, struct, union, class is declared but not defined }

func (*StructType) Defn


func (t *StructType) Defn() string

func (*StructType) String


func (t *StructType) String() string

type Tag
A Tag is the classification (the type) of an Entry.
type Tag uint32

const ( TagArrayType TagClassType TagEntryPoint TagEnumerationType TagFormalParameter TagImportedDeclaration TagLabel TagLexDwarfBlock TagMember TagPointerType TagReferenceType TagCompileUnit TagStringType TagStructType TagSubroutineType TagTypedef TagUnionType TagUnspecifiedParameters TagVariant TagCommonDwarfBlock TagCommonInclusion TagInheritance TagInlinedSubroutine TagModule TagPtrToMemberType TagSetType TagSubrangeType TagWithStmt TagAccessDeclaration TagBaseType TagCatchDwarfBlock TagConstType TagConstant TagEnumerator TagFileType TagFriend TagNamelist TagNamelistItem TagPackedType TagSubprogram TagTemplateTypeParameter TagTemplateValueParameter TagThrownType TagTryDwarfBlock TagVariantPart TagVariable TagVolatileType TagDwarfProcedure TagRestrictType TagInterfaceType TagNamespace TagImportedModule TagUnspecifiedType TagPartialUnit TagImportedUnit TagMutableType )

Tag Tag Tag Tag Tag Tag Tag Tag Tag Tag Tag Tag Tag Tag Tag Tag Tag Tag Tag Tag Tag Tag Tag Tag Tag Tag Tag Tag Tag Tag Tag Tag Tag Tag Tag Tag Tag Tag Tag Tag Tag Tag Tag Tag Tag Tag Tag Tag Tag Tag Tag Tag Tag Tag Tag Tag

= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =

0x01 0x02 0x03 0x04 0x05 0x08 0x0A 0x0B 0x0D 0x0F 0x10 0x11 0x12 0x13 0x15 0x16 0x17 0x18 0x19 0x1A 0x1B 0x1C 0x1D 0x1E 0x1F 0x20 0x21 0x22 0x23 0x24 0x25 0x26 0x27 0x28 0x29 0x2A 0x2B 0x2C 0x2D 0x2E 0x2F 0x30 0x31 0x32 0x33 0x34 0x35 0x36 0x37 0x38 0x39 0x3A 0x3B 0x3C 0x3D 0x3E

func (Tag) GoString


func (t Tag) GoString() string

func (Tag) String


func (t Tag) String() string

type Type
A Type conventionally represents a pointer to any of the specific Type structures (CharType, StructType, etc.).
type Type interface { Common() *CommonType String() string Size() int64 }

type TypedefType
A TypedefType represents a named type.
type TypedefType struct { CommonType Type Type }

func (*TypedefType) Size


func (t *TypedefType) Size() int64

func (*TypedefType) String


func (t *TypedefType) String() string

type UcharType
A UcharType represents an unsigned character type.
type UcharType struct { BasicType }

type UintType
A UintType represents an unsigned integer type.
type UintType struct { BasicType }

type VoidType
A VoidType represents the C void type.
type VoidType struct { CommonType }

func (*VoidType) String


func (t *VoidType) String() string

Except as noted, this content is licensed under Creative Commons Attribution 3.0.

The Go Programming Language

Package elf
Constants func R_INFO func R_INFO32 func R_SYM32 func R_SYM64 func R_TYPE32 func R_TYPE64 func ST_TYPE type Class func (Class) GoString func (Class) String type Data func (Data) GoString func (Data) String type Dyn32 type Dyn64 type DynFlag func (DynFlag) GoString func (DynFlag) String type DynTag func (DynTag) GoString func (DynTag) String type File func NewFile func Open func (*File) Close func (*File) DWARF func (*File) Section type FileHeader type FormatError func (*FormatError) String type Header32 type Header64 type Machine func (Machine) GoString func (Machine) String type NType func (NType) GoString func (NType) String type OSABI func (OSABI) GoString func (OSABI) String type Prog func (*Prog) Open type Prog32 type Prog64 type R_ALPHA func (R_ALPHA) GoString func (R_ALPHA) String type R_ARM func (R_ARM) GoString func (R_ARM) String type R_PPC func (R_PPC) GoString func (R_PPC) String type R_SPARC func (R_SPARC) GoString func (R_SPARC) String type R_X86_64 func (R_X86_64) GoString func (R_X86_64) String type Rel32 type Rel64 type Rela32 type Rela64 type Section func (*Section) Data func (*Section) Open type Section32 type Section64 type SectionFlag func (SectionFlag) GoString func (SectionFlag) String type SectionHeader type SectionIndex func (SectionIndex) GoString func (SectionIndex) String type SectionType func (SectionType) GoString func (SectionType) String type Sym32 type Sym64 type SymBind func ST_BIND func (SymBind) GoString func (SymBind) String type SymType func (SymType) GoString func (SymType) String type SymVis func ST_VISIBILITY func (SymVis) GoString

type ProgFlag func (ProgFlag) GoString func (ProgFlag) String type ProgHeader type ProgType func (ProgType) GoString func (ProgType) String type R_386 func (R_386) GoString func (R_386) String import "debug/elf"

func (SymVis) String type Symbol type Type func (Type) GoString func (Type) String type Version func (Version) GoString func (Version) String

Package elf implements access to ELF object files. Package files


elf .go f ile.go

Constants
Indexes into the Header.Ident array.
const ( EI_CLASS EI_DATA EI_VERSION EI_OSABI EI_ABIVERSION EI_PAD EI_NIDENT )

= = = = = = =

4 5 6 7 8 9 16

/* /* /* /* /* /* /*

Class of machine. */ Data format. */ ELF format version. */ Operating system / ABI identification */ ABI version */ Start of padding (per SVR4 ABI). */ Size of e_ident array. */

* Magic number for the elf trampoline, chosen wisely to be an immediate * value.
const ARM_MAGIC_TRAMP_NUMBER = 0x5c000003

Initial magic number for ELF files.


const ELFMAG = "\177ELF"

const Sym32Size = 16

const Sym64Size = 24

func R_INFO
func R_INFO(sym, typ uint32) uint64

func R_INFO32
func R_INFO32(sym, typ uint32) uint32

func R_SYM32
func R_SYM32(info uint32) uint32

func R_SYM64
func R_SYM64(info uint64) uint32

func R_TYPE32
func R_TYPE32(info uint32) uint32

func R_TYPE64
func R_TYPE64(info uint64) uint32

func ST_TYPE
func ST_TYPE(bind SymBind, typ SymType) uint8

type Class
Class is found in Header.Ident[EI_CLASS] and Header.Class.
type Class byte

const ( ELFCLASSNONE Class = 0 /* Unknown class. */ ELFCLASS32 Class = 1 /* 32-bit architecture. */ ELFCLASS64 Class = 2 /* 64-bit architecture. */ )

func (Class) GoString


func (i Class) GoString() string

func (Class) String


func (i Class) String() string

type Data
Data is found in Header.Ident[EI_DATA] and Header.Data.
type Data byte

const ( ELFDATANONE Data = 0 /* Unknown data format. */ ELFDATA2LSB Data = 1 /* 2's complement little-endian. */ ELFDATA2MSB Data = 2 /* 2's complement big-endian. */ )

func (Data) GoString


func (i Data) GoString() string

func (Data) String


func (i Data) String() string

type Dyn32
* ELF32 Dynamic structure. The ".dynamic" section contains an array of them.
type Dyn32 struct { Tag int32 /* Entry type. */ Val uint32 /* Integer/Address value. */ }

type Dyn64
type Dyn64 struct { Tag int64 /* Entry type. */ Val uint64 /* Integer/address value */ }

type DynFlag
DT_FLAGS values.
type DynFlag int

const ( DF_ORIGIN DynFlag = 0x0001 /* Indicates that the object being loaded may make reference to the $ORIGIN substitution string */ DF_SYMBOLIC DynFlag = 0x0002 /* Indicates "symbolic" linking. */ DF_TEXTREL DynFlag = 0x0004 /* Indicates there may be relocations in non-writable segments. */ DF_BIND_NOW DynFlag = 0x0008 /* Indicates that the dynamic linker should process all relocations for the object containing this entry before transferring control to the program. */ DF_STATIC_TLS DynFlag = 0x0010 /* Indicates that the shared object or executable contains code using a static thread-local storage scheme. */ )

func (DynFlag) GoString


func (i DynFlag) GoString() string

func (DynFlag) String


func (i DynFlag) String() string

type DynTag
Dyn.Tag
type DynTag int

const ( DT_NULL DynTag = 0 /* Terminating entry. */ DT_NEEDED DynTag = 1 /* String table offset of a needed shared library. */ DT_PLTRELSZ DynTag = 2 /* Total size in bytes of PLT relocations. */ DT_PLTGOT DynTag = 3 /* Processor-dependent address. */ DT_HASH DynTag = 4 /* Address of symbol hash table. */ DT_STRTAB DynTag = 5 /* Address of string table. */ DT_SYMTAB DynTag = 6 /* Address of symbol table. */ DT_RELA DynTag = 7 /* Address of ElfNN_Rela relocations. */ DT_RELASZ DynTag = 8 /* Total size of ElfNN_Rela relocations. */ DT_RELAENT DynTag = 9 /* Size of each ElfNN_Rela relocation entry. */ DT_STRSZ DynTag = 10 /* Size of string table. */ DT_SYMENT DynTag = 11 /* Size of each symbol table entry. */ DT_INIT DynTag = 12 /* Address of initialization function. */ DT_FINI DynTag = 13 /* Address of finalization function. */ DT_SONAME DynTag = 14 /* String table offset of shared object name. */ DT_RPATH DynTag = 15 /* String table offset of library path. [sup] */ DT_SYMBOLIC DynTag = 16 /* Indicates "symbolic" linking. [sup] */ DT_REL DynTag = 17 /* Address of ElfNN_Rel relocations. */ DT_RELSZ DynTag = 18 /* Total size of ElfNN_Rel relocations. */ DT_RELENT DynTag = 19 /* Size of each ElfNN_Rel relocation. */ DT_PLTREL DynTag = 20 /* Type of relocation used for PLT. */ DT_DEBUG DynTag = 21 /* Reserved (not used). */ DT_TEXTREL DynTag = 22 /* Indicates there may be relocations in non-writable segments. [sup] */ DT_JMPREL DynTag = 23 /* Address of PLT relocations. */ DT_BIND_NOW DynTag = 24 /* [sup] */ DT_INIT_ARRAY DynTag = 25 /* Address of the array of pointers to initialization functions */ DT_FINI_ARRAY DynTag = 26 /* Address of the array of pointers to termination functions */ DT_INIT_ARRAYSZ DynTag = 27 /* Size in bytes of the array of initialization functions. */ DT_FINI_ARRAYSZ DynTag = 28 /* Size in bytes of the array of terminationfunctions. */ DT_RUNPATH DynTag = 29 /* String table offset of a null-terminated library search path string. */ DT_FLAGS DynTag = 30 /* Object specific flag values. */ DT_ENCODING DynTag = 32 /* Values greater than or equal to DT_ENCODING and less than DT_LOOS follow the rules for the interpretation of the d_un union as follows: even == 'd_ptr', even == 'd_val' or none */ DT_PREINIT_ARRAY DynTag = 32 /* Address of the array of pointers to pre-initialization functions. DT_PREINIT_ARRAYSZ DynTag = 33 /* Size in bytes of the array of pre-initialization functions. */ DT_LOOS DynTag = 0x6000000d /* First OS-specific */ DT_HIOS DynTag = 0x6ffff000 /* Last OS-specific */ DT_LOPROC DynTag = 0x70000000 /* First processor-specific type. */ DT_HIPROC DynTag = 0x7fffffff /* Last processor-specific type. */ )

func (DynTag) GoString


func (i DynTag) GoString() string

func (DynTag) String


func (i DynTag) String() string

type File
A File represents an open ELF file.

type File struct { FileHeader Sections []*Section Progs []*Prog // contains unexported fields }

func New File


func NewFile(r io.ReaderAt) (*File, os.Error) NewFile creates a new File for acecssing an ELF binary in an underlying reader. The ELF binary is expected to start at position 0 in the ReaderAt.

func Open
func Open(name string) (*File, os.Error) Open opens the named file using os.Open and prepares it for use as an ELF binary.

func (*File) Close


func (f *File) Close() os.Error Close closes the File. If the File was created using NewFile directly instead of Open, Close has no effect.

func (*File) DWARF


func (f *File) DWARF() (*dwarf.Data, os.Error)

func (*File) Section


func (f *File) Section(name string) *Section Section returns a section with the given name, or nil if no such section exists.

type FileHeader
A FileHeader represents an ELF file header.
type FileHeader struct { Class Class Data Data Version Version OSABI OSABI ABIVersion uint8 ByteOrder binary.ByteOrder Type Type Machine Machine }

type FormatError

type FormatError struct { // contains unexported fields }

func (*Form atError) String


func (e *FormatError) String() string

type Header32
* ELF32 File header.
type Header32 Ident Type Machine Version Entry Phoff Shoff Flags Ehsize Phentsize Phnum Shentsize Shnum Shstrndx } struct { [EI_NIDENT]byte uint16 uint16 uint32 uint32 uint32 uint32 uint32 uint16 uint16 uint16 uint16 uint16 uint16

/* /* /* /* /* /* /* /* /* /* /* /* /* /*

File identification. */ File type. */ Machine architecture. */ ELF format version. */ Entry point. */ Program header file offset. */ Section header file offset. */ Architecture-specific flags. */ Size of ELF header in bytes. */ Size of program header entry. */ Number of program header entries. */ Size of section header entry. */ Number of section header entries. */ Section name strings section. */

type Header64
type Header64 Ident Type Machine Version Entry Phoff Shoff Flags Ehsize Phentsize Phnum Shentsize Shnum Shstrndx } struct { [EI_NIDENT]byte uint16 uint16 uint32 uint64 uint64 uint64 uint32 uint16 uint16 uint16 uint16 uint16 uint16 /* /* /* /* /* /* /* /* /* /* /* /* /* /* File identification. */ File type. */ Machine architecture. */ ELF format version. */ Entry point. */ Program header file offset. */ Section header file offset. */ Architecture-specific flags. */ Size of ELF header in bytes. */ Size of program header entry. */ Number of program header entries. */ Size of section header entry. */ Number of section header entries. */ Section name strings section. */

type Machine
Machine is found in Header.Machine.

type Machine uint16

const ( EM_NONE EM_M32 EM_SPARC EM_386 EM_68K EM_88K EM_860 EM_MIPS EM_S370 EM_MIPS_RS3_LE EM_PARISC EM_VPP500 EM_SPARC32PLUS EM_960 EM_PPC EM_PPC64 EM_S390 EM_V800 EM_FR20 EM_RH32 EM_RCE EM_ARM EM_SH EM_SPARCV9 EM_TRICORE EM_ARC EM_H8_300 EM_H8_300H EM_H8S EM_H8_500 EM_IA_64 EM_MIPS_X EM_COLDFIRE EM_68HC12 EM_MMA EM_PCP EM_NCPU EM_NDR1 EM_STARCORE EM_ME16 EM_ST100 EM_TINYJ EM_X86_64

Machine Machine Machine Machine Machine Machine Machine Machine Machine Machine Machine Machine Machine Machine Machine Machine Machine Machine Machine Machine Machine Machine Machine Machine Machine Machine Machine Machine Machine Machine Machine Machine Machine Machine Machine Machine Machine Machine Machine Machine Machine Machine Machine

= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =

0 1 2 3 4 5 7 8 9 10 15 17 18 19 20 21 22 36 37 38 39 40 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62

/* /* /* /* /* /* /* /* /* /* /* /* /* /* /* /* /* /* /* /* /* /* /* /* /* /* /* /* /* /* /* /* /* /* /* /* /* /* /* /* /* /* /*

Unknown machine. */ AT&T WE32100. */ Sun SPARC. */ Intel i386. */ Motorola 68000. */ Motorola 88000. */ Intel i860. */ MIPS R3000 Big-Endian only. */ IBM System/370. */ MIPS R3000 Little-Endian. */ HP PA-RISC. */ Fujitsu VPP500. */ SPARC v8plus. */ Intel 80960. */ PowerPC 32-bit. */ PowerPC 64-bit. */ IBM System/390. */ NEC V800. */ Fujitsu FR20. */ TRW RH-32. */ Motorola RCE. */ ARM. */ Hitachi SH. */ SPARC v9 64-bit. */ Siemens TriCore embedded processor. */ Argonaut RISC Core. */ Hitachi H8/300. */ Hitachi H8/300H. */ Hitachi H8S. */ Hitachi H8/500. */ Intel IA-64 Processor. */ Stanford MIPS-X. */ Motorola ColdFire. */ Motorola M68HC12. */ Fujitsu MMA. */ Siemens PCP. */ Sony nCPU. */ Denso NDR1 microprocessor. */ Motorola Star*Core processor. */ Toyota ME16 processor. */ STMicroelectronics ST100 processor. */ Advanced Logic Corp. TinyJ processor. */ Advanced Micro Devices x86-64 */

/* Non-standard or deprecated. */ EM_486 Machine = 6 /* EM_MIPS_RS4_BE Machine = 10 /* EM_ALPHA_STD Machine = 41 /* EM_ALPHA Machine = 0x9026 /* )

Intel i486. */ MIPS R4000 Big-Endian */ Digital Alpha (standard value). */ Alpha (written in the absence of an ABI) */

func (Machine) GoString


func (i Machine) GoString() string

func (Machine) String

func (i Machine) String() string

type NType
NType values; used in core files.
type NType int

const ( NT_PRSTATUS NType = 1 /* Process status. */ NT_FPREGSET NType = 2 /* Floating point registers. */ NT_PRPSINFO NType = 3 /* Process state info. */ )

func (NType) GoString


func (i NType) GoString() string

func (NType) String


func (i NType) String() string

type OSABI
OSABI is found in Header.Ident[EI_OSABI] and Header.OSABI.
type OSABI byte

const ( ELFOSABI_NONE ELFOSABI_HPUX ELFOSABI_NETBSD ELFOSABI_LINUX ELFOSABI_HURD ELFOSABI_86OPEN ELFOSABI_SOLARIS ELFOSABI_AIX ELFOSABI_IRIX ELFOSABI_FREEBSD ELFOSABI_TRU64 ELFOSABI_MODESTO ELFOSABI_OPENBSD ELFOSABI_OPENVMS ELFOSABI_NSK ELFOSABI_ARM ELFOSABI_STANDALONE )

OSABI OSABI OSABI OSABI OSABI OSABI OSABI OSABI OSABI OSABI OSABI OSABI OSABI OSABI OSABI OSABI OSABI

= = = = = = = = = = = = = = = = =

0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 97 255

/* /* /* /* /* /* /* /* /* /* /* /* /* /* /* /* /*

UNIX System V ABI */ HP-UX operating system */ NetBSD */ GNU/Linux */ GNU/Hurd */ 86Open common IA32 ABI */ Solaris */ AIX */ IRIX */ FreeBSD */ TRU64 UNIX */ Novell Modesto */ OpenBSD */ Open VMS */ HP Non-Stop Kernel */ ARM */ Standalone (embedded) application */

func (OSABI) GoString


func (i OSABI) GoString() string

func (OSABI) String


func (i OSABI) String() string

type Prog
A Prog represents a single ELF program header in an ELF binary.
type Prog struct { ProgHeader // Embed ReaderAt for ReadAt method. // Do not embed SectionReader directly // to avoid having Read and Seek. // If a client wants Read and Seek it must use // Open() to avoid fighting over the seek offset // with other clients. io.ReaderAt // contains unexported fields }

func (*Prog) Open


func (p *Prog) Open() io.ReadSeeker Open returns a new ReadSeeker reading the ELF program body.

type Prog32
* ELF32 Program header.
type Prog32 struct { Type uint32 /* Off uint32 /* Vaddr uint32 /* Paddr uint32 /* Filesz uint32 /* Memsz uint32 /* Flags uint32 /* Align uint32 /* }

Entry type. */ File offset of contents. */ Virtual address in memory image. */ Physical address (not used). */ Size of contents in file. */ Size of contents in memory. */ Access permission flags. */ Alignment in memory and file. */

type Prog64

type Prog64 struct { Type uint32 /* Flags uint32 /* Off uint64 /* Vaddr uint64 /* Paddr uint64 /* Filesz uint64 /* Memsz uint64 /* Align uint64 /* }

Entry type. */ Access permission flags. */ File offset of contents. */ Virtual address in memory image. */ Physical address (not used). */ Size of contents in file. */ Size of contents in memory. */ Alignment in memory and file. */

type ProgFlag
Prog.Flag
type ProgFlag uint32

const ( PF_X PF_W PF_R PF_MASKOS PF_MASKPROC )

ProgFlag ProgFlag ProgFlag ProgFlag ProgFlag

= = = = =

0x1 0x2 0x4 0x0ff00000 0xf0000000

/* /* /* /* /*

Executable. */ Writable. */ Readable. */ Operating system-specific. */ Processor-specific. */

func (ProgFlag) GoString


func (i ProgFlag) GoString() string

func (ProgFlag) String


func (i ProgFlag) String() string

type ProgHeader
A ProgHeader represents a single ELF program header.
type ProgHeader struct { Type ProgType Flags ProgFlag Vaddr uint64 Paddr uint64 Filesz uint64 Memsz uint64 Align uint64 }

type ProgType
Prog.Type

type ProgType int

const ( PT_NULL PT_LOAD PT_DYNAMIC PT_INTERP PT_NOTE PT_SHLIB PT_PHDR PT_TLS PT_LOOS PT_HIOS PT_LOPROC PT_HIPROC )

ProgType ProgType ProgType ProgType ProgType ProgType ProgType ProgType ProgType ProgType ProgType ProgType

= = = = = = = = = = = =

0 1 2 3 4 5 6 7 0x60000000 0x6fffffff 0x70000000 0x7fffffff

/* /* /* /* /* /* /* /* /* /* /* /*

Unused entry. */ Loadable segment. */ Dynamic linking information segment. */ Pathname of interpreter. */ Auxiliary information. */ Reserved (not used). */ Location of program header itself. */ Thread local storage segment */ First OS-specific. */ Last OS-specific. */ First processor-specific type. */ Last processor-specific type. */

func (ProgType) GoString


func (i ProgType) GoString() string

func (ProgType) String


func (i ProgType) String() string

type R_386
Relocation types for 386.
type R_386 int

const ( R_386_NONE R_386_32 R_386_PC32 R_386_GOT32 R_386_PLT32 R_386_COPY R_386_GLOB_DAT R_386_JMP_SLOT R_386_RELATIVE R_386_GOTOFF R_386_GOTPC R_386_TLS_TPOFF R_386_TLS_IE R_386_TLS_GOTIE R_386_TLS_LE R_386_TLS_GD R_386_TLS_LDM R_386_TLS_GD_32 R_386_TLS_GD_PUSH R_386_TLS_GD_CALL R_386_TLS_GD_POP R_386_TLS_LDM_32 R_386_TLS_LDM_PUSH R_386_TLS_LDM_CALL R_386_TLS_LDM_POP R_386_TLS_LDO_32 R_386_TLS_IE_32 R_386_TLS_LE_32 R_386_TLS_DTPMOD32 R_386_TLS_DTPOFF32 R_386_TLS_TPOFF32 )

R_386 R_386 R_386 R_386 R_386 R_386 R_386 R_386 R_386 R_386 R_386 R_386 R_386 R_386 R_386 R_386 R_386 R_386 R_386 R_386 R_386 R_386 R_386 R_386 R_386 R_386 R_386 R_386 R_386 R_386 R_386

= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =

0 1 2 3 4 5 6 7 8 9 10 14 15 16 17 18 19 24 25 26 27 28 29 30 31 32 33 34 35 36 37

/* /* /* /* /* /* /* /* /* /* /* /* /* /* /* /* /* /* /* /* /* /* /* /* /* /* /* /* /* /* /*

No relocation. */ Add symbol value. */ Add PC-relative symbol value. */ Add PC-relative GOT offset. */ Add PC-relative PLT offset. */ Copy data from shared object. */ Set GOT entry to data address. */ Set GOT entry to code address. */ Add load address of shared object. */ Add GOT-relative symbol address. */ Add PC-relative GOT table address. */ Negative offset in static TLS block */ Absolute address of GOT for -ve static TLS */ GOT entry for negative static TLS block */ Negative offset relative to static TLS */ 32 bit offset to GOT (index,off) pair */ 32 bit offset to GOT (index,zero) pair */ 32 bit offset to GOT (index,off) pair */ pushl instruction for Sun ABI GD sequence */ call instruction for Sun ABI GD sequence */ popl instruction for Sun ABI GD sequence */ 32 bit offset to GOT (index,zero) pair */ pushl instruction for Sun ABI LD sequence */ call instruction for Sun ABI LD sequence */ popl instruction for Sun ABI LD sequence */ 32 bit offset from start of TLS block */ 32 bit offset to GOT static TLS offset entry */ 32 bit offset within static TLS block */ GOT entry containing TLS index */ GOT entry containing TLS offset */ GOT entry of -ve static TLS offset */

func (R_386) GoString


func (i R_386) GoString() string

func (R_386) String


func (i R_386) String() string

type R_ALPHA
Relocation types for Alpha.
type R_ALPHA int

const ( R_ALPHA_NONE R_ALPHA_REFLONG R_ALPHA_REFQUAD R_ALPHA_GPREL32 R_ALPHA_LITERAL R_ALPHA_LITUSE R_ALPHA_GPDISP R_ALPHA_BRADDR R_ALPHA_HINT R_ALPHA_SREL16 R_ALPHA_SREL32 R_ALPHA_SREL64 R_ALPHA_OP_PUSH R_ALPHA_OP_STORE R_ALPHA_OP_PSUB R_ALPHA_OP_PRSHIFT R_ALPHA_GPVALUE R_ALPHA_GPRELHIGH R_ALPHA_GPRELLOW R_ALPHA_IMMED_GP_16 R_ALPHA_IMMED_GP_HI32 R_ALPHA_IMMED_SCN_HI32 R_ALPHA_IMMED_BR_HI32 R_ALPHA_IMMED_LO32 R_ALPHA_COPY R_ALPHA_GLOB_DAT R_ALPHA_JMP_SLOT R_ALPHA_RELATIVE )

R_ALPHA R_ALPHA R_ALPHA R_ALPHA R_ALPHA R_ALPHA R_ALPHA R_ALPHA R_ALPHA R_ALPHA R_ALPHA R_ALPHA R_ALPHA R_ALPHA R_ALPHA R_ALPHA R_ALPHA R_ALPHA R_ALPHA R_ALPHA R_ALPHA R_ALPHA R_ALPHA R_ALPHA R_ALPHA R_ALPHA R_ALPHA R_ALPHA

= = = = = = = = = = = = = = = = = = = = = = = = = = = =

0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27

/* /* /* /* /* /* /* /* /* /* /* /* /* /* /* /*

No reloc */ Direct 32 bit */ Direct 64 bit */ GP relative 32 bit */ GP relative 16 bit w/optimization */ Optimization hint for LITERAL */ Add displacement to GP */ PC+4 relative 23 bit shifted */ PC+4 relative 16 bit shifted */ PC relative 16 bit */ PC relative 32 bit */ PC relative 64 bit */ OP stack push */ OP stack pop and store */ OP stack subtract */ OP stack right shift */

/* /* /* /*

Copy symbol at runtime */ Create GOT entry */ Create PLT entry */ Adjust by program base */

func (R_ALPHA) GoString


func (i R_ALPHA) GoString() string

func (R_ALPHA) String


func (i R_ALPHA) String() string

type R_ARM
Relocation types for ARM.
type R_ARM int

const ( R_ARM_NONE R_ARM_PC24 R_ARM_ABS32 R_ARM_REL32 R_ARM_PC13 R_ARM_ABS16 R_ARM_ABS12 R_ARM_THM_ABS5 R_ARM_ABS8 R_ARM_SBREL32 R_ARM_THM_PC22 R_ARM_THM_PC8 R_ARM_AMP_VCALL9 R_ARM_SWI24 R_ARM_THM_SWI8 R_ARM_XPC25 R_ARM_THM_XPC22 R_ARM_COPY R_ARM_GLOB_DAT R_ARM_JUMP_SLOT R_ARM_RELATIVE R_ARM_GOTOFF R_ARM_GOTPC R_ARM_GOT32 R_ARM_PLT32 R_ARM_GNU_VTENTRY R_ARM_GNU_VTINHERIT R_ARM_RSBREL32 R_ARM_THM_RPC22 R_ARM_RREL32 R_ARM_RABS32 R_ARM_RPC24 R_ARM_RBASE )

R_ARM R_ARM R_ARM R_ARM R_ARM R_ARM R_ARM R_ARM R_ARM R_ARM R_ARM R_ARM R_ARM R_ARM R_ARM R_ARM R_ARM R_ARM R_ARM R_ARM R_ARM R_ARM R_ARM R_ARM R_ARM R_ARM R_ARM R_ARM R_ARM R_ARM R_ARM R_ARM R_ARM

= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =

0 /* No relocation. */ 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 20 /* Copy data from shared object. */ 21 /* Set GOT entry to data address. */ 22 /* Set GOT entry to code address. */ 23 /* Add load address of shared object. */ 24 /* Add GOT-relative symbol address. */ 25 /* Add PC-relative GOT table address. */ 26 /* Add PC-relative GOT offset. */ 27 /* Add PC-relative PLT offset. */ 100 101 250 251 252 253 254 255

func (R_ARM) GoString


func (i R_ARM) GoString() string

func (R_ARM) String


func (i R_ARM) String() string

type R_PPC
Relocation types for PowerPC.
type R_PPC int

const ( R_PPC_NONE R_PPC_ADDR32 R_PPC_ADDR24 R_PPC_ADDR16 R_PPC_ADDR16_LO R_PPC_ADDR16_HI R_PPC_ADDR16_HA R_PPC_ADDR14 R_PPC_ADDR14_BRTAKEN R_PPC_ADDR14_BRNTAKEN R_PPC_REL24 R_PPC_REL14 R_PPC_REL14_BRTAKEN R_PPC_REL14_BRNTAKEN R_PPC_GOT16 R_PPC_GOT16_LO R_PPC_GOT16_HI R_PPC_GOT16_HA R_PPC_PLTREL24 R_PPC_COPY R_PPC_GLOB_DAT R_PPC_JMP_SLOT R_PPC_RELATIVE R_PPC_LOCAL24PC R_PPC_UADDR32 R_PPC_UADDR16 R_PPC_REL32 R_PPC_PLT32 R_PPC_PLTREL32 R_PPC_PLT16_LO R_PPC_PLT16_HI R_PPC_PLT16_HA R_PPC_SDAREL16 R_PPC_SECTOFF R_PPC_SECTOFF_LO R_PPC_SECTOFF_HI R_PPC_SECTOFF_HA R_PPC_TLS R_PPC_DTPMOD32 R_PPC_TPREL16 R_PPC_TPREL16_LO R_PPC_TPREL16_HI R_PPC_TPREL16_HA R_PPC_TPREL32 R_PPC_DTPREL16 R_PPC_DTPREL16_LO R_PPC_DTPREL16_HI R_PPC_DTPREL16_HA R_PPC_DTPREL32 R_PPC_GOT_TLSGD16 R_PPC_GOT_TLSGD16_LO R_PPC_GOT_TLSGD16_HI R_PPC_GOT_TLSGD16_HA R_PPC_GOT_TLSLD16 R_PPC_GOT_TLSLD16_LO R_PPC_GOT_TLSLD16_HI R_PPC_GOT_TLSLD16_HA R_PPC_GOT_TPREL16 R_PPC_GOT_TPREL16_LO R_PPC_GOT_TPREL16_HI R_PPC_GOT_TPREL16_HA R_PPC_EMB_NADDR32 R_PPC_EMB_NADDR16 R_PPC_EMB_NADDR16_LO R_PPC_EMB_NADDR16_HI

R_PPC R_PPC R_PPC R_PPC R_PPC R_PPC R_PPC R_PPC R_PPC R_PPC R_PPC R_PPC R_PPC R_PPC R_PPC R_PPC R_PPC R_PPC R_PPC R_PPC R_PPC R_PPC R_PPC R_PPC R_PPC R_PPC R_PPC R_PPC R_PPC R_PPC R_PPC R_PPC R_PPC R_PPC R_PPC R_PPC R_PPC R_PPC R_PPC R_PPC R_PPC R_PPC R_PPC R_PPC R_PPC R_PPC R_PPC R_PPC R_PPC R_PPC R_PPC R_PPC R_PPC R_PPC R_PPC R_PPC R_PPC R_PPC R_PPC R_PPC R_PPC R_PPC R_PPC R_PPC R_PPC

= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =

0 /* No relocation. */ 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 101 102 103 104

func (R_PPC) GoString


func (i R_PPC) GoString() string

func (R_PPC) String


func (i R_PPC) String() string

type R_SPARC
Relocation types for SPARC.
type R_SPARC int

const ( R_SPARC_NONE R_SPARC_8 R_SPARC_16 R_SPARC_32 R_SPARC_DISP8 R_SPARC_DISP16 R_SPARC_DISP32 R_SPARC_WDISP30 R_SPARC_WDISP22 R_SPARC_HI22 R_SPARC_22 R_SPARC_13 R_SPARC_LO10 R_SPARC_GOT10 R_SPARC_GOT13 R_SPARC_GOT22 R_SPARC_PC10 R_SPARC_PC22 R_SPARC_WPLT30 R_SPARC_COPY R_SPARC_GLOB_DAT R_SPARC_JMP_SLOT R_SPARC_RELATIVE R_SPARC_UA32 R_SPARC_PLT32 R_SPARC_HIPLT22 R_SPARC_LOPLT10 R_SPARC_PCPLT32 R_SPARC_PCPLT22 R_SPARC_PCPLT10 R_SPARC_10 R_SPARC_11 R_SPARC_64 R_SPARC_OLO10 R_SPARC_HH22 R_SPARC_HM10 R_SPARC_LM22 R_SPARC_PC_HH22 R_SPARC_PC_HM10 R_SPARC_PC_LM22 R_SPARC_WDISP16 R_SPARC_WDISP19 R_SPARC_GLOB_JMP R_SPARC_7 R_SPARC_5 R_SPARC_6 R_SPARC_DISP64 R_SPARC_PLT64 R_SPARC_HIX22 R_SPARC_LOX10 R_SPARC_H44 R_SPARC_M44 R_SPARC_L44 R_SPARC_REGISTER R_SPARC_UA64 R_SPARC_UA16 )

R_SPARC R_SPARC R_SPARC R_SPARC R_SPARC R_SPARC R_SPARC R_SPARC R_SPARC R_SPARC R_SPARC R_SPARC R_SPARC R_SPARC R_SPARC R_SPARC R_SPARC R_SPARC R_SPARC R_SPARC R_SPARC R_SPARC R_SPARC R_SPARC R_SPARC R_SPARC R_SPARC R_SPARC R_SPARC R_SPARC R_SPARC R_SPARC R_SPARC R_SPARC R_SPARC R_SPARC R_SPARC R_SPARC R_SPARC R_SPARC R_SPARC R_SPARC R_SPARC R_SPARC R_SPARC R_SPARC R_SPARC R_SPARC R_SPARC R_SPARC R_SPARC R_SPARC R_SPARC R_SPARC R_SPARC R_SPARC

= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =

0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55

func (R_SPARC) GoString


func (i R_SPARC) GoString() string

func (R_SPARC) String


func (i R_SPARC) String() string

type R_X86_64
Relocation types for x86-64.
type R_X86_64 int

const ( R_X86_64_NONE R_X86_64_64 R_X86_64_PC32 R_X86_64_GOT32 R_X86_64_PLT32 R_X86_64_COPY R_X86_64_GLOB_DAT R_X86_64_JMP_SLOT R_X86_64_RELATIVE R_X86_64_GOTPCREL R_X86_64_32 R_X86_64_32S R_X86_64_16 R_X86_64_PC16 R_X86_64_8 R_X86_64_PC8 R_X86_64_DTPMOD64 R_X86_64_DTPOFF64 R_X86_64_TPOFF64 R_X86_64_TLSGD R_X86_64_TLSLD R_X86_64_DTPOFF32 R_X86_64_GOTTPOFF R_X86_64_TPOFF32 )

R_X86_64 R_X86_64 R_X86_64 R_X86_64 R_X86_64 R_X86_64 R_X86_64 R_X86_64 R_X86_64 R_X86_64 R_X86_64 R_X86_64 R_X86_64 R_X86_64 R_X86_64 R_X86_64 R_X86_64 R_X86_64 R_X86_64 R_X86_64 R_X86_64 R_X86_64 R_X86_64 R_X86_64

= = = = = = = = = = = = = = = = = = = = = = = =

0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23

/* /* /* /* /* /* /* /* /* /* /* /* /* /* /* /* /* /* /* /* /* /* /* /*

No relocation. */ Add 64 bit symbol value. */ PC-relative 32 bit signed sym value. */ PC-relative 32 bit GOT offset. */ PC-relative 32 bit PLT offset. */ Copy data from shared object. */ Set GOT entry to data address. */ Set GOT entry to code address. */ Add load address of shared object. */ Add 32 bit signed pcrel offset to GOT. */ Add 32 bit zero extended symbol value */ Add 32 bit sign extended symbol value */ Add 16 bit zero extended symbol value */ Add 16 bit signed extended pc relative symbol value */ Add 8 bit zero extended symbol value */ Add 8 bit signed extended pc relative symbol value */ ID of module containing symbol */ Offset in TLS block */ Offset in static TLS block */ PC relative offset to GD GOT entry */ PC relative offset to LD GOT entry */ Offset in TLS block */ PC relative offset to IE GOT entry */ Offset in static TLS block */

func (R_X86_64) GoString


func (i R_X86_64) GoString() string

func (R_X86_64) String


func (i R_X86_64) String() string

type Rel32
ELF32 Relocations that don't need an addend field.
type Rel32 struct { Off uint32 /* Location to be relocated. */ Info uint32 /* Relocation type and symbol index. */ }

type Rel64
ELF64 relocations that don't need an addend field.
type Rel64 struct { Off uint64 /* Location to be relocated. */ Info uint64 /* Relocation type and symbol index. */ }

type Rela32
ELF32 Relocations that need an addend field.
type Rela32 struct { Off uint32 /* Location to be relocated. */ Info uint32 /* Relocation type and symbol index. */ Addend int32 /* Addend. */ }

type Rela64
ELF64 relocations that need an addend field.
type Rela64 struct { Off uint64 /* Location to be relocated. */ Info uint64 /* Relocation type and symbol index. */ Addend int64 /* Addend. */ }

type Section
A Section represents a single section in an ELF file.
type Section struct { SectionHeader // Embed ReaderAt for ReadAt method. // Do not embed SectionReader directly // to avoid having Read and Seek. // If a client wants Read and Seek it must use // Open() to avoid fighting over the seek offset // with other clients. io.ReaderAt // contains unexported fields }

func (*Section) Data


func (s *Section) Data() ([]byte, os.Error)

Data reads and returns the contents of the ELF section.

func (*Section) Open


func (s *Section) Open() io.ReadSeeker Open returns a new ReadSeeker reading the ELF section.

type Section32
* ELF32 Section header.
type Section32 struct { Name uint32 /* Type uint32 /* Flags uint32 /* Addr uint32 /* Off uint32 /* Size uint32 /* Link uint32 /* Info uint32 /* Addralign uint32 /* Entsize uint32 /* }

Section name (index into the section header string table). */ Section type. */ Section flags. */ Address in memory image. */ Offset in file. */ Size in bytes. */ Index of a related section. */ Depends on section type. */ Alignment in bytes. */ Size of each entry in section. */

type Section64
type Section64 struct { Name uint32 /* Type uint32 /* Flags uint64 /* Addr uint64 /* Off uint64 /* Size uint64 /* Link uint32 /* Info uint32 /* Addralign uint64 /* Entsize uint64 /* } Section name (index into the section header string table). */ Section type. */ Section flags. */ Address in memory image. */ Offset in file. */ Size in bytes. */ Index of a related section. */ Depends on section type. */ Alignment in bytes. */ Size of each entry in section. */

type SectionFlag
Section flags.
type SectionFlag uint32

const ( SHF_WRITE SHF_ALLOC SHF_EXECINSTR SHF_MERGE SHF_STRINGS SHF_INFO_LINK SHF_LINK_ORDER SHF_OS_NONCONFORMING SHF_GROUP SHF_TLS SHF_MASKOS SHF_MASKPROC )

SectionFlag SectionFlag SectionFlag SectionFlag SectionFlag SectionFlag SectionFlag SectionFlag SectionFlag SectionFlag SectionFlag SectionFlag

= = = = = = = = = = = =

0x1 0x2 0x4 0x10 0x20 0x40 0x80 0x100 0x200 0x400 0x0ff00000 0xf0000000

/* /* /* /* /* /* /* /* /* /* /* /*

Section contains writable data. */ Section occupies memory. */ Section contains instructions. */ Section may be merged. */ Section contains strings. */ sh_info holds section index. */ Special ordering requirements. */ OS-specific processing required. */ Member of section group. */ Section contains TLS data. */ OS-specific semantics. */ Processor-specific semantics. */

func (SectionFlag) GoString


func (i SectionFlag) GoString() string

func (SectionFlag) String


func (i SectionFlag) String() string

type SectionHeader
A SectionHeader represents a single ELF section header.
type SectionHeader struct { Name string Type SectionType Flags SectionFlag Addr uint64 Offset uint64 Size uint64 Link uint32 Info uint32 Addralign uint64 Entsize uint64 }

type SectionIndex
Special section indices.
type SectionIndex int

const ( SHN_UNDEF SHN_LORESERVE SHN_LOPROC SHN_HIPROC SHN_LOOS SHN_HIOS SHN_ABS SHN_COMMON SHN_XINDEX SHN_HIRESERVE )

SectionIndex SectionIndex SectionIndex SectionIndex SectionIndex SectionIndex SectionIndex SectionIndex SectionIndex SectionIndex

= = = = = = = = = =

0 0xff00 0xff00 0xff1f 0xff20 0xff3f 0xfff1 0xfff2 0xffff 0xffff

/* /* /* /* /* /* /* /* /* /*

Undefined, missing, irrelevant. */ First of reserved range. */ First processor-specific. */ Last processor-specific. */ First operating system-specific. */ Last operating system-specific. */ Absolute values. */ Common data. */ Escape -- index stored elsewhere. */ Last of reserved range. */

func (SectionIndex) GoString


func (i SectionIndex) GoString() string

func (SectionIndex) String


func (i SectionIndex) String() string

type SectionType
Section type.
type SectionType uint32

const ( SHT_NULL SHT_PROGBITS SHT_SYMTAB SHT_STRTAB SHT_RELA SHT_HASH SHT_DYNAMIC SHT_NOTE SHT_NOBITS SHT_REL SHT_SHLIB SHT_DYNSYM SHT_INIT_ARRAY SHT_FINI_ARRAY SHT_PREINIT_ARRAY SHT_GROUP SHT_SYMTAB_SHNDX SHT_LOOS SHT_HIOS SHT_LOPROC SHT_HIPROC SHT_LOUSER SHT_HIUSER )

SectionType SectionType SectionType SectionType SectionType SectionType SectionType SectionType SectionType SectionType SectionType SectionType SectionType SectionType SectionType SectionType SectionType SectionType SectionType SectionType SectionType SectionType SectionType

= = = = = = = = = = = = = = = = = = = = = = =

0 1 2 3 4 5 6 7 8 9 10 11 14 15 16 17 18 0x60000000 0x6fffffff 0x70000000 0x7fffffff 0x80000000 0xffffffff

/* /* /* /* /* /* /* /* /* /* /* /* /* /* /* /* /* /* /* /* /* /* /*

inactive */ program defined information */ symbol table section */ string table section */ relocation section with addends */ symbol hash table section */ dynamic section */ note section */ no space section */ relocation section - no addends */ reserved - purpose unknown */ dynamic symbol table section */ Initialization function pointers. */ Termination function pointers. */ Pre-initialization function ptrs. */ Section group. */ Section indexes (see SHN_XINDEX). */ First of OS specific semantics */ Last of OS specific semantics */ reserved range for processor */ specific section header types */ reserved range for application */ specific indexes */

func (SectionType) GoString


func (i SectionType) GoString() string

func (SectionType) String


func (i SectionType) String() string

type Sym32
ELF32 Symbol.
type Sym32 struct { Name uint32 Value uint32 Size uint32 Info uint8 Other uint8 Shndx uint16 }

type Sym64
* ELF64 symbol table entries.
type Sym64 struct { Name uint32 /* Info uint8 /* Other uint8 /* Shndx uint16 /* Value uint64 /* Size uint64 /* }

String table index of name. */ Type and binding information. */ Reserved (not used). */ Section index of symbol. */ Symbol value. */ Size of associated object. */

type SymBind
Symbol Binding - ELFNN_ST_BIND - st_info
type SymBind int

const ( STB_LOCAL STB_GLOBAL STB_WEAK STB_LOOS STB_HIOS STB_LOPROC STB_HIPROC )

SymBind SymBind SymBind SymBind SymBind SymBind SymBind

= = = = = = =

0 1 2 10 12 13 15

/* /* /* /* /* /* /*

Local symbol */ Global symbol */ like global - lower precedence */ Reserved range for operating system */ specific semantics. */ reserved range for processor */ specific semantics. */

func ST_BIND
func ST_BIND(info uint8) SymBind

func (Sym Bind) GoString


func (i SymBind) GoString() string

func (Sym Bind) String


func (i SymBind) String() string

type SymType
Symbol type - ELFNN_ST_TYPE - st_info
type SymType int

const ( STT_NOTYPE STT_OBJECT STT_FUNC STT_SECTION STT_FILE STT_COMMON STT_TLS STT_LOOS STT_HIOS STT_LOPROC STT_HIPROC )

SymType SymType SymType SymType SymType SymType SymType SymType SymType SymType SymType

= = = = = = = = = = =

0 1 2 3 4 5 6 10 12 13 15

/* /* /* /* /* /* /* /* /* /* /*

Unspecified type. */ Data object. */ Function. */ Section. */ Source file. */ Uninitialized common block. */ TLS object. */ Reserved range for operating system */ specific semantics. */ reserved range for processor */ specific semantics. */

func (Sym Type) GoString


func (i SymType) GoString() string

func (Sym Type) String


func (i SymType) String() string

type SymVis
Symbol visibility - ELFNN_ST_VISIBILITY - st_other
type SymVis int

const ( STV_DEFAULT STV_INTERNAL STV_HIDDEN STV_PROTECTED )

SymVis SymVis SymVis SymVis

= = = =

0x0 0x1 0x2 0x3

/* /* /* /*

Default visibility (see binding). */ Special meaning in relocatable objects. */ Not visible. */ Visible but not preemptible. */

func ST_VISIBILITY
func ST_VISIBILITY(other uint8) SymVis

func (Sym Vis) GoString


func (i SymVis) GoString() string

func (Sym Vis) String


func (i SymVis) String() string

type Symbol
A Symbol represents an entry in an ELF symbol table section.
type Symbol struct { Name uint32 Info, Other byte Section uint32 Value, Size uint64 }

type Type
Type is found in Header.Type.
type Type uint16

const ( ET_NONE ET_REL ET_EXEC ET_DYN ET_CORE ET_LOOS ET_HIOS ET_LOPROC ET_HIPROC )

Type Type Type Type Type Type Type Type Type

= = = = = = = = =

0 1 2 3 4 0xfe00 0xfeff 0xff00 0xffff

/* /* /* /* /* /* /* /* /*

Unknown type. */ Relocatable. */ Executable. */ Shared object. */ Core file. */ First operating system specific. */ Last operating system-specific. */ First processor-specific. */ Last processor-specific. */

func (Type) GoString


func (i Type) GoString() string

func (Type) String


func (i Type) String() string

type Version
Version is found in Header.Ident[EI_VERSION] and Header.Version.
type Version byte

const ( EV_NONE Version = 0 EV_CURRENT Version = 1 )

func (Version) GoString


func (i Version) GoString() string

func (Version) String


func (i Version) String() string

Except as noted, this content is licensed under Creative Commons Attribution 3.0.

The Go Programming Language

Package gosym
type DecodingError func (*DecodingError) String type Func type LineTable func NewLineTable func (*LineTable) LineToPC func (*LineTable) PCToLine type Obj type Sym func (*Sym) BaseName func (*Sym) PackageName func (*Sym) ReceiverName func (*Sym) Static type Table import "debug/gosym" Package gosym implements access to the Go symbol and line number tables embedded in Go binaries generated by the gc compilers. Package files
pclntab.go sy mtab.go

func NewTable func (*Table) LineToPC func (*Table) LookupFunc func (*Table) LookupSym func (*Table) PCToFunc func (*Table) PCToLine func (*Table) SymByAddr type UnknownFileError func (UnknownFileError) String type UnknownLineError func (*UnknownLineError) String

type DecodingError
DecodingError represents an error during the decoding of the symbol table.
type DecodingError struct { // contains unexported fields }

func (*DecodingError) String


func (e *DecodingError) String() string

type Func
A Func collects information about a single function.

type Func struct { Entry uint64 *Sym End uint64 Params []*Sym Locals []*Sym FrameSize int LineTable *LineTable Obj *Obj }

type LineTable
type LineTable struct { Data []byte PC uint64 Line int }

func New LineTable


func NewLineTable(data []byte, text uint64) *LineTable NewLineTable returns a new PC/line table corresponding to the encoded data. Text must be the start address of the corresponding text segment.

func (*LineTable) LineToPC


func (t *LineTable) LineToPC(line int, maxpc uint64) uint64

func (*LineTable) PCToLine


func (t *LineTable) PCToLine(pc uint64) int

type Obj
An Obj represents a single object file.
type Obj struct { Funcs []Func Paths []Sym }

type Sym
A Sym represents a single symbol table entry.

type Sym struct { Value uint64 Type byte Name string GoType uint64 // If this symbol if a function symbol, the corresponding Func Func *Func }

func (*Sym ) BaseNam e


func (s *Sym) BaseName() string BaseName returns the symbol name without the package or receiver name.

func (*Sym ) PackageNam e


func (s *Sym) PackageName() string PackageName returns the package part of the symbol name, or the empty string if there is none.

func (*Sym ) ReceiverNam e


func (s *Sym) ReceiverName() string ReceiverName returns the receiver type name of this symbol, or the empty string if there is none.

func (*Sym ) Static


func (s *Sym) Static() bool Static returns whether this symbol is static (not visible outside its file).

type Table
Table represents a Go symbol table. It stores all of the symbols decoded from the program and provides methods to translate between symbols, names, and addresses.
type Table struct { Syms []Sym Funcs []Func Files map[string]*Obj Objs []Obj }

func New Table


func NewTable(symtab []byte, pcln *LineTable) (*Table, os.Error) NewTable decodes the Go symbol table in data, returning an in-memory representation.

func (*Table) LineToPC


func (t *Table) LineToPC(file string, line int) (pc uint64, fn *Func, err os.Error) LineToPC looks up the first program counter on the given line in the named file. Returns UnknownPathError or UnknownLineError if there is an error looking up this line.

func (*Table) LookupFunc


func (t *Table) LookupFunc(name string) *Func LookupFunc returns the text, data, or bss symbol with the given name, or nil if no such symbol is found.

func (*Table) LookupSym


func (t *Table) LookupSym(name string) *Sym LookupSym returns the text, data, or bss symbol with the given name, or nil if no such symbol is found.

func (*Table) PCToFunc


func (t *Table) PCToFunc(pc uint64) *Func PCToFunc returns the function containing the program counter pc, or nil if there is no such function.

func (*Table) PCToLine


func (t *Table) PCToLine(pc uint64) (file string, line int, fn *Func) PCToLine looks up line number information for a program counter. If there is no information, it returns fn == nil.

func (*Table) Sym ByAddr


func (t *Table) SymByAddr(addr uint64) *Sym SymByAddr returns the text, data, or bss symbol starting at the given address. TODO(rsc): Allow lookup by any address within the symbol.

type UnknownFileError
UnknownFileError represents a failure to find the specific file in the symbol table.
type UnknownFileError string

func (Unknow nFileError) String


func (e UnknownFileError) String() string

type UnknownLineError
UnknownLineError represents a failure to map a line to a program counter, either because the line is beyond the bounds of the file or because there is no code on the given line.
type UnknownLineError struct { File string Line int }

func (*Unknow nLineError) String

func (e *UnknownLineError) String() string

Except as noted, this content is licensed under Creative Commons Attribution 3.0.

The Go Programming Language

Package macho
Constants type Cpu func (Cpu) GoString func (Cpu) String type File func NewFile func Open func (*File) Close func (*File) DWARF func (*File) Section func (*File) Segment type FileHeader type FormatError func (*FormatError) String type Load type LoadBytes func (LoadBytes) Raw type LoadCmd func (LoadCmd) GoString import "debug/macho" Package macho implements access to Mach-O object files, as defined by http://developer.apple.com /mac/library/documentation/DeveloperTools/Conceptual/MachORuntime/Reference/reference.html. Package files
f ile.go macho.go

type type type

type type type type

type type type type type

func (LoadCmd) String Regs386 RegsAMD64 Section func (*Section) Data func (*Section) Open Section32 Section64 SectionHeader Segment func (*Segment) Data func (*Segment) Open Segment32 Segment64 SegmentHeader Thread Type

Constants
const ( Magic32 uint32 = 0xfeedface Magic64 uint32 = 0xfeedfacf )

type Cpu
A Cpu is a Mach-O cpu type.
type Cpu uint32

const ( Cpu386 Cpu = 7 CpuAmd64 Cpu = Cpu386 + 1<<24 )

func (Cpu) GoString


func (i Cpu) GoString() string

func (Cpu) String


func (i Cpu) String() string

type File
A File represents an open Mach-O file.
type File struct { FileHeader ByteOrder binary.ByteOrder Loads []Load Sections []*Section // contains unexported fields }

func New File


func NewFile(r io.ReaderAt) (*File, os.Error) NewFile creates a new File for acecssing a Mach-O binary in an underlying reader. The Mach-O binary is expected to start at position 0 in the ReaderAt.

func Open
func Open(name string) (*File, os.Error) Open opens the named file using os.Open and prepares it for use as a Mach-O binary.

func (*File) Close


func (f *File) Close() os.Error Close closes the File. If the File was created using NewFile directly instead of Open, Close has no effect.

func (*File) DWARF


func (f *File) DWARF() (*dwarf.Data, os.Error) DWARF returns the DWARF debug information for the Mach-O file.

func (*File) Section


func (f *File) Section(name string) *Section Section returns the first section with the given name, or nil if no such section exists.

func (*File) Segm ent


func (f *File) Segment(name string) *Segment Segment returns the first Segment with the given name, or nil if no such segment exists.

type FileHeader
A FileHeader represents a Mach-O file header.
type FileHeader struct { Magic uint32 Cpu Cpu SubCpu uint32 Type Type Ncmd uint32 Cmdsz uint32 Flags uint32 }

type FormatError
type FormatError struct { // contains unexported fields }

func (*Form atError) String


func (e *FormatError) String() string

type Load
A Load represents any Mach-O load command.
type Load interface { Raw() []byte }

type LoadBytes
A LoadBytes is the uninterpreted bytes of a Mach-O load command.
type LoadBytes []byte

func (LoadBytes) Raw


func (b LoadBytes) Raw() []byte

type LoadCmd
A LoadCmd is a Mach-O load command.
type LoadCmd uint32

const ( LoadCmdSegment LoadCmdSegment64 LoadCmdThread LoadCmdUnixThread )

LoadCmd LoadCmd LoadCmd LoadCmd

= = = =

1 25 4 5 // thread+stack

func (LoadCm d) GoString


func (i LoadCmd) GoString() string

func (LoadCm d) String


func (i LoadCmd) String() string

type Regs386
Regs386 is the Mach-O 386 register structure.
type Regs386 struct { AX uint32 BX uint32 CX uint32 DX uint32 DI uint32 SI uint32 BP uint32 SP uint32 SS uint32 FLAGS uint32 IP uint32 CS uint32 DS uint32 ES uint32 FS uint32 GS uint32 }

type RegsAMD64
RegsAMD64 is the Mach-O AMD64 register structure.

type RegsAMD64 struct { AX uint64 BX uint64 CX uint64 DX uint64 DI uint64 SI uint64 BP uint64 SP uint64 R8 uint64 R9 uint64 R10 uint64 R11 uint64 R12 uint64 R13 uint64 R14 uint64 R15 uint64 IP uint64 FLAGS uint64 CS uint64 FS uint64 GS uint64 }

type Section
type Section struct { SectionHeader // Embed ReaderAt for ReadAt method. // Do not embed SectionReader directly // to avoid having Read and Seek. // If a client wants Read and Seek it must use // Open() to avoid fighting over the seek offset // with other clients. io.ReaderAt // contains unexported fields }

func (*Section) Data


func (s *Section) Data() ([]byte, os.Error) Data reads and returns the contents of the Mach-O section.

func (*Section) Open


func (s *Section) Open() io.ReadSeeker Open returns a new ReadSeeker reading the Mach-O section.

type Section32
A Section32 is a 32-bit Mach-O section header.

type Section32 struct { Name [16]byte Seg [16]byte Addr uint32 Size uint32 Offset uint32 Align uint32 Reloff uint32 Nreloc uint32 Flags uint32 Reserve1 uint32 Reserve2 uint32 }

type Section64
A Section32 is a 64-bit Mach-O section header.
type Section64 struct { Name [16]byte Seg [16]byte Addr uint64 Size uint64 Offset uint32 Align uint32 Reloff uint32 Nreloc uint32 Flags uint32 Reserve1 uint32 Reserve2 uint32 Reserve3 uint32 }

type SectionHeader
type SectionHeader struct { Name string Seg string Addr uint64 Size uint64 Offset uint32 Align uint32 Reloff uint32 Nreloc uint32 Flags uint32 }

type Segment
A Segment represents a Mach-O 32-bit or 64-bit load segment command.

type Segment struct { LoadBytes SegmentHeader // Embed ReaderAt for ReadAt method. // Do not embed SectionReader directly // to avoid having Read and Seek. // If a client wants Read and Seek it must use // Open() to avoid fighting over the seek offset // with other clients. io.ReaderAt // contains unexported fields }

func (*Segm ent) Data


func (s *Segment) Data() ([]byte, os.Error) Data reads and returns the contents of the segment.

func (*Segm ent) Open


func (s *Segment) Open() io.ReadSeeker Open returns a new ReadSeeker reading the segment.

type Segment32
A Segment32 is a 32-bit Mach-O segment load command.
type Segment32 struct { Cmd LoadCmd Len uint32 Name [16]byte Addr uint32 Memsz uint32 Offset uint32 Filesz uint32 Maxprot uint32 Prot uint32 Nsect uint32 Flag uint32 }

type Segment64
A Segment64 is a 64-bit Mach-O segment load command.

type Segment64 struct { Cmd LoadCmd Len uint32 Name [16]byte Addr uint64 Memsz uint64 Offset uint64 Filesz uint64 Maxprot uint32 Prot uint32 Nsect uint32 Flag uint32 }

type SegmentHeader
A SegmentHeader is the header for a Mach-O 32-bit or 64-bit load segment command.
type SegmentHeader struct { Cmd LoadCmd Len uint32 Name string Addr uint64 Memsz uint64 Offset uint64 Filesz uint64 Maxprot uint32 Prot uint32 Nsect uint32 Flag uint32 }

type Thread
A Thread is a Mach-O thread state command.
type Thread struct { Cmd LoadCmd Len uint32 Type uint32 Data []uint32 }

type Type
A Type is a Mach-O file type, either an object or an executable.
type Type uint32

const ( TypeObj Type = 1 TypeExec Type = 2 )

Except as noted, this content is licensed under Creative Commons Attribution 3.0.

The Go Programming Language

Package proc
type Breakpoint func (Breakpoint) PC func (Breakpoint) String type Cause type Process func Attach func ForkExec type ProcessExited func (ProcessExited) String type Regs type Signal func (Signal) Name func (Signal) String type Stopped import "debug/proc" Package ptrace provides a platform-independent interface for tracing and controlling running processes. It supports multi-threaded processes and provides typical low-level debugging controls such as breakpoints, single stepping, and manipulating memory and registers. Package files
proc.go proc_darwin.go proc_f reebsd.go proc_linux.go proc_mingw.go proc_nacl.go regs_darwin_386.go regs_darwin_amd64.go regs_f reebsd_386.go regs_f reebsd_amd64.go regs_linux_386.go regs_linux_amd64.go regs_linux_arm.go regs_mingw_386.go regs_mingw_amd64.go regs_nacl_386.go

type type

type

type

func (Stopped) String Thread ThreadCreate func (*ThreadCreate) NewThread func (*ThreadCreate) String ThreadExit func (*ThreadExit) ExitStatus func (*ThreadExit) Exited func (*ThreadExit) Signaled func (*ThreadExit) StopSignal func (*ThreadExit) String Word

type Breakpoint
Breakpoint is a stop cause resulting from a thread reaching a set breakpoint.
type Breakpoint Word

func (Breakpoint) PC
func (c Breakpoint) PC() Word PC returns the program counter that the program is stopped at.

func (Breakpoint) String


func (c Breakpoint) String() string

type Cause

A Cause explains why a thread is stopped.


type Cause interface { String() string }

type Process
Process is a process being traced. It consists of a set of threads. A process can be running, stopped, or terminated. The process's state extends to all of its threads.
type Process interface { // Threads returns an array of all threads in this process. Threads() []Thread // AddBreakpoint creates a new breakpoint at program counter // pc. Breakpoints can only be created when the process is // stopped. It is an error if a breakpoint already exists at // pc. AddBreakpoint(pc Word) os.Error // RemoveBreakpoint removes the breakpoint at the program // counter pc. It is an error if no breakpoint exists at pc. RemoveBreakpoint(pc Word) os.Error // Stop stops all running threads in this process before // returning. Stop() os.Error // Continue resumes execution of all threads in this process. // Any thread that is stopped on a breakpoint will be stepped // over that breakpoint. Any thread that is stopped because // of a signal (other than SIGSTOP or SIGTRAP) will receive // the pending signal. Continue() os.Error // WaitStop waits until all threads in process p are stopped // as a result of some thread hitting a breakpoint, receiving // a signal, creating a new thread, or exiting. WaitStop() os.Error // Detach detaches from this process. // will be resumed. Detach() os.Error } All stopped threads

func Attach
func Attach(pid int) (Process, os.Error) Attach attaches to process pid and stops all of its threads.

func ForkExec
func ForkExec(argv0 string, argv []string, envv []string, dir string, fd []*os.File) (Process, os.Error)

ForkExec forks the current process and execs argv0, stopping the new process after the exec syscall. See os.ForkExec for additional details.

type ProcessExited
type ProcessExited struct{}

func (ProcessExited) String


func (p ProcessExited) String() string

type Regs
Regs is a set of named machine registers, including a program counter, link register, and stack pointer. TODO(austin) There's quite a proliferation of methods here. We could make a Reg interface with Get and Set and make this just PC, Link, SP, Names, and Reg. We could also put Index in Reg and that makes it easy to get the index of things like the PC (currently there's just no way to know that). This would also let us include other per-register information like how to print it.
type Regs interface { // PC returns the value of the program counter. PC() Word // SetPC sets the program counter to val. SetPC(val Word) os.Error // Link returns the link register, if any. Link() Word // SetLink sets the link register to val. SetLink(val Word) os.Error // SP returns the value of the stack pointer. SP() Word // SetSP sets the stack pointer register to val. SetSP(val Word) os.Error // Names returns the names of all of the registers. Names() []string // Get returns the value of a register, where i corresponds to // the index of the register's name in the array returned by // Names. Get(i int) Word // Set sets the value of a register. Set(i int, val Word) os.Error }

type Signal

Signal is a stop cause resulting from a thread receiving a signal. When the process is continued, the signal will be delivered.
type Signal string

func (Signal) Nam e


func (c Signal) Name() string Signal returns the signal being delivered to the thread.

func (Signal) String


func (c Signal) String() string

type Stopped
Stopped is a stop cause used for threads that are stopped either by user request (e.g., from the Stop method or after single stepping), or that are stopped because some other thread caused the program to stop.
type Stopped struct{}

func (Stopped) String


func (c Stopped) String() string

type Thread
Thread is a thread in the process being traced.

type Thread interface { // Step steps this thread by a single instruction. The thread // must be stopped. If the thread is currently stopped on a // breakpoint, this will step over the breakpoint. // // XXX What if it's stopped because of a signal? Step() os.Error // Stopped returns the reason that this thread is stopped. // is an error is the thread not stopped. Stopped() (Cause, os.Error) // Regs retrieves the current register values from this // thread. The thread must be stopped. Regs() (Regs, os.Error) // Peek reads len(out) bytes from the address addr in this // thread into out. The thread must be stopped. It returns // the number of bytes successfully read. If an error occurs, // such as attempting to read unmapped memory, this count // could be short and an error will be returned. If this does // encounter unmapped memory, it will read up to the byte // preceding the unmapped area. Peek(addr Word, out []byte) (int, os.Error) // Poke writes b to the address addr in this thread. The // thread must be stopped. It returns the number of bytes // successfully written. If an error occurs, such as // attempting to write to unmapped memory, this count could be // short and an error will be returned. If this does // encounter unmapped memory, it will write up to the byte // preceding the unmapped area. Poke(addr Word, b []byte) (int, os.Error) } It

type ThreadCreate
ThreadCreate is a stop cause returned from an existing thread when it creates a new thread. The new thread exists in a primordial form at this point and will begin executing in earnest when the process is continued.
type ThreadCreate struct { // contains unexported fields }

func (*ThreadCreate) New Thread


func (c *ThreadCreate) NewThread() Thread

func (*ThreadCreate) String


func (c *ThreadCreate) String() string

type ThreadExit
ThreadExit is a stop cause resulting from a thread exiting. When this cause first arises, the thread will still be

in the list of process threads and its registers and memory will still be accessible.
type ThreadExit struct { // contains unexported fields }

func (*ThreadExit) ExitStatus


func (c *ThreadExit) ExitStatus() int ExitStatus returns the exit status of the thread if it exited normally or -1 otherwise.

func (*ThreadExit) Exited


func (c *ThreadExit) Exited() bool Exited returns true if the thread exited normally.

func (*ThreadExit) Signaled


func (c *ThreadExit) Signaled() bool Signaled returns true if the thread was terminated by a signal.

func (*ThreadExit) StopSignal


func (c *ThreadExit) StopSignal() string StopSignal returns the signal that terminated the thread, or "" if it was not terminated by a signal.

func (*ThreadExit) String


func (c *ThreadExit) String() string

type Word
type Word uint64

Except as noted, this content is licensed under Creative Commons Attribution 3.0.

The Go Programming Language

Package ebnf
func Verify type Alternative func (Alternative) Pos type Expression type Grammar func Parse type Group type Name type Option type Production import "ebnf" A library for EBNF grammars. The input is text ([]byte) satisfying the following grammar (represented itself in EBNF):
Production Expression Alternative Term Group Option Repetition = = = = = = = name "=" Expression "." . Alternative { "|" Alternative } . Term { Term } . name | token [ "..." token ] | Group | Option | Repetition . "(" Expression ")" . "[" Expression "]" . "{" Expression "}" .

func (*Production) Pos type Range func (Range) Pos type Repetition type Sequence func (Sequence) Pos type Token

A name is a Go identifier, a token is a Go string, and comments and white space follow the same rules as for the Go language. Production names starting with an uppercase Unicode letter denote non-terminal productions (i.e., productions which allow white-space and comments between tokens); all other production names denote lexical productions. Package files
ebnf .go parser.go

func Verify
func Verify(grammar Grammar, start string) os.Error Verify checks that:
- all productions used are defined - all productions defined are used when beginning at start - lexical productions refer only to other lexical productions

type Alternative

An Alternative node represents a non-empty list of alternative expressions.


type Alternative []Expression // x | y | z

func (Alternative) Pos


func (x Alternative) Pos() token.Position

type Expression
An Expression node represents a production expression.
type Expression interface { // Pos is the position of the first character of the syntactic construct Pos() token.Position }

type Grammar
A Grammar is a set of EBNF productions. The map is indexed by production name.
type Grammar map[string]*Production

func Parse
func Parse(filename string, src []byte) (Grammar, os.Error) Parse parses a set of EBNF productions from source src. It returns a set of productions. Errors are reported for incorrect syntax and if a production is declared more than once.

type Group
A Group node represents a grouped expression.
type Group struct { token.Position Body Expression // (body) }

type Name
A Name node represents a production name.

type Name struct { token.Position String string }

type Option
An Option node represents an optional expression.
type Option struct { token.Position Body Expression // [body] }

type Production
A Production node represents an EBNF production.
type Production struct { Name *Name Expr Expression }

func (*Production) Pos


func (p *Production) Pos() token.Position

type Range
A List node represents a range of characters.
type Range struct { Begin, End *Token // begin ... end }

func (Range) Pos


func (x Range) Pos() token.Position

type Repetition
A Repetition node represents a repeated expression.

type Repetition struct { token.Position Body Expression // {body} }

type Sequence
A Sequence node represents a non-empty list of sequential expressions.
type Sequence []Expression // x y z

func (Sequence) Pos


func (x Sequence) Pos() token.Position

type Token
A Token node represents a literal.
type Token struct { token.Position String string }

Except as noted, this content is licensed under Creative Commons Attribution 3.0.

The Go Programming Language

Package ascii85
func Decode func Encode func MaxEncodedLen func NewDecoder func NewEncoder type CorruptInputError func (CorruptInputError) String import "encoding/ascii85" Package ascii85 implements the ascii85 data encoding as used in the btoa tool and Adobe's PostScript and PDF document formats. Package files
ascii85.go

func Decode
func Decode(dst, src []byte, flush bool) (ndst, nsrc int, err os.Error) Decode decodes src into dst, returning both the number of bytes written to dst and the number consumed from src. If src contains invalid ascii85 data, Decode will return the number of bytes successfully written and a CorruptInputError. Decode ignores space and control characters in src. Often, ascii85-encoded data is wrapped in <~ and ~> symbols. Decode expects these to have been stripped by the caller. If flush is true, Decode assumes that src represents the end of the input stream and processes it completely rather than wait for the completion of another 32-bit block. NewDecoder wraps an io.Reader interface around Decode.

func Encode
func Encode(dst, src []byte) int Encode encodes src into at most MaxEncodedLen(len(src)) bytes of dst, returning the actual number of bytes written. The encoding handles 4-byte chunks, using a special encoding for the last fragment, so Encode is not appropriate for use on individual blocks of a large data stream. Use NewEncoder() instead. Often, ascii85-encoded data is wrapped in <~ and ~> symbols. Encode does not add these.

func MaxEncodedLen

func MaxEncodedLen(n int) int MaxEncodedLen returns the maximum length of an encoding of n source bytes.

func NewDecoder
func NewDecoder(r io.Reader) io.Reader NewDecoder constructs a new ascii85 stream decoder.

func NewEncoder
func NewEncoder(w io.Writer) io.WriteCloser NewEncoder returns a new ascii85 stream encoder. Data written to the returned writer will be encoded and then written to w. Ascii85 encodings operate in 32-bit blocks; when finished writing, the caller must Close the returned encoder to flush any trailing partial block.

type CorruptInputError
type CorruptInputError int64

func (CorruptInputError) String


func (e CorruptInputError) String() string

Except as noted, this content is licensed under Creative Commons Attribution 3.0.

The Go Programming Language

Package base64
Variables func NewDecoder func NewEncoder type CorruptInputError func (CorruptInputError) String type Encoding func NewEncoding func (*Encoding) Decode func (*Encoding) DecodedLen func (*Encoding) Encode func (*Encoding) EncodedLen import "encoding/base64" Package base64 implements base64 encoding as specified by RFC 4648. Package files
base64.go

Variables
StdEncoding is the standard base64 encoding, as defined in RFC 4648.
var StdEncoding = NewEncoding(encodeStd)

URLEncoding is the alternate base64 encoding defined in RFC 4648. It is typically used in URLs and file names.
var URLEncoding = NewEncoding(encodeURL)

func NewDecoder
func NewDecoder(enc *Encoding, r io.Reader) io.Reader NewDecoder constructs a new base64 stream decoder.

func NewEncoder
func NewEncoder(enc *Encoding, w io.Writer) io.WriteCloser NewEncoder returns a new base64 stream encoder. Data written to the returned writer will be encoded using

enc and then written to w. Base64 encodings operate in 4-byte blocks; when finished writing, the caller must Close the returned encoder to flush any partially written blocks.

type CorruptInputError
type CorruptInputError int64

func (CorruptInputError) String


func (e CorruptInputError) String() string

type Encoding
An Encoding is a radix 64 encoding/decoding scheme, defined by a 64-character alphabet. The most common encoding is the "base64" encoding defined in RFC 4648 and used in MIME (RFC 2045) and PEM (RFC 1421). RFC 4648 also defines an alternate encoding, which is the standard encoding with - and _ substituted for + and /.
type Encoding struct { // contains unexported fields }

func New Encoding


func NewEncoding(encoder string) *Encoding NewEncoding returns a new Encoding defined by the given alphabet, which must be a 64-byte string.

func (*Encoding) Decode


func (enc *Encoding) Decode(dst, src []byte) (n int, err os.Error) Decode decodes src using the encoding enc. It writes at most DecodedLen(len(src)) bytes to dst and returns the number of bytes written. If src contains invalid base64 data, it will return the number of bytes successfully written and CorruptInputError.

func (*Encoding) DecodedLen


func (enc *Encoding) DecodedLen(n int) int DecodedLen returns the maximum length in bytes of the decoded data corresponding to n bytes of base64encoded data.

func (*Encoding) Encode


func (enc *Encoding) Encode(dst, src []byte) Encode encodes src using the encoding enc, writing EncodedLen(len(src)) bytes to dst. The encoding pads the output to a multiple of 4 bytes, so Encode is not appropriate for use on individual blocks of a large data stream. Use NewEncoder() instead.

func (*Encoding) EncodedLen

func (enc *Encoding) EncodedLen(n int) int EncodedLen returns the length in bytes of the base64 encoding of an input buffer of length n.

Except as noted, this content is licensed under Creative Commons Attribution 3.0.

The Go Programming Language

Package binary
func Read func TotalSize func Write type ByteOrder import "encoding/binary" This package implements translation between unsigned integer values and byte sequences. Package files
binary .go

func Read
func Read(r io.Reader, order ByteOrder, data interface{}) os.Error Read reads structured binary data from r into data. Data must be a pointer to a fixed-size value or a slice of fixed-size values. A fixed-size value is either a fixed-size integer (int8, uint8, int16, uint16, ...) or an array or struct containing only fixed-size values. Bytes read from r are decoded using the specified byte order and written to successive fields of the data.

func TotalSize
func TotalSize(v reflect.Value) int

func Write
func Write(w io.Writer, order ByteOrder, data interface{}) os.Error Write writes the binary representation of data into w. Data must be a fixed-size value or a pointer to a fixed-size value. A fixed-size value is either a fixed-size integer (int8, uint8, int16, uint16, ...) or an array or struct containing only fixed-size values. Bytes written to w are encoded using the specified byte order and read from successive fields of the data.

type ByteOrder
A ByteOrder specifies how to convert byte sequences into 16-, 32-, or 64-bit unsigned integers.

type ByteOrder interface { Uint16(b []byte) uint16 Uint32(b []byte) uint32 Uint64(b []byte) uint64 PutUint16([]byte, uint16) PutUint32([]byte, uint32) PutUint64([]byte, uint64) String() string }

var BigEndian ByteOrder = bigEndian(0)

var LittleEndian ByteOrder = littleEndian(0)

Except as noted, this content is licensed under Creative Commons Attribution 3.0.

The Go Programming Language

Package git85
func Decode func Encode func EncodedLen func MaxDecodedLen func NewDecoder func NewEncoder type CorruptInputError func (CorruptInputError) String import "encoding/git85" Package git85 implements the radix 85 data encoding used in the Git version control system. Package files
git.go

func Decode
func Decode(dst, src []byte) (n int, err os.Error) Decode decodes src into at most MaxDecodedLen(len(src)) bytes, returning the actual number of bytes written to dst. If Decode encounters invalid input, it returns a CorruptInputError.

func Encode
func Encode(dst, src []byte) int Encode encodes src into EncodedLen(len(src)) bytes of dst. As a convenience, it returns the number of bytes written to dst, but this value is always EncodedLen(len(src)). Encode implements the radix 85 encoding used in the Git version control tool. The encoding splits src into chunks of at most 52 bytes and encodes each chunk on its own line.

func EncodedLen
func EncodedLen(n int) int EncodedLen returns the length of an encoding of n source bytes.

func MaxDecodedLen

func MaxDecodedLen(n int) int

func NewDecoder
func NewDecoder(r io.Reader) io.Reader NewDecoder returns a new Git base85 stream decoder.

func NewEncoder
func NewEncoder(w io.Writer) io.WriteCloser NewEncoder returns a new Git base85 stream encoder. Data written to the returned writer will be encoded and then written to w. The Git encoding operates on 52-byte blocks; when finished writing, the caller must Close the returned encoder to flush any partially written blocks.

type CorruptInputError
type CorruptInputError int64

func (CorruptInputError) String


func (e CorruptInputError) String() string

Except as noted, this content is licensed under Creative Commons Attribution 3.0.

The Go Programming Language

Package hex
func Decode func DecodeString func DecodedLen func Encode func EncodeToString func EncodedLen type InvalidHexCharError func (InvalidHexCharError) String type OddLengthInputError func (OddLengthInputError) String import "encoding/hex" This package implements hexadecimal encoding and decoding. Package files
hex.go

func Decode
func Decode(dst, src []byte) (int, os.Error) Decode decodes src into DecodedLen(len(src)) bytes, returning the actual number of bytes written to dst. If Decode encounters invalid input, it returns an OddLengthInputError or an InvalidHexCharError.

func DecodeString
func DecodeString(s string) ([]byte, os.Error) DecodeString returns the bytes represented by the hexadecimal string s.

func DecodedLen
func DecodedLen(x int) int

func Encode
func Encode(dst, src []byte) int Encode encodes src into EncodedLen(len(src)) bytes of dst. As a convenience, it returns the number of bytes written to dst, but this value is always EncodedLen(len(src)). Encode implements hexadecimal encoding.

func EncodeToString
func EncodeToString(src []byte) string EncodeToString returns the hexadecimal encoding of src.

func EncodedLen
func EncodedLen(n int) int EncodedLen returns the length of an encoding of n source bytes.

type InvalidHexCharError
InvalidHexCharError results from finding an invalid character in a hex string.
type InvalidHexCharError byte

func (InvalidHexCharError) String


func (e InvalidHexCharError) String() string

type OddLengthInputError
OddLengthInputError results from decoding an odd length slice.
type OddLengthInputError struct{}

func (OddLengthInputError) String


func (OddLengthInputError) String() string

Except as noted, this content is licensed under Creative Commons Attribution 3.0.

The Go Programming Language

Package pem
func Encode func EncodeToMemory type Block func Decode import "encoding/pem" This package 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. Package files
pem.go

func Encode
func Encode(out io.Writer, b *Block) (err os.Error)

func EncodeToMemory
func EncodeToMemory(b *Block) []byte

type Block
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.


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. }

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.

Except as noted, this content is licensed under Creative Commons Attribution 3.0.

The Go Programming Language

Package exec
Constants func LookPath type Cmd func Run func (*Cmd) Close func (*Cmd) Wait import "exec" The exec package runs external commands. Package files
exec.go

Constants
Arguments to Run.
const ( DevNull = iota PassThrough Pipe MergeWithStdout )

func LookPath
func LookPath(file string) (string, os.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. TODO(rsc): Does LookPath belong in os instead?

type Cmd
A Cmd represents a running command. Stdin, Stdout, and Stderr are Files representing pipes connected to the running command's standard input, output, and error, or else nil, depending on the arguments to Run. Pid is the running command's operating system process ID.

type Cmd struct { Stdin *os.File Stdout *os.File Stderr *os.File Pid int }

func Run
func Run(argv0 string, argv, envv []string, dir string, stdin, stdout, stderr int) (p *Cmd, err os.Error) Run starts the binary prog running with arguments argv and environment envv. It returns a pointer to a new Cmd representing the command or an error. The parameters stdin, stdout, and stderr specify how to handle standard input, output, and error. The choices are DevNull (connect to /dev/null), PassThrough (connect to the current process's standard stream), Pipe (connect to an operating system pipe), and MergeWithStdout (only for standard error; use the same file descriptor as was used for standard output). If a parameter is Pipe, then the corresponding field (Stdin, Stdout, Stderr) of the returned Cmd is the other end of the pipe. Otherwise the field in Cmd is nil.

func (*Cm d) Close


func (p *Cmd) Close() os.Error Close waits for the running command p to exit, if it hasn't already, and then closes the non-nil file descriptors p.Stdin, p.Stdout, and p.Stderr.

func (*Cm d) Wait


func (p *Cmd) Wait(options int) (*os.Waitmsg, os.Error) Wait waits for the running command p, returning the Waitmsg returned by os.Wait and an error. The options are passed through to os.Wait. Setting options to 0 waits for p to exit; other options cause Wait to return for other process events; see package os for details.

Except as noted, this content is licensed under Creative Commons Attribution 3.0.

The Go Programming Language

Package datafmt
type Environment type Format func Parse func (Format) Eval func (Format) Fprint func (Format) Print func (Format) Sprint type Formatter import "exp/datafmt" The datafmt package implements syntax-directed, type-driven formatting of arbitrary data structures. Formatting a data structure consists of two phases: first, a parser reads a format specification and builds a "compiled" format. Then, the format can be applied repeatedly to arbitrary values. Applying a format to a value evaluates to a []byte containing the formatted value bytes, or nil. A format specification is a set of package declarations and format rules:
Format Entry = [ Entry { ";" Entry } [ ";" ] ] . = PackageDecl | FormatRule .

type FormatterMap type State func (*State) Env func (*State) LinePos func (*State) Pos func (*State) Write

(The syntax of a format specification is presented in the same EBNF notation as used in the Go language specification. The syntax of white space, comments, identifiers, and string literals is the same as in Go.) A package declaration binds a package name (such as 'ast') to a package import path (such as '"go/ast"'). Each package used (in a type name, see below) must be declared once before use.
PackageDecl = PackageName ImportPath . PackageName = identifier . ImportPath = string .

A format rule binds a rule name to a format expression. A rule name may be a type name or one of the special names 'default' or '/'. A type name may be the name of a predeclared type (for example, 'int', 'float32', etc.), the package-qualified name of a user-defined type (for example, 'ast.MapType'), or an identifier indicating the structure of unnamed composite types ('array', 'chan', 'func', 'interface', 'map', or 'ptr'). Each rule must have a unique name; rules can be declared in any order.
FormatRule RuleName TypeName = RuleName "=" Expression . = TypeName | "default" | "/" . = [ PackageName "." ] identifier .

To format a value, the value's type name is used to select the format rule (there is an override mechanism, see below). The format expression of the selected rule specifies how the value is formatted. Each format expression, when applied to a value, evaluates to a byte sequence or nil. In its most general form, a format expression is a list of alternatives, each of which is a sequence of

operands:
Expression Sequence = [ Sequence ] { "|" [ Sequence ] } . = Operand { Operand } .

The formatted result produced by an expression is the result of the first alternative sequence that evaluates to a non-nil result; if there is no such alternative, the expression evaluates to nil. The result produced by an operand sequence is the concatenation of the results of its operands. If any operand in the sequence evaluates to nil, the entire sequence evaluates to nil. There are five kinds of operands:
Operand = Literal | Field | Group | Option | Repetition .

Literals evaluate to themselves, with two substitutions. First, %-formats expand in the manner of fmt.Printf, with the current value passed as the parameter. Second, the current indentation (see below) is inserted after every newline or form feed character.
Literal = string .

This table shows string literals applied to the value 42 and the corresponding formatted result:
"foo" "%x" "x = %d" "%#x = %d" foo 2a x = 42 0x2a = 42

A field operand is a field name optionally followed by an alternate rule name. The field name may be an identifier or one of the special names @ or *.
Field FieldName = FieldName [ ":" RuleName ] . = identifier | "@" | "*" .

If the field name is an identifier, the current value must be a struct, and there must be a field with that name in the struct. The same lookup rules apply as in the Go language (for instance, the name of an anonymous field is the unqualified type name). The field name denotes the field value in the struct. If the field is not found, formatting is aborted and an error message is returned. (TODO consider changing the semantics such that if a field is not found, it evaluates to nil). The special name '@' denotes the current value. The meaning of the special name '*' depends on the type of the current value:
array, slice types interfaces pointers array, slice element (inside {} only, see below) value stored in interface value pointed to by pointer

(Implementation restriction: channel, function and map types are not supported due to missing reflection support). Fields are evaluated as follows: If the field value is nil, or an array or slice element does not exist, the result is nil (see below for details on array/slice elements). If the value is not nil the field value is formatted

(recursively) using the rule corresponding to its type name, or the alternate rule name, if given. The following example shows a complete format specification for a struct 'myPackage.Point'. Assume the package
package myPackage // in directory myDir/myPackage type Point struct { name string; x, y int; }

Applying the format specification


myPackage "myDir/myPackage"; int = "%d"; hexInt = "0x%x"; string = "---%s---"; myPackage.Point = name "{" x ", " y:hexInt "}";

to the value myPackage.Point{"foo", 3, 15} results in


---foo---{3, 0xf}

Finally, an operand may be a grouped, optional, or repeated expression. A grouped expression ("group") groups a more complex expression (body) so that it can be used in place of a single operand:
Group = "(" [ Indentation ">>" ] Body ")" . Indentation = Expression . Body = Expression .

A group body may be prefixed by an indentation expression followed by '>>'. The indentation expression is applied to the current value like any other expression and the result, if not nil, is appended to the current indentation during the evaluation of the body (see also formatting state, below). An optional expression ("option") is enclosed in '[]' brackets.
Option = "[" Body "]" .

An option evaluates to its body, except that if the body evaluates to nil, the option expression evaluates to an empty []byte. Thus an option's purpose is to protect the expression containing the option from a nil operand. A repeated expression ("repetition") is enclosed in '{}' braces.
Repetition Separator = "{" Body [ "/" Separator ] "}" . = Expression .

A repeated expression is evaluated as follows: The body is evaluated repeatedly and its results are concatenated until the body evaluates to nil. The result of the repetition is the (possibly empty) concatenation, but it is never nil. An implicit index is supplied for the evaluation of the body: that index is used to address elements of arrays or slices. If the corresponding elements do not exist, the field denoting the element evaluates to nil (which in turn may terminate the repetition).

The body of a repetition may be followed by a '/' and a "separator" expression. If the separator is present, it is invoked between repetitions of the body. The following example shows a complete format specification for formatting a slice of unnamed type. Applying the specification
int = "%b"; array = { * / ", " };

// array is the type name for an unnamed slice

to the value '[]int{2, 3, 5, 7}' results in


10, 11, 101, 111

Default rule: If a format rule named 'default' is present, it is used for formatting a value if no other rule was found. A common default rule is
default = "%v"

to provide default formatting for basic types without having to specify a specific rule for each basic type. Global separator rule: If a format rule named '/' is present, it is invoked with the current value between literals. If the separator expression evaluates to nil, it is ignored. For instance, a global separator rule may be used to punctuate a sequence of values with commas. The rules:
default = "%v"; / = ", ";

will format an argument list by printing each one in its default format, separated by a comma and a space. Package files
dataf mt.go parser.go

type Environment
An application-specific environment may be provided to Format.Apply; the environment is available inside custom formatters via State.Env(). Environments must implement copying; the Copy method must return an complete copy of the receiver. This is necessary so that the formatter can save and restore an environment (in case of an absent expression). If the Environment doesn't change during formatting (this is under control of the custom formatters), the Copy function can simply return the receiver, and thus can be very light-weight.
type Environment interface { Copy() Environment }

type Format

A Format is the result of parsing a format specification. The format may be applied repeatedly to format values.
type Format map[string]expr

func Parse
func Parse(filename string, src []byte, fmap FormatterMap) (Format, os.Error) Parse parses a set of format productions from source src. Custom formatters may be provided via a map of formatter functions. If there are no errors, the result is a Format and the error is nil. Otherwise the format is nil and a non-empty ErrorList is returned.

func (Form at) Eval


func (f Format) Eval(env Environment, args ...) ([]byte, os.Error) Eval formats each argument according to the format f and returns the resulting []byte and os.Error. If an error occured, the []byte contains the partially formatted result. An environment env may be passed in which is available in custom formatters through the state parameter.

func (Form at) Fprint


func (f Format) Fprint(w io.Writer, env Environment, args ...) (int, os.Error) Fprint formats each argument according to the format f and writes to w. The result is the total number of bytes written and an os.Error, if any.

func (Form at) Print


func (f Format) Print(args ...) (int, os.Error) Print formats each argument according to the format f and writes to standard output. The result is the total number of bytes written and an os.Error, if any.

func (Form at) Sprint


func (f Format) Sprint(args ...) string Sprint formats each argument according to the format f and returns the resulting string. If an error occurs during formatting, the result string contains the partially formatted result followed by an error message.

type Formatter
Custom formatters implement the Formatter function type. A formatter is invoked with the current formatting state, the value to format, and the rule name under which the formatter was installed (the same formatter function may be installed under different names). The formatter may access the current state to guide formatting and use State.Write to append to the state's output. A formatter must return a boolean value indicating if it evaluated to a non-nil value (true), or a nil value (false).
type Formatter func(state *State, value interface{}, ruleName string) bool

type FormatterMap
A FormatterMap is a set of custom formatters. It maps a rule name to a formatter function.
type FormatterMap map[string]Formatter

type State
State represents the current formatting state. It is provided as argument to custom formatters.
type State struct { // contains unexported fields }

func (*State) Env


func (s *State) Env() interface{} Env returns the environment passed to Format.Apply.

func (*State) LinePos


func (s *State) LinePos() token.Position LinePos returns the position of the current line beginning in the state's output buffer. Line numbers start at 1.

func (*State) Pos


func (s *State) Pos() token.Position Pos returns the position of the next byte to be written to the output buffer. Line numbers start at 1.

func (*State) Write


func (s *State) Write(data []byte) (int, os.Error) Write writes data to the output buffer, inserting the indentation string after each newline or form feed character. It cannot return an error.

Except as noted, this content is licensed under Creative Commons Attribution 3.0.

The Go Programming Language

Package draw
func Border func Draw func DrawMask type Color func (Color) At func (Color) ColorModel func (Color) Height func (Color) RGBA func (Color) SetAlpha func (Color) Width type Context type Image type Mouse type Op type Point func Pt func (Point) Add func (Point) Div func (Point) Eq func (Point) Mul import "exp/draw" Package draw provides basic graphics and drawing primitives, in the style of the Plan 9 graphics library (see http://plan9.bell-labs.com/magic/man2html/2/draw) and the X Render extension. Package files
arith.go color.go draw.go ev ent.go

func (Point) Sub type Rectangle func Rect func Rpt func (Rectangle) Add func (Rectangle) Canon func (Rectangle) Clip func (Rectangle) Combine func (Rectangle) Dx func (Rectangle) Dy func (Rectangle) Empty func (Rectangle) In func (Rectangle) Inset func (Rectangle) Overlaps func (Rectangle) Sub Bugs Subdirectories

func Border
func Border(dst Image, r Rectangle, w int, src image.Image, sp Point) Border aligns r.Min in dst with sp in src and then replaces pixels in a w-pixel border around r in dst with the result of the Porter-Duff compositing operation src over dst. If w is positive, the border extends w pixels inside r. If w is negative, the border extends w pixels outside r.

func Draw
func Draw(dst Image, r Rectangle, src image.Image, sp Point) Draw calls DrawMask with a nil mask and an Over op.

func DrawMask
func DrawMask(dst Image, r Rectangle, src image.Image, sp Point, mask image.Image, mp Point, op Op) DrawMask aligns r.Min in dst with sp in src and mp in mask and then replaces the rectangle r in dst with the result of a Porter-Duff composition. A nil mask is treated as opaque. The implementation is simple and slow. TODO(nigeltao): Optimize this.

type Color
A Color represents a color with 8-bit R, G, B, and A values, packed into a uint320xRRGGBBAAso that comparison is defined on colors. Color implements image.Color. Color also implements image.Image: it is a 10x10-pixel image of uniform color.
type Color uint32

var ( Opaque Transparent Black White Red Green Blue Cyan Magenta Yellow PaleYellow DarkYellow DarkGreen PaleGreen MedGreen DarkBlue PaleBlueGreen PaleBlue BlueGreen GreyGreen PaleGreyGreen YellowGreen MedBlue GreyBlue PaleGreyBlue PurpleBlue )

Color Color Color Color Color Color Color Color Color Color Color Color Color Color Color Color Color Color Color Color Color Color Color Color Color Color

= = = = = = = = = = = = = = = = = = = = = = = = = =

0xFFFFFFFF 0x00000000 0x000000FF 0xFFFFFFFF 0xFF0000FF 0x00FF00FF 0x0000FFFF 0x00FFFFFF 0xFF00FFFF 0xFFFF00FF 0xFFFFAAFF 0xEEEE9EFF 0x448844FF 0xAAFFAAFF 0x88CC88FF 0x000055FF 0xAAFFFFFF 0x0000BBFF 0x008888FF 0x55AAAAFF 0x9EEEEEFF 0x99994CFF 0x000099FF 0x005DBBFF 0x4993DDFF 0x8888CCFF

func (Color) At
func (c Color) At(x, y int) image.Color

func (Color) ColorModel


func (c Color) ColorModel() image.ColorModel

func (Color) Height

func (c Color) Height() int

func (Color) RGBA


func (c Color) RGBA() (r, g, b, a uint32)

func (Color) SetAlpha


func (c Color) SetAlpha(a uint8) Color SetAlpha returns the color obtained by changing c's alpha value to a and scaling r, g, and b appropriately.

func (Color) Width


func (c Color) Width() int

type Context
A Context represents a single graphics window.
type Context interface { // Screen returns an editable Image of window. Screen() Image // FlushImage flushes changes made to Screen() back to screen. FlushImage() // KeyboardChan returns a channel carrying keystrokes. // An event is sent each time a key is pressed or released. // The value k represents key k being pressed. // The value -k represents key k being released. // The specific set of key values is not specified, // but ordinary character represent themselves. KeyboardChan() <-chan int // MouseChan returns a channel carrying mouse events. // A new event is sent each time the mouse moves or a // button is pressed or released. MouseChan() <-chan Mouse // ResizeChan returns a channel carrying resize events. // An event is sent each time the window is resized; // the client should respond by calling Screen() to obtain // the new screen image. // The value sent on the channel is always ``true'' and can be ignored. ResizeChan() <-chan bool // QuitChan returns a channel carrying quit requests. // After reading a value from the quit channel, the application // should exit. QuitChan() <-chan bool }

type Image
A draw.Image is an image.Image with a Set method to change a single pixel.

type Image interface { image.Image Set(x, y int, c image.Color) }

type Mouse
A Mouse represents the state of the mouse.
type Mouse struct Buttons int Point Nsec int64 } { // bit mask of buttons: 1<<0 is left, 1<<1 middle, 1<<2 right // location of cursor // time stamp

type Op
A Porter-Duff compositing operator.
type Op int

const ( // Over specifies ``(src in mask) over dst''. Over Op = iota // Src specifies ``src in mask''. Src )

type Point
A Point is an X, Y coordinate pair.
type Point struct { X, Y int }

ZP is the zero Point.


var ZP Point

func Pt
func Pt(X, Y int) Point Pt is shorthand for Point{X, Y}.

func (Point) Add

func (p Point) Add(q Point) Point Add returns the sum of p and q: Pt(p.X+q.X, p.Y+q.Y).

func (Point) Div


func (p Point) Div(k int) Point Div returns p divided by k: Pt(p.X/k, p.Y/k).

func (Point) Eq
func (p Point) Eq(q Point) bool Eq returns true if p and q are equal.

func (Point) Mul


func (p Point) Mul(k int) Point Mul returns p scaled by k: Pt(p.X*k p.Y*k).

func (Point) Sub


func (p Point) Sub(q Point) Point Sub returns the difference of p and q: Pt(p.X-q.X, p.Y-q.Y).

type Rectangle
A Rectangle contains the Points with Min.X <= X < Max.X, Min.Y <= Y < Max.Y.
type Rectangle struct { Min, Max Point }

ZR is the zero Rectangle.


var ZR Rectangle

func Rect
func Rect(x0, y0, x1, y1 int) Rectangle Rect is shorthand for Rectangle{Pt(x0, y0), Pt(x1, y1)}.

func Rpt
func Rpt(min, max Point) Rectangle Rpt is shorthand for Rectangle{min, max}.

func (Rectangle) Add


func (r Rectangle) Add(p Point) Rectangle Add returns the rectangle r translated by p: Rpt(r.Min.Add(p), r.Max.Add(p)).

func (Rectangle) Canon


func (r Rectangle) Canon() Rectangle Canon returns a canonical version of r: the returned rectangle has Min.X <= Max.X and Min.Y <= Max.Y.

func (Rectangle) Clip


func (r Rectangle) Clip(r1 Rectangle) Rectangle Clip returns the largest rectangle containing only points shared by r and r1.

func (Rectangle) Com bine


func (r Rectangle) Combine(r1 Rectangle) Rectangle Combine returns the smallest rectangle containing all points from r and from r1.

func (Rectangle) Dx
func (r Rectangle) Dx() int Dx returns the width of the rectangle r: r.Max.X - r.Min.X.

func (Rectangle) Dy
func (r Rectangle) Dy() int Dy returns the width of the rectangle r: r.Max.Y - r.Min.Y.

func (Rectangle) Em pty


func (r Rectangle) Empty() bool Empty retruns true if r contains no points.

func (Rectangle) In
func (r Rectangle) In(r1 Rectangle) bool InRect returns true if all the points in r are also in r1.

func (Rectangle) Inset


func (r Rectangle) Inset(n int) Rectangle Inset returns the rectangle r inset by n: Rect(r.Min.X+n, r.Min.Y+n, r.Max.X-n, r.Max.Y-n).

func (Rectangle) Overlaps


func (r Rectangle) Overlaps(r1 Rectangle) bool Overlaps returns true if r and r1 cross; that is, it returns true if they share any point.

func (Rectangle) Sub


func (r Rectangle) Sub(p Point) Rectangle Sub returns the rectangle r translated by -p: Rpt(r.Min.Sub(p), r.Max.Sub(p)).

Bugs
This is a toy library and not ready for production use.

Subdirectories
Name .. x11 Synopsis This package implements an X11 backend for the exp/draw package.

Except as noted, this content is licensed under Creative Commons Attribution 3.0.

The Go Programming Language

Package eval
Variables type ArrayType func NewArrayType func (*ArrayType) String func (*ArrayType) Zero type ArrayValue type BoolValue type BoundedType type Code type Constant type Def type DivByZeroError func (DivByZeroError) String type FloatValue type Frame func (*Frame) Get type Func type FuncDecl func (*FuncDecl) String type FuncType func FuncFromNativeTyped func NewFuncType func (*FuncType) String func (*FuncType) Zero type FuncValue func FuncFromNative type IMethod type IdealFloatValue type IdealIntValue type IndexError func (IndexError) String type IntValue type Interface type InterfaceType func NewInterfaceType func (*InterfaceType) String func (*InterfaceType) Zero type InterfaceValue type KeyError func (KeyError) String type Map type MapType func NewMapType func (*MapType) String func (*MapType) Zero type MapValue func (*NamedType) Complete func (*NamedType) String func (*NamedType) Zero NegativeCapacityError func (NegativeCapacityError) String NegativeLengthError func (NegativeLengthError) String NilPointerError func (NilPointerError) String PtrType func NewPtrType func (*PtrType) String func (*PtrType) Zero PtrValue RedefinitionError func (*RedefinitionError) String Scope func (*Scope) NewFrame Slice SliceError func (SliceError) String SliceType func NewSliceType func (*SliceType) String func (*SliceType) Zero SliceValue StringValue StructField StructType func NewStructType func (*StructType) String func (*StructType) Zero StructValue Thread func (*Thread) Abort func (*Thread) Try Type func TypeFromNative func TypeOfNative UintValue Value Variable World func NewWorld func (*World) Compile func (*World) CompileDeclList

type type type type

type type type type type type

type type type type

type type

type

type type type type

type Method type MultiType func NewMultiType func (*MultiType) String func (*MultiType) Zero type NamedType func NewNamedType import "exp/eval"

func (*World) CompileExpr func (*World) CompileStmtList func (*World) DefineConst func (*World) DefineVar Other packages

This package is the beginning of an interpreter for Go. It can run simple Go programs but does not implement interface values or packages. Package files
abort.go bridge.go compiler.go expr.go expr1.go f unc.go scope.go stmt.go ty pe.go ty pec.go util.go v alue.go world.go

Variables
var ( Uint8Type Uint16Type Uint32Type Uint64Type = = = = universe.DefineType("uint8", universePos, &uintType{commonType{}, 8, false, "uint8"}) universe.DefineType("uint16", universePos, &uintType{commonType{}, 16, false, "uint16"}) universe.DefineType("uint32", universePos, &uintType{commonType{}, 32, false, "uint32"}) universe.DefineType("uint64", universePos, &uintType{commonType{}, 64, false, "uint64"})

UintType = universe.DefineType("uint", universePos, &uintType{commonType{}, 0, false, "uint"}) UintptrType = universe.DefineType("uintptr", universePos, &uintType{commonType{}, 0, true, "uintptr"}) )

var ( Int8Type Int16Type Int32Type Int64Type

= = = =

universe.DefineType("int8", universePos, &intType{commonType{}, 8, "int8"}) universe.DefineType("int16", universePos, &intType{commonType{}, 16, "int16"}) universe.DefineType("int32", universePos, &intType{commonType{}, 32, "int32"}) universe.DefineType("int64", universePos, &intType{commonType{}, 64, "int64"})

IntType = universe.DefineType("int", universePos, &intType{commonType{}, 0, "int"}) )

var ( Float32Type = universe.DefineType("float32", universePos, &floatType{commonType{}, 32, "float32"}) Float64Type = universe.DefineType("float64", universePos, &floatType{commonType{}, 64, "float64"}) FloatType = universe.DefineType("float", universePos, &floatType{commonType{}, 0, "float"}) )

var BoolType = universe.DefineType("bool", universePos, &boolType{})

var StringType = universe.DefineType("string", universePos, &stringType{})

type ArrayType

type ArrayType struct { Len int64 Elem Type // contains unexported fields }

func New ArrayType


func NewArrayType(len int64, elem Type) *ArrayType

func (*ArrayType) String


func (t *ArrayType) String() string

func (*ArrayType) Zero


func (t *ArrayType) Zero() Value

type ArrayValue
type ArrayValue interface { Value // TODO(austin) Get() is here for uniformity, but is // completely useless. If a lot of other types have similarly // useless Get methods, just special-case these uses. Get(*Thread) ArrayValue Elem(*Thread, int64) Value // Sub returns an ArrayValue backed by the same array that // starts from element i and has length len. Sub(i int64, len int64) ArrayValue }

type BoolValue
type BoolValue interface { Value Get(*Thread) bool Set(*Thread, bool) }

type BoundedType
type BoundedType interface { Type // contains unexported methods }

type Code

type Code interface { // The type of the value Run returns, or nil if Run returns nil. Type() Type // Run runs the code; if the code is a single expression // with a value, it returns the value; otherwise it returns nil. Run() (Value, os.Error) }

type Constant
type Constant struct { token.Position Type Type Value Value }

type Def
A definition can be a *Variable, *Constant, or Type.
type Def interface { Pos() token.Position }

type DivByZeroError
type DivByZeroError struct{}

func (DivByZeroError) String


func (DivByZeroError) String() string

type FloatValue
type FloatValue interface { Value Get(*Thread) float64 Set(*Thread, float64) }

type Frame

type Frame struct { Outer *Frame Vars []Value }

func (*Fram e) Get


func (f *Frame) Get(level int, index int) Value

type Func
type Func interface { NewFrame() *Frame Call(*Thread) }

type FuncDecl
type FuncDecl struct { Type *FuncType Name *ast.Ident // nil for function literals // InNames will be one longer than Type.In if this function is // variadic. InNames []*ast.Ident OutNames []*ast.Ident }

func (*FuncDecl) String


func (t *FuncDecl) String() string

type FuncType
type FuncType struct { // TODO(austin) Separate receiver Type for methods? In []Type Variadic bool Out []Type // contains unexported fields }

func FuncFrom NativeTyped


func FuncFromNativeTyped(fn func(*Thread, []Value, []Value), t interface{}) (*FuncType, FuncValue) FuncFromNativeTyped is like FuncFromNative, but constructs the function type from a function pointer using reflection. Typically, the type will be given as a nil pointer to a function with the desired signature.

func New FuncType


func NewFuncType(in []Type, variadic bool, out []Type) *FuncType

func (*FuncType) String


func (t *FuncType) String() string

func (*FuncType) Zero


func (t *FuncType) Zero() Value

type FuncValue
type FuncValue interface { Value Get(*Thread) Func Set(*Thread, Func) }

func FuncFrom Native


func FuncFromNative(fn func(*Thread, []Value, []Value), t *FuncType) FuncValue FuncFromNative creates an interpreter function from a native function that takes its in and out arguments as slices of interpreter Value's. While somewhat inconvenient, this avoids value marshalling.

type IMethod
type IMethod struct { Name string Type *FuncType }

type IdealFloatValue
type IdealFloatValue interface { Value Get() *bignum.Rational }

type IdealIntValue
TODO(austin) IdealIntValue and IdealFloatValue should not exist because ideals are not l-values.

type IdealIntValue interface { Value Get() *bignum.Integer }

type IndexError
type IndexError struct { Idx, Len int64 }

func (IndexError) String


func (e IndexError) String() string

type IntValue
type IntValue interface { Value Get(*Thread) int64 Set(*Thread, int64) }

type Interface
type Interface struct { Type Type Value Value }

type InterfaceType
type InterfaceType struct { // contains unexported fields }

func New InterfaceType


func NewInterfaceType(methods []IMethod, embeds []*InterfaceType) *InterfaceType

func (*InterfaceType) String


func (t *InterfaceType) String() string

func (*InterfaceType) Zero

func (t *InterfaceType) Zero() Value

type InterfaceValue
type InterfaceValue interface { Value Get(*Thread) Interface Set(*Thread, Interface) }

type KeyError
type KeyError struct { Key interface{} }

func (KeyError) String


func (e KeyError) String() string

type Map
type Map interface { Len(*Thread) int64 // Retrieve an element from the map, returning nil if it does // not exist. Elem(t *Thread, key interface{}) Value // Set an entry in the map. If val is nil, delete the entry. SetElem(t *Thread, key interface{}, val Value) // TODO(austin) Perhaps there should be an iterator interface instead. Iter(func(key interface{}, val Value) bool) }

type MapType
type MapType struct { Key Type Elem Type // contains unexported fields }

func New MapType


func NewMapType(key Type, elem Type) *MapType

func (*MapType) String


func (t *MapType) String() string

func (*MapType) Zero


func (t *MapType) Zero() Value

type MapValue
type MapValue interface { Value Get(*Thread) Map Set(*Thread, Map) }

type Method
type Method struct { // contains unexported fields }

type MultiType
MultiType is a special type used for multi-valued expressions, akin to a tuple type. It's not generally accessible within the language.
type MultiType struct { Elems []Type // contains unexported fields }

func New MultiType


func NewMultiType(elems []Type) *MultiType

func (*MultiType) String


func (t *MultiType) String() string

func (*MultiType) Zero


func (t *MultiType) Zero() Value

type NamedType

type NamedType struct { token.Position Name string // Underlying type. If incomplete is true, this will be nil. // If incomplete is false and this is still nil, then this is // a placeholder type representing an error. Def Type // contains unexported fields }

func New Nam edType


func NewNamedType(name string) *NamedType TODO(austin) This is temporarily needed by the debugger's remote type parser. This should only be possible with block.DefineType.

func (*Nam edType) Com plete


func (t *NamedType) Complete(def Type)

func (*Nam edType) String


func (t *NamedType) String() string

func (*Nam edType) Zero


func (t *NamedType) Zero() Value

type NegativeCapacityError
type NegativeCapacityError struct { Len int64 }

func (NegativeCapacityError) String


func (e NegativeCapacityError) String() string

type NegativeLengthError
type NegativeLengthError struct { Len int64 }

func (NegativeLengthError) String


func (e NegativeLengthError) String() string

type NilPointerError

type NilPointerError struct{}

func (NilPointerError) String


func (NilPointerError) String() string

type PtrType
type PtrType struct { Elem Type // contains unexported fields }

func New PtrType


func NewPtrType(elem Type) *PtrType

func (*PtrType) String


func (t *PtrType) String() string

func (*PtrType) Zero


func (t *PtrType) Zero() Value

type PtrValue
type PtrValue interface { Value Get(*Thread) Value Set(*Thread, Value) }

type RedefinitionError
type RedefinitionError struct { Name string Prev Def }

func (*RedefinitionError) String


func (e *RedefinitionError) String() string

type Scope
A Scope is the compile-time analogue of a Frame, which captures some subtree of blocks.

type Scope struct { // contains unexported fields }

func (*Scope) New Fram e


func (s *Scope) NewFrame(outer *Frame) *Frame

type Slice
type Slice struct { Base ArrayValue Len, Cap int64 }

type SliceError
type SliceError struct { Lo, Hi, Cap int64 }

func (SliceError) String


func (e SliceError) String() string

type SliceType
type SliceType struct { Elem Type // contains unexported fields }

func New SliceType


func NewSliceType(elem Type) *SliceType

func (*SliceType) String


func (t *SliceType) String() string

func (*SliceType) Zero


func (t *SliceType) Zero() Value

type SliceValue

type SliceValue interface { Value Get(*Thread) Slice Set(*Thread, Slice) }

type StringValue
type StringValue interface { Value Get(*Thread) string Set(*Thread, string) }

type StructField
type StructField struct { Name string Type Type Anonymous bool }

type StructType
type StructType struct { Elems []StructField // contains unexported fields }

func New StructType


func NewStructType(fields []StructField) *StructType

func (*StructType) String


func (t *StructType) String() string

func (*StructType) Zero


func (t *StructType) Zero() Value

type StructValue

type StructValue interface { Value // TODO(austin) This is another useless Get() Get(*Thread) StructValue Field(*Thread, int) Value }

type Thread
type Thread struct { // contains unexported fields }

func (*Thread) Abort


func (t *Thread) Abort(err os.Error) Abort aborts the thread's current computation, causing the innermost Try to return err.

func (*Thread) Try


func (t *Thread) Try(f func(t *Thread)) os.Error Try executes a computation; if the computation Aborts, Try returns the error passed to abort.

type Type
type Type interface {

// Zero returns a new zero value of this type. Zero() Value // String returns the string representation of this type. String() string // The position where this type was defined, if any. Pos() token.Position // contains unexported methods }

var EmptyType Type = NewMultiType([]Type{})

var IdealFloatType Type = &idealFloatType{}

var IdealIntType Type = &idealIntType{}

func TypeFrom Native


func TypeFromNative(t reflect.Type) Type TypeFromNative converts a regular Go type into a the corresponding interpreter Type.

func TypeOfNative
func TypeOfNative(v interface{}) Type TypeOfNative returns the interpreter Type of a regular Go value.

type UintValue
type UintValue interface { Value Get(*Thread) uint64 Set(*Thread, uint64) }

type Value
type Value interface { String() string // Assign copies another value // assume that the other value // value interface (BoolValue, // anything about its specific Assign(t *Thread, o Value) }

into this one. It should satisfies the same specific etc.), but must not assume type.

type Variable
type Variable struct { token.Position // Index of this variable in the Frame structure Index int // Static type of this variable Type Type // Value of this variable. This is only used by Scope.NewFrame; // therefore, it is useful for global scopes but cannot be used // in function scopes. Init Value }

type World
type World struct { // contains unexported fields }

func New World


func NewWorld() *World

func (*World) Com pile


func (w *World) Compile(text string) (Code, os.Error)

func (*World) Com pileDeclList


func (w *World) CompileDeclList(decls []ast.Decl) (Code, os.Error)

func (*World) Com pileExpr


func (w *World) CompileExpr(e ast.Expr) (Code, os.Error)

func (*World) Com pileStm tList


func (w *World) CompileStmtList(stmts []ast.Stmt) (Code, os.Error)

func (*World) DefineConst


func (w *World) DefineConst(name string, t Type, val Value) os.Error

func (*World) DefineVar


func (w *World) DefineVar(name string, t Type, val Value) os.Error

Other packages
main

Except as noted, this content is licensed under Creative Commons Attribution 3.0.

The Go Programming Language

Package exception
type Exception func Try func (*Exception) Catch func (*Exception) String type Handler import "exp/exception" This package illustrates how basic try-catch exception handling can be emulated using goroutines, channels, and closures. This package is *not* intended as a general exception handler library. Package files
exception.go

type Exception
An Exception carries an exception value.
type Exception struct { Value interface{} // Value may be the nil exception }

func Try
func Try(f func(throw Handler)) *Exception Try invokes a function f with a Handler to throw exceptions. The function f may terminate abnormally with an arbitrary exception x by calling throw(x) within f. If an exception is thrown, Try returns an *Exception; otherwise it returns nil. Usage pattern:
if x := exception.Try(func(throw exception.Handler) { ... throw(42); // terminate f by throwing exception 42 ... }); x != nil { // catch exception, e.g. print it fmt.Println(x.Value); }

Alternative:

exception.Try(func(throw exception.Handler) { ... throw(42); // terminate f by throwing exception 42 ... }).Catch(func (x interface{}) { // catch exception, e.g. print it fmt.Println(x); })

func (*Exception) Catch


func (x *Exception) Catch(f Handler) If x != nil, Catch invokes f with the exception value x.Value. See Try for usage patterns.

func (*Exception) String


func (x *Exception) String() string

type Handler
A Handler function handles an arbitrary exception value x.
type Handler func(x interface{})

Except as noted, this content is licensed under Creative Commons Attribution 3.0.

The Go Programming Language

Package iterable
func All func Any func Data func Find func Inject type ByteArray func (ByteArray) Iter type FloatArray func (FloatArray) Iter type Group type Grouper type Injector type IntArray func (IntArray) Iter type Iterable func Chain func Cycle func Drop import "exp/iterable" The iterable package provides several traversal and searching methods. It can be used on anything that satisfies the Iterable interface, including vector, though certain functions, such as Map, can also be used on something that would produce an infinite amount of data. Package files
array .go iterable.go

func DropWhile func Filter func GroupBy func Map func Partition func Repeat func RepeatTimes func Slice func Take func TakeWhile func Unique func Zip func ZipWith2 func ZipWith3 type StringArray func (StringArray) Iter

func All
func All(iter Iterable, f func(interface{}) bool) bool All tests whether f is true for every element of iter.

func Any
func Any(iter Iterable, f func(interface{}) bool) bool Any tests whether f is true for at least one element of iter.

func Data
func Data(iter Iterable) []interface{}

Data returns a slice containing the elements of iter.

func Find
func Find(iter Iterable, f func(interface{}) bool) interface{} Find returns the first element of iter that satisfies f. Returns nil if no such element is found.

func Inject
func Inject(iter Iterable, initial interface{}, f Injector) interface{} Inject combines the elements of iter by repeatedly calling f with an accumulated value and each element in order. The starting accumulated value is initial, and after each call the accumulated value is set to the return value of f. For instance, to compute a sum:
var arr IntArray = []int{ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; sum := iterable.Inject(arr, 0, func(ax interface {}, x interface {}) interface {} { return ax.(int) + x.(int) }).(int)

type ByteArray
type ByteArray []byte

func (ByteArray) Iter


func (a ByteArray) Iter() <-chan interface{}

type FloatArray
type FloatArray []float

func (FloatArray) Iter


func (a FloatArray) Iter() <-chan interface{}

type Group
Group is the type for elements returned by the GroupBy function.
type Group struct { Key interface{} // key value for matching items Vals Iterable // Iterable for receiving values in the group }

type Grouper
Key defines the interface required by the GroupBy function.
type Grouper interface { // Return the key for the given value Key(interface{}) interface{} // Compute equality for the given keys Equal(a, b interface{}) bool }

type Injector
Injector is a type representing a function that takes two arguments, an accumulated value and an element, and returns the next accumulated value. See the Inject function.
type Injector func(interface{}, interface{}) interface{}

type IntArray
type IntArray []int

func (IntArray) Iter


func (a IntArray) Iter() <-chan interface{}

type Iterable
type Iterable interface { // Iter should return a fresh channel each time it is called. Iter() <-chan interface{} }

func Chain
func Chain(args []Iterable) Iterable Chain returns an Iterable that concatentates all values from the specified Iterables.

func Cycle
func Cycle(iter Iterable) Iterable Cycle repeats the values of iter in order infinitely.

func Drop
func Drop(iter Iterable, n int) Iterable

Drop returns an Iterable that returns each element of iter after the first n elements.

func DropWhile
func DropWhile(iter Iterable, f func(interface{}) bool) Iterable DropWhile returns an Iterable that returns each element of iter after the initial sequence for which f returns true.

func Filter
func Filter(iter Iterable, f func(interface{}) bool) Iterable Filter returns an Iterable that returns the elements of iter that satisfy f.

func GroupBy
func GroupBy(iter Iterable, k Grouper) Iterable GroupBy combines sequences of logically identical values from iter using k to generate a key to compare values. Each value emitted by the returned Iterable is of type Group, which contains the key used for matching the values for the group, and an Iterable for retrieving all the values in the group.

func Map
func Map(iter Iterable, f func(interface{}) interface{}) Iterable Map returns an Iterable that returns the result of applying f to each element of iter.

func Partition
func Partition(iter Iterable, f func(interface{}) bool) (Iterable, Iterable) Partition(iter, f) returns Filter(iter, f) and Filter(iter, !f).

func Repeat
func Repeat(v interface{}) Iterable Repeat generates an infinite stream of v.

func RepeatTim es
func RepeatTimes(v interface{}, n int) Iterable RepeatTimes generates a stream of n copies of v.

func Slice
func Slice(iter Iterable, start, stop int) Iterable Slice returns an Iterable that contains the elements from iter with indexes in [start, stop).

func Take
func Take(iter Iterable, n int) Iterable Take returns an Iterable that contains the first n elements of iter.

func TakeWhile

func TakeWhile(iter Iterable, f func(interface{}) bool) Iterable TakeWhile returns an Iterable that contains elements from iter while f is true.

func Unique
func Unique(iter Iterable, id Grouper) Iterable Unique removes duplicate values which occur consecutively using id to compute keys.

func Zip
func Zip(args []Iterable) Iterable Zip returns an Iterable of []interface{} consisting of the next element from each input Iterable. The length of the returned Iterable is the minimum of the lengths of the input Iterables.

func ZipWith2
func ZipWith2(f func(c, d interface{}) interface{}, a, b Iterable) Iterable ZipWith returns an Iterable containing the result of executing f using arguments read from a and b.

func ZipWith3
func ZipWith3(f func(d, e, f interface{}) interface{}, a, b, c Iterable) Iterable ZipWith returns an Iterable containing the result of executing f using arguments read from a, b and c.

type StringArray
type StringArray []string

func (StringArray) Iter


func (a StringArray) Iter() <-chan interface{}

Except as noted, this content is licensed under Creative Commons Attribution 3.0.

The Go Programming Language

Package av
Constants Variables func AudioStream type Color func (Color) RGBA type Image func (*Image) At func (*Image) ColorModel func (*Image) Height func (*Image) Set func (*Image) Width import "exp/nacl/av" Package av implements audio and video access for Native Client binaries running standalone or embedded in a web browser window. The C version of the API is documented at http://nativeclient.googlecode.com/svn/data/docs_tarball /nacl/googleclient/native_client/scons-out/doc/html/group__audio__video.html Package files
av .go ev ent.go image.go

type Window func Init func (*Window) FlushImage func (*Window) KeyboardChan func (*Window) MouseChan func (*Window) QuitChan func (*Window) ResizeChan func (*Window) Screen

Constants
Subsystem values for Init.
const ( SubsystemVideo = 1 << iota SubsystemAudio SubsystemEmbed )

Audio formats.
const ( AudioFormatStereo44K = iota AudioFormatStereo48K )

Variables
ColorModel is the color model corresponding to the Native Client Color.

var ColorModel = image.ColorModelFunc(toColor)

func AudioStream
func AudioStream(data []uint16) (nextSize int, err os.Error) AudioStream provides access to the audio device. Each call to AudioStream writes the given data, which should be a slice of 16-bit stereo PCM audio samples, and returns the number of samples required by the next call to AudioStream. To find out the initial number of samples to write, call AudioStream(nil).

type Color
A Color represents a Native Client color value, a 32-bit R, G, B, A value packed as 0xAARRGGBB.
type Color uint32

func (Color) RGBA


func (p Color) RGBA() (r, g, b, a uint32)

type Image
An Image represents a Native Client frame buffer. The pixels in the image can be accessed as a single linear slice or as a two-dimensional slice of slices. Image implements image.Image.
type Image struct { Linear []Color Pixel [][]Color }

func (*Im age) At


func (m *Image) At(x, y int) image.Color

func (*Im age) ColorModel


func (m *Image) ColorModel() image.ColorModel

func (*Im age) Height


func (m *Image) Height() int

func (*Im age) Set


func (m *Image) Set(x, y int, color image.Color)

func (*Im age) Width


func (m *Image) Width() int

type Window
A Window represents a connection to the Native Client window. It implements draw.Context.
type Window struct { Embedded bool // running as part of a web page? *Image // screen image // contains unexported fields }

func Init
func Init(subsys int, dx, dy int) (*Window, os.Error) Init initializes the Native Client subsystems specified by subsys. Init must be called before using any of the other functions in this package, and it must be called only once. If the SubsystemVideo flag is set, Init requests a window of size dxdy. When embedded in a web page, the web page's window specification overrides the parameters to Init, so the returned Window may have a different size than requested. If the SubsystemAudio flag is set, Init requests a connection to the audio device carrying 44 kHz 16-bit stereo PCM audio samples.

func (*Window ) FlushIm age


func (w *Window) FlushImage()

func (*Window ) KeyboardChan


func (w *Window) KeyboardChan() <-chan int

func (*Window ) MouseChan


func (w *Window) MouseChan() <-chan draw.Mouse

func (*Window ) QuitChan


func (w *Window) QuitChan() <-chan bool

func (*Window ) ResizeChan


func (w *Window) ResizeChan() <-chan bool

func (*Window ) Screen


func (w *Window) Screen() draw.Image

Except as noted, this content is licensed under Creative Commons Attribution 3.0.

The Go Programming Language

Package srpc
func Add func Enabled func Serve func ServeRuntime type Client func NewClient func (*Client) NewRPC type Errno import "exp/nacl/srpc" This package implements Native Client's simple RPC (SRPC). Package files
client.go msg.go serv er.go

func (Errno) String type Handler type RPC func (*RPC) Call func (*RPC) Start Bugs

func Add
func Add(name, fmt string, handler Handler) Add registers a handler for the named method. Fmt is a Native Client format string, a sequence of alphabetic characters representing the types of the parameter values, a colon, and then a sequence of alphabetic characters representing the types of the returned values. The format characters and corresponding dynamic types are:
b C d D h i I s bool []byte float64 []float64 int // a file descriptor (aka handle) int32 []int32 string

func Enabled
func Enabled() bool Enabled returns true if SRPC is enabled in the Native Client runtime.

func Serve
func Serve(fd int) os.Error

Serve accepts new SRPC connections from the file descriptor fd and answers RPCs issued on those connections. It closes fd and returns an error if the imc_accept system call fails.

func ServeRuntime
func ServeRuntime() os.Error ServeRuntime serves RPCs issued by the Native Client embedded runtime. This should be called by main once all methods have been registered using Add.

type Client
A Client represents the client side of an SRPC connection.
type Client struct { // contains unexported fields }

func New Client


func NewClient(fd int) (c *Client, err os.Error) NewClient allocates a new client using the file descriptor fd.

func (*Client) New RPC


func (c *Client) NewRPC(done chan *RPC) *RPC NewRPC creates a new RPC on the client connection.

type Errno
An Errno is an SRPC status code.
type Errno uint32

const ( OK Errno = 256 + iota ErrBreak ErrMessageTruncated ErrNoMemory ErrProtocolMismatch ErrBadRPCNumber ErrBadArgType ErrTooFewArgs ErrTooManyArgs ErrInArgTypeMismatch ErrOutArgTypeMismatch ErrInternalError ErrAppError )

func (Errno) String


func (e Errno) String() string

type Handler
A Handler is a handler for an SRPC method. It reads arguments from arg, checks size for array limits, writes return values to ret, and returns an Errno status code.
type Handler interface { Run(arg, ret []interface{}, size []int) Errno }

type RPC
An RPC represents a single RPC issued by a client.
type RPC struct { Ret []interface{} // Done chan *RPC // Errno Errno // // contains unexported }

Return values Channel where notification of done arrives Status code fields

func (*RPC) Call


func (r *RPC) Call(name string, arg []interface{}) (ret []interface{}, err Errno) Call is a convenient wrapper that starts the RPC request, waits for it to finish, and then returns the results. Its implementation is:
r.Start(name, arg); <-r.Done; return r.Ret, r.Errno;

func (*RPC) Start


func (r *RPC) Start(name string, arg []interface{}) Start issues an RPC request for method name with the given arguments. The RPC r must not be in use for another pending request. To wait for the RPC to finish, receive from r.Done and then inspect r.Ret and r.Errno.

Bugs
Add's format string should be replaced by analyzing the type of an arbitrary func passed in an interface{} using reflection.

Except as noted, this content is licensed under Creative Commons Attribution 3.0.

The Go Programming Language

Package expvar
func Iter func Publish func RemoveAll type Int func NewInt func (*Int) Add func (*Int) String type IntFunc func (IntFunc) String type KeyValue type Map func NewMap func (*Map) Add import "expvar" The expvar package provides a standardized interface to public variables, such as operation counters in servers. It exposes these variables via HTTP at /debug/vars in JSON format. Package files
expv ar.go

func (*Map) Get func (*Map) Init func (*Map) Iter func (*Map) Set func (*Map) String type String func NewString func (*String) Set func (*String) String type Var func Get

func Iter
func Iter() <-chan KeyValue

func Publish
func Publish(name string, v Var) Publish declares an named exported variable. This should be called from a package's init function when it creates its Vars. If the name is already registered then this will log.Crash.

func RemoveAll
func RemoveAll() RemoveAll removes all exported variables. This is for tests; don't call this on a real server.

type Int
Int is a 64-bit integer variable, and satisfies the Var interface.

type Int struct { // contains unexported fields }

func New Int


func NewInt(name string) *Int

func (*Int) Add


func (v *Int) Add(delta int64)

func (*Int) String


func (v *Int) String() string

type IntFunc
IntFunc wraps a func() int64 to create a value that satisfies the Var interface. The function will be called each time the Var is evaluated.
type IntFunc func() int64

func (IntFunc) String


func (v IntFunc) String() string

type KeyValue
KeyValue represents a single entry in a Map.
type KeyValue struct { Key string Value Var }

type Map
Map is a string-to-Var map variable, and satisfies the Var interface.
type Map struct { // contains unexported fields }

func New Map


func NewMap(name string) *Map

func (*Map) Add

func (v *Map) Add(key string, delta int64)

func (*Map) Get


func (v *Map) Get(key string) Var

func (*Map) Init


func (v *Map) Init() *Map

func (*Map) Iter


func (v *Map) Iter() <-chan KeyValue

func (*Map) Set


func (v *Map) Set(key string, av Var)

func (*Map) String


func (v *Map) String() string

type String
String is a string variable, and satisfies the Var interface.
type String struct { // contains unexported fields }

func New String


func NewString(name string) *String

func (*String) Set


func (v *String) Set(value string)

func (*String) String


func (v *String) String() string

type Var
Var is an abstract type for all exported variables.
type Var interface { String() string }

func Get
func Get(name string) Var

Get retrieves a named exported variable.

Except as noted, this content is licensed under Creative Commons Attribution 3.0.

The Go Programming Language

Package flag
Variables func Arg func Args func Bool func BoolVar func Float func Float64 func Float64Var func FloatVar func Int func Int64 func Int64Var func IntVar func NArg func NFlag func Parse import "flag" The flag package implements command-line flag parsing. Usage: 1) Define flags using flag.String(), Bool(), Int(), etc. Example:
import "flag" var ip *int = flag.Int("flagname", 1234, "help message for flagname")

func PrintDefaults func Set func String func StringVar func Uint func Uint64 func Uint64Var func UintVar func Visit func VisitAll type Flag func Lookup type FlagValue

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") }

2) After all flags are defined, call


flag.Parse()

to parse the command line into the defined flags. 3) 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);

4) After parsing, flag.Arg(i) is the i'th argument after the flags. Args are indexed from 0 up to flag.NArg(). 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, true, false, TRUE, FALSE, True, False. Package files
f lag.go

Variables
Usage prints to standard error a default usage message documenting all defined flags. The function is a variable that may be changed to point to a custom function.
var Usage = func() { fmt.Fprintf(os.Stderr, "Usage of %s:\n", os.Args[0]) 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.

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 Float
func Float(name string, value float, usage string) *float Float defines a float flag with specified name, default value, and usage string. The return value is the address of a float variable that stores the value of the flag.

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 FloatVar
func FloatVar(p *float, name string, value float, usage string) FloatVar defines a float flag with specified name, default value, and usage string. The argument p points to a float 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

func Parse
func Parse() Parse parses the command-line flags. Must be called after all flags are defined and before any are accessed by the program.

func PrintDefaults
func PrintDefaults() PrintDefaults prints to standard error the default values of all defined flags.

func Set
func Set(name, value string) bool

Set sets the value of the named flag. It returns true if the set succeeded; false if there is no such flag defined.

func String
func String(name, 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, 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 Visit

func Visit(fn func(*Flag)) Visit visits the flags, calling fn for each. It visits only those flags that have been set.

func VisitAll
func VisitAll(fn func(*Flag)) VisitAll visits the flags, calling fn for each. It visits all flags, even those not set.

type Flag
A Flag represents the state of a flag.
type Flag struct { Name string Usage string Value FlagValue DefValue string }

// // // //

name as it appears on command line help message value as set default value (as text); for usage message

func Lookup
func Lookup(name string) *Flag Lookup returns the Flag structure of the named flag, returning nil if none exists.

type FlagValue
FlagValue is the interface to the dynamic value stored in a flag. (The default value is represented as a string.)
type FlagValue interface { String() string // contains unexported methods }

Except as noted, this content is licensed under Creative Commons Attribution 3.0.

The Go Programming Language

Package fmt
func Fprint func Fprintf func Fprintln func Print func Printf func Println func Sprint func Sprintf func Sprintln type Formatter type GoStringer type State type Stringer import "fmt" Package fmt implements formatted I/O with functions analogous to C's printf. The format 'verbs' are derived from C's but are simpler. The verbs: General:
%v %#v %T the value in a default format. when printing structs, the plus flag (%+v) adds field names a Go-syntax representation of the value a Go-syntax representation of the type of the value

Boolean:
%t the word true or false

Integer:
%b %c %d %o %x %X base 2 the character represented by the corresponding Unicode code point base 10 base 8 base 16, with lower-case letters for a-f base 16, with upper-case letters for A-F

Floating-point and complex constituents:

%e %E %f %g %G

scientific notation, e.g. -1234.456e+78 scientific notation, e.g. -1234.456E+78 decimal point but no exponent, e.g. 123.456 whichever of %e or %f produces more compact output whichever of %E or %f produces more compact output

String and slice of bytes:


%s %q %x the uninterpreted bytes of the string or slice a double-quoted string safely escaped with Go syntax base 16 notation with 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). For numeric values, the width and precision flags control formatting; width sets the width of the field, precision the number of places after the decimal, if appropriate. The format %6.2f prints 123.45. The width of a field is the number of Unicode code points in the string. This differs from C's printf where the field width is the number of bytes. Other flags:
+ # always print a sign for numeric values 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); suppress 0x for %p (%#p); print a raw (backquoted) string if possible for %q (%#q) (space) leave a space for elided sign in numbers (% d); put spaces between bytes printing strings or slices in hex (% x) pad with leading zeros rather than spaces

' ' 0

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. If an operand implements interface Formatter, that interface can be used for fine control of formatting. If an operand implements method String() string that method will be used for %v, %s, or Print etc. Package files
f ormat.go print.go

func Fprint
func Fprint(w io.Writer, a ...interface{}) (n int, error os.Error) Fprint formats using the default formats for its operands and writes to w. Spaces are added between operands when neither is a string.

func Fprintf
func Fprintf(w io.Writer, format string, a ...interface{}) (n int, error os.Error) Fprintf formats according to a format specifier and writes to w.

func Fprintln
func Fprintln(w io.Writer, a ...interface{}) (n int, error os.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.

func Print
func Print(a ...interface{}) (n int, errno os.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.

func Printf
func Printf(format string, a ...interface{}) (n int, errno os.Error) Printf formats according to a format specifier and writes to standard output.

func Println
func Println(a ...interface{}) (n int, errno os.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.

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.

type Formatter
Formatter is the interface implemented by values with a custom formatter. The implementation of Format may call Sprintf or Fprintf(f) etc. to generate its output.
type Formatter interface { Format(f State, c int) }

type GoStringer
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 GoStringer interface { GoString() string }

type State
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 State interface { // Write is the function to call to emit formatted output to be printed. Write(b []byte) (ret int, err os.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 returns whether the flag c, a character, has been set. Flag(int) bool }

type Stringer
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 a %s or %v format or to an unformatted printer such as Print.
type Stringer interface { String() string }

Except as noted, this content is licensed under Creative Commons Attribution 3.0.

The Go Programming Language

Package ast
func FileExports func IsExported func PackageExports func Walk type ArrayType type AssignStmt func (*AssignStmt) Pos type BadDecl type BadExpr type BadStmt type BasicLit type BinaryExpr func (*BinaryExpr) Pos type BlockStmt type BranchStmt type CallExpr func (*CallExpr) Pos type CaseClause type ChanDir type ChanType type CommClause type Comment type CommentGroup type CompositeLit func (*CompositeLit) Pos type Decl type DeclStmt func (*DeclStmt) Pos type DeferStmt type Ellipsis type EmptyStmt type Expr type ExprStmt func (*ExprStmt) Pos type Field func (*Field) Pos type FieldList func (*FieldList) NumFields type File func MergePackageFiles type ForStmt type FuncDecl func (*FuncDecl) Pos type FuncLit func (*FuncLit) Pos type FuncType type type type type type type type type type type type func (*Ident) Name func (*Ident) String IfStmt ImportSpec func (*ImportSpec) Pos IncDecStmt func (*IncDecStmt) Pos IndexExpr func (*IndexExpr) Pos InterfaceType KeyValueExpr func (*KeyValueExpr) Pos LabeledStmt func (*LabeledStmt) Pos MapType Node ObjKind Object func NewObj func (*Object) IsExported Package ParenExpr RangeStmt ReturnStmt Scope func NewScope func (*Scope) Declare func (*Scope) Lookup SelectStmt SelectorExpr func (*SelectorExpr) Pos SliceExpr func (*SliceExpr) Pos Spec StarExpr Stmt StructType SwitchStmt TypeAssertExpr func (*TypeAssertExpr) Pos TypeCaseClause TypeSpec func (*TypeSpec) Pos TypeSwitchStmt UnaryExpr ValueSpec

type type type type type

type type type type type type type type type type type type type type

type GenDecl type GoStmt type Ident func NewIdent func (*Ident) IsExported import "go/ast"

func (*ValueSpec) Pos type Visitor

The AST package declares the types used to represent syntax trees for Go packages. Package files
ast.go f ilter.go scope.go walk.go

func FileExports
func FileExports(src *File) bool FileExports trims the AST for a Go source file in place such that only exported nodes remain: all top-level identifiers which are not exported and their associated information (such as type, initial value, or function body) are removed. Non-exported fields and methods of exported types are stripped, and the function bodies of exported functions are set to nil. The File.comments list is not changed. FileExports returns true if there is an exported declaration; it returns false otherwise.

func IsExported
func IsExported(name string) bool IsExported returns whether name is an exported Go symbol (i.e., whether it begins with an uppercase letter).

func PackageExports
func PackageExports(pkg *Package) bool PackageExports trims the AST for a Go package in place such that only exported nodes remain. The pkg.Files list is not changed, so that file names and top-level package comments don't get lost. PackageExports returns true if there is an exported declaration; it returns false otherwise.

func Walk
func Walk(v Visitor, node interface{}) Walk traverses an AST in depth-first order: If node != nil, it invokes v.Visit(node). If the visitor w returned by v.Visit(node) is not nil, Walk visits each of the children of node with the visitor w, followed by a call of w.Visit(nil). Walk may be called with any of the named ast node types. It also accepts arguments of type []*Field, []*Ident, []Expr, []Stmt and []Decl; the respective children are the slice elements.

type ArrayType
An ArrayType node represents an array or slice type.
type ArrayType struct { // position of "[" token.Position Len Expr // Ellipsis node for [...]T array types, nil for slice types Elt Expr // element type }

type AssignStmt
An AssignStmt node represents an assignment or a short variable declaration.
type AssignStmt struct { Lhs []Expr TokPos token.Position // position of Tok Tok token.Token // assignment token, DEFINE Rhs []Expr }

func (*AssignStm t) Pos


func (s *AssignStmt) Pos() token.Position

type BadDecl
A BadDecl node is a placeholder for declarations containing syntax errors for which no correct declaration nodes can be created.
type BadDecl struct { token.Position // beginning position of bad declaration }

type BadExpr
A BadExpr node is a placeholder for expressions containing syntax errors for which no correct expression nodes can be created.
type BadExpr struct { token.Position // beginning position of bad expression }

type BadStmt
A BadStmt node is a placeholder for statements containing syntax errors for which no correct statement nodes can be created.

type BadStmt struct { token.Position // beginning position of bad statement }

type BasicLit
A BasicLit node represents a literal of basic type.
type BasicLit struct { token.Position // literal position Kind token.Token // token.INT, token.FLOAT, token.CHAR, or token.STRING Value []byte // literal string; e.g. 42, 0x7f, 3.14, 1e-9, 'a', '\x7f', "foo" or `\m\n\o` }

type BinaryExpr
A BinaryExpr node represents a binary expression.
type BinaryExpr struct { X Expr OpPos token.Position Op token.Token Y Expr }

// // // //

left operand position of Op operator right operand

func (*BinaryExpr) Pos


func (x *BinaryExpr) Pos() token.Position

type BlockStmt
A BlockStmt node represents a braced statement list.
type BlockStmt struct { token.Position // position of "{" List []Stmt Rbrace token.Position // position of "}" }

type BranchStmt
A BranchStmt node represents a break, continue, goto, or fallthrough statement.

type BranchStmt struct { // position of Tok token.Position Tok token.Token // keyword token (BREAK, CONTINUE, GOTO, FALLTHROUGH) Label *Ident }

type CallExpr
A CallExpr node represents an expression followed by an argument list.
type CallExpr struct { Fun Expr Lparen token.Position Args []Expr Rparen token.Position }

// // // //

function expression position of "(" function arguments positions of ")"

func (*CallExpr) Pos


func (x *CallExpr) Pos() token.Position

type CaseClause
A CaseClause represents a case of an expression switch statement.
type CaseClause struct { token.Position Values []Expr Colon token.Position Body []Stmt }

// // // //

position of "case" or "default" keyword nil means default case position of ":" statement list; or nil

type ChanDir
The direction of a channel type is indicated by one of the following constants.
type ChanDir int

const ( SEND ChanDir = 1 << iota RECV )

type ChanType
A ChanType node represents a channel type.

type ChanType struct { // position of "chan" keyword or "<-" (whichever comes first) token.Position Dir ChanDir // channel direction Value Expr // value type }

type CommClause
A CommClause node represents a case of a select statement.
type CommClause struct { token.Position Tok token.Token Lhs, Rhs Expr Colon token.Position Body []Stmt }

// // // // //

position of "case" or "default" keyword ASSIGN or DEFINE (valid only if Lhs != nil) Rhs == nil means default case position of ":" statement list; or nil

type Comment
A Comment node represents a single //-style or /*-style comment.
type Comment struct { token.Position // beginning position of the comment Text []byte // comment text (excluding '\n' for //-style comments) }

type CommentGroup
A CommentGroup represents a sequence of comments with no other tokens and no empty lines between.
type CommentGroup struct { List []*Comment }

type CompositeLit
A CompositeLit node represents a composite literal.
type CompositeLit struct { Type Expr // Lbrace token.Position // Elts []Expr // Rbrace token.Position // }

literal type position of "{" list of composite elements position of "}"

func (*Com positeLit) Pos

func (x *CompositeLit) Pos() token.Position

type Decl
All declaration nodes implement the Decl interface.
type Decl interface { Node // contains unexported methods }

type DeclStmt
A DeclStmt node represents a declaration in a statement list.
type DeclStmt struct { Decl Decl }

func (*DeclStm t) Pos


func (s *DeclStmt) Pos() token.Position Pos() implementations for statement nodes where the position corresponds to the position of a sub-node.

type DeferStmt
A DeferStmt node represents a defer statement.
type DeferStmt struct { token.Position // position of "defer" keyword Call *CallExpr }

type Ellipsis
An Ellipsis node stands for the "..." type in a parameter list or the "..." length in an array type.
type Ellipsis struct { token.Position // position of "..." Elt Expr // ellipsis element type (parameter lists only) }

type EmptyStmt
An EmptyStmt node represents an empty statement. The "position" of the empty statement is the position of

the immediately preceeding semicolon.


type EmptyStmt struct { token.Position // position of preceeding ";" }

type Expr
All expression nodes implement the Expr interface.
type Expr interface { Node // contains unexported methods }

type ExprStmt
An ExprStmt node represents a (stand-alone) expression in a statement list.
type ExprStmt struct { X Expr // expression }

func (*ExprStm t) Pos


func (s *ExprStmt) Pos() token.Position

type Field
A Field represents a Field declaration list in a struct type, a method list in an interface type, or a parameter/result declaration in a signature.
type Field struct { Doc *CommentGroup Names []*Ident Type Expr Tag *BasicLit Comment *CommentGroup }

// // // // //

associated documentation; or nil field/method/parameter names; or nil if anonymous field field/method/parameter type field tag; or nil line comments; or nil

func (*Field) Pos


func (f *Field) Pos() token.Position

type FieldList
A FieldList represents a list of Fields, enclosed by parentheses or braces.

type FieldList struct { Opening token.Position // position of opening parenthesis/brace List []*Field // field list Closing token.Position // position of closing parenthesis/brace }

func (*FieldList) Num Fields


func (f *FieldList) NumFields() int NumFields returns the number of (named and anonymous fields) in a FieldList.

type File
A File node represents a Go source file. The Comments list contains all comments in the source file in order of appearance, including the comments that are pointed to from other nodes via Doc and Comment fields.
type File struct { Doc token.Position Name Decls Comments }

*CommentGroup

// // *Ident // []Decl // []*CommentGroup //

associated documentation; or nil position of "package" keyword package name top-level declarations list of all comments in the source file

func MergePackageFiles
func MergePackageFiles(pkg *Package, complete bool) *File MergePackageFiles creates a file AST by merging the ASTs of the files belonging to a package. If complete is set, the package files are assumed to contain the complete, unfiltered package information. In this case, MergePackageFiles collects all entities and all comments. Otherwise (complete == false), MergePackageFiles excludes duplicate entries and does not collect comments that are not attached to AST nodes.

type ForStmt
A ForStmt represents a for statement.
type ForStmt struct { token.Position // position of "for" keyword Init Stmt Cond Expr Post Stmt Body *BlockStmt }

type FuncDecl

A FuncDecl node represents a function declaration.


type FuncDecl struct { Doc *CommentGroup Recv *FieldList Name *Ident Type *FuncType Body *BlockStmt }

// // // // //

associated documentation; or nil receiver (methods); or nil (functions) function/method name position of Func keyword, parameters and results function body; or nil (forward declaration)

func (*FuncDecl) Pos


func (d *FuncDecl) Pos() token.Position The position of a FuncDecl node is the position of its function type.

type FuncLit
A FuncLit node represents a function literal.
type FuncLit struct { Type *FuncType // function type Body *BlockStmt // function body }

func (*FuncLit) Pos


func (x *FuncLit) Pos() token.Position Pos() implementations for expression/type where the position corresponds to the position of a sub-node.

type FuncType
A FuncType node represents a function type.
type FuncType struct { token.Position // position of "func" keyword Params *FieldList // (incoming) parameters Results *FieldList // (outgoing) results }

type GenDecl
A GenDecl node (generic declaration node) represents an import, constant, type or variable declaration. A valid Lparen position (Lparen.Line > 0) indicates a parenthesized declaration. Relationship between Tok value and Specs element type:

token.IMPORT token.CONST token.TYPE token.VAR

*ImportSpec *ValueSpec *TypeSpec *ValueSpec

type GenDecl struct { Doc *CommentGroup token.Position Tok token.Token Lparen token.Position Specs []Spec Rparen token.Position }

// // // //

associated documentation; or nil position of Tok IMPORT, CONST, TYPE, VAR position of '(', if any

// position of ')', if any

type GoStmt
A GoStmt node represents a go statement.
type GoStmt struct { token.Position // position of "go" keyword Call *CallExpr }

type Ident
An Ident node represents an identifier.
type Ident struct { token.Position // identifier position Obj *Object // denoted object }

func New Ident


func NewIdent(name string) *Ident NewIdent creates a new Ident without position and minimal object information. Useful for ASTs generated by code other than the Go parser.

func (*Ident) IsExported


func (id *Ident) IsExported() bool IsExported returns whether id is an exported Go symbol (i.e., whether it begins with an uppercase letter).

func (*Ident) Nam e


func (id *Ident) Name() string Name returns an identifier's name.

func (*Ident) String

func (id *Ident) String() string

type IfStmt
An IfStmt node represents an if statement.
type IfStmt struct token.Position Init Cond Body Else } { // position of "if" keyword Stmt Expr *BlockStmt Stmt

type ImportSpec
An ImportSpec node represents a single package import.
type ImportSpec struct { Doc *CommentGroup Name *Ident Path *BasicLit Comment *CommentGroup }

// // // //

associated documentation; or nil local package name (including "."); or nil package path line comments; or nil

func (*Im portSpec) Pos


func (s *ImportSpec) Pos() token.Position Pos() implementations for spec nodes.

type IncDecStmt
An IncDecStmt node represents an increment or decrement statement.
type IncDecStmt struct { X Expr Tok token.Token // INC or DEC }

func (*IncDecStm t) Pos


func (s *IncDecStmt) Pos() token.Position

type IndexExpr
An IndexExpr node represents an expression followed by an index.

type IndexExpr struct { X Expr // expression Index Expr // index expression }

func (*IndexExpr) Pos


func (x *IndexExpr) Pos() token.Position

type InterfaceType
An InterfaceType node represents an interface type.
type InterfaceType struct { token.Position // position of "interface" keyword Methods *FieldList // list of methods Incomplete bool // true if (source) methods are missing in the Methods list }

type KeyValueExpr
A KeyValueExpr node represents (key : value) pairs in composite literals.
type KeyValueExpr struct { Key Expr Colon token.Position // position of ":" Value Expr }

func (*KeyValueExpr) Pos


func (x *KeyValueExpr) Pos() token.Position

type LabeledStmt
A LabeledStmt node represents a labeled statement.
type LabeledStmt struct { Label *Ident Stmt Stmt }

func (*LabeledStm t) Pos


func (s *LabeledStmt) Pos() token.Position

type MapType

A MapType node represents a map type.


type MapType struct { token.Position // position of "map" keyword Key Expr Value Expr }

type Node
All node types implement the Node interface.
type Node interface { // Pos returns the (beginning) position of the node. Pos() token.Position }

type ObjKind
type ObjKind int

The list of possible Object kinds.


const ( Err ObjKind = iota // object kind unknown (forward reference or error) Pkg // package Con // constant Typ // type Var // variable Fun // function or method )

type Object
An Object describes a language entity such as a package, constant, type, variable, or function (incl. methods).
type Object struct { Kind ObjKind Pos token.Position // declaration position Name string // declared name }

func New Obj


func NewObj(kind ObjKind, pos token.Position, name string) *Object

func (*Object) IsExported

func (obj *Object) IsExported() bool IsExported returns whether obj is exported.

type Package
A Package node represents a set of source files collectively building a Go package.
type Package struct { // package name Name string Scope *Scope // package scope Files map[string]*File // Go source files by filename }

type ParenExpr
A ParenExpr node represents a parenthesized expression.
type ParenExpr struct { token.Position // position of "(" X Expr // parenthesized expression Rparen token.Position // position of ")" }

type RangeStmt
A RangeStmt represents a for statement with a range clause.
type RangeStmt struct { token.Position Key, Value Expr TokPos token.Position Tok token.Token X Expr Body *BlockStmt }

// // // // //

position of "for" keyword Value may be nil position of Tok ASSIGN, DEFINE value to range over

type ReturnStmt
A ReturnStmt node represents a return statement.
type ReturnStmt struct { token.Position // position of "return" keyword Results []Expr }

type Scope
A Scope maintains the set of named language entities visible in the scope and a link to the immediately surrounding (outer) scope.
type Scope struct { Outer *Scope Objects map[string]*Object }

func New Scope


func NewScope(outer *Scope) *Scope NewScope creates a new scope nested in the outer scope.

func (*Scope) Declare


func (s *Scope) Declare(obj *Object) *Object Declare attempts to insert a named object into the scope s. If the scope does not contain an object with that name yet, Declare inserts the object, and returns it. Otherwise, the scope remains unchanged and Declare returns the object found in the scope instead.

func (*Scope) Lookup


func (s *Scope) Lookup(name string) *Object Lookup looks up an object in the current scope chain. The result is nil if the object is not found.

type SelectStmt
An SelectStmt node represents a select statement.
type SelectStmt struct { token.Position // position of "select" keyword Body *BlockStmt // CommClauses only }

type SelectorExpr
A SelectorExpr node represents an expression followed by a selector.
type SelectorExpr struct { X Expr // expression Sel *Ident // field selector }

func (*SelectorExpr) Pos


func (x *SelectorExpr) Pos() token.Position

type SliceExpr
An SliceExpr node represents an expression followed by slice indices.
type SliceExpr X Expr Index Expr End Expr } struct { // expression // beginning of slice range // end of slice range; or nil

func (*SliceExpr) Pos


func (x *SliceExpr) Pos() token.Position

type Spec
The Spec type stands for any of *ImportSpec, *ValueSpec, and *TypeSpec.
type Spec interface { Node // contains unexported methods }

type StarExpr
A StarExpr node represents an expression of the form "*" Expression. Semantically it could be a unary "*" expression, or a pointer type.
type StarExpr struct { // position of "*" token.Position X Expr // operand }

type Stmt
All statement nodes implement the Stmt interface.
type Stmt interface { Node // contains unexported methods }

type StructType
A StructType node represents a struct type.

type StructType struct { // position of "struct" keyword token.Position Fields *FieldList // list of field declarations Incomplete bool // true if (source) fields are missing in the Fields list }

type SwitchStmt
A SwitchStmt node represents an expression switch statement.
type SwitchStmt struct { token.Position // position of "switch" keyword Init Stmt Tag Expr Body *BlockStmt // CaseClauses only }

type TypeAssertExpr
A TypeAssertExpr node represents an expression followed by a type assertion.
type TypeAssertExpr struct { X Expr // expression Type Expr // asserted type; nil means type switch X.(type) }

func (*TypeAssertExpr) Pos


func (x *TypeAssertExpr) Pos() token.Position

type TypeCaseClause
A TypeCaseClause represents a case of a type switch statement.
type TypeCaseClause struct { token.Position Types []Expr Colon token.Position Body []Stmt }

// // // //

position of "case" or "default" keyword nil means default case position of ":" statement list; or nil

type TypeSpec
A TypeSpec node represents a type declaration (TypeSpec production).

type TypeSpec struct { Doc *CommentGroup Name *Ident Type Expr Comment *CommentGroup }

// // // //

associated documentation; or nil type name *ArrayType, *StructType, *FuncType, *InterfaceType, *MapType, *ChanType or *Ident line comments; or nil

func (*TypeSpec) Pos


func (s *TypeSpec) Pos() token.Position

type TypeSwitchStmt
An TypeSwitchStmt node represents a type switch statement.
type TypeSwitchStmt struct { token.Position // position of "switch" keyword Init Stmt Assign Stmt // x := y.(type) Body *BlockStmt // TypeCaseClauses only }

type UnaryExpr
A UnaryExpr node represents a unary expression. Unary "*" expressions are represented via StarExpr nodes.
type UnaryExpr struct { token.Position // position of Op Op token.Token // operator X Expr // operand }

type ValueSpec
A ValueSpec node represents a constant or variable declaration (ConstSpec or VarSpec production).
type ValueSpec struct { Doc *CommentGroup Names []*Ident Type Expr Values []Expr Comment *CommentGroup }

// // // // //

associated documentation; or nil value names value type; or nil initial values; or nil line comments; or nil

func (*ValueSpec) Pos


func (s *ValueSpec) Pos() token.Position

type Visitor
A Visitor's Visit method is invoked for each node encountered by Walk. If the result visitor w is not nil, Walk visits each of the children of node with the visitor w, followed by a call of w.Visit(nil).
type Visitor interface { Visit(node interface{}) (w Visitor) }

Except as noted, this content is licensed under Creative Commons Attribution 3.0.

The Go Programming Language

Package doc
func CommentText func ToHTML type FuncDoc type PackageDoc func NewFileDoc func NewPackageDoc func (*PackageDoc) Filter type TypeDoc type ValueDoc import "go/doc" The doc package extracts source code documentation from a Go AST. Package files
comment.go doc.go

func CommentText
func CommentText(comment *ast.CommentGroup) string CommentText returns the text of comment, with the comment markers - //, /*, and */ - removed.

func ToHTML
func ToHTML(w io.Writer, s []byte) Convert comment text to formatted HTML. The comment was prepared by DocReader, so it is known not to have leading, trailing blank lines nor to have trailing spaces at the end of lines. The comment markers have already been removed. Turn each run of multiple \n into </p><p> T urn each run of indented lines into <pre> without indent. TODO(rsc): I'd like to pass in an array of variable names []string and then italicize those strings when they appear as words.

type FuncDoc
FuncDoc is the documentation for a func declaration, either a top-level function or a method function.

type FuncDoc struct { Doc string Recv ast.Expr // TODO(rsc): Would like string here Name string Decl *ast.FuncDecl }

type PackageDoc
PackageDoc is the documentation for an entire package.
type PackageDoc PackageName ImportPath Filenames Doc Consts Types Vars Funcs Bugs } struct { string string []string string []*ValueDoc []*TypeDoc []*ValueDoc []*FuncDoc []string

func New FileDoc


func NewFileDoc(file *ast.File) *PackageDoc

func New PackageDoc


func NewPackageDoc(pkg *ast.Package, importpath string) *PackageDoc

func (*PackageDoc) Filter


func (p *PackageDoc) Filter(names []string) Filter eliminates information from d that is not about one of the given names. TODO: Recognize "Type.Method" as a name. TODO(r): maybe precompile the regexps.

type TypeDoc
TypeDoc is the documentation for a declared type. Consts and Vars are sorted lists of constants and variables of (mostly) that type. Factories is a sorted list of factory functions that return that type. Methods is a sorted list of method functions on that type.

type TypeDoc struct { Doc string Type *ast.TypeSpec Consts []*ValueDoc Vars []*ValueDoc Factories []*FuncDoc Methods []*FuncDoc Decl *ast.GenDecl // contains unexported fields }

type ValueDoc
ValueDoc is the documentation for a group of declared values, either vars or consts.
type ValueDoc struct { Doc string Decl *ast.GenDecl // contains unexported fields }

Except as noted, this content is licensed under Creative Commons Attribution 3.0.

The Go Programming Language

Package parser
Constants func ParseDeclList func ParseDir func ParseExpr func ParseFile func ParseFiles func ParseStmtList import "go/parser" A parser for Go source files. Input may be provided in a variety of forms (see the various Parse* functions); the output is an abstract syntax tree (AST) representing the Go source. The parser is invoked through one of the Parse* functions. Package files
interf ace.go parser.go

Constants
The mode parameter to the Parse* functions is a set of flags (or 0). They control the amount of source code parsed and other optional parser functionality.
const ( PackageClauseOnly uint = 1 << iota // parsing stops after package clause ImportsOnly // parsing stops after import declarations ParseComments // parse comments and add them to AST Trace // print a trace of parsed productions )

func ParseDeclList
func ParseDeclList(filename string, src interface{}, scope *ast.Scope) ([]ast.Decl, os.Error) ParseDeclList parses a list of Go declarations and returns the list of corresponding AST nodes. The filename, src, and scope arguments have the same interpretation as for ParseFile. If there is an error, the node list may be nil or contain partial ASTs.

func ParseDir
func ParseDir(path string, filter func(*os.Dir) bool, mode uint) (map[string]*ast.Package, os.Error)

ParseDir calls ParseFile for the files in the directory specified by path and returns a map of package name -> package AST with all the packages found. If filter != nil, only the files with os.Dir entries passing through the filter are considered. The mode bits are passed to ParseFile unchanged. If the directory couldn't be read, a nil map and the respective error are returned. If a parse error occured, a non-nil but incomplete map and the error are returned.

func ParseExpr
func ParseExpr(filename string, src interface{}, scope *ast.Scope) (ast.Expr, os.Error) ParseExpr parses a Go expression and returns the corresponding AST node. The filename, src, and scope arguments have the same interpretation as for ParseFile. If there is an error, the result expression may be nil or contain a partial AST.

func ParseFile
func ParseFile(filename string, src interface{}, scope *ast.Scope, mode uint) (*ast.File, os.Error) ParseFile parses a Go source file and returns a File node. If src != nil, ParseFile parses the file source from src. src may be provided in a variety of formats. At the moment the following types are supported: string, []byte, and io.Reader. In this case, filename is only used for source position information and error messages. If src == nil, ParseFile parses the file specified by filename. If scope != nil, it is the immediately surrounding scope for the file (the package scope) and it is used to lookup and declare identifiers. When parsing multiple files belonging to a package, the same scope should be provided to all files. The mode parameter controls the amount of source text parsed and other optional parser functionality. If the source couldn't be read, the returned AST is nil and the error indicates the specific failure. If the source was read but syntax errors were found, the result is a partial AST (with ast.BadX nodes representing the fragments of erroneous source code). Multiple errors are returned via a scanner.ErrorList which is sorted by file position.

func ParseFiles
func ParseFiles(filenames []string, scope *ast.Scope, mode uint) (map[string]*ast.Package, os.Error) ParseFiles calls ParseFile for each file in the filenames list and returns a map of package name -> package AST with all the packages found. The mode bits are passed to ParseFile unchanged. Files with parse errors are ignored. In this case the map of packages may be incomplete (missing packages and/or incomplete packages) and the last error encountered is returned.

func ParseStmtList

func ParseStmtList(filename string, src interface{}, scope *ast.Scope) ([]ast.Stmt, os.Error) ParseStmtList parses a list of Go statements and returns the list of corresponding AST nodes. The filename, src, and scope arguments have the same interpretation as for ParseFile. If there is an error, the node list may be nil or contain partial ASTs.

Except as noted, this content is licensed under Creative Commons Attribution 3.0.

The Go Programming Language

Package printer
Constants func Fprint type Config func (*Config) Fprint type HTMLTag type Styler import "go/printer" The printer package implements printing of AST nodes. Package files
nodes.go printer.go

Constants
General printing is controlled with these Config.Mode flags.
const ( GenHTML uint = 1 << iota // generate HTML RawFormat // do not use a tabwriter; if set, UseSpaces is ignored TabIndent // use tabs for indentation independent of UseSpaces UseSpaces // use spaces instead of tabs for alignment )

func Fprint
func Fprint(output io.Writer, node interface{}) os.Error Fprint "pretty-prints" an AST node to output. It calls Config.Fprint with default settings.

type Config
A Config node controls the output of Fprint.
type Config struct { Mode uint // default: 0 Tabwidth int // default: 8 Styler Styler // default: nil }

func (*Config) Fprint

func (cfg *Config) Fprint(output io.Writer, node interface{}) (int, os.Error) Fprint "pretty-prints" an AST node to output and returns the number of bytes written and an error (if any) for a given configuration cfg. The node type must be *ast.File, or assignment-compatible to ast.Expr, ast.Decl, or ast.Stmt.

type HTMLTag
An HTMLTag specifies a start and end tag.
type HTMLTag struct { Start, End string // empty if tags are absent }

type Styler
A Styler specifies formatting of line tags and elementary Go words. A format consists of text and a (possibly empty) surrounding HTML tag.
type Styler interface { LineTag(line int) ([]byte, HTMLTag) Comment(c *ast.Comment, line []byte) ([]byte, HTMLTag) BasicLit(x *ast.BasicLit) ([]byte, HTMLTag) Ident(id *ast.Ident) ([]byte, HTMLTag) Token(tok token.Token) ([]byte, HTMLTag) }

Except as noted, this content is licensed under Creative Commons Attribution 3.0.

The Go Programming Language

Package scanner
Constants func PrintError func Tokenize type Error func (*Error) String type ErrorHandler type ErrorList func (ErrorList) Len func (ErrorList) Less func (ErrorList) String func (ErrorList) Swap import "go/scanner" A scanner for Go source text. Takes a []byte as source which can then be tokenized through repeated calls to the Scan function. For a sample use of a scanner, see the implementation of Tokenize. Package files
errors.go scanner.go

type ErrorVector func (*ErrorVector) Error func (*ErrorVector) ErrorCount func (*ErrorVector) GetError func (*ErrorVector) GetErrorList func (*ErrorVector) Reset type Scanner func (*Scanner) Init func (*Scanner) Scan

Constants
These constants control the construction of the ErrorList returned by GetErrors.
const ( Raw = iota // leave error list unchanged Sorted // sort error list by file, line, and column number NoMultiples // sort error list and leave only the first error per line )

The mode parameter to the Init function is a set of flags (or 0). They control scanner behavior.
const ( ScanComments = 1 << iota // return comments as COMMENT tokens AllowIllegalChars // do not report an error for illegal chars InsertSemis // automatically insert semicolons )

func PrintError
func PrintError(w io.Writer, err os.Error) PrintError is a utility function that prints a list of errors to w, one error per line, if the err parameter is an

ErrorList. Otherwise it prints the err string.

func Tokenize
func Tokenize(filename string, src []byte, err ErrorHandler, mode uint, f func(pos token.Position, tok token.Token, lit []byte) bool) int Tokenize calls a function f with the token position, token value, and token text for each token in the source src. The other parameters have the same meaning as for the Init function. Tokenize keeps scanning until f returns false (usually when the token value is token.EOF). The result is the number of errors encountered.

type Error
Within ErrorVector, an error is represented by an Error node. The position Pos, if valid, points to the beginning of the offending token, and the error condition is described by Msg.
type Error struct { Pos token.Position Msg string }

func (*Error) String


func (e *Error) String() string

type ErrorHandler
An implementation of an ErrorHandler may be provided to the Scanner. If a syntax error is encountered and a handler was installed, Error is called with a position and an error message. The position points to the beginning of the offending token.
type ErrorHandler interface { Error(pos token.Position, msg string) }

type ErrorList
An ErrorList is a (possibly sorted) list of Errors.
type ErrorList []*Error

func (ErrorList) Len


func (p ErrorList) Len() int ErrorList implements the sort Interface.

func (ErrorList) Less

func (p ErrorList) Less(i, j int) bool

func (ErrorList) String


func (p ErrorList) String() string

func (ErrorList) Sw ap
func (p ErrorList) Swap(i, j int)

type ErrorVector
ErrorVector implements the ErrorHandler interface. It maintains a list of errors which can be retrieved with GetErrorList and GetError. The zero value for an ErrorVector is an empty ErrorVector ready to use. A common usage pattern is to embed an ErrorVector alongside a scanner in a data structure that uses the scanner. By passing a reference to an ErrorVector to the scanner's Init call, default error handling is obtained.
type ErrorVector struct { // contains unexported fields }

func (*ErrorVector) Error


func (h *ErrorVector) Error(pos token.Position, msg string) ErrorVector implements the ErrorHandler interface.

func (*ErrorVector) ErrorCount


func (h *ErrorVector) ErrorCount() int ErrorCount returns the number of errors collected.

func (*ErrorVector) GetError


func (h *ErrorVector) GetError(mode int) os.Error GetError is like GetErrorList, but it returns an os.Error instead so that a nil result can be assigned to an os.Error variable and remains nil.

func (*ErrorVector) GetErrorList


func (h *ErrorVector) GetErrorList(mode int) ErrorList GetErrorList returns the list of errors collected by an ErrorVector. The construction of the ErrorList returned is controlled by the mode parameter. If there are no errors, the result is nil.

func (*ErrorVector) Reset


func (h *ErrorVector) Reset() Reset resets an ErrorVector to no errors.

type Scanner
A Scanner holds the scanner's internal state while processing a given text. It can be allocated as part of another data structure but must be initialized via Init before use. For a sample use, see the implementation of Tokenize.
type Scanner struct {

// public state - ok to modify ErrorCount int // number of errors encountered // contains unexported fields }

func (*Scanner) Init


func (S *Scanner) Init(filename string, src []byte, err ErrorHandler, mode uint) Init prepares the scanner S to tokenize the text src. Calls to Scan will use the error handler err if they encounter a syntax error and err is not nil. Also, for each error encountered, the Scanner field ErrorCount is incremented by one. The filename parameter is used as filename in the token.Position returned by Scan for each token. The mode parameter determines how comments and illegal characters are handled.

func (*Scanner) Scan


func (S *Scanner) Scan() (pos token.Position, tok token.Token, lit []byte) Scan scans the next token and returns the token position pos, the token tok, and the literal text lit corresponding to the token. The source end is indicated by token.EOF. For more tolerant parsing, Scan will return a valid token if possible even if a syntax error was encountered. Thus, even if the resulting token sequence contains no illegal tokens, a client may not assume that no error occurred. Instead it must check the scanner's ErrorCount or the number of calls of the error handler, if there was one installed.

Except as noted, this content is licensed under Creative Commons Attribution 3.0.

The Go Programming Language

Package token
Constants type Position func (*Position) IsValid func (*Position) Pos func (Position) String type Token func Lookup func (Token) IsKeyword func (Token) IsLiteral func (Token) IsOperator func (Token) Precedence func (Token) String import "go/token" This package defines constants representing the lexical tokens of the Go programming language and basic operations on tokens (printing, predicates). Package files
token.go

Constants
A set of constants for precedence-based expression parsing. Non-operators have lowest precedence, followed by operators starting with precedence 1 up to unary operators. The highest precedence corresponds serves as "catch-all" precedence for selector, indexing, and other operator and delimiter tokens.
const ( LowestPrec = 0 // non-operators UnaryPrec = 7 HighestPrec = 8 )

type Position
Token source positions are represented by a Position value. A Position is valid if the line number is > 0.
type Position struct { Filename string // Offset int // Line int // Column int // }

filename, if any byte offset, starting at 0 line number, starting at 1 column number, starting at 1 (character count)

func (*Position) IsValid


func (pos *Position) IsValid() bool IsValid returns true if the position is valid.

func (*Position) Pos


func (pos *Position) Pos() Position Pos is an accessor method for anonymous Position fields. It returns its receiver.

func (Position) String


func (pos Position) String() string

type Token
Token is the set of lexical tokens of the Go programming language.
type Token int

The list of tokens.

const ( // Special tokens ILLEGAL Token = iota EOF COMMENT

// Identifiers and basic type literals // (these tokens stand for classes of literals) IDENT // main INT // 12345 FLOAT // 123.45 IMAG // 123.45i CHAR // 'a' STRING // "abc"

// Operators and delimiters ADD // + SUB // MUL // * QUO // / REM // % AND OR XOR SHL SHR AND_NOT // // // // // // & | ^ << >> &^ // // // // // += -= *= /= %= // // // // // // &= |= ^= <<= >>= &^=

ADD_ASSIGN SUB_ASSIGN MUL_ASSIGN QUO_ASSIGN REM_ASSIGN

AND_ASSIGN OR_ASSIGN XOR_ASSIGN SHL_ASSIGN SHR_ASSIGN AND_NOT_ASSIGN LAND LOR ARROW INC DEC // // // // // && || <++ -== < > = !

EQL LSS GTR ASSIGN NOT

// // // // //

NEQ LEQ GEQ DEFINE ELLIPSIS

// // // // //

!= <= >= := ...

LPAREN // ( LBRACK // [ LBRACE // {

func Lookup
func Lookup(ident []byte) Token Lookup maps an identifier to its keyword token or IDENT (if not a keyword).

func (Token) IsKeyw ord


func (tok Token) IsKeyword() bool IsKeyword returns true for tokens corresponding to keywords; returns false otherwise.

func (Token) IsLiteral


func (tok Token) IsLiteral() bool IsLiteral returns true for tokens corresponding to identifiers and basic type literals; returns false otherwise.

func (Token) IsOperator


func (tok Token) IsOperator() bool IsOperator returns true for tokens corresponding to operators and delimiters; returns false otherwise.

func (Token) Precedence


func (op Token) Precedence() int Precedence returns the operator precedence of the binary operator op. If op is not a binary operator, the result is LowestPrecedence.

func (Token) String


func (tok Token) String() string String returns the string corresponding to the token tok. For operators, delimiters, and keywords the string is the actual token character sequence (e.g., for the token ADD, the string is "+"). For all other tokens the string corresponds to the token constant name (e.g. for the token IDENT, the string is "IDENT").

Except as noted, this content is licensed under Creative Commons Attribution 3.0.

The Go Programming Language

Package gob
func Debug type Decoder func NewDecoder func (*Decoder) Decode type Encoder func NewEncoder func (*Encoder) Encode Other packages import "gob" The gob package manages streams of gobs - binary values exchanged between an Encoder (transmitter) and a Decoder (receiver). A typical use is transporting arguments and results of remote procedure calls (RPCs) such as those provided by package "rpc". A stream of gobs is self-describing. Each data item in the stream is preceded by a specification of its type, expressed in terms of a small set of predefined types. Pointers are not transmitted, but the things they point to are transmitted; that is, the values are flattened. Recursive types work fine, but recursive values (data with cycles) are problematic. This may change. To use gobs, create an Encoder and present it with a series of data items as values or addresses that can be dereferenced to values. (At the moment, these items must be structs (struct, *struct, **struct etc.), but this may change.) The Encoder makes sure all type information is sent before it is needed. At the receive side, a Decoder retrieves values from the encoded stream and unpacks them into local variables. The source and destination values/types need not correspond exactly. For structs, fields (identified by name) that are in the source but absent from the receiving variable will be ignored. Fields that are in the receiving variable but missing from the transmitted type or value will be ignored in the destination. If a field with the same name is present in both, their types must be compatible. Both the receiver and transmitter will do all necessary indirection and dereferencing to convert between gobs and actual Go values. For instance, a gob type that is schematically,
struct { a, b int }

can be sent from or received into any of these Go types:


struct { a, b int } *struct { a, b int } struct { *a, **b int } struct { a, b int64 } // // // // the same extra indirection of the struct extra indirection of the fields different concrete value type; see below

It may also be received into any of these:

struct struct struct struct struct

{ { { { {

a, b int } b, a int } a, b, c int } b int } b, c int }

// // // // //

the same ordering doesn't matter; matching is by name extra field (c) ignored missing field (a) ignored; data will be dropped missing field (a) ignored; extra field (c) ignored.

Attempting to receive into these types will draw a decode error:


struct struct struct struct { { { { a int; b uint } a int; b float } } c, d int } // // // // change of signedness for b change of type for b no field names in common no field names in common

Integers are transmitted two ways: arbitrary precision signed integers or arbitrary precision unsigned integers. There is no int8, int16 etc. discrimination in the gob format; there are only signed and unsigned integers. As described below, the transmitter sends the value in a variable-length encoding; the receiver accepts the value and stores it in the destination variable. Floating-point numbers are always sent using IEEE-754 64-bit precision (see below). Signed integers may be received into any signed integer variable: int, int16, etc.; unsigned integers may be received into any unsigned integer variable; and floating point values may be received into any floating point variable. However, the destination variable must be able to represent the value or the decode operation will fail. Structs, arrays and slices are also supported. Strings and arrays of bytes are supported with a special, efficient representation (see below). Maps are not supported yet, but they will be. Interfaces, functions, and channels cannot be sent in a gob. Attempting to encode a value that contains one will fail. The rest of this comment documents the encoding, details that are not important for most users. Details are presented bottom-up. An unsigned integer is sent one of two ways. If it is less than 128, it is sent as a byte with that value. Otherwise it is sent as a minimal-length big-endian (high byte first) byte stream holding the value, preceded by one byte holding the byte count, negated. Thus 0 is transmitted as (00), 7 is transmitted as (07) and 256 is transmitted as (FE 01 00). A boolean is encoded within an unsigned integer: 0 for false, 1 for true. A signed integer, i, is encoded within an unsigned integer, u. Within u, bits 1 upward contain the value; bit 0 says whether they should be complemented upon receipt. The encode algorithm looks like this:
uint u; if i < 0 { u = (^i << 1) | 1 // complement i, bit 0 is 1 } else { u = (i << 1) // do not complement i, bit 0 is 0 } encodeUnsigned(u)

The low bit is therefore analogous to a sign bit, but making it the complement bit instead guarantees that the largest negative integer is not a special case. For example, -129=^128=(^256>>1) encodes as (01 82). Floating-point numbers are always sent as a representation of a float64 value. That value is converted to a uint64 using math.Float64bits. The uint64 is then byte-reversed and sent as a regular unsigned integer. The

byte-reversal means the exponent and high-precision part of the mantissa go first. Since the low bits are often zero, this can save encoding bytes. For instance, 17.0 is encoded in only two bytes (40 e2). Strings and slices of bytes are sent as an unsigned count followed by that many uninterpreted bytes of the value. All other slices and arrays are sent as an unsigned count followed by that many elements using the standard gob encoding for their type, recursively. Structs are sent as a sequence of (field number, field value) pairs. The field value is sent using the standard gob encoding for its type, recursively. If a field has the zero value for its type, it is omitted from the transmission. The field number is defined by the type of the encoded struct: the first field of the encoded type is field 0, the second is field 1, etc. When encoding a value, the field numbers are delta encoded for efficiency and the fields are always sent in order of increasing field number; the deltas are therefore unsigned. The initialization for the delta encoding sets the field number to -1, so an unsigned integer field 0 with value 7 is transmitted as unsigned delta = 1, unsigned value = 7 or (81 87). Finally, after all the fields have been sent a terminating mark denotes the end of the struct. T hat mark is a delta=0 value, which has representation (80). The representation of types is described below. When a type is defined on a given connection between an Encoder and Decoder, it is assigned a signed integer type id. When Encoder.Encode(v) is called, it makes sure there is an id assigned for the type of v and all its elements and then it sends the pair (typeid, encoded-v) where typeid is the type id of the encoded type of v and encoded-v is the gob encoding of the value v. To define a type, the encoder chooses an unused, positive type id and sends the pair (-type id, encoded-type) where encoded-type is the gob encoding of a wireType description, constructed from these types:
type wireType struct { s structType; } type fieldType struct { name string; // the id int; // the } type commonType { name string; // the id int; // the } type structType struct { commonType; field []fieldType; }

name of the field. type id of the field, which must be already defined

name of the struct type id of the type, repeated for so it's inside the type

// the fields of the struct.

If there are nested type ids, the types for all inner type ids must be defined before the top-level type id is used to describe an encoded-v. For simplicity in setup, the connection is defined to understand these types a priori, as well as the basic gob types int, uint, etc. Their ids are:

bool int uint float []byte string wireType structType commonType fieldType

1 2 3 4 5 6 7 8 9 10

In summary, a gob stream looks like


((-type id, encoding of a wireType)* (type id, encoding of a value))*

where * signifies zero or more repetitions and the type id of a value must be predefined or be defined before the value in the stream. Package files
debug.go decode.go decoder.go encode.go encoder.go ty pe.go

func Debug
func Debug(r io.Reader) Debug prints a human-readable representation of the gob data read from r.

type Decoder
A Decoder manages the receipt of type and data information read from the remote side of a connection.
type Decoder struct { // contains unexported fields }

func New Decoder


func NewDecoder(r io.Reader) *Decoder NewDecoder returns a new decoder that reads from the io.Reader.

func (*Decoder) Decode


func (dec *Decoder) Decode(e interface{}) os.Error Decode reads the next value from the connection and stores it in the data represented by the empty interface value. The value underlying e must be the correct type for the next data item received.

type Encoder
An Encoder manages the transmission of type and data information to the other side of a connection.

type Encoder struct { // contains unexported fields }

func New Encoder


func NewEncoder(w io.Writer) *Encoder NewEncoder returns a new encoder that will transmit on the io.Writer.

func (*Encoder) Encode


func (enc *Encoder) Encode(e interface{}) os.Error Encode transmits the data item represented by the empty interface value, guaranteeing that all necessary type information has been transmitted first.

Other packages
main

Except as noted, this content is licensed under Creative Commons Attribution 3.0.

The Go Programming Language

Package adler32
Constants func Checksum func New import "hash/adler32" This package implements the Adler-32 checksum. 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 mostsignificant-byte first (network) order.

Package files
adler32.go

Constants
The size of an Adler-32 checksum in bytes.
const Size = 4

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.

Except as noted, this content is licensed under Creative Commons Attribution 3.0.

The Go Programming Language

Package crc32
Constants Variables func Checksum func ChecksumIEEE func New func NewIEEE func Update type Table func MakeTable import "hash/crc32" This package implements the 32-bit cyclic redundancy check, or CRC-32, checksum. See http://en.wikipedia.org/wiki/Cyclic_redundancy_check for information. Package files
crc32.go

Constants
Predefined polynomials.
const ( // Far and away the most common CRC-32 polynomial. // Used by ethernet (IEEE 802.3), v.42, fddi, gzip, zip, png, mpeg-2, ... 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 )

The size of a CRC-32 checksum in bytes.


const Size = 4

Variables

IEEETable is the table for the IEEE polynomial.


var IEEETable = MakeTable(IEEE)

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.

func NewIEEE
func NewIEEE() hash.Hash32 NewIEEE creates a new hash.Hash32 computing the CRC-32 checksum using the IEEE polynomial.

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
Table is a 256-word table representing the polynomial for efficient processing.
type Table [256]uint32

func MakeTable
func MakeTable(poly uint32) *Table MakeTable returns the Table constructed from the specified polynomial.

Except as noted, this content is licensed under Creative Commons Attribution 3.0.

The Go Programming Language

Package crc64
Constants func Checksum func New func Update type Table func MakeTable import "hash/crc64" This package implements the 64-bit cyclic redundancy check, or CRC-64, checksum. See http://en.wikipedia.org/wiki/Cyclic_redundancy_check for information. Package files
crc64.go

Constants
Predefined polynomials.
const ( // The ISO polynomial, defined in ISO 3309 and used in HDLC. ISO = 0xD800000000000000 // The ECMA polynomial, defined in ECMA 182. ECMA = 0xC96C5795D7870F42 )

The size of a CRC-64 checksum in bytes.


const Size = 8

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.

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
Table is a 256-word table representing the polynomial for efficient processing.
type Table [256]uint64

func MakeTable
func MakeTable(poly uint64) *Table MakeTable returns the Table constructed from the specified polynomial.

Except as noted, this content is licensed under Creative Commons Attribution 3.0.

The Go Programming Language

Package http
Constants Variables func CanonicalHeaderKey func CanonicalPath func DumpRequest func DumpResponse func Handle func ListenAndServe func NewChunkedWriter func NotFound func Redirect func Serve func ServeFile func URLEscape func URLUnescape type ClientConn func NewClientConn func (*ClientConn) Close func (*ClientConn) Pending func (*ClientConn) Read func (*ClientConn) Write type Conn func (*Conn) Flush func (*Conn) Hijack func (*Conn) SetHeader func (*Conn) Write func (*Conn) WriteHeader type Handler func FileServer func NotFoundHandler func RedirectHandler type HandlerFunc func (HandlerFunc) ServeHTTP type ProtocolError type Request import "http" The http package implements parsing of HTTP requests, replies, and URLs and provides an extensible HTTP server and a basic HTTP client. Package files
chunked.go client.go dump.go f s.go lex.go persist.go request.go response.go serv er.go status.go transf er.go url.go

func ReadRequest func (*Request) FormValue func (*Request) ParseForm func (*Request) ProtoAtLeast func (*Request) Write type Response func Get func Post func ReadResponse func (*Response) AddHeader func (*Response) GetHeader func (*Response) ProtoAtLeast func (*Response) Write type ServeMux func NewServeMux func (*ServeMux) Handle func (*ServeMux) ServeHTTP type ServerConn func NewServerConn func (*ServerConn) Close func (*ServerConn) Pending func (*ServerConn) Read func (*ServerConn) Write type URL func ParseURL func ParseURLReference func (*URL) String type URLError func (*URLError) String type URLEscapeError func (URLEscapeError) String Other packages

Constants

HTTP status codes, defined in RFC 2616.


const ( StatusContinue = 100 StatusSwitchingProtocols = 101 StatusOK StatusCreated StatusAccepted StatusNonAuthoritativeInfo StatusNoContent StatusResetContent StatusPartialContent StatusMultipleChoices StatusMovedPermanently StatusFound StatusSeeOther StatusNotModified StatusUseProxy StatusTemporaryRedirect = = = = = = = = = = = = = = 200 201 202 203 204 205 206

300 301 302 303 304 305 307 = = = = = = = = = = = = = = = = = = 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417

StatusBadRequest StatusUnauthorized StatusPaymentRequired StatusForbidden StatusNotFound StatusMethodNotAllowed StatusNotAcceptable StatusProxyAuthRequired StatusRequestTimeout StatusConflict StatusGone StatusLengthRequired StatusPreconditionFailed StatusRequestEntityTooLarge StatusRequestURITooLong StatusUnsupportedMediaType StatusRequestedRangeNotSatisfiable StatusExpectationFailed StatusInternalServerError StatusNotImplemented StatusBadGateway StatusServiceUnavailable StatusGatewayTimeout StatusHTTPVersionNotSupported ) = = = = = =

500 501 502 503 504 505

Variables
Errors introduced by the HTTP server.
var ( ErrWriteAfterFlush = os.NewError("Conn.Write called after Flush") ErrHijacked = os.NewError("Conn has been hijacked") )

var ( ErrLineTooLong ErrHeaderTooLong ErrShortBody ErrNotSupported ErrUnexpectedTrailer ErrMissingContentLength )

= = = = = =

&ProtocolError{"header line too long"} &ProtocolError{"header too long"} &ProtocolError{"entity body too short"} &ProtocolError{"feature not supported"} &ProtocolError{"trailer header without chunked transfer encoding"} &ProtocolError{"missing ContentLength in HEAD response"}

DefaultServeMux is the default ServeMux used by Serve.


var DefaultServeMux = NewServeMux()

var ErrPersistEOF = &ProtocolError{"persistent connection closed"}

func CanonicalHeaderKey
func CanonicalHeaderKey(s string) string CanonicalHeaderKey returns the canonical format of the HTTP 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".

func CanonicalPath
func CanonicalPath(path string) string CanonicalPath applies the algorithm specified in RFC 2396 to simplify the path, removing unnecessary . and .. elements.

func DumpRequest
func DumpRequest(req *Request, body bool) (dump []byte, err os.Error) DumpRequest returns the wire representation of req, optionally including the request body, for debugging. DumpRequest is semantically a no-op, but in order to dump the body, it reads the body data into memory and changes req.Body to refer to the in-memory copy.

func DumpResponse
func DumpResponse(resp *Response, body bool) (dump []byte, err os.Error) DumpResponse is like DumpRequest but dumps a response.

func Handle
func Handle(pattern string, handler Handler)

Handle registers the handler for the given pattern in the DefaultServeMux.

func ListenAndServe
func ListenAndServe(addr string, handler Handler) os.Error ListenAndServe listens on the TCP network address addr and then calls Serve with handler to handle requests on incoming connections. Handler is typically nil, in which case the DefaultServeMux is used. A trivial example server is:
package main import ( "http"; "io"; ) // hello world, the web server func HelloServer(c *http.Conn, req *http.Request) { io.WriteString(c, "hello, world!\n"); } func main() { http.Handle("/hello", http.HandlerFunc(HelloServer)); err := http.ListenAndServe(":12345", nil); if err != nil { panic("ListenAndServe: ", err.String()) } }

func NewChunkedWriter
func NewChunkedWriter(w io.Writer) io.WriteCloser NewChunkedWriter returns a new writer that translates writes into HTTP "chunked" format before writing them to w. Closing the returned writer sends the final 0-length chunk that marks the end of the stream.

func NotFound
func NotFound(c *Conn, req *Request) NotFound replies to the request with an HTTP 404 not found error.

func Redirect
func Redirect(c *Conn, url string, code int) Redirect replies to the request with a redirect to url, which may be a path relative to the request path.

func Serve
func Serve(l net.Listener, handler Handler) os.Error Serve accepts incoming HTTP connections on the listener l, creating a new service thread for each. The service threads read requests and then call handler to reply to them. Handler is typically nil, in which case the DefaultServeMux is used.

func ServeFile
func ServeFile(c *Conn, r *Request, name string) ServeFile replies to the request with the contents of the named file or directory.

func URLEscape
func URLEscape(s string) string URLEscape converts a string into URL-encoded form.

func URLUnescape
func URLUnescape(s string) (string, os.Error) URLUnescape unescapes a URL-encoded string, converting %AB into the byte 0xAB and '+' into ' ' (space). It returns an error if any % is not followed by two hexadecimal digits.

type ClientConn
A ClientConn sends request and receives headers over an underlying connection, while respecting the HTTP keepalive logic. ClientConn is not responsible for closing the underlying connection. One must call Close to regain control of that connection and deal with it as desired.
type ClientConn struct { // contains unexported fields }

func New ClientConn


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.

func (*ClientConn) Close


func (cc *ClientConn) Close() (c net.Conn, r *bufio.Reader) Close detaches the ClientConn and returns the underlying connection as well as the read-side bufio which may have some left over data. Close may be called before the user or Read have signaled the end of the keep-alive logic. The user should not call Close 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() (resp *Response, err os.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 *Request) os.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. Write can be called concurrently with Read, but not with another Write.

type Conn
A Conn represents the server side of a single active HTTP connection.
type Conn struct { RemoteAddr string // network address of remote side Req *Request // current HTTP request // contains unexported fields }

func (*Conn) Flush


func (c *Conn) Flush() Flush sends any buffered data to the client.

func (*Conn) Hijack


func (c *Conn) Hijack() (rwc io.ReadWriteCloser, buf *bufio.ReadWriter, err os.Error) Hijack lets the caller take over the connection. After a call to c.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.

func (*Conn) SetHeader


func (c *Conn) SetHeader(hdr, val string) SetHeader sets a header line in the eventual reply. For example, SetHeader("Content-Type", "text/html; charset=utf-8") will result in the header line

Content-Type: text/html; charset=utf-8

being sent. UTF-8 encoded HTML is the default setting for Content-Type in this library, so users need not make that particular call. Calls to SetHeader after WriteHeader (or Write) are ignored.

func (*Conn) Write


func (c *Conn) Write(data []byte) (n int, err os.Error) 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.

func (*Conn) WriteHeader


func (c *Conn) WriteHeader(code int) 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.

type Handler
Objects implementing the Handler interface can be registered to serve a particular path or subtree in the HTTP server. ServeHTTP should write reply headers and data to the Conn and then return. Returning signals that the request is finished and that the HTTP server can move on to the next request on the connection.
type Handler interface { ServeHTTP(*Conn, *Request) }

func FileServer
func FileServer(root, prefix string) Handler FileServer returns a handler that serves HTTP requests with the contents of the file system rooted at root. It strips prefix from the incoming requests before looking up the file name in the file system.

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.

type HandlerFunc
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 object that calls f.
type HandlerFunc func(*Conn, *Request)

func (HandlerFunc) ServeHTTP


func (f HandlerFunc) ServeHTTP(c *Conn, req *Request) ServeHTTP calls f(c, req).

type ProtocolError
HTTP request parsing errors.
type ProtocolError struct { os.ErrorString }

type Request
A Request represents a parsed HTTP request header.

type Request struct { Method string RawURL string URL *URL Proto string ProtoMajor int ProtoMinor int

// // // // // //

GET, POST, PUT, etc. The raw URL given in the request. Parsed URL. "HTTP/1.0" 1 0

// A header mapping request lines to their values. // If the header says // // Accept-Language: en-us // accept-encoding: gzip, deflate // Connection: keep-alive // // then // // Header = map[string]string{ // "Accept-Encoding": "en-us", // "Accept-Language": "gzip, deflate", // "Connection": "keep-alive" // } // // HTTP defines that header names are case-insensitive. // The request parser implements this by canonicalizing the // name, making the first character and any characters // following a hyphen uppercase and the rest lowercase. Header map[string]string // The message body. 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. ContentLength int64 // TransferEncoding lists the transfer encodings from outermost to innermost. // An empty list denotes the "identity" encoding. TransferEncoding []string // Whether to close the connection after replying to this request. Close bool // 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. Host string // 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 structure field is that the compiler // can diagnose programs that use the alternate // (correct English) spelling req.Referrer but cannot // diagnose programs that use Header["Referrer"]. Referer string // The User-Agent: header string, if sent in the request. UserAgent string // The parsed form. Only available after ParseForm is called.

func ReadRequest
func ReadRequest(b *bufio.Reader) (req *Request, err os.Error) ReadRequest reads and parses a request from b.

func (*Request) Form Value


func (r *Request) FormValue(key string) string FormValue returns the first value for the named component of the query. FormValue calls ParseForm if necessary.

func (*Request) ParseForm


func (r *Request) ParseForm() (err os.Error) ParseForm parses the request body as a form for POST requests, or the raw query for GET requests. It is idempotent.

func (*Request) ProtoAtLeast


func (r *Request) ProtoAtLeast(major, minor int) bool ProtoAtLeast returns whether the HTTP protocol used in the request is at least major.minor.

func (*Request) Write


func (req *Request) Write(w io.Writer) os.Error Write writes an HTTP/1.1 request -- header and body -- in wire format. This method consults the following fields of req:
Host RawURL, if non-empty, or else URL Method (defaults to "GET") UserAgent (defaults to defaultUserAgent) Referer Header Body

If Body is present, Write forces "Transfer-Encoding: chunked" as a header and then closes Body when finished sending it.

type Response
Response represents the response from an HTTP request.

type Response struct { Status string // StatusCode int // Proto string // ProtoMajor int // ProtoMinor int //

e.g. e.g. e.g. e.g. e.g.

"200 OK" 200 "HTTP/1.0" 1 0

// RequestMethod records the method used in the HTTP request. // Header fields such as Content-Length have method-specific meaning. RequestMethod string // e.g. "HEAD", "CONNECT", "GET", etc.

// Header maps header keys to values. If the response had multiple // headers with the same key, they will 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 map[string]string // Body represents the response body. Body io.ReadCloser // ContentLength records the length of the associated content. The // value -1 indicates that the length is unknown. Unless RequestMethod // 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. Like for Header, if the // response has multiple trailer lines with the same key, they will be // concatenated, delimited by commas. Trailer map[string]string }

func Get
func Get(url string) (r *Response, finalURL string, err os.Error) Get issues a GET to the specified URL. If the response is one of the following redirect codes, it follows the redirect, up to a maximum of 10 redirects:
301 302 303 307 (Moved Permanently) (Found) (See Other) (Temporary Redirect)

finalURL is the URL from which the response was fetched -- identical to the input URL unless redirects were

followed. Caller should close r.Body when done reading it.

func Post
func Post(url string, bodyType string, body io.Reader) (r *Response, err os.Error) Post issues a POST to the specified URL. Caller should close r.Body when done reading it.

func ReadResponse
func ReadResponse(r *bufio.Reader, requestMethod string) (resp *Response, err os.Error) ReadResponse reads and returns an HTTP response from r. The RequestMethod parameter specifies the method used in the corresponding request (e.g., "GET", "HEAD"). 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) AddHeader


func (r *Response) AddHeader(key, value string) AddHeader adds a value under the given key. Keys are not case sensitive.

func (*Response) GetHeader


func (r *Response) GetHeader(key string) (value string) GetHeader returns the value of the response header with the given key. If there were multiple headers with this key, their values are concatenated, with a comma delimiter. If there were no response headers with the given key, GetHeader returns an empty string. Keys are not case sensitive.

func (*Response) ProtoAtLeast


func (r *Response) ProtoAtLeast(major, minor int) bool ProtoAtLeast returns whether the HTTP protocol used in the response is at least major.minor.

func (*Response) Write


func (resp *Response) Write(w io.Writer) os.Error Writes the response (header, body and trailer) in wire format. This method consults the following fields of resp:
StatusCode ProtoMajor ProtoMinor RequestMethod TransferEncoding Trailer Body ContentLength Header, values for non-canonical keys will have unpredictable behavior

type ServeMux
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 named fixed paths, like "/favicon.ico", or subtrees, like "/images/" (note the trailing slash). Patterns must begin with /. 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 receiver requests for any other paths in the "/images/" subtree. In the future, the pattern syntax may be relaxed to allow an optional host-name at the beginning of the pattern, so that a handler might register for the two patterns "/codesearch" and "codesearch.google.com/" without taking over requests for http://www.google.com/. ServeMux also takes care of sanitizing the URL request path, redirecting any request containing . or .. elements to an equivalent .- and ..-free URL.
type ServeMux struct { // contains unexported fields }

func New ServeMux


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.

func (*ServeMux) ServeHTTP


func (mux *ServeMux) ServeHTTP(c *Conn, req *Request) ServeHTTP dispatches the request to the handler whose pattern most closely matches the request URL.

type ServerConn
A ServerConn reads requests and sends responses over an underlying connection, until the HTTP keepalive logic commands an end. ServerConn does not close the underlying connection. Instead, the user calls Close and regains 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.
type ServerConn struct { // contains unexported fields }

func New ServerConn


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.

func (*ServerConn) Close


func (sc *ServerConn) Close() (c net.Conn, r *bufio.Reader) Close detaches the ServerConn and returns the underlying connection as well as the read-side bufio which may have some left over data. Close may be called before Read has signaled the end of the keep-alive logic. The user should not call Close 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 *Request, err os.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). Read can be called concurrently with Write, but not with another Read.

func (*ServerConn) Write


func (sc *ServerConn) Write(resp *Response) os.Error Write writes a repsonse. 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. Write can be called concurrently with Read, but not with another Write.

type URL
A URL represents a parsed URL (technically, a URI reference). The general form represented is:
scheme://[userinfo@]host/path[?query][#fragment]

The Raw, RawPath, and RawQuery fields are in "wire format" (special characters must be hex-escaped if not meant to have special meaning). All other fields are logical values; '+' or '%' represent themselves. Note, the reason for using wire format for the query is that it needs to be split into key/value pairs before decoding.
type URL struct { Raw string Scheme string RawPath string Authority string Userinfo string Host string Path string RawQuery string Fragment string }

// // // // // // // // //

the original string scheme //[userinfo@]host/path[?query][#fragment] [userinfo@]host userinfo host /path query fragment

func ParseURL
func ParseURL(rawurl string) (url *URL, err os.Error) ParseURL parses rawurl into a URL structure. The string rawurl is assumed not to have a #fragment suffix. (Web browsers strip #fragment before sending the URL to a web server.)

func ParseURLReference
func ParseURLReference(rawurlref string) (url *URL, err os.Error) ParseURLReference is like ParseURL but allows a trailing #fragment.

func (*URL) String


func (url *URL) String() string String reassembles url into a valid URL string. There are redundant fields stored in the URL structure: the String method consults Scheme, Path, Host, Userinfo, RawQuery, and Fragment, but not Raw, RawPath or Authority.

type URLError
URLError reports an error and the operation and URL that caused it.
type URLError struct { Op string URL string Error os.Error }

func (*URLError) String


func (e *URLError) String() string

type URLEscapeError
type URLEscapeError string

func (URLEscapeError) String


func (e URLEscapeError) String() string

Other packages
main

Except as noted, this content is licensed under Creative Commons Attribution 3.0.

The Go Programming Language

Package image
Variables type Alpha func NewAlpha func (*Alpha) At func (*Alpha) ColorModel func (*Alpha) Height func (*Alpha) Set func (*Alpha) Width type AlphaColor func (AlphaColor) RGBA type Color type ColorImage func (ColorImage) At func (ColorImage) ColorModel func (ColorImage) Height func (ColorImage) RGBA func (ColorImage) Width type ColorModel type ColorModelFunc func (ColorModelFunc) Convert type Image type NRGBA func NewNRGBA func (*NRGBA) At func (*NRGBA) ColorModel func (*NRGBA) Height func (*NRGBA) Set func (*NRGBA) Width type NRGBA64 func NewNRGBA64 func (*NRGBA64) At func (*NRGBA64) ColorModel func (*NRGBA64) Height func (*NRGBA64) Set func (*NRGBA64) Width import "image" The image package implements a basic 2-D image library. Package files
color.go image.go names.go

type NRGBA64Color func (NRGBA64Color) RGBA type NRGBAColor func (NRGBAColor) RGBA type Paletted func NewPaletted func (*Paletted) At func (*Paletted) ColorIndexAt func (*Paletted) ColorModel func (*Paletted) Height func (*Paletted) SetColorIndex func (*Paletted) Width type PalettedColorModel func (PalettedColorModel) Convert type RGBA func NewRGBA func (*RGBA) At func (*RGBA) ColorModel func (*RGBA) Height func (*RGBA) Set func (*RGBA) Width type RGBA64 func NewRGBA64 func (*RGBA64) At func (*RGBA64) ColorModel func (*RGBA64) Height func (*RGBA64) Set func (*RGBA64) Width type RGBA64Color func (RGBA64Color) RGBA type RGBAColor func (RGBAColor) RGBA Subdirectories

Variables

Colors from the HTML 4.01 specification: http://www.w3.org/TR/REC-html40/types.html#h-6.5 These names do not necessarily match those from other lists, such as the X11 color names.
var ( Aqua Black Blue Fuchsia Gray Green Lime Maroon Navy Olive Red Purple Silver Teal White Yellow

= = = = = = = = = = = = = = = =

ColorImage{RGBAColor{0x00, ColorImage{RGBAColor{0x00, ColorImage{RGBAColor{0x00, ColorImage{RGBAColor{0xff, ColorImage{RGBAColor{0x80, ColorImage{RGBAColor{0x00, ColorImage{RGBAColor{0x00, ColorImage{RGBAColor{0x80, ColorImage{RGBAColor{0x00, ColorImage{RGBAColor{0x80, ColorImage{RGBAColor{0xff, ColorImage{RGBAColor{0x80, ColorImage{RGBAColor{0xc0, ColorImage{RGBAColor{0x00, ColorImage{RGBAColor{0xff, ColorImage{RGBAColor{0xff,

0xff, 0x00, 0x00, 0x00, 0x80, 0x80, 0xff, 0x00, 0x00, 0x80, 0x00, 0x00, 0xc0, 0x80, 0xff, 0xff,

0xff, 0x00, 0xff, 0xff, 0x80, 0x00, 0x00, 0x00, 0x80, 0x00, 0x00, 0x80, 0xc0, 0x80, 0xff, 0x00,

0xff}} 0xff}} 0xff}} 0xff}} 0xff}} 0xff}} 0xff}} 0xff}} 0xff}} 0xff}} 0xff}} 0xff}} 0xff}} 0xff}} 0xff}} 0xff}}

// These synonyms are not in HTML 4.01. Cyan = Aqua Magenta = Fuchsia )

type Alpha
An Alpha is an in-memory image backed by a 2-D slice of AlphaColor values.
type Alpha struct { // The Pixel field's indices are y first, then x, so that At(x, y) == Pixel[y][x]. Pixel [][]AlphaColor }

func New Alpha


func NewAlpha(w, h int) *Alpha NewAlpha returns a new Alpha with the given width and height.

func (*Alpha) At
func (p *Alpha) At(x, y int) Color

func (*Alpha) ColorModel


func (p *Alpha) ColorModel() ColorModel

func (*Alpha) Height


func (p *Alpha) Height() int

func (*Alpha) Set


func (p *Alpha) Set(x, y int, c Color)

func (*Alpha) Width


func (p *Alpha) Width() int

type AlphaColor
An AlphaColor represents an 8-bit alpha.
type AlphaColor struct { A uint8 }

func (AlphaColor) RGBA


func (c AlphaColor) RGBA() (r, g, b, a uint32)

type Color
All Colors can convert themselves, with a possible loss of precision, to 128-bit alpha-premultiplied RGBA.
type Color interface { RGBA() (r, g, b, a uint32) }

type ColorImage
A ColorImage is a practically infinite-sized Image of uniform Color. It implements both the Color and Image interfaces.
type ColorImage struct { C Color }

func (ColorIm age) At


func (c ColorImage) At(x, y int) Color

func (ColorIm age) ColorModel


func (c ColorImage) ColorModel() ColorModel

func (ColorIm age) Height


func (c ColorImage) Height() int

func (ColorIm age) RGBA


func (c ColorImage) RGBA() (r, g, b, a uint32)

func (ColorIm age) Width

func (c ColorImage) Width() int

type ColorModel
A ColorModel can convert foreign Colors, with a possible loss of precision, to a Color from its own color model.
type ColorModel interface { Convert(c Color) Color }

The ColorModel associated with AlphaColor.


var AlphaColorModel ColorModel = ColorModelFunc(toAlphaColor)

The ColorModel associated with NRGBA64Color.


var NRGBA64ColorModel ColorModel = ColorModelFunc(toNRGBA64Color)

The ColorModel associated with NRGBAColor.


var NRGBAColorModel ColorModel = ColorModelFunc(toNRGBAColor)

The ColorModel associated with RGBA64Color.


var RGBA64ColorModel ColorModel = ColorModelFunc(toRGBA64Color)

The ColorModel associated with RGBAColor.


var RGBAColorModel ColorModel = ColorModelFunc(toRGBAColor)

type ColorModelFunc
The ColorModelFunc type is an adapter to allow the use of an ordinary color conversion function as a ColorModel. If f is such a function, ColorModelFunc(f) is a ColorModel object that invokes f to implement the conversion.
type ColorModelFunc func(Color) Color

func (ColorModelFunc) Convert


func (f ColorModelFunc) Convert(c Color) Color

type Image
An Image is a rectangular grid of Colors drawn from a ColorModel.

type Image interface { ColorModel() ColorModel Width() int Height() int // At(0, 0) returns the upper-left pixel of the grid. // At(Width()-1, Height()-1) returns the lower-right pixel. At(x, y int) Color }

type NRGBA
A NRGBA is an in-memory image backed by a 2-D slice of NRGBAColor values.
type NRGBA struct { // The Pixel field's indices are y first, then x, so that At(x, y) == Pixel[y][x]. Pixel [][]NRGBAColor }

func New NRGBA


func NewNRGBA(w, h int) *NRGBA NewNRGBA returns a new NRGBA with the given width and height.

func (*NRGBA) At
func (p *NRGBA) At(x, y int) Color

func (*NRGBA) ColorModel


func (p *NRGBA) ColorModel() ColorModel

func (*NRGBA) Height


func (p *NRGBA) Height() int

func (*NRGBA) Set


func (p *NRGBA) Set(x, y int, c Color)

func (*NRGBA) Width


func (p *NRGBA) Width() int

type NRGBA64
A NRGBA64 is an in-memory image backed by a 2-D slice of NRGBA64Color values.
type NRGBA64 struct { // The Pixel field's indices are y first, then x, so that At(x, y) == Pixel[y][x]. Pixel [][]NRGBA64Color }

func New NRGBA64


func NewNRGBA64(w, h int) *NRGBA64 NewNRGBA64 returns a new NRGBA64 with the given width and height.

func (*NRGBA64) At
func (p *NRGBA64) At(x, y int) Color

func (*NRGBA64) ColorModel


func (p *NRGBA64) ColorModel() ColorModel

func (*NRGBA64) Height


func (p *NRGBA64) Height() int

func (*NRGBA64) Set


func (p *NRGBA64) Set(x, y int, c Color)

func (*NRGBA64) Width


func (p *NRGBA64) Width() int

type NRGBA64Color
An NRGBA64Color represents a non-alpha-premultiplied 64-bit color, having 16 bits for each of red, green, blue and alpha.
type NRGBA64Color struct { R, G, B, A uint16 }

func (NRGBA64Color) RGBA


func (c NRGBA64Color) RGBA() (r, g, b, a uint32)

type NRGBAColor
An NRGBAColor represents a non-alpha-premultiplied 32-bit color.
type NRGBAColor struct { R, G, B, A uint8 }

func (NRGBAColor) RGBA


func (c NRGBAColor) RGBA() (r, g, b, a uint32)

type Paletted

A Paletted is an in-memory image backed by a 2-D slice of uint8 values and a PalettedColorModel.
type Paletted struct { // The Pixel field's indices are y first, then x, so that At(x, y) == Palette[Pixel[y][x]]. Pixel [][]uint8 Palette PalettedColorModel }

func New Paletted


func NewPaletted(w, h int, m PalettedColorModel) *Paletted NewPaletted returns a new Paletted with the given width, height and palette.

func (*Paletted) At
func (p *Paletted) At(x, y int) Color

func (*Paletted) ColorIndexAt


func (p *Paletted) ColorIndexAt(x, y int) uint8

func (*Paletted) ColorModel


func (p *Paletted) ColorModel() ColorModel

func (*Paletted) Height


func (p *Paletted) Height() int

func (*Paletted) SetColorIndex


func (p *Paletted) SetColorIndex(x, y int, index uint8)

func (*Paletted) Width


func (p *Paletted) Width() int

type PalettedColorModel
A PalettedColorModel represents a fixed palette of colors.
type PalettedColorModel []Color

func (PalettedColorModel) Convert


func (p PalettedColorModel) Convert(c Color) Color Convert returns the palette color closest to c in Euclidean R,G,B space.

type RGBA
An RGBA is an in-memory image backed by a 2-D slice of RGBAColor values.

type RGBA struct { // The Pixel field's indices are y first, then x, so that At(x, y) == Pixel[y][x]. Pixel [][]RGBAColor }

func New RGBA


func NewRGBA(w, h int) *RGBA NewRGBA returns a new RGBA with the given width and height.

func (*RGBA) At
func (p *RGBA) At(x, y int) Color

func (*RGBA) ColorModel


func (p *RGBA) ColorModel() ColorModel

func (*RGBA) Height


func (p *RGBA) Height() int

func (*RGBA) Set


func (p *RGBA) Set(x, y int, c Color)

func (*RGBA) Width


func (p *RGBA) Width() int

type RGBA64
An RGBA64 is an in-memory image backed by a 2-D slice of RGBA64Color values.
type RGBA64 struct { // The Pixel field's indices are y first, then x, so that At(x, y) == Pixel[y][x]. Pixel [][]RGBA64Color }

func New RGBA64


func NewRGBA64(w, h int) *RGBA64 NewRGBA64 returns a new RGBA64 with the given width and height.

func (*RGBA64) At
func (p *RGBA64) At(x, y int) Color

func (*RGBA64) ColorModel


func (p *RGBA64) ColorModel() ColorModel

func (*RGBA64) Height

func (p *RGBA64) Height() int

func (*RGBA64) Set


func (p *RGBA64) Set(x, y int, c Color)

func (*RGBA64) Width


func (p *RGBA64) Width() int

type RGBA64Color
An RGBA64Color represents a 64-bit alpha-premultiplied color, having 16 bits for each of red, green, blue and alpha.
type RGBA64Color struct { R, G, B, A uint16 }

func (RGBA64Color) RGBA


func (c RGBA64Color) RGBA() (r, g, b, a uint32)

type RGBAColor
An RGBAColor represents a traditional 32-bit alpha-premultiplied color, having 8 bits for each of red, green, blue and alpha.
type RGBAColor struct { R, G, B, A uint8 }

func (RGBAColor) RGBA


func (c RGBAColor) RGBA() (r, g, b, a uint32)

Subdirectories
Name .. jpeg png Synopsis The jpeg package implements a decoder for JPEG images, as defined in ITU-T T.81. The png package implements a PNG image decoder and encoder.

Except as noted, this content is licensed under Creative Commons Attribution 3.0.

The Go Programming Language

Package jpeg
func Decode type FormatError func (FormatError) String type Reader type UnsupportedError func (UnsupportedError) String import "image/jpeg" The jpeg package implements a decoder for JPEG images, as defined in ITU-T T.81. Package files
huf f man.go idct.go reader.go

func Decode
func Decode(r io.Reader) (image.Image, os.Error) Decode reads a JPEG formatted image from r and returns it as an image.Image.

type FormatError
A FormatError reports that the input is not a valid JPEG.
type FormatError string

func (Form atError) String


func (e FormatError) String() string

type Reader
If the passed in io.Reader does not also have ReadByte, then Decode will introduce its own buffering.
type Reader interface { io.Reader ReadByte() (c byte, err os.Error) }

type UnsupportedError

An UnsupportedError reports that the input uses a valid but unimplemented JPEG feature.
type UnsupportedError string

func (UnsupportedError) String


func (e UnsupportedError) String() string

Except as noted, this content is licensed under Creative Commons Attribution 3.0.

The Go Programming Language

Package png
func Decode func Encode type FormatError func (FormatError) String type IDATDecodingError func (IDATDecodingError) String type UnsupportedError func (UnsupportedError) String import "image/png" The png package implements a PNG image decoder and encoder. The PNG specification is at http://www.libpng.org/pub/png/spec/1.2/PNG-Contents.html Package files
reader.go writer.go

func Decode
func Decode(r io.Reader) (image.Image, os.Error) Decode reads a PNG formatted image from r and returns it as an image.Image. The type of Image returned depends on the PNG contents.

func Encode
func Encode(w io.Writer, m image.Image) os.Error Encode writes the Image m to w in PNG format. Any Image may be encoded, but images that are not image.NRGBA might be encoded lossily.

type FormatError
A FormatError reports that the input is not a valid PNG.
type FormatError string

func (Form atError) String


func (e FormatError) String() string

type IDATDecodingError
An IDATDecodingError wraps an inner error (such as a ZLIB decoding error) encountered while processing an IDAT chunk.
type IDATDecodingError struct { Err os.Error }

func (IDATDecodingError) String


func (e IDATDecodingError) String() string

type UnsupportedError
An UnsupportedError reports that the input uses a valid but unimplemented PNG feature.
type UnsupportedError string

func (UnsupportedError) String


func (e UnsupportedError) String() string

Except as noted, this content is licensed under Creative Commons Attribution 3.0.

The Go Programming Language

Package io
Variables func Copy func Copyn func ReadAtLeast func ReadFull func WriteString type Closer type Error type PipeReader func Pipe func (*PipeReader) Close func (*PipeReader) CloseWithError func (*PipeReader) Read type PipeWriter func (*PipeWriter) Close func (*PipeWriter) CloseWithError func (*PipeWriter) Write type ReadByter type ReadCloser type ReadSeeker type ReadWriteCloser import "io" This package 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. Package files
io.go pipe.go

type ReadWriteSeeker type ReadWriter type Reader func LimitReader type ReaderAt type ReaderFrom type SectionReader func NewSectionReader func (*SectionReader) Read func (*SectionReader) ReadAt func (*SectionReader) Seek func (*SectionReader) Size type Seeker type WriteCloser type WriteSeeker type Writer type WriterAt type WriterTo Subdirectories

Variables
ErrShortWrite means that a write accepted fewer bytes than requested but failed to return an explicit error.
var ErrShortWrite os.Error = &Error{"short write"}

ErrUnexpectedEOF means that os.EOF was encountered in the middle of reading a fixed-size block or data structure.
var ErrUnexpectedEOF os.Error = &Error{"unexpected EOF"}

func Copy
func Copy(dst Writer, src Reader) (written int64, err os.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 error, if any. If dst implements the ReaderFrom interface, the copy is implemented by calling dst.ReadFrom(src). Otherwise, if src implements the WriterTo interface, the copy is implemented by calling src.WriteTo(dst).

func Copyn
func Copyn(dst Writer, src Reader, n int64) (written int64, err os.Error) Copyn copies n bytes (or until an error) from src to dst. It returns the number of bytes copied and the error, if any. If dst implements the ReaderFrom interface, the copy is implemented by calling dst.ReadFrom(src).

func ReadAtLeast
func ReadAtLeast(r Reader, buf []byte, min int) (n int, err os.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 os.EOF only if no bytes were read. If an EOF happens after reading fewer than min bytes, ReadAtLeast returns ErrUnexpectedEOF.

func ReadFull
func ReadFull(r Reader, buf []byte) (n int, err os.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 os.EOF only if no bytes were read. If an EOF happens after reading some but not all the bytes, ReadFull returns ErrUnexpectedEOF.

func WriteString
func WriteString(w Writer, s string) (n int, err os.Error) WriteString writes the contents of the string s to w, which accepts an array of bytes.

type Closer
Closer is the interface that wraps the basic Close method.
type Closer interface { Close() os.Error }

type Error
Error represents an unexpected I/O behavior.
type Error struct { os.ErrorString }

type PipeReader
A PipeReader is the read half of a pipe.
type PipeReader struct { // contains unexported fields }

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.

func (*PipeReader) Close


func (r *PipeReader) Close() os.Error Close closes the reader; subsequent writes to the write half of the pipe will return the error os.EPIPE.

func (*PipeReader) CloseWithError


func (r *PipeReader) CloseWithError(rerr os.Error) os.Error CloseWithError closes the reader; subsequent writes to the write half of the pipe will return the error rerr.

func (*PipeReader) Read


func (r *PipeReader) Read(data []byte) (n int, err os.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 nil.

type PipeWriter
Write half of pipe.
type PipeWriter struct { // contains unexported fields }

func (*PipeWriter) Close

func (w *PipeWriter) Close() os.Error Close closes the writer; subsequent reads from the read half of the pipe will return no bytes and a nil error.

func (*PipeWriter) CloseWithError


func (w *PipeWriter) CloseWithError(werr os.Error) os.Error CloseWithError closes the writer; subsequent reads from the read half of the pipe will return no bytes and the error werr.

func (*PipeWriter) Write


func (w *PipeWriter) Write(data []byte) (n int, err os.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 os.EPIPE.

type ReadByter
ReadByter is the interface that wraps the ReadByte method. ReadByte reads and returns the next byte from the input. If no byte is available, err will be set.
type ReadByter interface { ReadByte() (c byte, err os.Error) }

type ReadCloser
ReadCloser is the interface that groups the basic Read and Close methods.
type ReadCloser interface { Reader Closer }

type ReadSeeker
ReadSeeker is the interface that groups the basic Read and Seek methods.
type ReadSeeker interface { Reader Seeker }

type ReadWriteCloser

ReadWriteCloser is the interface that groups the basic Read, Write and Close methods.
type ReadWriteCloser interface { Reader Writer Closer }

type ReadWriteSeeker
ReadWriteSeeker is the interface that groups the basic Read, Write and Seek methods.
type ReadWriteSeeker interface { Reader Writer Seeker }

type ReadWriter
ReadWriter is the interface that groups the basic Read and Write methods.
type ReadWriter interface { Reader Writer }

type Reader
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 rather than block waiting for more. At the end of the input stream, Read returns 0, os.EOF. Read may return a non-zero number of bytes with a non-nil err. In particular, a Read that exhausts the input may return n > 0, os.EOF.
type Reader interface { Read(p []byte) (n int, err os.Error) }

func Lim itReader


func LimitReader(r Reader, n int64) Reader LimitReader returns a Reader that reads from r but stops with os.EOF after n bytes.

type ReaderAt
ReaderAt is the interface that wraps the basic ReadAt method. ReadAt reads len(p) bytes into p starting at offset off in the underlying data stream. It returns the number of bytes read (0 <= n <= len(p)) and any error encountered. 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. At the end of the input stream, ReadAt returns 0, os.EOF. ReadAt may return a non-zero number of bytes with a non-nil err. In particular, a ReadAt that exhausts the input may return n > 0, os.EOF.
type ReaderAt interface { ReadAt(p []byte, off int64) (n int, err os.Error) }

type ReaderFrom
ReaderFrom is the interface that wraps the ReadFrom method.
type ReaderFrom interface { ReadFrom(r Reader) (n int64, err os.Error) }

type SectionReader
SectionReader implements Read, Seek, and ReadAt on a section of an underlying ReaderAt.
type SectionReader struct { // contains unexported fields }

func New SectionReader


func NewSectionReader(r ReaderAt, off int64, n int64) *SectionReader NewSectionReader returns a SectionReader that reads from r starting at offset off and stops with os.EOF after n bytes.

func (*SectionReader) Read


func (s *SectionReader) Read(p []byte) (n int, err os.Error)

func (*SectionReader) ReadAt


func (s *SectionReader) ReadAt(p []byte, off int64) (n int, err os.Error)

func (*SectionReader) Seek


func (s *SectionReader) Seek(offset int64, whence int) (ret int64, err os.Error)

func (*SectionReader) Size


func (s *SectionReader) Size() int64 Size returns the size of the section in bytes.

type Seeker
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 origin of the file, 1 means relative to the current offset, and 2 means relative to the end. Seek returns the new offset and an Error, if any.
type Seeker interface { Seek(offset int64, whence int) (ret int64, err os.Error) }

type WriteCloser
WriteCloser is the interface that groups the basic Write and Close methods.
type WriteCloser interface { Writer Closer }

type WriteSeeker
WriteSeeker is the interface that groups the basic Write and Seek methods.
type WriteSeeker interface { Writer Seeker }

type Writer
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).
type Writer interface { Write(p []byte) (n int, err os.Error) }

type WriterAt
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).
type WriterAt interface { WriteAt(p []byte, off int64) (n int, err os.Error) }

type WriterTo
WriterTo is the interface that wraps the WriteTo method.
type WriterTo interface { WriteTo(w Writer) (n int64, err os.Error) }

Subdirectories
Name .. ioutil Synopsis

Except as noted, this content is licensed under Creative Commons Attribution 3.0.

The Go Programming Language

Package json
func Decode func Marshal func Parse func Quote func Unmarshal func Unquote type Builder type MarshalError func (*MarshalError) String type ParseError func (*ParseError) String Bugs import "json" The json package implements a simple parser and representation for JSON (JavaScript Object Notation), as defined at http://www.json.org/. Package files
decode.go error.go parse.go struct.go

func Decode
func Decode(s string) (data interface{}, err os.Error) Decode parses the string s as a JSON-syntax string and returns the generic JSON object representation. The object representation is a tree of Go data types. The data return value may be one of float64, string, bool, nil, []interface{} or map[string]interface{}. The array and map elements may in turn contain any of the types listed above and so on. If Decode encounters a syntax error, it returns with err set to an instance of ParseError. See ParseError documentation for details.

func Marshal
func Marshal(w io.Writer, val interface{}) os.Error Marshal writes the JSON encoding of val to w. Due to limitations in JSON, val cannot include cyclic data structures, channels, functions, or maps.

func Parse

func Parse(s string, builder Builder) (ok bool, errindx int, errtok string) Parse parses the JSON syntax string s and makes calls to the builder to construct a parsed representation. On success, it returns with ok set to true. On error, it returns with ok set to false, errindx set to the byte index in s where a syntax error occurred, and errtok set to the offending token.

func Quote
func Quote(s string) string Quote quotes the raw string s using JSON syntax, so that Unquote(Quote(s)) = s, true.

func Unmarshal
func Unmarshal(s string, val interface{}) (ok bool, errtok string) Unmarshal parses the JSON syntax string s and fills in an arbitrary struct or slice pointed at by val. It uses the reflect package to assign to fields and arrays embedded in val. Well-formed data that does not fit into the struct is discarded. For example, given these definitions:
type Email struct { Where string; Addr string; } type Result struct { Name string; Phone string; Email []Email } var r = Result{ "name", "phone", nil }

unmarshalling the JSON syntax string


{ "email": [ { "where": "home", "addr": "gre@example.com" }, { "where": "work", "addr": "gre@work.com" } ], "name": "Grace R. Emlin", "address": "123 Main Street" }

via Unmarshal(s, &r) is equivalent to assigning

r = Result{ "Grace R. Emlin", // name "phone", // no phone given []Email{ Email{ "home", "gre@example.com" }, Email{ "work", "gre@work.com" } } }

Note that the field r.Phone has not been modified and that the JSON field "address" was discarded. Because Unmarshal uses the reflect package, it can only assign to upper case fields. Unmarshal uses a case-insensitive comparison to match JSON field names to struct field names. To unmarshal a top-level JSON array, pass in a pointer to an empty slice of the correct type. On success, Unmarshal returns with ok set to true. On a syntax error, it returns with ok set to false and errtok set to the offending token.

func Unquote
func Unquote(s string) (t string, ok bool) Unquote unquotes the JSON-quoted string s, returning a raw string t. If s is not a valid JSON-quoted string, Unquote returns with ok set to false.

type Builder
A Builder is an interface implemented by clients and passed to the JSON parser. It gives clients full control over the eventual representation returned by the parser.
type Builder interface { // Set value Int64(i int64) Uint64(i uint64) Float64(f float64) String(s string) Bool(b bool) Null() Array() Map() // Create sub-Builders Elem(i int) Builder Key(s string) Builder // Flush changes to parent Builder if necessary. Flush() }

type MarshalError

type MarshalError struct { T reflect.Type }

func (*MarshalError) String


func (e *MarshalError) String() string

type ParseError
ParseError aggregates information about a JSON parse error. It is compatible with the os.Error interface.
type ParseError struct { Index int // A byte index in JSON string where the error occurred Token string // An offending token }

func (*ParseError) String


func (pe *ParseError) String() string Produce a string representation of this ParseError.

Bugs
The json Builder interface needs to be reconciled with the xml Builder interface.

Except as noted, this content is licensed under Creative Commons Attribution 3.0.

The Go Programming Language

Package log
Constants func Crash func Crashf func Exit func Exitf func Stderr func Stderrf func Stdout import "log" Rudimentary logging package. Defines a type, Logger, with simple methods for formatting output to one or two destinations. Also has predefined Loggers accessible through helper functions Stdout[f], Stderr[f], Exit[f], and Crash[f], which are easier to use than creating a Logger manually. Exit exits when written to. Crash causes a crash when written to. Package files
log.go

func Stdoutf type Logger func New func (*Logger) Log func (*Logger) Logf func (*Logger) Output

Constants
These flags define the properties of the Logger and the output they produce.
const ( // Flags Lok = iota Lexit // terminate execution when written Lcrash // crash (panic) when written // 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). A colon appears after these items: // 2009/0123 01:23:23.123123 /a/b/c/d.go:23: message Ldate = 1 << iota // the date: 2009/0123 Ltime // the time: 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 )

func Crash
func Crash(v ...interface{}) Crash is equivalent to Stderr() followed by a call to panic().

func Crashf
func Crashf(format string, v ...interface{}) Crashf is equivalent to Stderrf() followed by a call to panic().

func Exit
func Exit(v ...interface{}) Exit is equivalent to Stderr() followed by a call to os.Exit(1).

func Exitf
func Exitf(format string, v ...interface{}) Exitf is equivalent to Stderrf() followed by a call to os.Exit(1).

func Stderr
func Stderr(v ...interface{}) Stderr is a helper function for easy logging to stderr. It is analogous to Fprint(os.Stderr).

func Stderrf
func Stderrf(format string, v ...interface{}) Stderrf is a helper function for easy formatted logging to stderr. It is analogous to Fprintf(os.Stderr).

func Stdout
func Stdout(v ...interface{}) Stdout is a helper function for easy logging to stdout. It is analogous to Print().

func Stdoutf
func Stdoutf(format string, v ...interface{}) Stdoutf is a helper functions for easy formatted logging to stdout. It is analogous to Printf().

type Logger
Logger represents an active logging object.

type Logger struct { // contains unexported fields }

func New
func New(out0, out1 io.Writer, prefix string, flag int) *Logger New creates a new Logger. The out0 and out1 variables set the destinations to which log data will be written; out1 may be nil. The prefix appears at the beginning of each generated log line. The flag argument defines the logging properties.

func (*Logger) Log


func (l *Logger) Log(v ...interface{}) Log is analogous to Print() for a Logger.

func (*Logger) Logf


func (l *Logger) Logf(format string, v ...interface{}) Logf is analogous to Printf() for a Logger.

func (*Logger) Output


func (l *Logger) Output(calldepth int, s string) os.Error Output writes the output for a logging event. The string s contains the text to print after the time stamp; calldepth is used to recover the PC. It is provided for generality, although at the moment on all pre-defined paths it will be 2.

Except as noted, this content is licensed under Creative Commons Attribution 3.0.

The Go Programming Language

Package math
Constants func Acos func Acosh func Asin func Asinh func Atan func Atan2 func Atanh func Cbrt func Ceil func Copysign func Cos func Cosh func Erf func Erfc func Exp func Exp2 func Expm1 func Fabs func Fdim func Float32bits func Float32frombits func Float64bits func Float64frombits func Floor func Fmax func Fmin func Fmod func Frexp import "math" The math package provides basic constants and mathematical functions. Package files
acosh.go asin.go asin_decl.go asinh.go atan.go atan2.go atan2_decl.go atan_decl.go atanh.go bits.go cbrt.go const.go copy sign.go erf .go exp.go exp2_decl.go exp_decl.go expm1.go expm1_decl.go f abs.go f abs_decl.go f dim.go f loor.go f loor_decl.go f mod.go f mod_decl.go f rexp.go f rexp_decl.go hy pot.go hy pot_decl.go hy pot_port.go ldexp.go ldexp_decl.go lgamma.go log.go log1p.go log1p_decl.go log_decl.go logb.go modf .go modf _decl.go nextaf ter.go pow.go pow10.go remainder.go remainder_decl.go sin.go sin_decl.go sincos.go sincos_decl.go sinh.go sqrt.go sqrt_decl.go sqrt_port.go tan.go tan_decl.go tanh.go unsaf e.go

func Hypot func Ilogb func Inf func IsInf func IsNaN func Ldexp func Lgamma func Log func Log10 func Log1p func Log2 func Logb func Modf func NaN func Nextafter func Pow func Pow10 func Remainder func Sin func Sincos func Sinh func Sqrt func Tan func Tanh func Trunc Bugs

Constants
Mathematical constants. Reference: http://www.research.att.com/~njas/sequences/Axxxxxx

const ( E = 2.71828182845904523536028747135266249775724709369995957496696763 // A001113 Pi = 3.14159265358979323846264338327950288419716939937510582097494459 // A000796 Phi = 1.61803398874989484820458683436563811772030917980576286213544862 // A001622 Sqrt2 SqrtE SqrtPi SqrtPhi Ln2 Log2E Ln10 Log10E ) = = = = 1.41421356237309504880168872420969807856967187537694807317667974 1.64872127070012814684865078781416357165377610071014801157507931 1.77245385090551602729816748334114518279754945612238712821380779 1.27201964951406896425242246173749149171560804184009624861664038 // // // // A002193 A019774 A002161 A139339

= = = =

0.693147180559945309417232121458176568075500134360255254120680009 // A002162 1 / Ln2 2.30258509299404568401799145468436420760110148862877297603332790 // A002392 1 / Ln10

Floating-point limit values. Max is the largest finite value representable by the type. Min is the smallest nonzero value representable by the type.
const ( MaxFloat32 = 3.40282346638528859811704183484516925440e+38 /* 2^127 * (2^24 - 1) / 2^23 */ MinFloat32 = 1.401298464324817070923729583289916131280e-45 /* 1 / 2^(127 - 1 + 23) */ MaxFloat64 = 1.797693134862315708145274237317043567981e+308 /* 2^1023 * (2^53 - 1) / 2^52 */ MinFloat64 = 4.940656458412465441765687928682213723651e-324 /* 1 / 2^(1023 - 1 + 52) */ )

Integer limit values.


const ( MaxInt8 MinInt8 MaxInt16 MinInt16 MaxInt32 MinInt32 MaxInt64 MinInt64 MaxUint8 MaxUint16 MaxUint32 MaxUint64 )

= = = = = = = = = = = =

1<<7 - 1 -1 << 7 1<<15 - 1 -1 << 15 1<<31 - 1 -1 << 31 1<<63 - 1 -1 << 63 1<<8 - 1 1<<16 - 1 1<<32 - 1 1<<64 - 1

func Acos
func Acos(x float64) float64 Acos returns the arccosine of x. Special case is:
Acos(x) = NaN if x < -1 or x > 1

func Acosh
func Acosh(x float64) float64 Acosh(x) calculates the inverse hyperbolic cosine of x. Special cases are:
Acosh(x) = NaN if x < 1 Acosh(NaN) = NaN

func Asin
func Asin(x float64) float64 Asin returns the arcsine of x. Special case is:
Asin(x) = NaN if x < -1 or x > 1

func Asinh
func Asinh(x float64) float64 Asinh(x) calculates the inverse hyperbolic sine of x. Special cases are:
Asinh(+Inf) = +Inf Asinh(-Inf) = -Inf Asinh(NaN) = NaN

func Atan
func Atan(x float64) float64 Atan returns the arctangent of x.

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) = 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(x) calculates the inverse hyperbolic tangent of x. Special cases are:
Atanh(x) = NaN if x < -1 or x > 1 Atanh(1) = +Inf Atanh(-1) = -Inf Atanh(NaN) = NaN

func Cbrt
func Cbrt(x float64) float64 Cbrt returns the cube root of its argument. Special cases are:
Exp(+Inf) = +Inf Exp(-Inf) = -Inf Exp(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(+Inf) = +Inf Ceil(-Inf) = -Inf Ceil(NaN) = NaN

func Copysign
func Copysign(x, y float64) float64 Copysign(x, y) 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 x.

func Cosh
func Cosh(x float64) float64 Cosh returns the hyperbolic cosine of x.

func Erf
func Erf(x float64) float64 Erf(x) 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(x) 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 Fabs
func Fabs(x float64) float64 Fabs returns the absolute value of x. Special cases are:
Fabs(+Inf) = +Inf Fabs(-Inf) = +Inf Fabs(NaN) = NaN

func Fdim

func Fdim(x, y float64) float64 Fdim returns the maximum of x-y or 0.

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(+Inf) = +Inf Floor(-Inf) = -Inf Floor(NaN) = NaN

func Fmax
func Fmax(x, y float64) float64 Fmax returns the larger of x or y.

func Fmin
func Fmin(x, y float64) float64 Fmin returns the smaller of x or y.

func Fmod
func Fmod(x, y float64) float64 Fmod 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:
if x is not finite, Fmod returns NaN if y is 0 or NaN, Fmod returns 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).

func Hypot
func Hypot(p, q float64) float64 Hypot computes Sqrt(p*p + q*q), taking care to avoid unnecessary overflow and underflow. Special cases are:
Hypot(p, q) = +Inf if p or q is infinite Hypot(p, q) = NaN if p or q is NaN

func Ilogb
func Ilogb(x float64) int Ilogb(x) returns the binary logarithm of non-zero 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 returns whether f is an infinity, according to sign. If sign > 0, IsInf returns whether f is positive infinity. If sign < 0, IsInf returns whether f is negative infinity. If sign == 0, IsInf returns whether f is either infinity.

func IsNaN
func IsNaN(f float64) (is bool) IsNaN returns whether f is an IEEE 754 not-a-number value.

func Ldexp
func Ldexp(frac float64, exp int) float64 Ldexp is the inverse of Frexp. It returns frac 2^exp.

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(-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(x) returns the binary logarithm of non-zero x. Special cases are:
Logb(Inf) = +Inf Logb(0) = -Inf Logb(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(-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 value after x towards y. If x == y, then x is returned. Special cases are:
Nextafter(NaN, y) = NaN Nextafter(x, NaN) = NaN

func Pow
func Pow(x, y float64) float64 Pow returns x**y, the base-x exponential of y.

func Pow10
func Pow10(e int) float64 Pow10 returns 10**e, the base-10 exponential of e.

func Remainder
func Remainder(x, y float64) float64 Remainder returns the IEEE 754 floating-point remainder of x/y. Special cases are:

Remainder(x, NaN) Remainder(NaN, y) Remainder(Inf, y) Remainder(x, 0) = Remainder(x, Inf)

= NaN = NaN = NaN NaN = x

func Sin
func Sin(x float64) float64 Sin returns the sine of x.

func Sincos
func Sincos(x float64) (sin, cos float64) Sincos(x) returns Sin(x), Cos(x). Special conditions are:
Sincos(+Inf) = NaN, NaN Sincos(-Inf) = NaN, NaN Sincos(NaN) = NaN, NaN

func Sinh
func Sinh(x float64) float64 Sinh returns the hyperbolic sine of x.

func Sqrt
func Sqrt(x float64) float64 Sqrt returns the square root of x. Special cases are:
Sqrt(+Inf) = +Inf Sqrt(x < 0) = NaN Sqrt(NaN) = NaN

func Tan
func Tan(x float64) float64 Tan returns the tangent of x.

func Tanh
func Tanh(x float64) float64 Tanh computes the hyperbolic tangent of x.

func Trunc
func Trunc(x float64) float64 Trunc returns the integer value of x. Special cases are:
Trunc(+Inf) = +Inf Trunc(-Inf) = -Inf Trunc(NaN) = NaN

Bugs
The manual should define the special cases for all of these functions.

Except as noted, this content is licensed under Creative Commons Attribution 3.0.

The Go Programming Language

Package mime
func TypeByExtension import "mime" The mime package translates file name extensions to MIME types. It consults the local system's mime.types file, which must be installed under one of these names:
/etc/mime.types /etc/apache2/mime.types /etc/apache/mime.types

Package files
ty pe.go

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 "".

Except as noted, this content is licensed under Creative Commons Attribution 3.0.

The Go Programming Language

Package net
Constants Variables func LookupHost func LookupPort type Addr type AddrError func (*AddrError) String type Conn func Dial type DNSError func (*DNSError) String type IP func IPv4 func ParseIP func (IP) DefaultMask func (IP) Mask func (IP) String func (IP) To16 func (IP) To4 type IPMask func (IPMask) String type Listener func Listen type OpError func (*OpError) String type PacketConn func ListenPacket type TCPAddr func ResolveTCPAddr func (*TCPAddr) Network func (*TCPAddr) String type TCPConn func DialTCP func (*TCPConn) Close func (*TCPConn) LocalAddr func (*TCPConn) Read func (*TCPConn) RemoteAddr func (*TCPConn) SetKeepAlive func (*TCPConn) SetLinger func (*TCPConn) SetReadBuffer func (*TCPConn) SetReadTimeout func (*TCPConn) SetTimeout func (*TCPConn) SetWriteBuffer func (*TCPConn) SetWriteTimeout func (*TCPConn) Write type TCPListener type func (*UDPAddr) Network func (*UDPAddr) String UDPConn func DialUDP func ListenUDP func ListenUnixgram func (*UDPConn) Close func (*UDPConn) LocalAddr func (*UDPConn) Read func (*UDPConn) ReadFrom func (*UDPConn) ReadFromUDP func (*UDPConn) RemoteAddr func (*UDPConn) SetReadBuffer func (*UDPConn) SetReadTimeout func (*UDPConn) SetTimeout func (*UDPConn) SetWriteBuffer func (*UDPConn) SetWriteTimeout func (*UDPConn) Write func (*UDPConn) WriteTo func (*UDPConn) WriteToUDP UnixAddr func ResolveUnixAddr func (*UnixAddr) Network func (*UnixAddr) String UnixConn func DialUnix func (*UnixConn) Close func (*UnixConn) LocalAddr func (*UnixConn) Read func (*UnixConn) ReadFrom func (*UnixConn) ReadFromUnix func (*UnixConn) RemoteAddr func (*UnixConn) SetReadBuffer func (*UnixConn) SetReadTimeout func (*UnixConn) SetTimeout func (*UnixConn) SetWriteBuffer func (*UnixConn) SetWriteTimeout func (*UnixConn) Write func (*UnixConn) WriteTo func (*UnixConn) WriteToUnix UnixListener func ListenUnix func (*UnixListener) Accept func (*UnixListener) AcceptUnix func (*UnixListener) Addr func (*UnixListener) Close

type

type

type

func ListenTCP func (*TCPListener) Accept func (*TCPListener) AcceptTCP func (*TCPListener) Addr func (*TCPListener) Close type UDPAddr func ResolveUDPAddr import "net"

type UnknownNetworkError func (UnknownNetworkError) String type UnknownSocketError func (*UnknownSocketError) String

The net package provides a portable interface to Unix networks sockets, including TCP/IP, UDP, domain name resolution, and Unix domain sockets. Package files
dnsclient.go dnsconf ig.go dnsmsg.go f d.go f d_darwin.go f d_f reebsd.go f d_linux.go f d_nacl.go hosts.go ip.go ipsock.go net.go parse.go port.go sock.go tcpsock.go udpsock.go unixsock.go

Constants
IP address lengths (bytes).
const ( IPv4len = 4 IPv6len = 16 )

Variables
Well-known IPv4 addresses
var ( IPv4bcast IPv4allsys IPv4allrouter IPv4zero )

= = = =

IPv4(255, 255, 255, 255) // broadcast IPv4(224, 0, 0, 1) // all systems IPv4(224, 0, 0, 2) // all routers IPv4(0, 0, 0, 0) // all zeros

Well-known IPv6 addresses


var ( IPzero = make(IP, IPv6len) // all zeros )

func LookupHost
func LookupHost(name string) (cname string, addrs []string, err os.Error) LookupHost looks for name using the local hosts file and DNS resolver. It returns the canonical name for the host and an array of that host's addresses.

func LookupPort
func LookupPort(network, service string) (port int, err os.Error) LookupPort looks up the port for the given network and service.

type Addr
Addr represents a network end point address.
type Addr interface { Network() string // name of the network String() string // string form of address }

type AddrError
type AddrError struct { Error string Addr string }

func (*AddrError) String


func (e *AddrError) String() string

type Conn
Conn is a generic stream-oriented network connection.

type Conn interface { // Read reads data from the connection. // Read can be made to time out and return err == os.EAGAIN // after a fixed time limit; see SetTimeout and SetReadTimeout. Read(b []byte) (n int, err os.Error) // Write writes data to the connection. // Write can be made to time out and return err == os.EAGAIN // after a fixed time limit; see SetTimeout and SetReadTimeout. Write(b []byte) (n int, err os.Error) // Close closes the connection. Close() os.Error // LocalAddr returns the local network address. LocalAddr() Addr // RemoteAddr returns the remote network address. RemoteAddr() Addr // SetTimeout sets the read and write deadlines associated // with the connection. SetTimeout(nsec int64) os.Error // SetReadTimeout sets the time (in nanoseconds) that // Read will wait for data before returning os.EAGAIN. // Setting nsec == 0 (the default) disables the deadline. SetReadTimeout(nsec int64) os.Error // SetWriteTimeout sets the time (in nanoseconds) that // Write will wait to send its data before returning os.EAGAIN. // Setting nsec == 0 (the default) disables the deadline. // Even if write times out, it may return n > 0, indicating that // some of the data was successfully written. SetWriteTimeout(nsec int64) os.Error }

func Dial
func Dial(net, laddr, raddr string) (c Conn, err os.Error) Dial connects to the remote address raddr on the network net. If the string laddr is not empty, it is used as the local address for the connection. Known networks are "tcp", "tcp4" (IPv4-only), "tcp6" (IPv6-only), "udp", "udp4" (IPv4-only), and "udp6" (IPv6only). For IP networks, addresses have the form host:port. If host is a literal IPv6 address, it must be enclosed in square brackets. Examples:
Dial("tcp", Dial("tcp", Dial("tcp", Dial("tcp", "", "12.34.56.78:80") "", "google.com:80") "", "[de:ad:be:ef::ca:fe]:80") "127.0.0.1:123", "127.0.0.1:88")

type DNSError
DNSError represents a DNS lookup error.
type DNSError struct Error string // Name string // Server string // } { description of the error name looked for server used

func (*DNSError) String


func (e *DNSError) String() string

type IP
An IP is a single IP address, an array of bytes. Functions in this package accept either 4-byte (IP v4) or 16-byte (IP v6) arrays as input. Unless otherwise specified, functions in this package always return IP addresses in 16-byte form using the canonical embedding. 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 array: a 16-byte array can still be an IPv4 address.
type IP []byte

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 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) 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.

type IPMask
An IP mask is an IP address.
type IPMask []byte

func (IPMask) String


func (mask IPMask) String() string String returns the string representation of mask. If the mask is in the canonical form--ones followed by zeros--the string representation is just the decimal number of ones. If the mask is in a non-canonical form, it is formatted as an IP address.

type Listener
A Listener is a generic network listener for stream-oriented protocols. Accept waits for the next connection and Close closes the connection.
type Listener interface { Accept() (c Conn, err os.Error) Close() os.Error Addr() Addr // Listener's network address }

func Listen
func Listen(net, laddr string) (l Listener, err os.Error) Listen announces on the local network address laddr. The network string net must be a stream-oriented network: "tcp", "tcp4", "tcp6", or "unix".

type OpError

type OpError struct { Op string Net string Addr Addr Error os.Error }

func (*OpError) String


func (e *OpError) String() string

type PacketConn
PacketConn is a generic packet-oriented network connection.
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 err == os.EAGAIN // after a fixed time limit; see SetTimeout and SetReadTimeout. ReadFrom(b []byte) (n int, addr Addr, err os.Error) // WriteTo writes a packet with payload b to addr. // WriteTo can be made to time out and return err == os.EAGAIN // after a fixed time limit; see SetTimeout and SetWriteTimeout. // On packet-oriented connections, write timeouts are rare. WriteTo(b []byte, addr Addr) (n int, err os.Error) // Close closes the connection. Close() os.Error // LocalAddr returns the local network address. LocalAddr() Addr // SetTimeout sets the read and write deadlines associated // with the connection. SetTimeout(nsec int64) os.Error // SetReadTimeout sets the time (in nanoseconds) that // Read will wait for data before returning os.EAGAIN. // Setting nsec == 0 (the default) disables the deadline. SetReadTimeout(nsec int64) os.Error // SetWriteTimeout sets the time (in nanoseconds) that // Write will wait to send its data before returning os.EAGAIN. // Setting nsec == 0 (the default) disables the deadline. // Even if write times out, it may return n > 0, indicating that // some of the data was successfully written. SetWriteTimeout(nsec int64) os.Error }

func ListenPacket
func ListenPacket(net, laddr string) (c PacketConn, err os.Error) ListenPacket announces on the local network address laddr. The network string net must be a packet-oriented

network: "udp", "udp4", "udp6", or "unixgram".

type TCPAddr
TCPAddr represents the address of a TCP end point.
type TCPAddr struct { IP IP Port int }

func ResolveTCPAddr
func ResolveTCPAddr(addr string) (*TCPAddr, os.Error) ResolveTCPAddr parses addr as a TCP address of the form host:port and resolves domain names or port names to numeric addresses. A literal IPv6 host address must be enclosed in square brackets, as in "[::]:80".

func (*TCPAddr) Netw ork


func (a *TCPAddr) Network() string Network returns the address's network name, "tcp".

func (*TCPAddr) String


func (a *TCPAddr) String() string

type TCPConn
TCPConn is an implementation of the Conn interface for TCP network connections.
type TCPConn struct { // contains unexported fields }

func DialTCP
func DialTCP(net string, laddr, raddr *TCPAddr) (c *TCPConn, err os.Error) DialTCP is like Dial but can only connect to TCP networks and returns a TCPConn structure.

func (*TCPConn) Close


func (c *TCPConn) Close() os.Error Close closes the TCP connection.

func (*TCPConn) LocalAddr


func (c *TCPConn) LocalAddr() Addr LocalAddr returns the local network address, a *TCPAddr.

func (*TCPConn) Read


func (c *TCPConn) Read(b []byte) (n int, err os.Error) Read reads data from the TCP connection. Read can be made to time out and return err == os.EAGAIN after a fixed time limit; see SetTimeout and SetReadTimeout.

func (*TCPConn) Rem oteAddr


func (c *TCPConn) RemoteAddr() Addr RemoteAddr returns the remote network address, a *TCPAddr.

func (*TCPConn) SetKeepAlive


func (c *TCPConn) SetKeepAlive(keepalive bool) os.Error SetKeepAlive sets whether the operating system should send keepalive messages on the connection.

func (*TCPConn) SetLinger


func (c *TCPConn) SetLinger(sec int) os.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), Close returns immediately and the operating system finishes sending the data in the background. If sec == 0, Close returns immediately and the operating system discards any unsent or unacknowledged data. If sec > 0, Close blocks for at most sec seconds waiting for data to be sent and acknowledged.

func (*TCPConn) SetReadBuffer


func (c *TCPConn) SetReadBuffer(bytes int) os.Error SetReadBuffer sets the size of the operating system's receive buffer associated with the connection.

func (*TCPConn) SetReadTim eout


func (c *TCPConn) SetReadTimeout(nsec int64) os.Error SetReadTimeout sets the time (in nanoseconds) that Read will wait for data before returning os.EAGAIN. Setting nsec == 0 (the default) disables the deadline.

func (*TCPConn) SetTim eout


func (c *TCPConn) SetTimeout(nsec int64) os.Error SetTimeout sets the read and write deadlines associated with the connection.

func (*TCPConn) SetWriteBuffer


func (c *TCPConn) SetWriteBuffer(bytes int) os.Error SetWriteBuffer sets the size of the operating system's transmit buffer associated with the connection.

func (*TCPConn) SetWriteTim eout


func (c *TCPConn) SetWriteTimeout(nsec int64) os.Error SetWriteTimeout sets the time (in nanoseconds) that Write will wait to send its data before returning os.EAGAIN. Setting nsec == 0 (the default) disables the deadline. Even if write times out, it may return n > 0, indicating that some of the data was successfully written.

func (*TCPConn) Write


func (c *TCPConn) Write(b []byte) (n int, err os.Error) Write writes data to the TCP connection. Write can be made to time out and return err == os.EAGAIN after a fixed time limit; see SetTimeout and SetReadTimeout.

type TCPListener
TCPListener is a TCP network listener. Clients should typically use variables of type Listener instead of assuming TCP.
type TCPListener struct { // contains unexported fields }

func ListenTCP
func ListenTCP(net string, laddr *TCPAddr) (l *TCPListener, err os.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, it means to listen on some available port. The caller can use l.Addr() to retrieve the chosen address.

func (*TCPListener) Accept


func (l *TCPListener) Accept() (c Conn, err os.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() (c *TCPConn, err os.Error) AcceptTCP accepts the next incoming call and returns the new connection and the remote address.

func (*TCPListener) Addr


func (l *TCPListener) Addr() Addr Addr returns the listener's network address, a *TCPAddr.

func (*TCPListener) Close


func (l *TCPListener) Close() os.Error

Close stops listening on the TCP address. Already Accepted connections are not closed.

type UDPAddr
UDPAddr represents the address of a UDP end point.
type UDPAddr struct { IP IP Port int }

func ResolveUDPAddr
func ResolveUDPAddr(addr string) (*UDPAddr, os.Error) ResolveUDPAddr parses addr as a UDP address of the form host:port and resolves domain names or port names to numeric addresses. A literal IPv6 host address must be enclosed in square brackets, as in "[::]:80".

func (*UDPAddr) Netw ork


func (a *UDPAddr) Network() string Network returns the address's network name, "udp".

func (*UDPAddr) String


func (a *UDPAddr) String() string

type UDPConn
UDPConn is the implementation of the Conn and PacketConn interfaces for UDP network connections.
type UDPConn struct { // contains unexported fields }

func DialUDP
func DialUDP(net string, laddr, raddr *UDPAddr) (c *UDPConn, err os.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 ListenUDP
func ListenUDP(net string, laddr *UDPAddr) (c *UDPConn, err os.Error) ListenUDP listens for incoming UDP packets addressed to the local address laddr. The returned connection c's ReadFrom and WriteTo methods can be used to receive and send UDP packets with per-packet addressing.

func ListenUnixgram
func ListenUnixgram(net string, laddr *UnixAddr) (c *UDPConn, err os.Error)

ListenUnixgram listens for incoming Unix datagram packets addressed to the local address laddr. The returned connection c's ReadFrom and WriteTo methods can be used to receive and send UDP packets with per-packet addressing. The network net must be "unixgram".

func (*UDPConn) Close


func (c *UDPConn) Close() os.Error Close closes the UDP connection.

func (*UDPConn) LocalAddr


func (c *UDPConn) LocalAddr() Addr LocalAddr returns the local network address.

func (*UDPConn) Read


func (c *UDPConn) Read(b []byte) (n int, err os.Error) Read reads data from a single UDP packet on the connection. If the slice b is smaller than the arriving packet, the excess packet data may be discarded. Read can be made to time out and return err == os.EAGAIN after a fixed time limit; see SetTimeout and SetReadTimeout.

func (*UDPConn) ReadFrom


func (c *UDPConn) ReadFrom(b []byte) (n int, addr Addr, err os.Error) ReadFrom 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. ReadFrom can be made to time out and return err == os.EAGAIN after a fixed time limit; see SetTimeout and SetReadTimeout.

func (*UDPConn) ReadFrom UDP


func (c *UDPConn) ReadFromUDP(b []byte) (n int, addr *UDPAddr, err os.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 err == os.EAGAIN after a fixed time limit; see SetTimeout and SetReadTimeout.

func (*UDPConn) Rem oteAddr


func (c *UDPConn) RemoteAddr() Addr RemoteAddr returns the remote network address, a *UDPAddr.

func (*UDPConn) SetReadBuffer


func (c *UDPConn) SetReadBuffer(bytes int) os.Error SetReadBuffer sets the size of the operating system's receive buffer associated with the connection.

func (*UDPConn) SetReadTim eout

func (c *UDPConn) SetReadTimeout(nsec int64) os.Error SetReadTimeout sets the time (in nanoseconds) that Read will wait for data before returning os.EAGAIN. Setting nsec == 0 (the default) disables the deadline.

func (*UDPConn) SetTim eout


func (c *UDPConn) SetTimeout(nsec int64) os.Error SetTimeout sets the read and write deadlines associated with the connection.

func (*UDPConn) SetWriteBuffer


func (c *UDPConn) SetWriteBuffer(bytes int) os.Error SetWriteBuffer sets the size of the operating system's transmit buffer associated with the connection.

func (*UDPConn) SetWriteTim eout


func (c *UDPConn) SetWriteTimeout(nsec int64) os.Error SetWriteTimeout sets the time (in nanoseconds) that Write will wait to send its data before returning os.EAGAIN. Setting nsec == 0 (the default) disables the deadline. Even if write times out, it may return n > 0, indicating that some of the data was successfully written.

func (*UDPConn) Write


func (c *UDPConn) Write(b []byte) (n int, err os.Error) Write writes data to the connection as a single UDP packet. Write can be made to time out and return err == os.EAGAIN after a fixed time limit; see SetTimeout and SetReadTimeout.

func (*UDPConn) WriteTo


func (c *UDPConn) WriteTo(b []byte, addr Addr) (n int, err os.Error) WriteTo writes a UDP packet with payload b to addr via c. WriteTo can be made to time out and return err == os.EAGAIN after a fixed time limit; see SetTimeout and SetWriteTimeout. On packet-oriented connections such as UDP, write timeouts are rare.

func (*UDPConn) WriteToUDP


func (c *UDPConn) WriteToUDP(b []byte, addr *UDPAddr) (n int, err os.Error) WriteToUDP writes a UDP packet to addr via c, copying the payload from b. WriteToUDP can be made to time out and return err == os.EAGAIN after a fixed time limit; see SetTimeout and SetWriteTimeout. On packet-oriented connections such as UDP, write timeouts are rare.

type UnixAddr
UnixAddr represents the address of a Unix domain socket end point.

type UnixAddr struct { Name string Datagram bool }

func ResolveUnixAddr
func ResolveUnixAddr(net, addr string) (*UnixAddr, os.Error) ResolveUnixAddr parses addr as a Unix domain socket address. The string net gives the network name, "unix" or "unixgram".

func (*UnixAddr) Netw ork


func (a *UnixAddr) Network() string Network returns the address's network name, "unix" or "unixgram".

func (*UnixAddr) String


func (a *UnixAddr) String() string

type UnixConn
UnixConn is an implementation of the Conn interface for connections to Unix domain sockets.
type UnixConn struct { // contains unexported fields }

func DialUnix
func DialUnix(net string, laddr, raddr *UnixAddr) (c *UnixConn, err os.Error) DialUnix connects to the remote address raddr on the network net, which must be "unix" or "unixdgram". If laddr is not nil, it is used as the local address for the connection.

func (*UnixConn) Close


func (c *UnixConn) Close() os.Error Close closes the Unix domain connection.

func (*UnixConn) LocalAddr


func (c *UnixConn) LocalAddr() Addr LocalAddr returns the local network address, a *UnixAddr. Unlike in other protocols, LocalAddr is usually nil for dialed connections.

func (*UnixConn) Read


func (c *UnixConn) Read(b []byte) (n int, err os.Error) Read reads data from the Unix domain connection.

Read can be made to time out and return err == os.EAGAIN after a fixed time limit; see SetTimeout and SetReadTimeout.

func (*UnixConn) ReadFrom


func (c *UnixConn) ReadFrom(b []byte) (n int, addr Addr, err os.Error) ReadFrom reads a 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. ReadFrom can be made to time out and return err == os.EAGAIN after a fixed time limit; see SetTimeout and SetReadTimeout.

func (*UnixConn) ReadFrom Unix


func (c *UnixConn) ReadFromUnix(b []byte) (n int, addr *UnixAddr, err os.Error) ReadFromUnix reads a 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. ReadFromUnix can be made to time out and return err == os.EAGAIN after a fixed time limit; see SetTimeout and SetReadTimeout.

func (*UnixConn) Rem oteAddr


func (c *UnixConn) RemoteAddr() Addr RemoteAddr returns the remote network address, a *UnixAddr. Unlike in other protocols, RemoteAddr is usually nil for connections accepted by a listener.

func (*UnixConn) SetReadBuffer


func (c *UnixConn) SetReadBuffer(bytes int) os.Error SetReadBuffer sets the size of the operating system's receive buffer associated with the connection.

func (*UnixConn) SetReadTim eout


func (c *UnixConn) SetReadTimeout(nsec int64) os.Error SetReadTimeout sets the time (in nanoseconds) that Read will wait for data before returning os.EAGAIN. Setting nsec == 0 (the default) disables the deadline.

func (*UnixConn) SetTim eout


func (c *UnixConn) SetTimeout(nsec int64) os.Error SetTimeout sets the read and write deadlines associated with the connection.

func (*UnixConn) SetWriteBuffer


func (c *UnixConn) SetWriteBuffer(bytes int) os.Error SetWriteBuffer sets the size of the operating system's transmit buffer associated with the connection.

func (*UnixConn) SetWriteTim eout


func (c *UnixConn) SetWriteTimeout(nsec int64) os.Error SetWriteTimeout sets the time (in nanoseconds) that Write will wait to send its data before returning

os.EAGAIN. Setting nsec == 0 (the default) disables the deadline. Even if write times out, it may return n > 0, indicating that some of the data was successfully written.

func (*UnixConn) Write


func (c *UnixConn) Write(b []byte) (n int, err os.Error) Write writes data to the Unix domain connection. Write can be made to time out and return err == os.EAGAIN after a fixed time limit; see SetTimeout and SetReadTimeout.

func (*UnixConn) WriteTo


func (c *UnixConn) WriteTo(b []byte, addr Addr) (n int, err os.Error) WriteTo writes a packet to addr via c, copying the payload from b. WriteTo can be made to time out and return err == os.EAGAIN after a fixed time limit; see SetTimeout and SetWriteTimeout. On packet-oriented connections such as UDP, write timeouts are rare.

func (*UnixConn) WriteToUnix


func (c *UnixConn) WriteToUnix(b []byte, addr *UnixAddr) (n int, err os.Error) WriteToUnix writes a packet to addr via c, copying the payload from b. WriteToUnix can be made to time out and return err == os.EAGAIN after a fixed time limit; see SetTimeout and SetWriteTimeout. On packet-oriented connections such as UDP, write timeouts are rare.

type UnixListener
UnixListener is a Unix domain socket listener. Clients should typically use variables of type Listener instead of assuming Unix domain sockets.
type UnixListener struct { // contains unexported fields }

func ListenUnix
func ListenUnix(net string, laddr *UnixAddr) (l *UnixListener, err os.Error) ListenUnix announces on the Unix domain socket laddr and returns a Unix listener. Net must be "unix" (stream sockets).

func (*UnixListener) Accept


func (l *UnixListener) Accept() (c Conn, err os.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() (c *UnixConn, err os.Error)

AcceptUnix accepts the next incoming call and returns the new connection and the remote address.

func (*UnixListener) Addr


func (l *UnixListener) Addr() Addr Addr returns the listener's network address.

func (*UnixListener) Close


func (l *UnixListener) Close() os.Error Close stops listening on the Unix address. Already accepted connections are not closed.

type UnknownNetworkError
type UnknownNetworkError string

func (Unknow nNetw orkError) String


func (e UnknownNetworkError) String() string

type UnknownSocketError
type UnknownSocketError struct { // contains unexported fields }

func (*Unknow nSocketError) String


func (e *UnknownSocketError) String() string

Except as noted, this content is licensed under Creative Commons Attribution 3.0.

The Go Programming Language

Package netchan
type Dir type Exporter func NewExporter func (*Exporter) Addr func (*Exporter) Export type Importer func NewImporter func (*Importer) Import func (*Importer) ImportNValues import "netchan" The netchan package implements type-safe networked channels: it allows the two ends of a channel to appear on different computers connected by a network. It does this by transporting data sent to a channel on one machine so it can be recovered by a receive of a channel of the same type on the other. An exporter publishes a set of channels by name. An importer connects to the exporting machine and imports the channels by name. After importing the channels, the two machines can use the channels in the usual way. Networked channels are not synchronized; they always behave as if there is a buffer of at least one element between the two machines. TODO: at the moment, the exporting machine must send and the importing machine must receive. This restriction will be lifted soon. Package files
common.go export.go import.go

type Dir
type Dir int

const ( Recv Dir = iota Send )

type Exporter
An Exporter allows a set of channels to be published on a single network port. A single machine may have multiple Exporters but they must use different ports.

type Exporter struct { // contains unexported fields }

func New Exporter


func NewExporter(network, localaddr string) (*Exporter, os.Error) NewExporter creates a new Exporter to export channels on the network and local address defined as in net.Listen.

func (*Exporter) Addr


func (exp *Exporter) Addr() net.Addr Addr returns the Exporter's local network address.

func (*Exporter) Export


func (exp *Exporter) Export(name string, chT interface{}, dir Dir) os.Error Export exports a channel of a given type and specified direction. The channel to be exported is provided in the call and may be of arbitrary channel type. Despite the literal signature, the effective signature is
Export(name string, chT chan T, dir Dir)

where T must be a struct, pointer to struct, etc.

type Importer
An Importer allows a set of channels to be imported from a single remote machine/network port. A machine may have multiple importers, even from the same machine/network port.
type Importer struct { // contains unexported fields }

func New Im porter


func NewImporter(network, remoteaddr string) (*Importer, os.Error) NewImporter creates a new Importer object to import channels from an Exporter at the network and remote address as defined in net.Dial. The Exporter must be available and serving when the Importer is created.

func (*Im porter) Im port


func (imp *Importer) Import(name string, chT interface{}, dir Dir, pT interface{}) os.Error Import imports a channel of the given type and specified direction. It is equivalent to ImportNValues with a count of 0, meaning unbounded.

func (*Im porter) Im portNValues


func (imp *Importer) ImportNValues(name string, chT interface{}, dir Dir, pT

interface{}, n int) os.Error ImportNValues imports a channel of the given type and specified direction and then receives or transmits up to n values on that channel. A value of n==0 implies an unbounded number of values. The channel to be bound to the remote site's channel is provided in the call and may be of arbitrary channel type. Despite the literal signature, the effective signature is
ImportNValues(name string, chT chan T, dir Dir, pT T)

where T must be a struct, pointer to struct, etc. pT may be more indirect than the value type of the channel (e.g. chan T, pT *T) but it must be a pointer. Example usage:
imp, err := NewImporter("tcp", "netchanserver.mydomain.com:1234") if err != nil { log.Exit(err) } ch := make(chan myType) err := imp.ImportNValues("name", ch, Recv, new(myType), 1) if err != nil { log.Exit(err) } fmt.Printf("%+v\n", <-ch)

(TODO: Can we eliminate the need for pT?)

Except as noted, this content is licensed under Creative Commons Attribution 3.0.

The Go Programming Language

Package once
func Do import "once" This package provides a single function, Do, to run a function exactly once, usually used as part of initialization. Package files
once.go

func Do
func Do(f func()) Do is the the only exported piece of the package. For one-time initialization that is not done during init, wrap the initialization in a niladic function f() and call
Do(f)

If multiple processes call Do(f) simultaneously with the same f argument, only one will call f, and the others will block until f finishes running. Since a func() expression typically evaluates to a differerent function value each time it is evaluated, it is incorrect to pass such values to Do. For example,
func f(x int) { Do(func() { fmt.Println(x) }) }

behaves the same as


func f(x int) { fmt.Println(x) }

because the func() expression in the first creates a new func each time f runs, and each of those funcs is run once.

Except as noted, this content is licensed under Creative Commons Attribution 3.0.

The Go Programming Language

Package os
Constants Variables func Chdir func Chmod func Chown func Clearenv func Environ func Exec func Exit func ForkExec func Getegid func Getenv func Getenverror func Geteuid func Getgid func Getgroups func Getpagesize func Getpid func Getppid func Getuid func Getwd func Hostname func Lchown func Link func Mkdir func MkdirAll func Readlink func Remove func RemoveAll func Rename func Setenv func Symlink func Time func Truncate type Dir func Lstat func Stat func (*Dir) IsBlock func (*Dir) IsChar func (*Dir) IsDirectory func (*Dir) IsFifo func (*Dir) IsRegular import "os" The os package provides a platform-independent interface to operating system functionality. The design is Unix-like. func (*Dir) IsSocket func (*Dir) IsSymlink func (*Dir) Permission type Errno func (Errno) String type Error func NewError func NewSyscallError type ErrorString func (ErrorString) String type File func NewFile func Open func Pipe func (*File) Chdir func (*File) Chmod func (*File) Chown func (*File) Close func (*File) Fd func (*File) Name func (*File) Read func (*File) ReadAt func (*File) Readdir func (*File) Readdirnames func (*File) Seek func (*File) Stat func (*File) Truncate func (*File) Write func (*File) WriteAt func (*File) WriteString type LinkError func (*LinkError) String type PathError func (*PathError) String type SyscallError func (*SyscallError) String type Waitmsg func Wait func (Waitmsg) String Subdirectories

Package files
dir_darwin.go dir_f reebsd.go dir_linux.go dir_nacl.go env .go error.go exec.go f ile.go getwd.go path.go proc.go stat_darwin.go stat_f reebsd.go stat_linux.go stat_nacl.go sy s_darwin.go sy s_f reebsd.go sy s_linux.go sy s_nacl.go time.go ty pes.go

Constants
Flags to Open wrapping those of the underlying system. Not all flags may be implemented on a given system.
const ( O_RDONLY O_WRONLY O_RDWR O_APPEND O_ASYNC O_CREAT O_EXCL O_NOCTTY O_NONBLOCK O_NDELAY O_SYNC O_TRUNC O_CREATE )

= = = = = = = = = = = = =

syscall.O_RDONLY syscall.O_WRONLY syscall.O_RDWR syscall.O_APPEND syscall.O_ASYNC syscall.O_CREAT syscall.O_EXCL syscall.O_NOCTTY syscall.O_NONBLOCK O_NONBLOCK syscall.O_SYNC syscall.O_TRUNC O_CREAT

// // // // // // // // // // // // //

open the file read-only. open the file write-only. open the file read-write. open the file append-only. generate a signal when I/O is available. create a new file if none exists. used with O_CREAT, file must not exist do not make file the controlling tty. open in non-blocking mode. synonym for O_NONBLOCK open for synchronous I/O. if possible, truncate file when opened. create a new file if none exists.

Options for Wait.


const ( WNOHANG WSTOPPED WUNTRACED WRUSAGE )

= = = =

syscall.WNOHANG // Don't wait if no process has exited. syscall.WSTOPPED // If set, status of stopped subprocesses is also reported. WSTOPPED 1 << 20 // Record resource usage.

Variables
Stdin, Stdout, and Stderr are open Files pointing to the standard input, standard output, and standard error file descriptors.
var ( Stdin = NewFile(0, "/dev/stdin") Stdout = NewFile(1, "/dev/stdout") Stderr = NewFile(2, "/dev/stderr") )

var Args []string // provided by runtime

ENOENV is the Error indicating that an environment variable does not exist.
var ENOENV = NewError("no such environment variable")

var Envs []string // provided by runtime

func Chdir
func Chdir(dir string) Error Chdir changes the current working directory to the named directory.

func Chmod
func Chmod(name string, mode int) 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.

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.

func Clearenv
func Clearenv() Clearenv deletes all environment variables.

func Environ
func Environ() []string Environ returns an array of strings representing the environment, in the form "key=value".

func Exec
func Exec(argv0 string, argv []string, envv []string) Error Exec replaces the current process with an execution of the program named by argv0, with arguments argv and environment envv. If successful, Exec never returns. If it fails, it returns an Error. ForkExec is almost always a better way to execute a program.

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.

func ForkExec
func ForkExec(argv0 string, argv []string, envv []string, dir string, fd []*File) (pid int, err Error) ForkExec forks the current process and invokes Exec with the file, arguments, and environment specified by argv0, argv, and envv. It returns the process id of the forked process and an Error, if any. The fd array specifies the file descriptors to be set up in the new process: fd[0] will be Unix file descriptor 0 (standard input), fd[1] descriptor 1, and so on. A nil entry will cause the child to have no open file descriptor with that index. If dir is not empty, the child chdirs into the directory before execing the program.

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 Getenverror
func Getenverror(key string) (value string, err Error) Getenverror retrieves the value of the environment variable named by the key. It returns the value and an error, if any.

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() (string, 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 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.

func Link
func Link(oldname, newname string) Error Link creates a hard link.

func Mkdir
func Mkdir(name string, perm int) Error Mkdir creates a new directory with the specified name and permission bits. It returns an error, if any.

func MkdirAll
func MkdirAll(path string, perm int) 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 Readlink
func Readlink(name string) (string, Error) Readlink reads the contents of a symbolic link: the destination of the link. It returns the contents and an Error, if any.

func Remove
func Remove(name string) Error Remove removes the named file or directory.

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(oldname, newname string) Error

Rename renames a file.

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
func Symlink(oldname, newname string) Error Symlink creates a symbolic link.

func Time
func Time() (sec int64, nsec int64, err Error) Time returns the current time, in whole seconds and fractional nanoseconds, plus an Error if any. The current time is thus 1e9*sec+nsec, in nanoseconds. The zero of time is the Unix epoch.

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.

type Dir
A Dir describes a file and is returned by Stat, Fstat, and Lstat
type Dir struct { Dev Ino Nlink Mode Uid Gid Rdev Size Blksize Blocks Atime_ns Mtime_ns Ctime_ns Name FollowedSymlink }

uint64 uint64 uint64 uint32 uint32 uint32 uint64 uint64 uint64 uint64 uint64 uint64 uint64 string bool

// // // // // // // // // // // // // // //

device number of file system holding file. inode number. number of hard links. permission and mode bits. user id of owner. group id of owner. device type for special file. length in bytes. size of blocks, in bytes. number of blocks allocated for file. access time; nanoseconds since epoch. modified time; nanoseconds since epoch. status change time; nanoseconds since epoch. name of file as presented to Open. followed a symlink to get this information

func Lstat
func Lstat(name string) (dir *Dir, err Error) Lstat returns the Dir structure describing the named file and an error, if any. If the file is a symbolic link, the returned Dir describes the symbolic link. Lstat makes no attempt to follow the link.

func Stat
func Stat(name string) (dir *Dir, err Error) Stat returns a Dir structure describing the named file and an error, if any. If name names a valid symbolic link, the returned Dir describes the file pointed at by the link and has dir.FollowedSymlink set to true. If name names an invalid symbolic link, the returned Dir describes the link itself and has dir.FollowedSymlink set to false.

func (*Dir) IsBlock


func (dir *Dir) IsBlock() bool IsBlock reports whether the Dir describes a block special file.

func (*Dir) IsChar


func (dir *Dir) IsChar() bool IsChar reports whether the Dir describes a character special file.

func (*Dir) IsDirectory


func (dir *Dir) IsDirectory() bool IsDirectory reports whether the Dir describes a directory.

func (*Dir) IsFifo


func (dir *Dir) IsFifo() bool IsFifo reports whether the Dir describes a FIFO file.

func (*Dir) IsRegular


func (dir *Dir) IsRegular() bool IsRegular reports whether the Dir describes a regular file.

func (*Dir) IsSocket


func (dir *Dir) IsSocket() bool IsSocket reports whether the Dir describes a socket.

func (*Dir) IsSym link


func (dir *Dir) IsSymlink() bool IsSymlink reports whether the Dir describes a symbolic link.

func (*Dir) Perm ission


func (dir *Dir) Permission() int

Permission returns the file permission bits.

type Errno
Errno is the Unix error number. Names such as EINVAL are simple wrappers to convert the error number into an Error.
type Errno int64

func (Errno) String


func (e Errno) String() string

type Error
An Error can represent any printable error condition.
type Error interface { String() string }

Commonly known Unix errors.

var ( EPERM ENOENT ESRCH EINTR EIO ENXIO E2BIG ENOEXEC EBADF ECHILD EDEADLK ENOMEM EACCES EFAULT EBUSY EEXIST EXDEV ENODEV ENOTDIR EISDIR EINVAL ENFILE EMFILE ENOTTY EFBIG ENOSPC ESPIPE EROFS EMLINK EPIPE EAGAIN EDOM ERANGE EADDRINUSE ECONNREFUSED ENAMETOOLONG EAFNOSUPPORT )

Error Error Error Error Error Error Error Error Error Error Error Error Error Error Error Error Error Error Error Error Error Error Error Error Error Error Error Error Error Error Error Error Error Error Error Error Error

= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =

Errno(syscall.EPERM) Errno(syscall.ENOENT) Errno(syscall.ESRCH) Errno(syscall.EINTR) Errno(syscall.EIO) Errno(syscall.ENXIO) Errno(syscall.E2BIG) Errno(syscall.ENOEXEC) Errno(syscall.EBADF) Errno(syscall.ECHILD) Errno(syscall.EDEADLK) Errno(syscall.ENOMEM) Errno(syscall.EACCES) Errno(syscall.EFAULT) Errno(syscall.EBUSY) Errno(syscall.EEXIST) Errno(syscall.EXDEV) Errno(syscall.ENODEV) Errno(syscall.ENOTDIR) Errno(syscall.EISDIR) Errno(syscall.EINVAL) Errno(syscall.ENFILE) Errno(syscall.EMFILE) Errno(syscall.ENOTTY) Errno(syscall.EFBIG) Errno(syscall.ENOSPC) Errno(syscall.ESPIPE) Errno(syscall.EROFS) Errno(syscall.EMLINK) Errno(syscall.EPIPE) Errno(syscall.EAGAIN) Errno(syscall.EDOM) Errno(syscall.ERANGE) Errno(syscall.EADDRINUSE) Errno(syscall.ECONNREFUSED) Errno(syscall.ENAMETOOLONG) Errno(syscall.EAFNOSUPPORT)

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 io.ErrUnexpectedEOF or some other error giving more detail.
var EOF Error = eofError(0)

func New Error


func NewError(s string) Error NewError converts s to an ErrorString, which satisfies the Error interface.

func New SyscallError


func NewSyscallError(syscall string, errno int) Error NewSyscallError returns, as an Error, a new SyscallError with the given system call name and error number. As a convenience, if errno is 0, NewSyscallError returns nil.

type ErrorString
A helper type that can be embedded or wrapped to simplify satisfying Error.
type ErrorString string

func (ErrorString) String


func (e ErrorString) String() string

type File
File represents an open file descriptor.
type File struct { // contains unexported fields }

func New File


func NewFile(fd int, name string) *File NewFile returns a new File with the given file descriptor and name.

func Open
func Open(name string, flag int, perm int) (file *File, err Error) Open 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. It returns the File and an Error, if any.

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.

func (*File) Chm od


func (f *File) Chmod(mode int) Error Chmod changes the mode of the file to mode.

func (*File) Chow n


func (f *File) Chown(uid, gid int) Error Chown changes the numeric uid and gid of the named file.

func (*File) Close


func (file *File) Close() Error Close closes the File, rendering it unusable for I/O. It returns an Error, if any.

func (*File) Fd
func (file *File) Fd() int Fd returns the integer Unix file descriptor referencing the open file.

func (*File) Nam e


func (file *File) Name() string Name returns the name of the file as presented to Open.

func (*File) Read


func (file *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 EOF.

func (*File) ReadAt


func (file *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. EOF is signaled by a zero count with err set to EOF. ReadAt always returns a non-nil Error when n != len(b).

func (*File) Readdir


func (file *File) Readdir(count int) (dirs []Dir, err Error) Readdir reads the contents of the directory associated with file and returns an array of up to count Dir structures, as would be returned by Stat, in directory order. Subsequent calls on the same file will yield further Dirs. A negative count means to read until EOF. Readdir returns the array and an Error, if any.

func (*File) Readdirnam es


func (file *File) Readdirnames(count int) (names []string, err Error) Readdirnames reads the contents of the directory associated with file and returns an array of up to count names, in directory order. Subsequent calls on the same file will yield further names. A negative count means to read until EOF. Readdirnames returns the array and an Error, if any.

func (*File) Seek


func (file *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.

func (*File) Stat


func (file *File) Stat() (dir *Dir, err Error)

Stat returns the Dir structure describing file. It returns the Dir and an error, if any.

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.

func (*File) Write


func (file *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 (file *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 (file *File) WriteString(s string) (ret int, err Error) WriteString is like Write, but writes the contents of string s rather than an array of bytes.

type LinkError
LinkError records an error during a link or symlink or rename system call and the paths that caused it.
type LinkError struct { Op string Old string New string Error Error }

func (*LinkError) String


func (e *LinkError) String() string

type PathError
PathError records an error and the operation and file path that caused it.
type PathError struct { Op string Path string Error Error }

func (*PathError) String

func (e *PathError) String() string

type SyscallError
SyscallError records an error from a specific system call.
type SyscallError struct { Syscall string Errno Errno }

func (*SyscallError) String


func (e *SyscallError) String() string

type Waitmsg
Waitmsg stores the information about an exited process as reported by Wait.
type Waitmsg struct { Pid int // The process's id. syscall.WaitStatus // System-dependent status info. Rusage *syscall.Rusage // System-dependent resource usage info. }

func Wait
func Wait(pid int, options int) (w *Waitmsg, err Error) Wait waits for process pid to exit or stop, and then returns a Waitmsg describing its status and an Error, if any. The options (WNOHANG etc.) affect the behavior of the Wait call.

func (Waitm sg) String


func (w Waitmsg) String() string

Subdirectories
Name .. signal Synopsis Package signal implements operating system-independent signal handling.

Except as noted, this content is licensed under Creative Commons Attribution 3.0.

The Go Programming Language

Package signal
Variables type Signal type UnixSignal func (UnixSignal) String import "os/signal" Package signal implements operating system-independent signal handling. Package files
signal.go

Variables
Incoming is the global signal channel. All signals received by the program will be delivered to this channel.
var Incoming <-chan Signal

type Signal
A Signal can represent any operating system signal.
type Signal interface { String() string }

type UnixSignal
type UnixSignal int32

func (UnixSignal) String


func (sig UnixSignal) String() string

Except as noted, this content is licensed under Creative Commons Attribution 3.0.

The Go Programming Language

Package patch
Variables type Diff func ParseGitBinary type File type GitBinaryLiteral func (*GitBinaryLiteral) Apply type Op type Set func Parse func (*Set) Apply import "patch" Package patch implements parsing and execution of the textual and binary patch descriptions used by version control tools such as CVS, Git, Mercurial, and Subversion. Package files
apply .go git.go patch.go textdif f .go

type SyntaxError func (SyntaxError) String type TextChunk type TextDiff func ParseTextDiff func (TextDiff) Apply type Verb Bugs

Variables
var ErrPatchFailure = os.NewError("patch did not apply cleanly")

type Diff
A Diff is any object that describes changes to transform an old byte stream to a new one.
type Diff interface { // Apply applies the changes listed in the diff // to the string s, returning the new version of the string. // Note that the string s need not be a text string. Apply(old []byte) (new []byte, err os.Error) }

NoDiff is a no-op Diff implementation: it passes the old data through unchanged.
var NoDiff Diff = noDiffType(0)

func ParseGitBinary
func ParseGitBinary(raw []byte) (Diff, os.Error)

ParseGitBinary parses raw as a Git binary patch.

type File
A File represents a collection of changes to be made to a single file.
type File struct { Verb Src Dst OldMode, NewMode Diff }

Verb string // source for Verb == Copy, Verb == Rename string int // 0 indicates not used // changes to data; == NoDiff if operation does not edit file

type GitBinaryLiteral
GitBinaryLiteral represents a Git binary literal diff.
type GitBinaryLiteral struct { OldSHA1 []byte // if non-empty, the SHA1 hash of the original New []byte // the new contents }

func (*GitBinaryLiteral) Apply


func (d *GitBinaryLiteral) Apply(old []byte) ([]byte, os.Error) Apply implements the Diff interface's Apply method.

type Op
An Op is a single operation to execute to apply a patch.
type Op struct { Verb Verb // Src string // Dst string // Mode int // Data []byte // }

action source file destination file mode for destination (if non-zero) data for destination (if non-nil)

type Set
A Set represents a set of patches to be applied as a single atomic unit. Patch sets are often preceded by a descriptive header.

type Set struct { Header string // free-form text File []*File }

func Parse
func Parse(text []byte) (*Set, os.Error) Parse patches the patch text to create a patch Set. The patch text typically comprises a textual header and a sequence of file patches, as would be generated by CVS, Subversion, Mercurial, or Git.

func (*Set) Apply


func (set *Set) Apply(readFile func(string) ([]byte, os.Error)) ([]Op, os.Error) Apply applies the patch set to the files named in the patch set, constructing an in-memory copy of the new file state. It is the client's job to write the changes to the file system if desired. The function readFile should return the contents of the named file. Typically this function will be io.ReadFile.

type SyntaxError
A SyntaxError represents a syntax error encountered while parsing a patch.
type SyntaxError string

func (SyntaxError) String


func (e SyntaxError) String() string

type TextChunk
A TextChunk specifies an edit to a section of a file: the text beginning at Line, which should be exactly Old, is to be replaced with New.
type TextChunk struct { Line int Old []byte New []byte }

type TextDiff
type TextDiff []TextChunk

func ParseTextDiff

func ParseTextDiff(raw []byte) (TextDiff, os.Error)

func (TextDiff) Apply


func (d TextDiff) Apply(data []byte) ([]byte, os.Error) Apply applies the changes listed in the diff to the data, returning the new version.

type Verb
A Verb is an action performed on a file.
type Verb string

const ( Add Copy Delete Edit Rename )

Verb Verb Verb Verb Verb

= = = = =

"add" "copy" "delete" "edit" "rename"

Bugs
The Git binary delta format is not implemented, only Git binary literals.

Except as noted, this content is licensed under Creative Commons Attribution 3.0.

The Go Programming Language

Package path
Variables func Clean func Ext func Join func Match func Split func Walk type Visitor import "path" The path package implements utility routines for manipulating slash-separated filename paths. Package files
match.go path.go

Variables
var ErrBadPattern = os.NewError("syntax error in pattern")

func Clean
func Clean(path string) string Clean returns the shortest path name equivalent to path by purely lexical processing. It applies the following rules iteratively until no further processing can be done:
1. Replace multiple slashes with a single slash. 2. Eliminate each . path name element (the current directory). 3. Eliminate each inner .. path name element (the parent directory) along with the non-.. element that precedes it. 4. Eliminate .. elements that begin a rooted path: that is, replace "/.." by "/" at the beginning of a path.

If the result of this process is an empty string, Clean returns the string ".". See also Rob Pike, Lexical File Names in Plan 9 or Getting Dot-Dot right, http://plan9.bell-labs.com/sys/doc /lexnames.html

func Ext
func Ext(path string) string

Ext returns the file name extension used by path. The extension is the suffix beginning at the final dot in the final slash-separated element of path; it is empty if there is no dot.

func Join
func Join(elem ...string) string Join joins any number of path elements into a single path, adding a separating slash if necessary. All empty strings are ignored.

func Match
func Match(pattern, name string) (matched bool, err os.Error) Match returns true if name matches the shell file name pattern. The syntax used by pattern is:
pattern: { term } term: '*' matches any sequence of non-/ characters '?' matches any single non-/ character '[' [ '^' ] { character-range } ']' character class (must be non-empty) c matches character c (c != '*', '?', '\\', '[') '\\' c matches character c character-range: c '\\' c lo '-' hi

matches character c (c != '\\', '-', ']') matches character c matches character c for lo <= c <= hi

Match requires pattern to match all of name, not just a substring. The only possible error return is when pattern is malformed.

func Split
func Split(path string) (dir, file string) Split splits path immediately following the final slash, separating it into a directory and file name component. If there is no slash in path, DirFile returns an empty dir and file set to path.

func Walk
func Walk(root string, v Visitor, errors chan<- os.Error) Walk walks the file tree rooted at root, calling v.VisitDir or v.VisitFile for each directory or file in the tree, including root. If v.VisitDir returns false, Walk skips the directory's entries; otherwise it invokes itself for each directory entry in sorted order. An error reading a directory does not abort the Walk. If errors != nil, Walk sends each directory read error to the channel. Otherwise Walk discards the error.

type Visitor
Visitor methods are invoked for corresponding file tree entries visited by Walk. The parameter path is the full path of d relative to root.
type Visitor interface { VisitDir(path string, d *os.Dir) bool VisitFile(path string, d *os.Dir) }

Except as noted, this content is licensed under Creative Commons Attribution 3.0.

The Go Programming Language

Package rand
func ExpFloat64 func Float func Float32 func Float64 func Int func Int31 func Int31n func Int63 func Int63n func Intn func NormFloat64 func Perm func Seed func Uint32 type Rand func New func (*Rand) ExpFloat64 func (*Rand) Float func (*Rand) Float32 import "rand" Package rand implements pseudo-random number generators. Package files
exp.go normal.go rand.go rng.go zipf .go

func (*Rand) Float64 func (*Rand) Int func (*Rand) Int31 func (*Rand) Int31n func (*Rand) Int63 func (*Rand) Int63n func (*Rand) Intn func (*Rand) NormFloat64 func (*Rand) Perm func (*Rand) Seed func (*Rand) Uint32 type Source func NewSource type Zipf func NewZipf func (*Zipf) Uint64

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). To produce a distribution with a different rate parameter, callers can adjust the output using:
sample = ExpFloat64() / desiredRateParameter

func Float
func Float() float Float returns, as a float, a pseudo-random number in [0.0,1.0).

func Float32
func Float32() float32 Float32 returns, as a float32, a pseudo-random number in [0.0,1.0).

func Float64
func Float64() float64 Float64 returns, as a float64, a pseudo-random number in [0.0,1.0).

func Int
func Int() int Int returns a non-negative pseudo-random int.

func Int31
func Int31() int32 Int31 returns a non-negative pseudo-random 31-bit integer as an int32.

func Int31n
func Int31n(n int32) int32 Int31n returns, as an int32, a non-negative pseudo-random number in [0,n).

func Int63
func Int63() int64 Int63 returns a non-negative pseudo-random 63-bit integer as an int64.

func Int63n
func Int63n(n int64) int64 Int63n returns, as an int64, a non-negative pseudo-random number in [0,n).

func Intn
func Intn(n int) int Intn returns, as an int, a non-negative pseudo-random number in [0,n).

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). 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).

func Seed
func Seed(seed int64) Seed uses the provided seed value to initialize the generator to a deterministic state.

func Uint32
func Uint32() uint32 Uint32 returns a pseudo-random 32-bit value as a uint32.

type Rand
A Rand is a source of random numbers.
type Rand struct { // contains unexported fields }

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) Float


func (r *Rand) Float() float Float returns, as a float, a pseudo-random number in [0.0,1.0).

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).

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).

func (*Rand) Intn


func (r *Rand) Intn(n int) int Intn returns, as an int, a non-negative pseudo-random number in [0,n).

func (*Rand) Norm Float64


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) 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
A Source represents a source of uniformly-distributed pseudo-random int64 values in the range [0, 1<<63).
type Source interface { Int63() int64 Seed(seed int64) }

func New Source


func NewSource(seed int64) Source NewSource returns a new pseudo-random Source seeded with the given value.

type Zipf
A Zipf generates Zipf distributed variates.
type Zipf struct { // contains unexported fields }

func New Zipf


func NewZipf(r *Rand, s float64, v float64, imax uint64) *Zipf NewZipf returns a Zipf generating variates p(k) on [0, imax] proportional to (v+k)**(-s) where s>1 and k>=0, and v>=1.

func (*Zipf) Uint64


func (z *Zipf) Uint64() uint64 Uint64 returns a value drawn from the Zipf distributed described by the Zipf object.

Except as noted, this content is licensed under Creative Commons Attribution 3.0.

The Go Programming Language

Package reflect
func ArrayCopy func DeepEqual type ArrayOrSliceType type ArrayOrSliceValue type ArrayType func (*ArrayType) Elem func (*ArrayType) Len type ArrayValue func (*ArrayValue) Cap func (*ArrayValue) Elem func (*ArrayValue) Len func (*ArrayValue) Set func (*ArrayValue) SetValue type BoolType type BoolValue func (*BoolValue) Get func (*BoolValue) Set func (*BoolValue) SetValue type ChanDir func (ChanDir) String type ChanType func (*ChanType) Dir func (*ChanType) Elem type ChanValue func MakeChan func (*ChanValue) Cap func (*ChanValue) Close func (*ChanValue) Closed func (*ChanValue) Get func (*ChanValue) IsNil func (*ChanValue) Len func (*ChanValue) Recv func (*ChanValue) Send func (*ChanValue) Set func (*ChanValue) SetValue func (*ChanValue) TryRecv func (*ChanValue) TrySend type Complex128Type type Complex128Value func (*Complex128Value) Get func (*Complex128Value) Set func (*Complex128Value) SetValue type Complex64Type type Complex64Value func (*Complex64Value) Get func (*Complex64Value) Set func (*InterfaceType) NumMethod type InterfaceValue func (*InterfaceValue) Elem func (*InterfaceValue) IsNil func (*InterfaceValue) Method func (*InterfaceValue) Set func (*InterfaceValue) SetValue type MapType func (*MapType) Elem func (*MapType) Key type MapValue func MakeMap func (*MapValue) Elem func (*MapValue) Get func (*MapValue) IsNil func (*MapValue) Keys func (*MapValue) Len func (*MapValue) Set func (*MapValue) SetElem func (*MapValue) SetValue type Method type PtrType func (*PtrType) Elem type PtrValue func (*PtrValue) Elem func (*PtrValue) Get func (*PtrValue) IsNil func (*PtrValue) PointTo func (*PtrValue) Set func (*PtrValue) SetValue type SliceHeader type SliceType func (*SliceType) Elem type SliceValue func MakeSlice func (*SliceValue) Cap func (*SliceValue) Elem func (*SliceValue) Get func (*SliceValue) IsNil func (*SliceValue) Len func (*SliceValue) Set func (*SliceValue) SetLen func (*SliceValue) SetValue func (*SliceValue) Slice type StringHeader type StringType

func (*Complex64Value) SetValue type ComplexType type ComplexValue func (*ComplexValue) Get func (*ComplexValue) Set func (*ComplexValue) SetValue type Float32Type type Float32Value func (*Float32Value) Get func (*Float32Value) Set func (*Float32Value) SetValue type Float64Type type Float64Value func (*Float64Value) Get func (*Float64Value) Set func (*Float64Value) SetValue type FloatType type FloatValue func (*FloatValue) Get func (*FloatValue) Set func (*FloatValue) SetValue type FuncType func (*FuncType) DotDotDot func (*FuncType) In func (*FuncType) NumIn func (*FuncType) NumOut func (*FuncType) Out type FuncValue func (*FuncValue) Call func (*FuncValue) Get func (*FuncValue) IsNil func (*FuncValue) Set func (*FuncValue) SetValue type Int16Type type Int16Value func (*Int16Value) Get func (*Int16Value) Set func (*Int16Value) SetValue type Int32Type type Int32Value func (*Int32Value) Get func (*Int32Value) Set func (*Int32Value) SetValue type Int64Type type Int64Value func (*Int64Value) Get func (*Int64Value) Set func (*Int64Value) SetValue type Int8Type type Int8Value func (*Int8Value) Get func (*Int8Value) Set func (*Int8Value) SetValue type IntType type IntValue

type StringValue func (*StringValue) Get func (*StringValue) Set func (*StringValue) SetValue type StructField type StructType func (*StructType) Field func (*StructType) FieldByIndex func (*StructType) FieldByName func (*StructType) NumField type StructValue func (*StructValue) Field func (*StructValue) FieldByIndex func (*StructValue) FieldByName func (*StructValue) NumField func (*StructValue) Set func (*StructValue) SetValue type Type func Typeof type Uint16Type type Uint16Value func (*Uint16Value) Get func (*Uint16Value) Set func (*Uint16Value) SetValue type Uint32Type type Uint32Value func (*Uint32Value) Get func (*Uint32Value) Set func (*Uint32Value) SetValue type Uint64Type type Uint64Value func (*Uint64Value) Get func (*Uint64Value) Set func (*Uint64Value) SetValue type Uint8Type type Uint8Value func (*Uint8Value) Get func (*Uint8Value) Set func (*Uint8Value) SetValue type UintType type UintValue func (*UintValue) Get func (*UintValue) Set func (*UintValue) SetValue type UintptrType type UintptrValue func (*UintptrValue) Get func (*UintptrValue) Set func (*UintptrValue) SetValue type UnsafePointerType type UnsafePointerValue func (*UnsafePointerValue) Get func (*UnsafePointerValue) Set func (*UnsafePointerValue) SetValue type Value

func (*IntValue) Get func (*IntValue) Set func (*IntValue) SetValue type InterfaceType func (*InterfaceType) Method import "reflect"

func Indirect func MakeZero func NewValue

The reflect package 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 an object with interface type Type. That contains a pointer to a struct of type *StructType, *IntType, etc. representing the details of the underlying type. A type switch or type assertion can reveal which. A call to NewValue creates a Value representing the run-time data; it contains a *StructValue, *IntValue, etc. MakeZero takes a Type and returns a Value representing a zero value for that type. Package files
deepequal.go ty pe.go v alue.go

func ArrayCopy
func ArrayCopy(dst, src ArrayOrSliceValue) int ArrayCopy 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. The arrays dst and src must have the same element type.

func DeepEqual
func DeepEqual(a1, a2 interface{}) bool DeepEqual tests for deep equality. It uses normal == equality where possible but will scan members of arrays, slices, and fields of structs. It correctly handles recursive types.

type ArrayOrSliceType
ArrayOrSliceType is the common interface implemented by both ArrayType and SliceType.
type ArrayOrSliceType interface { Type Elem() Type }

type ArrayOrSliceValue
ArrayOrSliceValue is the common interface implemented by both ArrayValue and SliceValue.

type ArrayOrSliceValue interface { Value Len() int Cap() int Elem(i int) Value // contains unexported methods }

type ArrayType
ArrayType represents a fixed array type.
type ArrayType struct { // contains unexported fields }

func (*ArrayType) Elem


func (t *ArrayType) Elem() Type Elem returns the type of the array's elements.

func (*ArrayType) Len


func (t *ArrayType) Len() int Len returns the number of elements in the array.

type ArrayValue
An ArrayValue represents an array.
type ArrayValue struct { // contains unexported fields }

func (*ArrayValue) Cap


func (v *ArrayValue) Cap() int Cap returns the capacity of the array (equal to Len()).

func (*ArrayValue) Elem


func (v *ArrayValue) Elem(i int) Value Elem returns the i'th element of v.

func (*ArrayValue) Len


func (v *ArrayValue) Len() int Len returns the length of the array.

func (*ArrayValue) Set


func (v *ArrayValue) Set(x *ArrayValue) Set assigns x to v. The new value x must have the same type as v.

func (*ArrayValue) SetValue


func (v *ArrayValue) SetValue(x Value) Set sets v to the value x.

type BoolType
BoolType represents a boolean type.
type BoolType struct { // contains unexported fields }

type BoolValue
BoolValue represents a bool value.
type BoolValue struct { // contains unexported fields }

func (*BoolValue) Get


func (v *BoolValue) Get() bool Get returns the underlying bool value.

func (*BoolValue) Set


func (v *BoolValue) Set(x bool) Set sets v to the value x.

func (*BoolValue) SetValue


func (v *BoolValue) SetValue(x Value) Set sets v to the value x.

type ChanDir
ChanDir represents a channel type's direction.
type ChanDir int

const ( RecvDir ChanDir = 1 << iota SendDir BothDir = RecvDir | SendDir )

func (ChanDir) String


func (d ChanDir) String() string

type ChanType
ChanType represents a channel type.
type ChanType struct { // contains unexported fields }

func (*ChanType) Dir


func (t *ChanType) Dir() ChanDir Dir returns the channel direction.

func (*ChanType) Elem


func (t *ChanType) Elem() Type Elem returns the channel's element type.

type ChanValue
A ChanValue represents a chan.
type ChanValue struct { // contains unexported fields }

func MakeChan
func MakeChan(typ *ChanType, buffer int) *ChanValue MakeChan creates a new channel with the specified type and buffer size.

func (*ChanValue) Cap


func (v *ChanValue) Cap() int

func (*ChanValue) Close


func (v *ChanValue) Close() Close closes the channel.

func (*ChanValue) Closed


func (v *ChanValue) Closed() bool Closed returns the result of closed(c) on the underlying channel.

func (*ChanValue) Get


func (v *ChanValue) Get() uintptr Get returns the uintptr value of v. It is mainly useful for printing.

func (*ChanValue) IsNil


func (v *ChanValue) IsNil() bool IsNil returns whether v is a nil channel.

func (*ChanValue) Len


func (v *ChanValue) Len() int

func (*ChanValue) Recv


func (v *ChanValue) Recv() Value Recv receives and returns a value from the channel v.

func (*ChanValue) Send


func (v *ChanValue) Send(x Value) Send sends x on the channel v.

func (*ChanValue) Set


func (v *ChanValue) Set(x *ChanValue) Set assigns x to v. The new value x must have the same type as v.

func (*ChanValue) SetValue


func (v *ChanValue) SetValue(x Value) Set sets v to the value x.

func (*ChanValue) TryRecv


func (v *ChanValue) TryRecv() Value TryRecv attempts to receive a value from the channel v but will not block. It returns the value if one is received, nil otherwise.

func (*ChanValue) TrySend


func (v *ChanValue) TrySend(x Value) bool TrySend attempts to sends x on the channel v but will not block. It returns true if the value was sent, false otherwise.

type Complex128Type
Complex128Type represents a complex128 type.
type Complex128Type struct { // contains unexported fields }

type Complex128Value
Complex128Value represents a complex128 value.
type Complex128Value struct { // contains unexported fields }

func (*Com plex128Value) Get


func (v *Complex128Value) Get() complex128 Get returns the underlying complex128 value.

func (*Com plex128Value) Set


func (v *Complex128Value) Set(x complex128) Set sets v to the value x.

func (*Com plex128Value) SetValue


func (v *Complex128Value) SetValue(x Value) Set sets v to the value x.

type Complex64Type
Complex64Type represents a complex64 type.
type Complex64Type struct { // contains unexported fields }

type Complex64Value
Complex64Value represents a complex64 value.
type Complex64Value struct { // contains unexported fields }

func (*Com plex64Value) Get


func (v *Complex64Value) Get() complex64 Get returns the underlying complex64 value.

func (*Com plex64Value) Set


func (v *Complex64Value) Set(x complex64) Set sets v to the value x.

func (*Com plex64Value) SetValue


func (v *Complex64Value) SetValue(x Value) Set sets v to the value x.

type ComplexType
ComplexType represents a complex type.
type ComplexType struct { // contains unexported fields }

type ComplexValue
ComplexValue represents a complex value.
type ComplexValue struct { // contains unexported fields }

func (*Com plexValue) Get


func (v *ComplexValue) Get() complex Get returns the underlying complex value.

func (*Com plexValue) Set


func (v *ComplexValue) Set(x complex) Set sets v to the value x.

func (*Com plexValue) SetValue


func (v *ComplexValue) SetValue(x Value) Set sets v to the value x.

type Float32Type
Float32Type represents a float32 type.
type Float32Type struct { // contains unexported fields }

type Float32Value
Float32Value represents a float32 value.
type Float32Value struct { // contains unexported fields }

func (*Float32Value) Get


func (v *Float32Value) Get() float32 Get returns the underlying float32 value.

func (*Float32Value) Set


func (v *Float32Value) Set(x float32) Set sets v to the value x.

func (*Float32Value) SetValue


func (v *Float32Value) SetValue(x Value) Set sets v to the value x.

type Float64Type
Float64Type represents a float64 type.
type Float64Type struct { // contains unexported fields }

type Float64Value
Float64Value represents a float64 value.
type Float64Value struct { // contains unexported fields }

func (*Float64Value) Get


func (v *Float64Value) Get() float64 Get returns the underlying float64 value.

func (*Float64Value) Set


func (v *Float64Value) Set(x float64) Set sets v to the value x.

func (*Float64Value) SetValue


func (v *Float64Value) SetValue(x Value) Set sets v to the value x.

type FloatType
FloatType represents a float type.
type FloatType struct { // contains unexported fields }

type FloatValue
FloatValue represents a float value.
type FloatValue struct { // contains unexported fields }

func (*FloatValue) Get


func (v *FloatValue) Get() float Get returns the underlying float value.

func (*FloatValue) Set


func (v *FloatValue) Set(x float) Set sets v to the value x.

func (*FloatValue) SetValue


func (v *FloatValue) SetValue(x Value) Set sets v to the value x.

type FuncType
FuncType represents a function type.
type FuncType struct { // contains unexported fields }

func (*FuncType) DotDotDot


func (t *FuncType) DotDotDot() bool DotDotDot returns true if the final function input parameter is a "..." parameter. If so, the parameter's underlying static type - either interface{} or []T - is returned by t.In(t.NumIn() - 1). For concreteness, if t is func(x int, y ... float), then
t.NumIn() == 2 t.In(0) is the reflect.Type for "int" t.In(1) is the reflect.Type for "[]float" t.DotDotDot() == true

func (*FuncType) In
func (t *FuncType) In(i int) Type In returns the type of the i'th function input parameter.

func (*FuncType) Num In


func (t *FuncType) NumIn() int NumIn returns the number of input parameters.

func (*FuncType) Num Out


func (t *FuncType) NumOut() int NumOut returns the number of function output parameters.

func (*FuncType) Out


func (t *FuncType) Out(i int) Type Out returns the type of the i'th function output parameter.

type FuncValue
A FuncValue represents a function value.
type FuncValue struct { // contains unexported fields }

func (*FuncValue) Call

func (fv *FuncValue) Call(in []Value) []Value Call calls the function fv with input parameters in. It returns the function's output parameters as Values.

func (*FuncValue) Get


func (v *FuncValue) Get() uintptr Get returns the uintptr value of v. It is mainly useful for printing.

func (*FuncValue) IsNil


func (v *FuncValue) IsNil() bool IsNil returns whether v is a nil function.

func (*FuncValue) Set


func (v *FuncValue) Set(x *FuncValue) Set assigns x to v. The new value x must have the same type as v.

func (*FuncValue) SetValue


func (v *FuncValue) SetValue(x Value) Set sets v to the value x.

type Int16Type
Int16Type represents an int16 type.
type Int16Type struct { // contains unexported fields }

type Int16Value
Int16Value represents an int16 value.
type Int16Value struct { // contains unexported fields }

func (*Int16Value) Get


func (v *Int16Value) Get() int16 Get returns the underlying int16 value.

func (*Int16Value) Set


func (v *Int16Value) Set(x int16) Set sets v to the value x.

func (*Int16Value) SetValue


func (v *Int16Value) SetValue(x Value) Set sets v to the value x.

type Int32Type
Int32Type represents an int32 type.
type Int32Type struct { // contains unexported fields }

type Int32Value
Int32Value represents an int32 value.
type Int32Value struct { // contains unexported fields }

func (*Int32Value) Get


func (v *Int32Value) Get() int32 Get returns the underlying int32 value.

func (*Int32Value) Set


func (v *Int32Value) Set(x int32) Set sets v to the value x.

func (*Int32Value) SetValue


func (v *Int32Value) SetValue(x Value) Set sets v to the value x.

type Int64Type
Int64Type represents an int64 type.
type Int64Type struct { // contains unexported fields }

type Int64Value

Int64Value represents an int64 value.


type Int64Value struct { // contains unexported fields }

func (*Int64Value) Get


func (v *Int64Value) Get() int64 Get returns the underlying int64 value.

func (*Int64Value) Set


func (v *Int64Value) Set(x int64) Set sets v to the value x.

func (*Int64Value) SetValue


func (v *Int64Value) SetValue(x Value) Set sets v to the value x.

type Int8Type
Int8Type represents an int8 type.
type Int8Type struct { // contains unexported fields }

type Int8Value
Int8Value represents an int8 value.
type Int8Value struct { // contains unexported fields }

func (*Int8Value) Get


func (v *Int8Value) Get() int8 Get returns the underlying int8 value.

func (*Int8Value) Set


func (v *Int8Value) Set(x int8) Set sets v to the value x.

func (*Int8Value) SetValue

func (v *Int8Value) SetValue(x Value) Set sets v to the value x.

type IntType
IntType represents an int type.
type IntType struct { // contains unexported fields }

type IntValue
IntValue represents an int value.
type IntValue struct { // contains unexported fields }

func (*IntValue) Get


func (v *IntValue) Get() int Get returns the underlying int value.

func (*IntValue) Set


func (v *IntValue) Set(x int) Set sets v to the value x.

func (*IntValue) SetValue


func (v *IntValue) SetValue(x Value) Set sets v to the value x.

type InterfaceType
InterfaceType represents an interface type.
type InterfaceType struct { // contains unexported fields }

func (*InterfaceType) Method


func (t *InterfaceType) Method(i int) (m Method) Method returns the i'th interface method.

func (*InterfaceType) Num Method


func (t *InterfaceType) NumMethod() int NumMethod returns the number of interface methods.

type InterfaceValue
An InterfaceValue represents an interface value.
type InterfaceValue struct { // contains unexported fields }

func (*InterfaceValue) Elem


func (v *InterfaceValue) Elem() Value Elem returns the concrete value stored in the interface value v.

func (*InterfaceValue) IsNil


func (v *InterfaceValue) IsNil() bool IsNil returns whether v is a nil interface value.

func (*InterfaceValue) Method


func (v *InterfaceValue) Method(i int) *FuncValue Method returns a FuncValue corresponding to v's i'th method. The arguments to a Call on the returned FuncValue should not include a receiver; the FuncValue will use v as the receiver.

func (*InterfaceValue) Set


func (v *InterfaceValue) Set(x Value) Set assigns x to v.

func (*InterfaceValue) SetValue


func (v *InterfaceValue) SetValue(x Value) Set sets v to the value x.

type MapType
MapType represents a map type.
type MapType struct { // contains unexported fields }

func (*MapType) Elem

func (t *MapType) Elem() Type Elem returns the map element type.

func (*MapType) Key


func (t *MapType) Key() Type Key returns the map key type.

type MapValue
A MapValue represents a map value.
type MapValue struct { // contains unexported fields }

func MakeMap
func MakeMap(typ *MapType) *MapValue MakeMap creates a new map of the specified type.

func (*MapValue) Elem


func (v *MapValue) Elem(key Value) Value Elem returns the value associated with key in the map v. It returns nil if key is not found in the map.

func (*MapValue) Get


func (v *MapValue) Get() uintptr Get returns the uintptr value of v. It is mainly useful for printing.

func (*MapValue) IsNil


func (v *MapValue) IsNil() bool IsNil returns whether v is a nil map value.

func (*MapValue) Keys


func (v *MapValue) Keys() []Value Keys returns a slice containing all the keys present in the map, in unspecified order.

func (*MapValue) Len


func (v *MapValue) Len() int Len returns the number of keys in the map v.

func (*MapValue) Set


func (v *MapValue) Set(x *MapValue)

Set assigns x to v. The new value x must have the same type as v.

func (*MapValue) SetElem


func (v *MapValue) SetElem(key, val Value) SetElem sets the value associated with key in the map v to val. If val is nil, Put deletes the key from map.

func (*MapValue) SetValue


func (v *MapValue) SetValue(x Value) Set sets v to the value x.

type Method
Method represents a single method.
type Method PkgPath Name Type Func } struct { string // empty for uppercase Name string *FuncType *FuncValue

type PtrType
PtrType represents a pointer type.
type PtrType struct { // contains unexported fields }

func (*PtrType) Elem


func (t *PtrType) Elem() Type Elem returns the pointer element type.

type PtrValue
A PtrValue represents a pointer.
type PtrValue struct { // contains unexported fields }

func (*PtrValue) Elem


func (v *PtrValue) Elem() Value

Elem returns the value that v points to. If v is a nil pointer, Elem returns a nil Value.

func (*PtrValue) Get


func (v *PtrValue) Get() uintptr Get returns the uintptr value of v. It is mainly useful for printing.

func (*PtrValue) IsNil


func (v *PtrValue) IsNil() bool IsNil returns whether v is a nil pointer.

func (*PtrValue) PointTo


func (v *PtrValue) PointTo(x Value) PointTo changes v to point to x.

func (*PtrValue) Set


func (v *PtrValue) Set(x *PtrValue) Set assigns x to v. The new value x must have the same type as v.

func (*PtrValue) SetValue


func (v *PtrValue) SetValue(x Value) Set sets v to the value x.

type SliceHeader
runtime representation of slice
type SliceHeader struct { Data uintptr Len int Cap int }

type SliceType
SliceType represents a slice type.
type SliceType struct { // contains unexported fields }

func (*SliceType) Elem


func (t *SliceType) Elem() Type Elem returns the type of the slice's elements.

type SliceValue
A SliceValue represents a slice.
type SliceValue struct { // contains unexported fields }

func MakeSlice
func MakeSlice(typ *SliceType, len, cap int) *SliceValue MakeSlice creates a new zero-initialized slice value for the specified slice type, length, and capacity.

func (*SliceValue) Cap


func (v *SliceValue) Cap() int Cap returns the capacity of the slice.

func (*SliceValue) Elem


func (v *SliceValue) Elem(i int) Value Elem returns the i'th element of v.

func (*SliceValue) Get


func (v *SliceValue) Get() uintptr Get returns the uintptr address of the v.Cap()'th element. This gives the same result for all slices of the same array. It is mainly useful for printing.

func (*SliceValue) IsNil


func (v *SliceValue) IsNil() bool IsNil returns whether v is a nil slice.

func (*SliceValue) Len


func (v *SliceValue) Len() int Len returns the length of the slice.

func (*SliceValue) Set


func (v *SliceValue) Set(x *SliceValue) Set assigns x to v. The new value x must have the same type as v.

func (*SliceValue) SetLen


func (v *SliceValue) SetLen(n int) SetLen changes the length of v. The new length n must be between 0 and the capacity, inclusive.

func (*SliceValue) SetValue

func (v *SliceValue) SetValue(x Value) Set sets v to the value x.

func (*SliceValue) Slice


func (v *SliceValue) Slice(beg, end int) *SliceValue Slice returns a sub-slice of the slice v.

type StringHeader
StringHeader is the runtime representation of a string.
type StringHeader struct { Data uintptr Len int }

type StringType
StringType represents a string type.
type StringType struct { // contains unexported fields }

type StringValue
StringValue represents a string value.
type StringValue struct { // contains unexported fields }

func (*StringValue) Get


func (v *StringValue) Get() string Get returns the underlying string value.

func (*StringValue) Set


func (v *StringValue) Set(x string) Set sets v to the value x.

func (*StringValue) SetValue


func (v *StringValue) SetValue(x Value)

Set sets v to the value x.

type StructField
type StructField struct { PkgPath string // empty for uppercase Name Name string Type Type Tag string Offset uintptr Index []int Anonymous bool }

type StructType
StructType represents a struct type.
type StructType struct { // contains unexported fields }

func (*StructType) Field


func (t *StructType) Field(i int) (f StructField) Field returns the i'th struct field.

func (*StructType) FieldByIndex


func (t *StructType) FieldByIndex(index []int) (f StructField) FieldByIndex returns the nested field corresponding to index.

func (*StructType) FieldByNam e


func (t *StructType) FieldByName(name string) (f StructField, present bool) FieldByName returns the struct field with the given name and a boolean to indicate if the field was found.

func (*StructType) Num Field


func (t *StructType) NumField() int NumField returns the number of struct fields.

type StructValue
A StructValue represents a struct value.

type StructValue struct { // contains unexported fields }

func (*StructValue) Field


func (v *StructValue) Field(i int) Value Field returns the i'th field of the struct.

func (*StructValue) FieldByIndex


func (t *StructValue) FieldByIndex(index []int) (v Value) FieldByIndex returns the nested field corresponding to index.

func (*StructValue) FieldByNam e


func (t *StructValue) FieldByName(name string) Value FieldByName returns the struct field with the given name. The result is nil if no field was found.

func (*StructValue) Num Field


func (v *StructValue) NumField() int NumField returns the number of fields in the struct.

func (*StructValue) Set


func (v *StructValue) Set(x *StructValue) Set assigns x to v. The new value x must have the same type as v.

func (*StructValue) SetValue


func (v *StructValue) SetValue(x Value) Set sets v to the value x.

type Type
Type is the runtime representation of a Go type. Every type implements the methods listed here. Some types implement additional interfaces; use a type switch to find out what kind of type a Type is. Each type in a program has a unique Type, so == on Types corresponds to Go's type equality.

type Type interface { // PkgPath returns the type's package path. // The package path is a full package import path like "container/vector". // PkgPath returns an empty string for unnamed types. PkgPath() string // Name returns the type's name within its package. // Name returns an empty string for unnamed types. Name() string // String returns a string representation of the type. // The string representation may use shortened package names // (e.g., vector instead of "container/vector") and is not // guaranteed to be unique among types. To test for equality, // compare the Types directly. String() string // Size returns the number of bytes needed to store // a value of the given type; it is analogous to unsafe.Sizeof. Size() uintptr // Align returns the alignment of a value of this type // when allocated in memory. Align() int // FieldAlign returns the alignment of a value of this type // when used as a field in a struct. FieldAlign() int // For non-interface types, Method returns the i'th method with receiver T. // For interface types, Method returns the i'th method in the interface. // NumMethod returns the number of such methods. Method(int) Method NumMethod() int // contains unexported methods }

func Typeof
func Typeof(i interface{}) Type Typeof returns the reflection Type of the value in the interface{}.

type Uint16Type
Uint16Type represents a uint16 type.
type Uint16Type struct { // contains unexported fields }

type Uint16Value
Uint16Value represents a uint16 value.

type Uint16Value struct { // contains unexported fields }

func (*Uint16Value) Get


func (v *Uint16Value) Get() uint16 Get returns the underlying uint16 value.

func (*Uint16Value) Set


func (v *Uint16Value) Set(x uint16) Set sets v to the value x.

func (*Uint16Value) SetValue


func (v *Uint16Value) SetValue(x Value) Set sets v to the value x.

type Uint32Type
Uint32Type represents a uint32 type.
type Uint32Type struct { // contains unexported fields }

type Uint32Value
Uint32Value represents a uint32 value.
type Uint32Value struct { // contains unexported fields }

func (*Uint32Value) Get


func (v *Uint32Value) Get() uint32 Get returns the underlying uint32 value.

func (*Uint32Value) Set


func (v *Uint32Value) Set(x uint32) Set sets v to the value x.

func (*Uint32Value) SetValue


func (v *Uint32Value) SetValue(x Value)

Set sets v to the value x.

type Uint64Type
Uint64Type represents a uint64 type.
type Uint64Type struct { // contains unexported fields }

type Uint64Value
Uint64Value represents a uint64 value.
type Uint64Value struct { // contains unexported fields }

func (*Uint64Value) Get


func (v *Uint64Value) Get() uint64 Get returns the underlying uint64 value.

func (*Uint64Value) Set


func (v *Uint64Value) Set(x uint64) Set sets v to the value x.

func (*Uint64Value) SetValue


func (v *Uint64Value) SetValue(x Value) Set sets v to the value x.

type Uint8Type
Uint8Type represents a uint8 type.
type Uint8Type struct { // contains unexported fields }

type Uint8Value
Uint8Value represents a uint8 value.

type Uint8Value struct { // contains unexported fields }

func (*Uint8Value) Get


func (v *Uint8Value) Get() uint8 Get returns the underlying uint8 value.

func (*Uint8Value) Set


func (v *Uint8Value) Set(x uint8) Set sets v to the value x.

func (*Uint8Value) SetValue


func (v *Uint8Value) SetValue(x Value) Set sets v to the value x.

type UintType
UintType represents a uint type.
type UintType struct { // contains unexported fields }

type UintValue
UintValue represents a uint value.
type UintValue struct { // contains unexported fields }

func (*UintValue) Get


func (v *UintValue) Get() uint Get returns the underlying uint value.

func (*UintValue) Set


func (v *UintValue) Set(x uint) Set sets v to the value x.

func (*UintValue) SetValue


func (v *UintValue) SetValue(x Value)

Set sets v to the value x.

type UintptrType
UintptrType represents a uintptr type.
type UintptrType struct { // contains unexported fields }

type UintptrValue
UintptrValue represents a uintptr value.
type UintptrValue struct { // contains unexported fields }

func (*UintptrValue) Get


func (v *UintptrValue) Get() uintptr Get returns the underlying uintptr value.

func (*UintptrValue) Set


func (v *UintptrValue) Set(x uintptr) Set sets v to the value x.

func (*UintptrValue) SetValue


func (v *UintptrValue) SetValue(x Value) Set sets v to the value x.

type UnsafePointerType
UnsafePointerType represents an unsafe.Pointer type.
type UnsafePointerType struct { // contains unexported fields }

type UnsafePointerValue
UnsafePointerValue represents an unsafe.Pointer value.

type UnsafePointerValue struct { // contains unexported fields }

func (*UnsafePointerValue) Get


func (v *UnsafePointerValue) Get() uintptr Get returns the underlying uintptr value. Get returns uintptr, not unsafe.Pointer, so that programs that do not import "unsafe" cannot obtain a value of unsafe.Pointer type from "reflect".

func (*UnsafePointerValue) Set


func (v *UnsafePointerValue) Set(x unsafe.Pointer) Set sets v to the value x.

func (*UnsafePointerValue) SetValue


func (v *UnsafePointerValue) SetValue(x Value) Set sets v to the value x.

type Value
Value is the common interface to reflection values. The implementations of Value (e.g., ArrayValue, StructValue) have additional type-specific methods.
type Value interface { // Type returns the value's type. Type() Type // Interface returns the value as an interface{}. Interface() interface{} // CanSet returns whether the // Values obtained by the use // can be used in Get but not // If CanSet() returns false, // will cause a crash. CanSet() bool value can be changed. of non-exported struct fields Set. calling the type-specific Set

// SetValue assigns v to the value; v must have the same type as the value. SetValue(v Value) // Addr returns a pointer to the underlying data. // It is for advanced clients that also // import the "unsafe" package. Addr() uintptr // Method returns a FuncValue corresponding to the value's i'th method. // The arguments to a Call on the returned FuncValue // should not include a receiver; the FuncValue will use // the value as the receiver. Method(i int) *FuncValue // contains unexported methods }

func Indirect
func Indirect(v Value) Value Indirect returns the value that v points to. If v is a nil pointer, Indirect returns a nil Value. If v is not a pointer, Indirect returns v.

func MakeZero
func MakeZero(typ Type) Value MakeZero returns a zero Value for the specified Type.

func New Value


func NewValue(i interface{}) Value NewValue returns a new Value initialized to the concrete value stored in the interface i. NewValue(nil) returns nil.

Except as noted, this content is licensed under Creative Commons Attribution 3.0.

The Go Programming Language

Package regexp
Variables func Match func MatchString func QuoteMeta type Regexp func Compile func MustCompile func (*Regexp) AllMatches func (*Regexp) AllMatchesIter func (*Regexp) AllMatchesString func (*Regexp) AllMatchesStringIter func (*Regexp) Execute import "regexp" Package regexp implements a simple regular expression library. The syntax of the regular expressions accepted is:
regexp: concatenation { '|' concatenation } concatenation: { closure } closure: term [ '*' | '+' | '?' ] term: '^' '$' '.' character '[' [ '^' ] character-ranges ']' '(' regexp ')'

func (*Regexp) ExecuteString func (*Regexp) Match func (*Regexp) MatchSlices func (*Regexp) MatchString func (*Regexp) MatchStrings func (*Regexp) NumSubexp func (*Regexp) ReplaceAll func (*Regexp) ReplaceAllFunc func (*Regexp) ReplaceAllString func (*Regexp) ReplaceAllStringFunc

Package files
regexp.go

Variables
Error codes returned by failures to parse an expression.

var ( ErrInternal ErrUnmatchedLpar ErrUnmatchedRpar ErrUnmatchedLbkt ErrUnmatchedRbkt ErrBadRange ErrExtraneousBackslash ErrBadClosure ErrBareClosure ErrBadBackslash )

= = = = = = = = = =

os.NewError("internal error") os.NewError("unmatched '('") os.NewError("unmatched ')'") os.NewError("unmatched '['") os.NewError("unmatched ']'") os.NewError("bad range in character class") os.NewError("extraneous backslash") os.NewError("repeated closure (**, ++, etc.)") os.NewError("closure applies to nothing") os.NewError("illegal backslash escape")

func Match
func Match(pattern string, b []byte) (matched bool, error os.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 MatchString
func MatchString(pattern string, s string) (matched bool, error os.Error) MatchString checks whether a textual regular expression matches a string. More complicated queries need to use Compile and the full Regexp interface.

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
Regexp is the representation of a compiled regular expression. The public interface is entirely through methods.
type Regexp struct { // contains unexported fields }

func Com pile


func Compile(str string) (regexp *Regexp, error os.Error) Compile parses a regular expression and returns, if successful, a Regexp object that can be used to match against text.

func MustCom pile


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 (*Regexp) AllMatches


func (re *Regexp) AllMatches(b []byte, n int) [][]byte AllMatches slices the byte slice b into substrings that are successive matches of the Regexp within b. If n > 0, the function returns at most n matches. Text that does not match the expression will be skipped. Empty matches abutting a preceding match are ignored. The function returns a slice containing the matching substrings.

func (*Regexp) AllMatchesIter


func (re *Regexp) AllMatchesIter(b []byte, n int) <-chan []byte AllMatchesIter slices the byte slice b into substrings that are successive matches of the Regexp within b. If n > 0, the function returns at most n matches. Text that does not match the expression will be skipped. Empty matches abutting a preceding match are ignored. The function returns a channel that iterates over the matching substrings.

func (*Regexp) AllMatchesString


func (re *Regexp) AllMatchesString(s string, n int) []string AllMatchesString slices the string s into substrings that are successive matches of the Regexp within s. If n > 0, the function returns at most n matches. Text that does not match the expression will be skipped. Empty matches abutting a preceding match are ignored. The function returns a slice containing the matching substrings.

func (*Regexp) AllMatchesStringIter


func (re *Regexp) AllMatchesStringIter(s string, n int) <-chan string AllMatchesStringIter slices the string s into substrings that are successive matches of the Regexp within s. If n > 0, the function returns at most n matches. Text that does not match the expression will be skipped. Empty matches abutting a preceding match are ignored. The function returns a channel that iterates over the matching substrings.

func (*Regexp) Execute


func (re *Regexp) Execute(b []byte) (a []int) Execute matches the Regexp against the byte slice b. The return value is an array of integers, in pairs, identifying the positions of subslices matched by the expression.
b[a[0]:a[1]] is the subslice matched by the entire expression. b[a[2*i]:a[2*i+1]] for i > 0 is the subslice matched by the ith parenthesized subexpression.

A negative value means the subexpression did not match any element of the slice. An empty array means "no match".

func (*Regexp) ExecuteString

func (re *Regexp) ExecuteString(s string) (a []int) ExecuteString matches the Regexp against the string s. The return value is an array of integers, in pairs, identifying the positions of substrings matched by the expression.
s[a[0]:a[1]] is the substring matched by the entire expression. s[a[2*i]:a[2*i+1]] for i > 0 is the substring matched by the ith parenthesized subexpression.

A negative value means the subexpression did not match any element of the string. An empty array means "no match".

func (*Regexp) Match


func (re *Regexp) Match(b []byte) bool Match returns whether the Regexp matches the byte slice b. The return value is a boolean: true for match, false for no match.

func (*Regexp) MatchSlices


func (re *Regexp) MatchSlices(b []byte) (a [][]byte) MatchSlices matches the Regexp against the byte slice b. The return value is an array of subslices matched by the expression.
a[0] is the subslice matched by the entire expression. a[i] for i > 0 is the subslice matched by the ith parenthesized subexpression.

An empty array means no match.

func (*Regexp) MatchString


func (re *Regexp) MatchString(s string) bool MatchString returns whether the Regexp matches the string s. The return value is a boolean: true for match, false for no match.

func (*Regexp) MatchStrings


func (re *Regexp) MatchStrings(s string) (a []string) MatchStrings matches the Regexp against the string s. The return value is an array of strings matched by the expression.
a[0] is the substring matched by the entire expression. a[i] for i > 0 is the substring matched by the ith parenthesized subexpression.

An empty array means no match.

func (*Regexp) Num Subexp


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 in which all matches for the Regexp have been replaced by repl. No support is provided for expressions (e.g. \1 or $1) in the replacement text.

func (*Regexp) ReplaceAllFunc


func (re *Regexp) ReplaceAllFunc(src []byte, repl func([]byte) []byte) []byte ReplaceAllFunc returns a copy of src in which all matches for the Regexp have been replaced by the return value of of function repl (whose first argument is the matched []byte). No support is provided for expressions (e.g. \1 or $1) in the replacement string.

func (*Regexp) ReplaceAllString


func (re *Regexp) ReplaceAllString(src, repl string) string ReplaceAllString returns a copy of src in which all matches for the Regexp have been replaced by repl. No support is provided for expressions (e.g. \1 or $1) in the replacement string.

func (*Regexp) ReplaceAllStringFunc


func (re *Regexp) ReplaceAllStringFunc(src string, repl func(string) string) string ReplaceAllStringFunc returns a copy of src in which all matches for the Regexp have been replaced by the return value of of function repl (whose first argument is the matched string). No support is provided for expressions (e.g. \1 or $1) in the replacement string.

Except as noted, this content is licensed under Creative Commons Attribution 3.0.

The Go Programming Language

Package rpc
func Accept func HandleHTTP func Register func ServeConn type Call type Client func Dial func DialHTTP import "rpc" The rpc package provides access to the public 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, public 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 name is publicly visible, that is, begins with an upper case letter. - the method has two arguments, both pointers to publicly visible structs. - the method has return type os.Error.

func NewClient func (*Client) Call func (*Client) Go type InvalidRequest type Request type Response

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 an os.ErrorString. 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 structure containing the arguments, and a structure to receive the result parameters. Call waits for the remote call to complete; Go launches the call asynchronously and returns a channel that will signal completion. Package "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 Reply struct { C int } type Arith int func (t *Arith) Multiply(args *Args, reply *Reply) os.Error { reply.C = args.A * args.B; return nil } func (t *Arith) Divide(args *Args, reply *Reply) os.Error { if args.B == 0 { return os.ErrorString("divide by zero"); } reply.C = 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.Exit("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.Exit("dialing:", err); }

Then it can make a remote call:


// Synchronous call args := &server.Args{7,8}; reply := new(server.Reply); err = client.Call("Arith.Multiply", args, reply); if err != nil { log.Exit("arith error:", err); } fmt.Printf("Arith: %d*%d=%d", args.A, args.B, reply.C);

or

// Asynchronous call divCall := client.Go("Arith.Divide", args, reply, 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. Package files
client.go debug.go serv er.go

func Accept
func Accept(lis net.Listener) Accept accepts connections on the listener and serves requests 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. It is still necessary to invoke http.Serve(), typically in a go statement.

func Register
func Register(rcvr interface{}) os.Error Register publishes in the server the set of methods of the receiver value that satisfy the following conditions:
- public method - two arguments, both pointers to public structs - one return value of type os.Error

It returns an error if the receiver is not public or has no suitable methods.

func ServeConn
func ServeConn(conn io.ReadWriteCloser) ServeConn runs the server on a single connection. When the connection completes, service terminates. ServeConn blocks; the caller typically invokes it in a go statement.

type Call
Call represents an active RPC.

type Call struct { // The name of the service and method to call. ServiceMethod string Args interface{} // The argument to the function (*struct). Reply interface{} // The reply from the function (*struct). Error os.Error // After completion, the error status. Done chan *Call // Strobes when call is complete; value is the error status. // contains unexported fields }

type Client
Client represents an RPC Client. There may be multiple outstanding Calls associated with a single Client.
type Client struct { // contains unexported fields }

func Dial
func Dial(network, address string) (*Client, os.Error) Dial connects to an RPC server at the specified network address.

func DialHTTP
func DialHTTP(network, address string) (*Client, os.Error) DialHTTP connects to an HTTP RPC server at the specified network address.

func New Client


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.

func (*Client) Call


func (client *Client) Call(serviceMethod string, args interface{}, reply interface{}) os.Error Call invokes the named function, waits for it to complete, and returns its error status.

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 InvalidRequest
A value sent as a placeholder for the response when the server receives an invalid request.

type InvalidRequest struct { // contains unexported fields }

type Request
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 Request struct { ServiceMethod string // format: "Service.Method" Seq uint64 // sequence number chosen by client }

type Response
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 Response struct { ServiceMethod string // echoes that of the Request Seq uint64 // echoes that of the request Error string // error, if any. }

Except as noted, this content is licensed under Creative Commons Attribution 3.0.

The Go Programming Language

Package runtime
func Alloc func Breakpoint func Caller func Cgocalls func Free func GC func GOMAXPROCS func Goexit func Gosched func LockOSThread func Lookup func Semacquire func Semrelease func SetFinalizer func Siginit func Signame func Sigrecv func UnlockOSThread type ArrayType type BoolType type ChanDir type ChanType type Complex128Type type Complex64Type type ComplexType type Float32Type type Float64Type import "runtime" The runtime package contains operations that interact with Go's runtime system, such as functions to control goroutines. It also includes the low-level type information used by the reflect package; see reflect's documentation for the programmable interface to the run-time type system. Package files
extern.go ty pe.go

type FloatType type FuncType type Int16Type type Int32Type type Int64Type type Int8Type type IntType type InterfaceType type Itable type MapType type MemStatsType type PtrType type SliceType type StringType type StructType type Type type Uint16Type type Uint32Type type Uint64Type type Uint8Type type UintType type UintptrType type UnsafePointerType Subdirectories

func Alloc
func Alloc(uintptr) *byte Alloc allocates a block of the given size. FOR TESTING AND DEBUGGING ONLY.

func Breakpoint

func Breakpoint() Breakpoint() executes a breakpoint trap.

func Caller
func Caller(n int) (pc uintptr, file string, line int, ok bool) Caller reports file and line number information about function invocations on the calling goroutine's stack. The argument is the number of stack frames to ascend, with 0 identifying the the caller of Caller. The return values report the program counter, file name, and line number within the file of the corresponding call. The boolean ok is false if it was not possible to recover the information.

func Cgocalls
func Cgocalls() int64 Cgocalls returns the number of cgo calls made by the current process.

func Free
func Free(*byte) Free frees the block starting at the given pointer. FOR TESTING AND DEBUGGING ONLY.

func GC
func GC() GC runs a garbage collection.

func GOMAXPROCS
func GOMAXPROCS(n int) GOMAXPROCS sets the maximum number of CPUs that can be executing simultaneously. This call will go away when the scheduler improves.

func Goexit
func Goexit() Goexit terminates the goroutine that calls it. No other goroutine is affected.

func Gosched
func Gosched()

Gosched yields the processor, allowing other goroutines to run. It does not suspend the current goroutine, so execution resumes automatically.

func LockOSThread
func LockOSThread() LockOSThread wires the calling goroutine to its current operating system thread. Until the calling goroutine exits or calls UnlockOSThread, it will always execute in that thread, and no other goroutine can. LockOSThread cannot be used during init functions.

func Lookup
func Lookup(*byte) (*byte, uintptr) Lookup returns the base and size of the block containing the given pointer. FOR TESTING AND DEBUGGING ONLY.

func Semacquire
func Semacquire(s *uint32) Semacquire waits until *s > 0 and then atomically decrements it. It is intended as a simple sleep primitive for use by the synchronization library and should not be used directly.

func Semrelease
func Semrelease(s *uint32) Semrelease atomically increments *s and notifies a waiting goroutine if one is blocked in Semacquire. It is intended as a simple wakeup primitive for use by the synchronization library and should not be used directly.

func SetFinalizer
func SetFinalizer(x, f interface{}) SetFinalizer sets the finalizer associated with x to f. When the garbage collector finds an unreachable block with an associated finalizer, it clears the association and creates a new goroutine running f(x). Creating the new goroutine makes x reachable again, but now without an associated finalizer. Assuming that SetFinalizer is not called again, the next time the garbage collector sees that x is unreachable, it will free x. SetFinalizer(x, nil) clears any finalizer associated with f. The argument x must be a pointer to an object allocated by calling new or by taking the address of a composite literal. The argument f must be a function that takes a single argument of x's type and returns no arguments. If either of these is not true, SetFinalizer aborts the program. Finalizers are run in dependency order: if A points at B, both have finalizers, and they are otherwise unreachable, only the finalizer for A runs; once A is freed, the finalizer for B can run. If a cyclic structure includes a block with a finalizer, that cycle is not guaranteed to be garbage collected and the finalizer is not

guaranteed to run, because there is no ordering that respects the dependencies. The finalizer for x is scheduled to run at some arbitrary time after x becomes unreachable. There is no guarantee that finalizers will run before a program exits, so typically they are useful only for releasing non-memory resources associated with an object during a long-running program. For example, an os.File object could use a finalizer to close the associated operating system file descriptor when a program discards an os.File without calling Close, but it would be a mistake to depend on a finalizer to flush an in-memory I/O buffer such as a bufio.Writer, because the buffer would not be flushed at program exit. TODO(rsc): make os.File use SetFinalizer TODO(rsc): allow f to have (ignored) return values

func Siginit
func Siginit() Siginit enables receipt of signals via Sigrecv. It should typically be called during initialization.

func Signame
func Signame(sig int32) string Signame returns a string describing the signal, or "" if the signal is unknown.

func Sigrecv
func Sigrecv() uint32 Sigrecv returns a bitmask of signals that have arrived since the last call to Sigrecv. It blocks until at least one signal arrives.

func UnlockOSThread
func UnlockOSThread() UnlockOSThread unwires the calling goroutine from its fixed operating system thread. If the calling goroutine has not called LockOSThread, UnlockOSThread is a no-op.

type ArrayType
ArrayType represents a fixed array type.
type ArrayType struct { // contains unexported fields }

type BoolType

BoolType represents a boolean type.


type BoolType commonType

type ChanDir
ChanDir represents a channel type's direction.
type ChanDir int

const ( RecvDir ChanDir = 1 << iota // <-chan SendDir // chan<BothDir = RecvDir | SendDir // chan )

type ChanType
ChanType represents a channel type.
type ChanType struct { // contains unexported fields }

type Complex128Type
Complex128Type represents a complex128 type.
type Complex128Type commonType

type Complex64Type
Complex64Type represents a complex64 type.
type Complex64Type commonType

type ComplexType
ComplexType represents a complex type.
type ComplexType commonType

type Float32Type
Float32Type represents a float32 type.
type Float32Type commonType

type Float64Type
Float64Type represents a float64 type.
type Float64Type commonType

type FloatType
FloatType represents a float type.
type FloatType commonType

type FuncType
FuncType represents a function type.
type FuncType struct { // contains unexported fields }

type Int16Type
Int16Type represents an int16 type.
type Int16Type commonType

type Int32Type
Int32Type represents an int32 type.
type Int32Type commonType

type Int64Type

Int64Type represents an int64 type.


type Int64Type commonType

type Int8Type
Int8Type represents an int8 type.
type Int8Type commonType

type IntType
IntType represents an int type.
type IntType commonType

type InterfaceType
InterfaceType represents an interface type.
type InterfaceType struct { // contains unexported fields }

type Itable
* Must match iface.c:/Itab and compilers.
type Itable struct { Itype *Type // (*tab.inter).(*InterfaceType) is the interface type Type *Type Fn [100000]uintptr // bigger than we'll ever see // contains unexported fields }

type MapType
MapType represents a map type.
type MapType struct { // contains unexported fields }

type MemStatsType
type MemStatsType struct { Alloc uint64 TotalAlloc uint64 Sys uint64 Stacks uint64 InusePages uint64 NextGC uint64 HeapAlloc uint64 Lookups uint64 Mallocs uint64 PauseNs uint64 NumGC uint32 EnableGC bool DebugGC bool BySize [67]struct { Size uint32 Mallocs uint64 Frees uint64 } }

MemStats holds statistics about the memory system. The statistics are only approximate, as they are not interlocked on update.
var MemStats MemStatsType

type PtrType
PtrType represents a pointer type.
type PtrType struct { // contains unexported fields }

type SliceType
SliceType represents a slice type.
type SliceType struct { // contains unexported fields }

type StringType
StringType represents a string type.

type StringType commonType

type StructType
StructType represents a struct type.
type StructType struct { // contains unexported fields }

type Type
The compiler can only construct empty interface values at compile time; non-empty interface values get created during initialization. Type is an empty interface so that the compiler can lay out references as data.
type Type interface{}

type Uint16Type
Uint16Type represents a uint16 type.
type Uint16Type commonType

type Uint32Type
Uint32Type represents a uint32 type.
type Uint32Type commonType

type Uint64Type
Uint64Type represents a uint64 type.
type Uint64Type commonType

type Uint8Type
Uint8Type represents a uint8 type.

type Uint8Type commonType

type UintType
UintType represents a uint type.
type UintType commonType

type UintptrType
UintptrType represents a uintptr type.
type UintptrType commonType

type UnsafePointerType
UnsafePointerType represents an unsafe.Pointer type.
type UnsafePointerType commonType

Subdirectories
Name .. tiny Synopsis

Except as noted, this content is licensed under Creative Commons Attribution 3.0.

The Go Programming Language

Package scanner
Constants func TokenString type Position func (*Position) IsValid func (Position) String type Scanner func (*Scanner) Init func (*Scanner) Next func (*Scanner) Pos func (*Scanner) Scan func (*Scanner) TokenText import "scanner" A general-purpose scanner for UTF-8 encoded text. Takes an io.Reader providing the source which then can be tokenized through repeated calls to the Scan function. For compatibility with existing tools, the NUL character is not allowed (implementation restriction). By default, a Scanner skips white space and comments and recognizes literals as defined by the Go language spec. It may be customized to recognize only a subset of those literals and to recognize different white space characters. Basic usage pattern:
var s scanner.Scanner s.Init(src) tok := s.Scan() for tok != scanner.EOF { // do something with tok tok = s.Scan() }

Package files
scanner.go

Constants
Predefined mode bits to control recognition of tokens. For instance, to configure a Scanner such that it only recognizes (Go) identifiers, integers, and skips comments, set the Scanner's Mode field to:
ScanIdents | ScanInts | SkipComments

const ( ScanIdents ScanInts ScanFloats ScanChars ScanStrings ScanRawStrings ScanComments SkipComments GoTokens )

= = = = = = = = =

1 << -Ident 1 << -Int 1 << -Float // includes Ints 1 << -Char 1 << -String 1 << -RawString 1 << -Comment 1 << -skipComment // if set with ScanComments, comments become white space ScanIdents | ScanFloats | ScanChars | ScanStrings | ScanRawStrings | ScanComments | SkipCo

The result of Scan is one of the following tokens or a Unicode character.


const ( EOF = -(iota + 1) Ident Int Float Char String RawString Comment )

GoWhitespace is the default value for the Scanner's Whitespace field. Its value selects Go's white space characters.
const GoWhitespace = 1<<'\t' | 1<<'\n' | 1<<'\r' | 1<<' '

func TokenString
func TokenString(tok int) string TokenString returns a (visible) string for a token or Unicode character.

type Position
A source position is represented by a Position value. A position is valid if Line > 0.
type Position struct { Filename string // Offset int // Line int // Column int // }

filename, if any byte offset, starting at 0 line number, starting at 1 column number, starting at 0 (character count per line)

func (*Position) IsValid


func (pos *Position) IsValid() bool IsValid returns true if the position is valid.

func (Position) String


func (pos Position) String() string

type Scanner
A Scanner implements reading of Unicode characters and tokens from an io.Reader.
type Scanner struct {

// Error is called for each error encountered. If no Error // function is set, the error is reported to os.Stderr. Error func(s *Scanner, msg string) // ErrorCount is incremented by one for each error encountered. ErrorCount int // The Mode field controls which tokens are recognized. For instance, // to recognize Ints, set the (1<<-Int) bit in Mode. The field may be // changed at any time. Mode uint // The Whitespace field controls which characters // as white space. To recognize a character ch <= // set the ch'th bit in Whitespace (the Scanner's // for values ch > ' '). The field may be changed Whitespace uint64 are recognized ' ' as white space, behavior is undefined at any time.

// Current token position. The Offset, Line, and Column fields // are set by Scan(); the Filename field is left untouched by the // Scanner. Position // contains unexported fields }

func (*Scanner) Init


func (s *Scanner) Init(src io.Reader) *Scanner Init initializes a Scanner with a new source and returns itself. Error is set to nil, ErrorCount is set to 0, Mode is set to GoTokens, and Whitespace is set to GoWhitespace.

func (*Scanner) Next


func (s *Scanner) Next() int Next reads and returns the next Unicode character. It returns EOF at the end of the source. It reports a read error by calling s.Error, if set, or else prints an error message to os.Stderr. Next does not update the Scanner's Position field; use Pos() to get the current position.

func (*Scanner) Pos


func (s *Scanner) Pos() Position Position returns the current source position. If called before Next() or Scan(), it returns the position of the next Unicode character or token returned by these functions. If called afterwards, it returns the position immediately after the last character of the most recent token or character scanned.

func (*Scanner) Scan


func (s *Scanner) Scan() int Scan reads the next token or Unicode character from source and returns it. It only recognizes tokens t for which the respective Mode bit (1<<-t) is set. It returns EOF at the end of the source. It reports scanner errors (read and token errors) by calling s.Error, if set; otherwise it prints an error message to os.Stderr.

func (*Scanner) TokenText


func (s *Scanner) TokenText() string TokenText returns the string corresponding to the most recently scanned token. Valid after calling Scan().

Except as noted, this content is licensed under Creative Commons Attribution 3.0.

The Go Programming Language

Package sort
func FloatsAreSorted func IntsAreSorted func IsSorted func Sort func SortFloats func SortInts func SortStrings func StringsAreSorted type FloatArray func (FloatArray) Len func (FloatArray) Less func (FloatArray) Sort func (FloatArray) Swap import "sort" The sort package provides primitives for sorting arrays and user-defined collections. Package files
sort.go

type IntArray func (IntArray) Len func (IntArray) Less func (IntArray) Sort func (IntArray) Swap type Interface type StringArray func (StringArray) Len func (StringArray) Less func (StringArray) Sort func (StringArray) Swap

func FloatsAreSorted
func FloatsAreSorted(a []float) bool FloatsAreSorted tests whether an array of floats is sorted in increasing order.

func IntsAreSorted
func IntsAreSorted(a []int) bool IntsAreSorted tests whether an array of ints is sorted in increasing order.

func IsSorted
func IsSorted(data Interface) bool

func Sort
func Sort(data Interface)

func SortFloats
func SortFloats(a []float) SortFloats sorts an array of floats in increasing order.

func SortInts
func SortInts(a []int) SortInts sorts an array of ints in increasing order.

func SortStrings
func SortStrings(a []string) SortStrings sorts an array of strings in increasing order.

func StringsAreSorted
func StringsAreSorted(a []string) bool StringsAreSorted tests whether an array of strings is sorted in increasing order.

type FloatArray
FloatArray attaches the methods of Interface to []float, sorting in increasing order.
type FloatArray []float

func (FloatArray) Len


func (p FloatArray) Len() int

func (FloatArray) Less


func (p FloatArray) Less(i, j int) bool

func (FloatArray) Sort


func (p FloatArray) Sort() Sort is a convenience method.

func (FloatArray) Sw ap
func (p FloatArray) Swap(i, j int)

type IntArray

IntArray attaches the methods of Interface to []int, sorting in increasing order.


type IntArray []int

func (IntArray) Len


func (p IntArray) Len() int

func (IntArray) Less


func (p IntArray) Less(i, j int) bool

func (IntArray) Sort


func (p IntArray) Sort() Sort is a convenience method.

func (IntArray) Sw ap
func (p IntArray) Swap(i, j int)

type Interface
A type, typically a collection, that satisfies sort.Interface can be sorted by the routines in this package. The methods require that the elements of the collection be enumerated by an integer index.
type Interface interface { // Len is the number of elements in the collection. Len() int // Less returns whether the element with index i should sort // before the element with index j. Less(i, j int) bool // Swap swaps the elements with indexes i and j. Swap(i, j int) }

type StringArray
StringArray attaches the methods of Interface to []string, sorting in increasing order.
type StringArray []string

func (StringArray) Len


func (p StringArray) Len() int

func (StringArray) Less


func (p StringArray) Less(i, j int) bool

func (StringArray) Sort

func (p StringArray) Sort() Sort is a convenience method.

func (StringArray) Sw ap
func (p StringArray) Swap(i, j int)

Except as noted, this content is licensed under Creative Commons Attribution 3.0.

The Go Programming Language

Package strconv
Variables func Atof func Atof32 func Atof64 func Atoi func Atoi64 func Atoui func Atoui64 func Btoi64 func Btoui64 func CanBackquote func Ftoa func Ftoa32 func Ftoa64 func Itoa import "strconv" The strconv package implements conversions to and from string representations of basic data types. Package files
atof .go atoi.go decimal.go f toa.go itoa.go quote.go

func Itoa64 func Itob func Itob64 func Quote func Uitoa func Uitoa64 func Uitob func Uitob64 func Unquote func UnquoteChar type NumError func (*NumError) String

Variables
Floatsize gives the size of the float type, either 32 or 64.
var FloatSize = floatsize()

var IntSize = computeIntsize()

func Atof
func Atof(s string) (f float, err os.Error) Atof is like Atof32 or Atof64, depending on the size of float.

func Atof32
func Atof32(s string) (f float32, err os.Error)

Atof32 converts the string s to a 32-bit floating-point number. If s is well-formed and near a valid floating point number, Atof32 returns the nearest floating point number rounded using IEEE754 unbiased rounding. The errors that Atof32 returns have concrete type *NumError and include err.Num = s. If s is not syntactically well-formed, Atof32 returns err.Error = os.EINVAL. If s is syntactically well-formed but is more than 1/2 ULP away from the largest floating point number of the given size, Atof32 returns f = Inf, err.Error = os.ERANGE.

func Atof64
func Atof64(s string) (f float64, err os.Error) Atof64 converts the string s to a 64-bit floating-point number. Except for the type of its result, its definition is the same as that of Atof32.

func Atoi
func Atoi(s string) (i int, err os.Error) Atoi is like Atoi64 but returns its result as an int.

func Atoi64
func Atoi64(s string) (i int64, err os.Error) Atoi64 is like Atoui64 but allows signed numbers and returns its result in an int64.

func Atoui
func Atoui(s string) (i uint, err os.Error) Atoui is like Atoui64 but returns its result as a uint.

func Atoui64
func Atoui64(s string) (n uint64, err os.Error) Atoui64 interprets a string s as a decimal number and returns the corresponding value n. Atoui64 returns err == os.EINVAL if s is empty or contains invalid digits. It returns err == os.ERANGE if s cannot be represented by a uint64.

func Btoi64
func Btoi64(s string, base int) (i int64, err os.Error)

Btoi64 is like Btoui64 but allows signed numbers and returns its result in an int64.

func Btoui64
func Btoui64(s string, b int) (n uint64, err os.Error) Btoui64 interprets a string s in an arbitrary base b (2 to 36) and returns the corresponding value n. If b == 0, the base is taken from the string prefix: base 16 for "0x", base 8 for "0", and base 10 otherwise. The errors that Btoui64 returns have concrete type *NumError and include err.Num = s. If s is empty or contains invalid digits, err.Error = os.EINVAL; if the value corresponding to s cannot be represented by a uint64, err.Error = os.ERANGE.

func CanBackquote
func CanBackquote(s string) bool CanBackquote returns whether the string s would be a valid Go string literal if enclosed in backquotes.

func Ftoa
func Ftoa(f float, fmt byte, prec int) string Ftoa behaves as Ftoa32 or Ftoa64, depending on the size of the float type.

func Ftoa32
func Ftoa32(f float32, fmt byte, prec int) string Ftoa32 converts the 32-bit floating-point number f to a string, according to the format fmt and precision prec. The format fmt is one of 'b' (-ddddpddd, a binary exponent), 'e' (-d.ddddedd, a decimal exponent), 'f' (-ddd.dddd, no exponent), or 'g' ('e' for large exponents, 'f' otherwise). The precision prec controls the number of digits (excluding the exponent) printed by the 'e', 'f', and 'g' formats. For 'e' and 'f' it is the number of digits after the decimal point. For 'g' it is the total number of digits. The special precision -1 uses the smallest number of digits necessary such that Atof32 will return f exactly. Ftoa32(f) is not the same as Ftoa64(float32(f)), because correct rounding and the number of digits needed to identify f depend on the precision of the representation.

func Ftoa64
func Ftoa64(f float64, fmt byte, prec int) string Ftoa64 is like Ftoa32 but converts a 64-bit floating-point number.

func Itoa

func Itoa(i int) string Itoa returns the decimal string representation of i.

func Itoa64
func Itoa64(i int64) string Itoa64 returns the decimal string representation of i.

func Itob
func Itob(i int, base uint) string Itob returns the string representation of i in the given base.

func Itob64
func Itob64(i int64, base uint) string Itob64 returns the string representation of i in the given base.

func Quote
func Quote(s string) string Quote returns a double-quoted Go string literal representing s. The returned string s uses Go escape sequences (\t, \n, \xFF, \u0100) for control characters and non-ASCII characters.

func Uitoa
func Uitoa(i uint) string Uitoa returns the decimal string representation of i.

func Uitoa64
func Uitoa64(i uint64) string Uitoa64 returns the decimal string representation of i.

func Uitob
func Uitob(i uint, base uint) string Uitob returns the string representation of i in the given base.

func Uitob64
func Uitob64(u uint64, base uint) string Uitob64 returns the string representation of i in the given base.

func Unquote
func Unquote(s string) (t string, err os.Error) Unquote interprets s as a single-quoted, double-quoted, or backquoted Go string literal, returning the string value that s quotes. (If s is single-quoted, it would be a Go character literal; Unquote returns the corresponding one-character string.)

func UnquoteChar
func UnquoteChar(s string, quote byte) (value int, multibyte bool, tail string, err os.Error) UnquoteChar decodes the first character or byte in the escaped string or character literal represented by the string s. It returns four values: 1) value, the decoded Unicode code point or byte value; 2) multibyte, a boolean indicating whether the decoded character
requires a multibyte UTF-8 representation;

3) tail, the remainder of the string after the character; and 4) an error that will be nil if the character is syntactically valid. The second argument, quote, specifies the type of literal being parsed and therefore which escaped quote character is permitted. If set to a single quote, it permits the sequence \' and disallows unescaped '. If set to a double quote, it permits \" and disallows unescaped ". If set to zero, it does not permit either escape and allows both quote characters to appear unescaped.

type NumError
type NumError struct { Num string Error os.Error }

func (*Num Error) String


func (e *NumError) String() string

Except as noted, this content is licensed under Creative Commons Attribution 3.0.

The Go Programming Language

Package strings
func Count func Fields func HasPrefix func HasSuffix func Index func Join func LastIndex func Map func Repeat func Split func SplitAfter func ToLower func ToTitle func ToUpper func TrimSpace type Reader func NewReader func (*Reader) Read func (*Reader) ReadByte

import "strings" A package of simple functions to manipulate strings. Package files


reader.go strings.go

func Count
func Count(s, sep string) int Count counts the number of non-overlapping instances of sep in s.

func Fields
func Fields(s string) []string Fields splits the string s around each instance of one or more consecutive white space characters, returning an array of substrings of s or an empty list if s contains only white space.

func HasPrefix
func HasPrefix(s, prefix string) bool HasPrefix tests whether the string s begins with prefix.

func HasSuffix
func HasSuffix(s, suffix string) bool

HasSuffix tests whether the string s ends with suffix.

func Index
func Index(s, sep string) int Index returns the index of the first instance of sep in s, or -1 if sep is not present in s.

func Join
func Join(a []string, sep string) string Join concatenates the elements of a to create a single string. The separator string sep is placed between elements in the resulting string.

func LastIndex
func LastIndex(s, sep string) int LastIndex returns the index of the last instance of sep in s, or -1 if sep is not present in s.

func Map
func Map(mapping func(rune int) int, s string) string Map returns a copy of the string 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.

func Repeat
func Repeat(s string, count int) string Repeat returns a new string consisting of count copies of the string s.

func Split
func Split(s, sep string, n int) []string Split splits the string s around each instance of sep, returning an array of substrings of s. If sep is empty, Split splits s after each UTF-8 sequence. If n > 0, Split splits s into at most n substrings; the last substring will be the unsplit remainder.

func SplitAfter
func SplitAfter(s, sep string, n int) []string SplitAfter splits the string s after each instance of sep, returning an array of substrings of s. If sep is empty,

SplitAfter splits s after each UTF-8 sequence. If n > 0, SplitAfter splits s into at most n substrings; the last substring will be the unsplit remainder.

func ToLower
func ToLower(s string) string ToLower returns a copy of the string s with all Unicode letters mapped to their lower case.

func ToTitle
func ToTitle(s string) string ToTitle returns a copy of the string s with all Unicode letters mapped to their title case.

func ToUpper
func ToUpper(s string) string ToUpper returns a copy of the string s with all Unicode letters mapped to their upper case.

func TrimSpace
func TrimSpace(s string) string Trim returns a slice of the string s, with all leading and trailing white space removed, as defined by Unicode.

type Reader
A Reader satisfies calls to Read and ReadByte by reading from a string.
type Reader string

func New Reader


func NewReader(s string) *Reader NewReader returns a new Reader reading from s. It is similar to bytes.NewBufferString but more efficient and read-only.

func (*Reader) Read


func (r *Reader) Read(b []byte) (n int, err os.Error)

func (*Reader) ReadByte


func (r *Reader) ReadByte() (b byte, err os.Error)

Except as noted, this content is licensed under Creative Commons Attribution 3.0.

The Go Programming Language

Package sync
type Mutex func (*Mutex) Lock func (*Mutex) Unlock type RWMutex func (*RWMutex) Lock func (*RWMutex) RLock func (*RWMutex) RUnlock func (*RWMutex) Unlock import "sync" The sync package provides basic synchronization primitives such as mutual exclusion locks. These are intended for use by low-level library routines. Higher-level synchronization is better done via channels and communication. Package files
mutex.go rwmutex.go

type Mutex
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.
type Mutex struct { // contains unexported fields }

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 RWMutex

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. Writers take priority over Readers: no new RLocks are granted while a blocked Lock call is waiting.
type RWMutex struct { // contains unexported fields }

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. If the lock is already locked for writing or there is a writer already waiting to r the lock, RLock blocks until the writer has released the lock.

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. Like for Mutexes, a locked RWMutex is not associated with a particular goroutine. It is allowed for one goroutine to RLock (Lock) an RWMutex and then arrange for another goroutine to RUnlock (Unlock) it.

Except as noted, this content is licensed under Creative Commons Attribution 3.0.

The Go Programming Language

Package syscall
Constants Variables func Accept func Access func Acct func Adjtime func Adjtimex func AudioInit func AudioShutdown func AudioStream func Bind func Chdir func Chflags func Chmod func Chown func Chroot func Clock func Close func CloseOnExec func CondBroadcast func CondCreate func CondSignal func CondTimedWaitAbs func CondWait func Connect func Creat func Dup func Dup2 func EpollCreate func EpollCtl func EpollWait func Errstr func Exchangedata func Exec func Exit func Faccessat func Fallocate func Fchdir func Fchflags func Fchmod func Fchmodat func Fchown func Fchownat func Fdatasync func Flock func ForkExec func Select func SemCreate func SemPost func SemWait func Sendto func SetKevent func SetNonblock func Setdomainname func Setegid func Seteuid func Setfsgid func Setfsuid func Setgid func Setgroups func Sethostname func Setlogin func Setpgid func Setpriority func Setprivexec func Setregid func Setresgid func Setresuid func Setreuid func Setrlimit func Setsid func SetsockoptInt func SetsockoptLinger func SetsockoptTimeval func Settimeofday func Setuid func Shutdown func Sleep func Socket func Splice func Stat func Statfs func StringArrayPtr func StringBytePtr func StringByteSlice func Symlink func Sync func SyncFileRange func Syscall func Syscall6 func Sysctl func SysctlUint32

func Fpathconf func Fstat func Fstatfs func Fsync func Ftruncate func Futimesat func GetLastError func GetProcAddress func GetVersion func Getcwd func Getdents func Getdirentries func Getdtablesize func Getegid func Geteuid func Getfsstat func Getgid func Getgroups func Getpagesize func Getpgid func Getpgrp func Getpid func Getppid func Getpriority func Getrlimit func Getrusage func Getsid func Gettid func Gettimeofday func Getuid func Getwd func Ioperm func Iopl func Issetugid func Kevent func Kill func Klogctl func Kqueue func Lchown func Link func Listen func Lstat func Mkdir func Mkdirat func Mkfifo func Mknod func Mknodat func MultimediaInit func MultimediaShutdown func MutexCreate func MutexLock func MutexTryLock func MutexUnlock func Nanosleep func Open

func Sysinfo func Tee func Tgkill func Times func TimespecToNsec func TimevalToNsec func Truncate func Umask func Uname func Undelete func Unlink func Unlinkat func Unmount func Unshare func Ustat func Utime func Utimes func VideoInit func VideoPollEvent func VideoShutdown func VideoUpdate func Wait4 func Write type Bool func FreeLibrary type Cmsghdr type Dirent type EpollEvent type Fbootstraptransfer_t type FdSet type Flock_t type Fstore_t type Iovec type Kevent_t type Linger type Log2phys_t type Module func LoadLibrary func LoadLibraryA type Msghdr type PtraceRegs func (*PtraceRegs) PC func (*PtraceRegs) SetPC type Radvisory_t type RawSockaddr type RawSockaddrAny type RawSockaddrInet4 type RawSockaddrInet6 type RawSockaddrUnix type Rlimit type Rusage type Sockaddr func Getpeername func Getsockname type SockaddrInet4

func Openat func Pathconf func Pause func Pipe func PivotRoot func Pread func PtraceAttach func PtraceCont func PtraceDetach func PtraceForkExec func PtraceGetEventMsg func PtraceGetRegs func PtracePeekData func PtracePeekText func PtracePokeData func PtracePokeText func PtraceSetOptions func PtraceSetRegs func PtraceSingleStep func Pwrite func RawSyscall func Read func Readlink func Recvfrom func Rename func Renameat func Revoke func Rmdir func Seek import "syscall"

type type type type type type type type type type type type type type

SockaddrInet6 SockaddrUnix Stat_t Statfs_t Sysinfo_t Time_t func Time Timespec func NsecToTimespec Timeval func NsecToTimeval Timex Tms Ustat_t Utimbuf Utsname WaitStatus func (WaitStatus) Continued func (WaitStatus) CoreDump func (WaitStatus) ExitStatus func (WaitStatus) Exited func (WaitStatus) Signal func (WaitStatus) Signaled func (WaitStatus) StopSignal func (WaitStatus) Stopped func (WaitStatus) TrapCause

This package contains an interface to the low-level operating system primitives. The details vary depending on the underlying system. Its primary use 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. Package files
errstr.go exec.go sy scall.go sy scall_darwin.go sy scall_darwin_386.go sy scall_darwin_amd64.go sy scall_f reebsd.go sy scall_f reebsd_386.go sy scall_f reebsd_amd64.go sy scall_linux.go sy scall_linux_386.go sy scall_linux_amd64.go sy scall_linux_arm.go sy scall_mingw.go sy scall_mingw_386.go sy scall_nacl.go sy scall_nacl_386.go zerrors_darwin_386.go zerrors_darwin_amd64.go zerrors_f reebsd_386.go zerrors_f reebsd_amd64.go zerrors_linux_386.go zerrors_linux_amd64.go zerrors_linux_arm.go zerrors_mingw_386.go zerrors_nacl_386.go zsy scall_darwin_386.go zsy scall_darwin_amd64.go zsy scall_f reebsd_386.go zsy scall_f reebsd_amd64.go zsy scall_linux_386.go zsy scall_linux_amd64.go zsy scall_linux_arm.go zsy scall_mingw_386.go zsy scall_nacl_386.go zsy snum_darwin_386.go zsy snum_darwin_amd64.go zsy snum_f reebsd_386.go zsy snum_f reebsd_amd64.go zsy snum_linux_386.go zsy snum_linux_amd64.go zsy snum_linux_arm.go zsy snum_mingw_386.go zsy snum_nacl_386.go zty pes_darwin_386.go zty pes_darwin_amd64.go zty pes_f reebsd_386.go zty pes_f reebsd_amd64.go zty pes_linux_386.go zty pes_linux_amd64.go zty pes_linux_arm.go zty pes_mingw_386.go zty pes_nacl.go zty pes_nacl_386.go

Constants
Constants

const ( AF_APPLETALK AF_ASH AF_ATMPVC AF_ATMSVC AF_AX25 AF_BLUETOOTH AF_BRIDGE AF_CAN AF_DECnet AF_ECONET AF_FILE AF_IEEE802154 AF_INET AF_INET6 AF_IPX AF_IRDA AF_ISDN AF_IUCV AF_KEY AF_LLC AF_LOCAL AF_MAX AF_NETBEUI AF_NETLINK AF_NETROM AF_PACKET AF_PHONET AF_PPPOX AF_RDS AF_ROSE AF_ROUTE AF_RXRPC AF_SECURITY AF_SNA AF_TIPC AF_UNIX AF_UNSPEC AF_WANPIPE AF_X25 E2BIG EACCES EADDRINUSE EADDRNOTAVAIL EADV EAFNOSUPPORT EAGAIN EALREADY EBADE EBADF EBADFD EBADMSG EBADR EBADRQC EBADSLT EBFONT EBUSY ECANCELED ECHILD ECHRNG ECOMM ECONNABORTED ECONNREFUSED ECONNRESET EDEADLK EDEADLOCK

= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =

0x5 0x12 0x8 0x14 0x3 0x1f 0x7 0x1d 0xc 0x13 0x1 0x24 0x2 0xa 0x4 0x17 0x22 0x20 0xf 0x1a 0x1 0x25 0xd 0x10 0x6 0x11 0x23 0x18 0x15 0xb 0x10 0x21 0xe 0x16 0x1e 0x1 0 0x19 0x9 0x7 0xd 0x62 0x63 0x44 0x61 0xb 0x72 0x34 0x9 0x4d 0x4a 0x35 0x38 0x39 0x3b 0x10 0x7d 0xa 0x2c 0x46 0x67 0x6f 0x68 0x23 0x23

const ( SYS_SYSCALL_BASE = 0 SYS_RESTART_SYSCALL SYS_EXIT SYS_FORK SYS_READ SYS_WRITE SYS_OPEN SYS_CLOSE SYS_CREAT SYS_LINK SYS_UNLINK SYS_EXECVE SYS_CHDIR SYS_TIME SYS_MKNOD SYS_CHMOD SYS_LCHOWN SYS_LSEEK SYS_GETPID SYS_MOUNT SYS_UMOUNT SYS_SETUID SYS_GETUID SYS_STIME SYS_PTRACE SYS_ALARM SYS_PAUSE SYS_UTIME SYS_ACCESS SYS_NICE SYS_SYNC SYS_KILL SYS_RENAME SYS_MKDIR SYS_RMDIR SYS_DUP SYS_PIPE SYS_TIMES SYS_BRK SYS_SETGID SYS_GETGID SYS_GETEUID SYS_GETEGID SYS_ACCT SYS_UMOUNT2 SYS_IOCTL SYS_FCNTL SYS_SETPGID SYS_UMASK SYS_CHROOT SYS_USTAT SYS_DUP2 SYS_GETPPID SYS_GETPGRP SYS_SETSID SYS_SIGACTION SYS_SETREUID SYS_SETREGID SYS_SIGSUSPEND SYS_SIGPENDING SYS_SETHOSTNAME SYS_SETRLIMIT SYS_GETRLIMIT SYS_GETRUSAGE = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = (SYS_SYSCALL_BASE (SYS_SYSCALL_BASE (SYS_SYSCALL_BASE (SYS_SYSCALL_BASE (SYS_SYSCALL_BASE (SYS_SYSCALL_BASE (SYS_SYSCALL_BASE (SYS_SYSCALL_BASE (SYS_SYSCALL_BASE (SYS_SYSCALL_BASE (SYS_SYSCALL_BASE (SYS_SYSCALL_BASE (SYS_SYSCALL_BASE (SYS_SYSCALL_BASE (SYS_SYSCALL_BASE (SYS_SYSCALL_BASE (SYS_SYSCALL_BASE (SYS_SYSCALL_BASE (SYS_SYSCALL_BASE (SYS_SYSCALL_BASE (SYS_SYSCALL_BASE (SYS_SYSCALL_BASE (SYS_SYSCALL_BASE (SYS_SYSCALL_BASE (SYS_SYSCALL_BASE (SYS_SYSCALL_BASE (SYS_SYSCALL_BASE (SYS_SYSCALL_BASE (SYS_SYSCALL_BASE (SYS_SYSCALL_BASE (SYS_SYSCALL_BASE (SYS_SYSCALL_BASE (SYS_SYSCALL_BASE (SYS_SYSCALL_BASE (SYS_SYSCALL_BASE (SYS_SYSCALL_BASE (SYS_SYSCALL_BASE (SYS_SYSCALL_BASE (SYS_SYSCALL_BASE (SYS_SYSCALL_BASE (SYS_SYSCALL_BASE (SYS_SYSCALL_BASE (SYS_SYSCALL_BASE (SYS_SYSCALL_BASE (SYS_SYSCALL_BASE (SYS_SYSCALL_BASE (SYS_SYSCALL_BASE (SYS_SYSCALL_BASE (SYS_SYSCALL_BASE (SYS_SYSCALL_BASE (SYS_SYSCALL_BASE (SYS_SYSCALL_BASE (SYS_SYSCALL_BASE (SYS_SYSCALL_BASE (SYS_SYSCALL_BASE (SYS_SYSCALL_BASE (SYS_SYSCALL_BASE (SYS_SYSCALL_BASE (SYS_SYSCALL_BASE (SYS_SYSCALL_BASE (SYS_SYSCALL_BASE (SYS_SYSCALL_BASE (SYS_SYSCALL_BASE + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 0) 1) 2) 3) 4) 5) 6) 8) 9) 10) 11) 12) 13) 14) 15) 16) 19) 20) 21) 22) 23) 24) 25) 26) 27) 29) 30) 33) 34) 36) 37) 38) 39) 40) 41) 42) 43) 45) 46) 47) 49) 50) 51) 52) 54) 55) 57) 60) 61) 62) 63) 64) 65) 66) 67) 70) 71) 72) 73) 74) 75) 76) 77)

Constants
const ( PathMax SizeofSockaddrInet4 SizeofSockaddrInet6 SizeofSockaddrAny SizeofSockaddrUnix SizeofLinger SizeofMsghdr SizeofCmsghdr )

= = = = = = = =

0x1000 0x10 0x1c 0x70 0x6e 0x8 0x38 0x10

const ( AF_INET = 1 + iota AF_INET6 AF_UNIX IPPROTO_TCP SOCK_DGRAM SOCK_STREAM SOL_SOCKET SOMAXCONN SO_DONTROUTE SO_KEEPALIVE SO_LINGER SO_RCVBUF SO_REUSEADDR SO_SNDBUF TCP_NODELAY WNOHANG WSTOPPED PTRACE_TRACEME SO_BROADCAST = 0 SHUT_RDWR = 0 )

const ( // SYS_NOSYS = 0; // { int nosys(void); } { indirect syscall } SYS_EXIT = 1 // { void exit(int rval); } SYS_FORK = 2 // { int fork(void); } SYS_READ = 3 // { user_ssize_t read(int fd, user_addr_t cbuf, user_size_t nbyte); } SYS_WRITE = 4 // { user_ssize_t write(int fd, user_addr_t cbuf, user_size_t nbyte); } SYS_OPEN = 5 // { int open(user_addr_t path, int flags, int mode); } SYS_CLOSE = 6 // { int close(int fd); } SYS_WAIT4 = 7 // { int wait4(int pid, user_addr_t status, int options, user_addr_t rusage); } // SYS_NOSYS = 8; // { int nosys(void); } { old creat } SYS_LINK = 9 // { int link(user_addr_t path, user_addr_t link); } SYS_UNLINK = 10 // { int unlink(user_addr_t path); } // SYS_NOSYS = 11; // { int nosys(void); } { old execv } SYS_CHDIR = 12 // { int chdir(user_addr_t path); } SYS_FCHDIR = 13 // { int fchdir(int fd); } SYS_MKNOD = 14 // { int mknod(user_addr_t path, int mode, int dev); } SYS_CHMOD = 15 // { int chmod(user_addr_t path, int mode); } SYS_CHOWN = 16 // { int chown(user_addr_t path, int uid, int gid); } SYS_OGETFSSTAT = 18 // { int ogetfsstat(user_addr_t buf, int bufsize, int flags); } SYS_GETFSSTAT = 18 // { int getfsstat(user_addr_t buf, int bufsize, int flags); } // SYS_NOSYS = 19; // { int nosys(void); } { old lseek } SYS_GETPID = 20 // { int getpid(void); } // SYS_NOSYS = 21; // { int nosys(void); } { old mount } // SYS_NOSYS = 22; // { int nosys(void); } { old umount } SYS_SETUID = 23 // { int setuid(uid_t uid); } SYS_GETUID = 24 // { int getuid(void); } SYS_GETEUID = 25 // { int geteuid(void); } SYS_PTRACE = 26 // { int ptrace(int req, pid_t pid, caddr_t addr, int data); } SYS_RECVMSG = 27 // { int recvmsg(int s, struct msghdr *msg, int flags); } SYS_SENDMSG = 28 // { int sendmsg(int s, caddr_t msg, int flags); } SYS_RECVFROM = 29 // { int recvfrom(int s, void *buf, size_t len, int flags, struct sockaddr *from, int SYS_ACCEPT = 30 // { int accept(int s, caddr_t name, socklen_t *anamelen); } SYS_GETPEERNAME = 31 // { int getpeername(int fdes, caddr_t asa, socklen_t *alen); } SYS_GETSOCKNAME = 32 // { int getsockname(int fdes, caddr_t asa, socklen_t *alen); } // SYS_NOSYS = 27; // { int nosys(void); } // SYS_NOSYS = 28; // { int nosys(void); } // SYS_NOSYS = 29; // { int nosys(void); } // SYS_NOSYS = 30; // { int nosys(void); } // SYS_NOSYS = 31; // { int nosys(void); } // SYS_NOSYS = 32; // { int nosys(void); } SYS_ACCESS = 33 // { int access(user_addr_t path, int flags); } SYS_CHFLAGS = 34 // { int chflags(char *path, int flags); } SYS_FCHFLAGS = 35 // { int fchflags(int fd, int flags); } SYS_SYNC = 36 // { int sync(void); } SYS_KILL = 37 // { int kill(int pid, int signum, int posix); } // SYS_NOSYS = 38; // { int nosys(void); } { old stat } SYS_GETPPID = 39 // { int getppid(void); } // SYS_NOSYS = 40; // { int nosys(void); } { old lstat } SYS_DUP = 41 // { int dup(u_int fd); } SYS_PIPE = 42 // { int pipe(void); } SYS_GETEGID = 43 // { int getegid(void); } SYS_PROFIL = 44 // { int profil(short *bufbase, size_t bufsize, u_long pcoffset, u_int pcscale); } // SYS_NOSYS = 45; // { int nosys(void); } { old ktrace } SYS_SIGACTION = 46 // { int sigaction(int signum, struct __sigaction *nsa, struct sigaction *osa); } SYS_GETGID = 47 // { int getgid(void); } SYS_SIGPROCMASK = 48 // { int sigprocmask(int how, user_addr_t mask, user_addr_t omask); } SYS_GETLOGIN = 49 // { int getlogin(char *namebuf, u_int namelen); } SYS_SETLOGIN = 50 // { int setlogin(char *namebuf); } SYS_ACCT = 51 // { int acct(char *path); } SYS_SIGPENDING = 52 // { int sigpending(struct sigvec *osv); } SYS_SIGALTSTACK = 53 // { int sigaltstack(struct sigaltstack *nss, struct sigaltstack *oss); } SYS_IOCTL = 54 // { int ioctl(int fd, u_long com, caddr_t data); } SYS_REBOOT = 55 // { int reboot(int opt, char *command); } SYS_REVOKE = 56 // { int revoke(char *path); } SYS_SYMLINK = 57 // { int symlink(char *path, char *link); } SYS_READLINK = 58 // { int readlink(char *path, char *buf, int count); }

Constants

const ( AF_APPLETALK AF_CCITT AF_CHAOS AF_CNT AF_COIP AF_DATAKIT AF_DECnet AF_DLI AF_E164 AF_ECMA AF_HYLINK AF_IEEE80211 AF_IMPLINK AF_INET AF_INET6 AF_IPX AF_ISDN AF_ISO AF_LAT AF_LINK AF_LOCAL AF_MAX AF_NATM AF_NDRV AF_NETBIOS AF_NS AF_OSI AF_PPP AF_PUP AF_RESERVED_36 AF_ROUTE AF_SIP AF_SNA AF_SYSTEM AF_UNIX AF_UNSPEC E2BIG EACCES EADDRINUSE EADDRNOTAVAIL EAFNOSUPPORT EAGAIN EALREADY EAUTH EBADARCH EBADEXEC EBADF EBADMACHO EBADMSG EBADRPC EBUSY ECANCELED ECHILD ECONNABORTED ECONNREFUSED ECONNRESET EDEADLK EDESTADDRREQ EDEVERR EDOM EDQUOT EEXIST EFAULT EFBIG EFTYPE

= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =

0x10 0xa 0x5 0x15 0x14 0x9 0xc 0xd 0x1c 0x8 0xf 0x25 0x3 0x2 0x1e 0x17 0x1c 0x7 0xe 0x12 0x1 0x26 0x1f 0x1b 0x21 0x6 0x7 0x22 0x4 0x24 0x11 0x18 0xb 0x20 0x1 0 0x7 0xd 0x30 0x31 0x2f 0x23 0x25 0x50 0x56 0x55 0x9 0x58 0x5e 0x48 0x10 0x59 0xa 0x35 0x3d 0x36 0xb 0x27 0x53 0x21 0x45 0x11 0xe 0x1b 0x4f

Constants

const ( PathMax O_RDONLY O_WRONLY O_RDWR O_APPEND O_ASYNC O_CREAT O_NOCTTY O_NONBLOCK O_SYNC O_TRUNC O_CLOEXEC F_GETFD F_SETFD F_GETFL F_SETFL FD_CLOEXEC NAME_MAX S_IFMT S_IFIFO S_IFCHR S_IFDIR S_IFBLK S_IFREG S_IFLNK S_IFSOCK S_ISUID S_ISGID S_ISVTX S_IRUSR S_IWUSR S_IXUSR WNOHANG WUNTRACED WEXITED WSTOPPED WCONTINUED WNOWAIT WCLONE WALL WNOTHREAD AF_UNIX AF_INET AF_INET6 SOCK_STREAM SOCK_DGRAM SOCK_RAW SOCK_SEQPACKET SOL_SOCKET SO_REUSEADDR SO_KEEPALIVE SO_DONTROUTE SO_BROADCAST SO_LINGER SO_SNDBUF SO_RCVBUF SO_SNDTIMEO SO_RCVTIMEO IPPROTO_TCP IPPROTO_UDP TCP_NODELAY SOMAXCONN SizeofSockaddrInet4 SizeofSockaddrInet6 SizeofSockaddrAny

= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =

0x1000 0 0x1 0x2 0x400 0x2000 0x40 0x100 0x800 0x1000 0x200 0 0x1 0x2 0x3 0x4 0x1 0xff 0xf000 0x1000 0x2000 0x4000 0x6000 0x8000 0xa000 0xc000 0x800 0x400 0x200 0x100 0x80 0x40 0x1 0x2 0x4 0x2 0x8 0x1000000 0x80000000 0x40000000 0x20000000 0x1 0x2 0xa 0x1 0x2 0x3 0x5 0x1 0x2 0x9 0x5 0x6 0xd 0x7 0x8 0x15 0x14 0x6 0x11 0x1 0x80 0x10 0x1c 0x1c

const ( EPERM ENOENT ESRCH EINTR EIO ENXIO E2BIG ENOEXEC EBADF ECHILD EAGAIN ENOMEM EACCES EFAULT EBUSY EEXIST EXDEV ENODEV ENOTDIR EISDIR EINVAL ENFILE EMFILE ENOTTY EFBIG ENOSPC ESPIPE EROFS EMLINK EPIPE ENAMETOOLONG ENOSYS EDQUOT EDOM ERANGE ENOMSG ECHRNG EL3HLT EL3RST ELNRNG EUNATCH ENOCSI EL2HLT EDEADLK ENOLCK EBADE EBADR EXFULL ENOANO EBADRQC EBADSLT EBFONT ENOSTR ENODATA ETIME ENOSR ENONET ENOPKG EREMOTE ENOLINK EADV ESRMNT ECOMM EPROTO EMULTIHOP

= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =

1 2 3 4 5 6 7 8 9 10 11 12 13 14 16 17 18 19 20 21 22 23 24 25 27 28 29 30 31 32 36 38 122 33 34 35 37 39 40 41 42 43 44 45 46 50 51 52 53 54 55 57 60 61 62 63 64 65 66 67 68 69 70 71 74

Constants
const ( O_CLOEXEC S_IFMT S_IFIFO S_IFCHR S_IFDIR S_IFBLK S_IFREG S_IFLNK S_IFSOCK S_ISUID S_ISGID S_ISVTX S_IRUSR S_IWUSR S_IXUSR SizeofSockaddrInet4 SizeofSockaddrInet6 SizeofSockaddrAny SizeofSockaddrUnix SizeofLinger SizeofMsghdr SizeofCmsghdr PTRACE_TRACEME PTRACE_CONT PTRACE_KILL )

= = = = = = = = = = = = = = = = = = = = = = = = =

0 0xf000 0x1000 0x2000 0x4000 0x6000 0x8000 0xa000 0xc000 0x800 0x400 0x200 0x100 0x80 0x40 0x10 0x1c 0x6c 0x6a 0x8 0x30 0xc 0 0x7 0x8

const ( SYS_RESTART_SYSCALL SYS_EXIT SYS_FORK SYS_READ SYS_WRITE SYS_OPEN SYS_CLOSE SYS_WAITPID SYS_CREAT SYS_LINK SYS_UNLINK SYS_EXECVE SYS_CHDIR SYS_TIME SYS_MKNOD SYS_CHMOD SYS_LCHOWN SYS_BREAK SYS_OLDSTAT SYS_LSEEK SYS_GETPID SYS_MOUNT SYS_UMOUNT SYS_SETUID SYS_GETUID SYS_STIME SYS_PTRACE SYS_ALARM SYS_OLDFSTAT SYS_PAUSE SYS_UTIME SYS_STTY SYS_GTTY SYS_ACCESS SYS_NICE SYS_FTIME SYS_SYNC SYS_KILL SYS_RENAME SYS_MKDIR SYS_RMDIR SYS_DUP SYS_PIPE SYS_TIMES SYS_PROF SYS_BRK SYS_SETGID SYS_GETGID SYS_SIGNAL SYS_GETEUID SYS_GETEGID SYS_ACCT SYS_UMOUNT2 SYS_LOCK SYS_IOCTL SYS_FCNTL SYS_MPX SYS_SETPGID SYS_ULIMIT SYS_OLDOLDUNAME SYS_UMASK SYS_CHROOT SYS_USTAT SYS_DUP2 SYS_GETPPID

= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =

0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64

Constants

const ( AF_APPLETALK AF_CCITT AF_CHAOS AF_CNT AF_COIP AF_DATAKIT AF_DECnet AF_DLI AF_E164 AF_ECMA AF_HYLINK AF_IEEE80211 AF_IMPLINK AF_INET AF_INET6 AF_IPX AF_ISDN AF_ISO AF_LAT AF_LINK AF_LOCAL AF_MAX AF_NATM AF_NDRV AF_NETBIOS AF_NS AF_OSI AF_PPP AF_PUP AF_RESERVED_36 AF_ROUTE AF_SIP AF_SNA AF_SYSTEM AF_UNIX AF_UNSPEC E2BIG EACCES EADDRINUSE EADDRNOTAVAIL EAFNOSUPPORT EAGAIN EALREADY EAUTH EBADARCH EBADEXEC EBADF EBADMACHO EBADMSG EBADRPC EBUSY ECANCELED ECHILD ECONNABORTED ECONNREFUSED ECONNRESET EDEADLK EDESTADDRREQ EDEVERR EDOM EDQUOT EEXIST EFAULT EFBIG EFTYPE

= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =

0x10 0xa 0x5 0x15 0x14 0x9 0xc 0xd 0x1c 0x8 0xf 0x25 0x3 0x2 0x1e 0x17 0x1c 0x7 0xe 0x12 0x1 0x26 0x1f 0x1b 0x21 0x6 0x7 0x22 0x4 0x24 0x11 0x18 0xb 0x20 0x1 0 0x7 0xd 0x30 0x31 0x2f 0x23 0x25 0x50 0x56 0x55 0x9 0x58 0x5e 0x48 0x10 0x59 0xa 0x35 0x3d 0x36 0xb 0x27 0x53 0x21 0x45 0x11 0xe 0x1b 0x4f

const ( F_SETFD = 1 + iota FD_CLOEXEC F_GETFL F_SETFL O_NONBLOCK SYS_FORK SYS_PTRACE SYS_CHDIR SYS_DUP2 SYS_FCNTL SYS_EXECVE PTRACE_TRACEME SYS_CLOSE SYS_WRITE SYS_EXIT SYS_READ EPIPE EINTR )

const ( // SYS_NOSYS = 0; // { int nosys(void); } { indirect syscall } SYS_EXIT = 1 // { void exit(int rval); } SYS_FORK = 2 // { int fork(void); } SYS_READ = 3 // { user_ssize_t read(int fd, user_addr_t cbuf, user_size_t nbyte); } SYS_WRITE = 4 // { user_ssize_t write(int fd, user_addr_t cbuf, user_size_t nbyte); } SYS_OPEN = 5 // { int open(user_addr_t path, int flags, int mode); } SYS_CLOSE = 6 // { int close(int fd); } SYS_WAIT4 = 7 // { int wait4(int pid, user_addr_t status, int options, user_addr_t rusage); } // SYS_NOSYS = 8; // { int nosys(void); } { old creat } SYS_LINK = 9 // { int link(user_addr_t path, user_addr_t link); } SYS_UNLINK = 10 // { int unlink(user_addr_t path); } // SYS_NOSYS = 11; // { int nosys(void); } { old execv } SYS_CHDIR = 12 // { int chdir(user_addr_t path); } SYS_FCHDIR = 13 // { int fchdir(int fd); } SYS_MKNOD = 14 // { int mknod(user_addr_t path, int mode, int dev); } SYS_CHMOD = 15 // { int chmod(user_addr_t path, int mode); } SYS_CHOWN = 16 // { int chown(user_addr_t path, int uid, int gid); } SYS_OGETFSSTAT = 18 // { int ogetfsstat(user_addr_t buf, int bufsize, int flags); } SYS_GETFSSTAT = 18 // { int getfsstat(user_addr_t buf, int bufsize, int flags); } // SYS_NOSYS = 19; // { int nosys(void); } { old lseek } SYS_GETPID = 20 // { int getpid(void); } // SYS_NOSYS = 21; // { int nosys(void); } { old mount } // SYS_NOSYS = 22; // { int nosys(void); } { old umount } SYS_SETUID = 23 // { int setuid(uid_t uid); } SYS_GETUID = 24 // { int getuid(void); } SYS_GETEUID = 25 // { int geteuid(void); } SYS_PTRACE = 26 // { int ptrace(int req, pid_t pid, caddr_t addr, int data); } SYS_RECVMSG = 27 // { int recvmsg(int s, struct msghdr *msg, int flags); } SYS_SENDMSG = 28 // { int sendmsg(int s, caddr_t msg, int flags); } SYS_RECVFROM = 29 // { int recvfrom(int s, void *buf, size_t len, int flags, struct sockaddr *from, int SYS_ACCEPT = 30 // { int accept(int s, caddr_t name, socklen_t *anamelen); } SYS_GETPEERNAME = 31 // { int getpeername(int fdes, caddr_t asa, socklen_t *alen); } SYS_GETSOCKNAME = 32 // { int getsockname(int fdes, caddr_t asa, socklen_t *alen); } // SYS_NOSYS = 27; // { int nosys(void); } // SYS_NOSYS = 28; // { int nosys(void); } // SYS_NOSYS = 29; // { int nosys(void); } // SYS_NOSYS = 30; // { int nosys(void); } // SYS_NOSYS = 31; // { int nosys(void); } // SYS_NOSYS = 32; // { int nosys(void); } SYS_ACCESS = 33 // { int access(user_addr_t path, int flags); } SYS_CHFLAGS = 34 // { int chflags(char *path, int flags); } SYS_FCHFLAGS = 35 // { int fchflags(int fd, int flags); } SYS_SYNC = 36 // { int sync(void); } SYS_KILL = 37 // { int kill(int pid, int signum, int posix); } // SYS_NOSYS = 38; // { int nosys(void); } { old stat } SYS_GETPPID = 39 // { int getppid(void); } // SYS_NOSYS = 40; // { int nosys(void); } { old lstat } SYS_DUP = 41 // { int dup(u_int fd); } SYS_PIPE = 42 // { int pipe(void); } SYS_GETEGID = 43 // { int getegid(void); } SYS_PROFIL = 44 // { int profil(short *bufbase, size_t bufsize, u_long pcoffset, u_int pcscale); } // SYS_NOSYS = 45; // { int nosys(void); } { old ktrace } SYS_SIGACTION = 46 // { int sigaction(int signum, struct __sigaction *nsa, struct sigaction *osa); } SYS_GETGID = 47 // { int getgid(void); } SYS_SIGPROCMASK = 48 // { int sigprocmask(int how, user_addr_t mask, user_addr_t omask); } SYS_GETLOGIN = 49 // { int getlogin(char *namebuf, u_int namelen); } SYS_SETLOGIN = 50 // { int setlogin(char *namebuf); } SYS_ACCT = 51 // { int acct(char *path); } SYS_SIGPENDING = 52 // { int sigpending(struct sigvec *osv); } SYS_SIGALTSTACK = 53 // { int sigaltstack(struct sigaltstack *nss, struct sigaltstack *oss); } SYS_IOCTL = 54 // { int ioctl(int fd, u_long com, caddr_t data); } SYS_REBOOT = 55 // { int reboot(int opt, char *command); } SYS_REVOKE = 56 // { int revoke(char *path); } SYS_SYMLINK = 57 // { int symlink(char *path, char *link); } SYS_READLINK = 58 // { int readlink(char *path, char *buf, int count); }

Constants
const ( O_CLOEXEC S_IFMT S_IFIFO S_IFCHR S_IFDIR S_IFBLK S_IFREG S_IFLNK S_IFSOCK S_ISUID S_ISGID S_ISVTX S_IRUSR S_IWUSR S_IXUSR SizeofSockaddrInet4 SizeofSockaddrInet6 SizeofSockaddrAny SizeofSockaddrUnix SizeofLinger SizeofMsghdr SizeofCmsghdr PTRACE_TRACEME PTRACE_CONT PTRACE_KILL )

= = = = = = = = = = = = = = = = = = = = = = = = =

0 0xf000 0x1000 0x2000 0x4000 0x6000 0x8000 0xa000 0xc000 0x800 0x400 0x200 0x100 0x80 0x40 0x10 0x1c 0x6c 0x6a 0x8 0x1c 0xc 0 0x7 0x8

const ( // SYS_NOSYS = 0; SYS_EXIT SYS_FORK SYS_READ SYS_WRITE SYS_OPEN SYS_CLOSE SYS_WAIT4 SYS_LINK SYS_UNLINK SYS_CHDIR SYS_FCHDIR SYS_MKNOD SYS_CHMOD SYS_CHOWN SYS_OBREAK SYS_GETPID SYS_MOUNT SYS_UNMOUNT SYS_SETUID SYS_GETUID SYS_GETEUID SYS_PTRACE SYS_RECVMSG SYS_SENDMSG SYS_RECVFROM SYS_ACCEPT SYS_GETPEERNAME SYS_GETSOCKNAME SYS_ACCESS SYS_CHFLAGS SYS_FCHFLAGS SYS_SYNC SYS_KILL SYS_GETPPID SYS_DUP SYS_PIPE SYS_GETEGID SYS_PROFIL SYS_KTRACE SYS_GETGID SYS_GETLOGIN SYS_SETLOGIN SYS_ACCT SYS_SIGALTSTACK SYS_IOCTL SYS_REBOOT SYS_REVOKE SYS_SYMLINK SYS_READLINK SYS_EXECVE SYS_UMASK SYS_CHROOT SYS_MSYNC SYS_VFORK SYS_SBRK SYS_SSTK SYS_OVADVISE SYS_MUNMAP SYS_MPROTECT SYS_MADVISE SYS_MINCORE SYS_GETGROUPS SYS_SETGROUPS SYS_GETPGRP

// { int nosys(void); } syscall nosys_args int = 1 // { void sys_exit(int rval); } exit \ = 2 // { int fork(void); } = 3 // { ssize_t read(int fd, void *buf, \ = 4 // { ssize_t write(int fd, const void *buf, \ = 5 // { int open(char *path, int flags, int mode); } = 6 // { int close(int fd); } = 7 // { int wait4(int pid, int *status, \ = 9 // { int link(char *path, char *link); } = 10 // { int unlink(char *path); } = 12 // { int chdir(char *path); } = 13 // { int fchdir(int fd); } = 14 // { int mknod(char *path, int mode, int dev); } = 15 // { int chmod(char *path, int mode); } = 16 // { int chown(char *path, int uid, int gid); } = 17 // { int obreak(char *nsize); } break \ = 20 // { pid_t getpid(void); } = 21 // { int mount(char *type, char *path, \ = 22 // { int unmount(char *path, int flags); } = 23 // { int setuid(uid_t uid); } = 24 // { uid_t getuid(void); } = 25 // { uid_t geteuid(void); } = 26 // { int ptrace(int req, pid_t pid, \ = 27 // { int recvmsg(int s, struct msghdr *msg, \ = 28 // { int sendmsg(int s, struct msghdr *msg, \ = 29 // { int recvfrom(int s, caddr_t buf, \ = 30 // { int accept(int s, \ = 31 // { int getpeername(int fdes, \ = 32 // { int getsockname(int fdes, \ = 33 // { int access(char *path, int flags); } = 34 // { int chflags(char *path, int flags); } = 35 // { int fchflags(int fd, int flags); } = 36 // { int sync(void); } = 37 // { int kill(int pid, int signum); } = 39 // { pid_t getppid(void); } = 41 // { int dup(u_int fd); } = 42 // { int pipe(void); } = 43 // { gid_t getegid(void); } = 44 // { int profil(caddr_t samples, size_t size, \ = 45 // { int ktrace(const char *fname, int ops, \ = 47 // { gid_t getgid(void); } = 49 // { int getlogin(char *namebuf, u_int \ = 50 // { int setlogin(char *namebuf); } = 51 // { int acct(char *path); } = 53 // { int sigaltstack(stack_t *ss, \ = 54 // { int ioctl(int fd, u_long com, \ = 55 // { int reboot(int opt); } = 56 // { int revoke(char *path); } = 57 // { int symlink(char *path, char *link); } = 58 // { ssize_t readlink(char *path, char *buf, \ = 59 // { int execve(char *fname, char **argv, \ = 60 // { int umask(int newmask); } umask umask_args \ = 61 // { int chroot(char *path); } = 65 // { int msync(void *addr, size_t len, \ = 66 // { int vfork(void); } = 69 // { int sbrk(int incr); } = 70 // { int sstk(int incr); } = 72 // { int ovadvise(int anom); } vadvise \ = 73 // { int munmap(void *addr, size_t len); } = 74 // { int mprotect(const void *addr, size_t len, \ = 75 // { int madvise(void *addr, size_t len, \ = 78 // { int mincore(const void *addr, size_t len, \ = 79 // { int getgroups(u_int gidsetsize, \ = 80 // { int setgroups(u_int gidsetsize, \ = 81 // { int getpgrp(void); }

Constants
const ( PROT_READ PROT_WRITE MAP_SHARED SYS_FORK SYS_PTRACE SYS_CHDIR SYS_DUP2 SYS_FCNTL SYS_EXECVE O_RDONLY O_WRONLY O_RDWR O_APPEND O_ASYNC O_CREAT O_NOCTTY O_NONBLOCK O_SYNC O_TRUNC O_CLOEXEC O_EXCL F_GETFD F_SETFD F_GETFL F_SETFL FD_CLOEXEC S_IFMT S_IFIFO S_IFCHR S_IFDIR S_IFBLK S_IFREG S_IFLNK S_IFSOCK S_ISUID S_ISGID S_ISVTX S_IRUSR S_IWUSR S_IXUSR )

= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =

0x1 0x2 0x1 0 0 0 0 0 0 0 0x1 0x2 0x400 0x2000 0x40 0 0x800 0x1000 0x200 0 0 0x1 0x2 0x3 0x4 0 0x1f000 0x1000 0x2000 0x4000 0x6000 0x8000 0xa000 0xc000 0x800 0x400 0x200 0x100 0x80 0x40

Constants

const ( AF_APPLETALK AF_ARP AF_ATM AF_BLUETOOTH AF_CCITT AF_CHAOS AF_CNT AF_COIP AF_DATAKIT AF_DECnet AF_DLI AF_E164 AF_ECMA AF_HYLINK AF_IEEE80211 AF_IMPLINK AF_INET AF_INET6 AF_IPX AF_ISDN AF_ISO AF_LAT AF_LINK AF_LOCAL AF_MAX AF_NATM AF_NETBIOS AF_NETGRAPH AF_OSI AF_PUP AF_ROUTE AF_SCLUSTER AF_SIP AF_SLOW AF_SNA AF_UNIX AF_UNSPEC AF_VENDOR00 AF_VENDOR01 AF_VENDOR02 AF_VENDOR03 AF_VENDOR04 AF_VENDOR05 AF_VENDOR06 AF_VENDOR07 AF_VENDOR08 AF_VENDOR09 AF_VENDOR10 AF_VENDOR11 AF_VENDOR12 AF_VENDOR13 AF_VENDOR14 AF_VENDOR15 AF_VENDOR16 AF_VENDOR17 AF_VENDOR18 AF_VENDOR19 AF_VENDOR20 AF_VENDOR21 AF_VENDOR22 AF_VENDOR23 AF_VENDOR24 AF_VENDOR25 AF_VENDOR26 AF_VENDOR27

= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =

0x10 0x23 0x1e 0x24 0xa 0x5 0x15 0x14 0x9 0xc 0xd 0x1a 0x8 0xf 0x25 0x3 0x2 0x1c 0x17 0x1a 0x7 0xe 0x12 0x1 0x26 0x1d 0x6 0x20 0x7 0x4 0x11 0x22 0x18 0x21 0xb 0x1 0 0x27 0x29 0x2b 0x2d 0x2f 0x31 0x33 0x35 0x37 0x39 0x3b 0x3d 0x3f 0x41 0x43 0x45 0x47 0x49 0x4b 0x4d 0x4f 0x51 0x53 0x55 0x57 0x59 0x5b 0x5d

Constants

const ( AF_APPLETALK AF_ARP AF_ATM AF_BLUETOOTH AF_CCITT AF_CHAOS AF_CNT AF_COIP AF_DATAKIT AF_DECnet AF_DLI AF_E164 AF_ECMA AF_HYLINK AF_IEEE80211 AF_IMPLINK AF_INET AF_INET6 AF_IPX AF_ISDN AF_ISO AF_LAT AF_LINK AF_LOCAL AF_MAX AF_NATM AF_NETBIOS AF_NETGRAPH AF_OSI AF_PUP AF_ROUTE AF_SCLUSTER AF_SIP AF_SLOW AF_SNA AF_UNIX AF_UNSPEC AF_VENDOR00 AF_VENDOR01 AF_VENDOR02 AF_VENDOR03 AF_VENDOR04 AF_VENDOR05 AF_VENDOR06 AF_VENDOR07 AF_VENDOR08 AF_VENDOR09 AF_VENDOR10 AF_VENDOR11 AF_VENDOR12 AF_VENDOR13 AF_VENDOR14 AF_VENDOR15 AF_VENDOR16 AF_VENDOR17 AF_VENDOR18 AF_VENDOR19 AF_VENDOR20 AF_VENDOR21 AF_VENDOR22 AF_VENDOR23 AF_VENDOR24 AF_VENDOR25 AF_VENDOR26 AF_VENDOR27

= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =

0x10 0x23 0x1e 0x24 0xa 0x5 0x15 0x14 0x9 0xc 0xd 0x1a 0x8 0xf 0x25 0x3 0x2 0x1c 0x17 0x1a 0x7 0xe 0x12 0x1 0x26 0x1d 0x6 0x20 0x7 0x4 0x11 0x22 0x18 0x21 0xb 0x1 0 0x27 0x29 0x2b 0x2d 0x2f 0x31 0x33 0x35 0x37 0x39 0x3b 0x3d 0x3f 0x41 0x43 0x45 0x47 0x49 0x4b 0x4d 0x4f 0x51 0x53 0x55 0x57 0x59 0x5b 0x5d

Constants
const ( PathMax SizeofSockaddrInet4 SizeofSockaddrInet6 SizeofSockaddrAny SizeofSockaddrUnix SizeofLinger SizeofMsghdr SizeofCmsghdr )

= = = = = = = =

0x1000 0x10 0x1c 0x70 0x6e 0x8 0x1c 0xc

const ( // SYS_NOSYS = 0; SYS_EXIT SYS_FORK SYS_READ SYS_WRITE SYS_OPEN SYS_CLOSE SYS_WAIT4 SYS_LINK SYS_UNLINK SYS_CHDIR SYS_FCHDIR SYS_MKNOD SYS_CHMOD SYS_CHOWN SYS_OBREAK SYS_GETPID SYS_MOUNT SYS_UNMOUNT SYS_SETUID SYS_GETUID SYS_GETEUID SYS_PTRACE SYS_RECVMSG SYS_SENDMSG SYS_RECVFROM SYS_ACCEPT SYS_GETPEERNAME SYS_GETSOCKNAME SYS_ACCESS SYS_CHFLAGS SYS_FCHFLAGS SYS_SYNC SYS_KILL SYS_GETPPID SYS_DUP SYS_PIPE SYS_GETEGID SYS_PROFIL SYS_KTRACE SYS_GETGID SYS_GETLOGIN SYS_SETLOGIN SYS_ACCT SYS_SIGALTSTACK SYS_IOCTL SYS_REBOOT SYS_REVOKE SYS_SYMLINK SYS_READLINK SYS_EXECVE SYS_UMASK SYS_CHROOT SYS_MSYNC SYS_VFORK SYS_SBRK SYS_SSTK SYS_OVADVISE SYS_MUNMAP SYS_MPROTECT SYS_MADVISE SYS_MINCORE SYS_GETGROUPS SYS_SETGROUPS SYS_GETPGRP

// { int nosys(void); } syscall nosys_args int = 1 // { void sys_exit(int rval); } exit \ = 2 // { int fork(void); } = 3 // { ssize_t read(int fd, void *buf, \ = 4 // { ssize_t write(int fd, const void *buf, \ = 5 // { int open(char *path, int flags, int mode); } = 6 // { int close(int fd); } = 7 // { int wait4(int pid, int *status, \ = 9 // { int link(char *path, char *link); } = 10 // { int unlink(char *path); } = 12 // { int chdir(char *path); } = 13 // { int fchdir(int fd); } = 14 // { int mknod(char *path, int mode, int dev); } = 15 // { int chmod(char *path, int mode); } = 16 // { int chown(char *path, int uid, int gid); } = 17 // { int obreak(char *nsize); } break \ = 20 // { pid_t getpid(void); } = 21 // { int mount(char *type, char *path, \ = 22 // { int unmount(char *path, int flags); } = 23 // { int setuid(uid_t uid); } = 24 // { uid_t getuid(void); } = 25 // { uid_t geteuid(void); } = 26 // { int ptrace(int req, pid_t pid, \ = 27 // { int recvmsg(int s, struct msghdr *msg, \ = 28 // { int sendmsg(int s, struct msghdr *msg, \ = 29 // { int recvfrom(int s, caddr_t buf, \ = 30 // { int accept(int s, \ = 31 // { int getpeername(int fdes, \ = 32 // { int getsockname(int fdes, \ = 33 // { int access(char *path, int flags); } = 34 // { int chflags(char *path, int flags); } = 35 // { int fchflags(int fd, int flags); } = 36 // { int sync(void); } = 37 // { int kill(int pid, int signum); } = 39 // { pid_t getppid(void); } = 41 // { int dup(u_int fd); } = 42 // { int pipe(void); } = 43 // { gid_t getegid(void); } = 44 // { int profil(caddr_t samples, size_t size, \ = 45 // { int ktrace(const char *fname, int ops, \ = 47 // { gid_t getgid(void); } = 49 // { int getlogin(char *namebuf, u_int \ = 50 // { int setlogin(char *namebuf); } = 51 // { int acct(char *path); } = 53 // { int sigaltstack(stack_t *ss, \ = 54 // { int ioctl(int fd, u_long com, \ = 55 // { int reboot(int opt); } = 56 // { int revoke(char *path); } = 57 // { int symlink(char *path, char *link); } = 58 // { ssize_t readlink(char *path, char *buf, \ = 59 // { int execve(char *fname, char **argv, \ = 60 // { int umask(int newmask); } umask umask_args \ = 61 // { int chroot(char *path); } = 65 // { int msync(void *addr, size_t len, \ = 66 // { int vfork(void); } = 69 // { int sbrk(int incr); } = 70 // { int sstk(int incr); } = 72 // { int ovadvise(int anom); } vadvise \ = 73 // { int munmap(void *addr, size_t len); } = 74 // { int mprotect(const void *addr, size_t len, \ = 75 // { int madvise(void *addr, size_t len, \ = 78 // { int mincore(const void *addr, size_t len, \ = 79 // { int getgroups(u_int gidsetsize, \ = 80 // { int setgroups(u_int gidsetsize, \ = 81 // { int getpgrp(void); }

const ( SYS_READ SYS_WRITE SYS_OPEN SYS_CLOSE SYS_STAT SYS_FSTAT SYS_LSTAT SYS_POLL SYS_LSEEK SYS_MMAP SYS_MPROTECT SYS_MUNMAP SYS_BRK SYS_RT_SIGACTION SYS_RT_SIGPROCMASK SYS_RT_SIGRETURN SYS_IOCTL SYS_PREAD64 SYS_PWRITE64 SYS_READV SYS_WRITEV SYS_ACCESS SYS_PIPE SYS_SELECT SYS_SCHED_YIELD SYS_MREMAP SYS_MSYNC SYS_MINCORE SYS_MADVISE SYS_SHMGET SYS_SHMAT SYS_SHMCTL SYS_DUP SYS_DUP2 SYS_PAUSE SYS_NANOSLEEP SYS_GETITIMER SYS_ALARM SYS_SETITIMER SYS_GETPID SYS_SENDFILE SYS_SOCKET SYS_CONNECT SYS_ACCEPT SYS_SENDTO SYS_RECVFROM SYS_SENDMSG SYS_RECVMSG SYS_SHUTDOWN SYS_BIND SYS_LISTEN SYS_GETSOCKNAME SYS_GETPEERNAME SYS_SOCKETPAIR SYS_SETSOCKOPT SYS_GETSOCKOPT SYS_CLONE SYS_FORK SYS_VFORK SYS_EXECVE SYS_EXIT SYS_WAIT4 SYS_KILL SYS_UNAME SYS_SEMGET

= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =

0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64

Constants
const ( O_CLOEXEC SizeofSockaddrInet4 SizeofSockaddrInet6 SizeofSockaddrAny SizeofSockaddrUnix SizeofLinger SizeofMsghdr SizeofCmsghdr PTRACE_TRACEME PTRACE_CONT PTRACE_KILL )

= = = = = = = = = = =

0 0x10 0x1c 0x6c 0x6a 0x8 0x1c 0xc 0 0x7 0x8

Constants
const ( PathMax SizeofSockaddrInet4 SizeofSockaddrInet6 SizeofSockaddrAny SizeofSockaddrUnix SizeofLinger SizeofMsghdr SizeofCmsghdr )

= = = = = = = =

0x1000 0x10 0x1c 0x70 0x6e 0x8 0x1c 0xc

Constants
const ( O_CLOEXEC SizeofSockaddrInet4 SizeofSockaddrInet6 SizeofSockaddrAny SizeofSockaddrUnix SizeofLinger SizeofMsghdr SizeofCmsghdr PTRACE_TRACEME PTRACE_CONT PTRACE_KILL )

= = = = = = = = = = =

0 0x10 0x1c 0x6c 0x6a 0x8 0x30 0xc 0 0x7 0x8

Constants

const ( EMULTIHOP EUNATCH EAFNOSUPPORT EREMCHG EACCES EL3RST EDESTADDRREQ EILSEQ ESPIPE EMLINK EOWNERDEAD ENOTTY EBADE EBADF EBADR EADV ERANGE ECANCELED ETXTBSY ENOMEM EINPROGRESS ENOTEMPTY ENOTBLK EPROTOTYPE ERESTART EISNAM ENOMSG EALREADY ETIMEDOUT ENODATA EINTR ENOLINK EPERM ELOOP ENETDOWN ESTALE ENOTSOCK ENOSR ECHILD ELNRNG EPIPE EBADMSG EBFONT EREMOTE ETOOMANYREFS EPFNOSUPPORT ENONET EXFULL EBADSLT ENOTNAM ENOCSI EADDRINUSE ENETRESET EISDIR EIDRM ECOMM EBADFD EL2HLT ENOKEY EINVAL ESHUTDOWN EKEYREJECTED ELIBSCN ENAVAIL EOVERFLOW

= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =

0x48 0x31 0x61 0x4e 0xd 0x2f 0x59 0x54 0x1d 0x1f 0x82 0x19 0x34 0x9 0x35 0x44 0x22 0x7d 0x1a 0xc 0x73 0x27 0xf 0x5b 0x55 0x78 0x2a 0x72 0x6e 0x3d 0x4 0x43 0x1 0x28 0x64 0x74 0x58 0x3f 0xa 0x30 0x20 0x4a 0x3b 0x42 0x6d 0x60 0x40 0x36 0x39 0x76 0x32 0x62 0x66 0x15 0x2b 0x46 0x4d 0x33 0x7e 0x16 0x6c 0x81 0x51 0x77 0x4b

Constants

const ( AF_APPLETALK AF_ASH AF_ATMPVC AF_ATMSVC AF_AX25 AF_BLUETOOTH AF_BRIDGE AF_CAN AF_DECnet AF_ECONET AF_FILE AF_IEEE802154 AF_INET AF_INET6 AF_IPX AF_IRDA AF_ISDN AF_IUCV AF_KEY AF_LLC AF_LOCAL AF_MAX AF_NETBEUI AF_NETLINK AF_NETROM AF_PACKET AF_PHONET AF_PPPOX AF_RDS AF_ROSE AF_ROUTE AF_RXRPC AF_SECURITY AF_SNA AF_TIPC AF_UNIX AF_UNSPEC AF_WANPIPE AF_X25 E2BIG EACCES EADDRINUSE EADDRNOTAVAIL EADV EAFNOSUPPORT EAGAIN EALREADY EBADE EBADF EBADFD EBADMSG EBADR EBADRQC EBADSLT EBFONT EBUSY ECANCELED ECHILD ECHRNG ECOMM ECONNABORTED ECONNREFUSED ECONNRESET EDEADLK EDEADLOCK

= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =

0x5 0x12 0x8 0x14 0x3 0x1f 0x7 0x1d 0xc 0x13 0x1 0x24 0x2 0xa 0x4 0x17 0x22 0x20 0xf 0x1a 0x1 0x25 0xd 0x10 0x6 0x11 0x23 0x18 0x15 0xb 0x10 0x21 0xe 0x16 0x1e 0x1 0 0x19 0x9 0x7 0xd 0x62 0x63 0x44 0x61 0xb 0x72 0x34 0x9 0x4d 0x4a 0x35 0x38 0x39 0x3b 0x10 0x7d 0xa 0x2c 0x46 0x67 0x6f 0x68 0x23 0x23

const ( SYS_NULL SYS_OPEN SYS_CLOSE SYS_READ SYS_WRITE SYS_LSEEK SYS_IOCTL SYS_STAT SYS_FSTAT SYS_CHMOD SYS_SYSBRK SYS_MMAP SYS_MUNMAP SYS_GETDENTS SYS_EXIT SYS_GETPID SYS_SCHED_YIELD SYS_SYSCONF SYS_GETTIMEOFDAY SYS_CLOCK SYS_MULTIMEDIA_INIT SYS_MULTIMEDIA_SHUTDOWN SYS_VIDEO_INIT SYS_VIDEO_SHUTDOWN SYS_VIDEO_UPDATE SYS_VIDEO_POLL_EVENT SYS_AUDIO_INIT SYS_AUDIO_SHUTDOWN SYS_AUDIO_STREAM SYS_IMC_MAKEBOUNDSOCK SYS_IMC_ACCEPT SYS_IMC_CONNECT SYS_IMC_SENDMSG SYS_IMC_RECVMSG SYS_IMC_MEM_OBJ_CREATE SYS_IMC_SOCKETPAIR SYS_MUTEX_CREATE SYS_MUTEX_LOCK SYS_MUTEX_TRYLOCK SYS_MUTEX_UNLOCK SYS_COND_CREATE SYS_COND_WAIT SYS_COND_SIGNAL SYS_COND_BROADCAST SYS_COND_TIMED_WAIT_ABS SYS_THREAD_CREATE SYS_THREAD_EXIT SYS_TLS_INIT SYS_THREAD_NICE SYS_SRPC_GET_FD SYS_SEM_CREATE SYS_SEM_WAIT SYS_SEM_POST SYS_SEM_GET_VALUE )

= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =

1 10 11 12 13 14 15 16 17 18 20 21 22 23 30 31 32 33 40 41 50 51 52 53 54 55 56 57 58 60 61 62 63 64 65 66 70 71 72 73 74 75 76 77 79 80 81 82 83 90 100 101 102 103

const ( EMINGW = 99 /* otherwise unused */ )

* Pseudo-system calls

The const provides a compile-time constant so clients can adjust to whether there is a working Getwd and avoid even linking this function into the binary. See ../os/getwd.go.
const ImplementsGetwd = false

const ImplementsGetwd = true

* Pseudo-system calls

The const provides a compile-time constant so clients can adjust to whether there is a working Getwd and avoid even linking this function into the binary. See ../os/getwd.go.
const ImplementsGetwd = false

const ImplementsGetwd = true

const OS = "freebsd"

const OS = "nacl"

const OS = "mingw"

const OS = "darwin"

const OS = "linux"

const ( SIGTRAP = 5 )

Variables
var ( SYS_KERNEL32 SYS_GET_LAST_ERROR SYS_LOAD_LIBRARY_A SYS_FREE_LIBRARY SYS_GET_PROC_ADDRESS SYS_GET_VERSION ) = = = = = = loadDll("kernel32.dll") getSysProcAddr(SYS_KERNEL32, getSysProcAddr(SYS_KERNEL32, getSysProcAddr(SYS_KERNEL32, getSysProcAddr(SYS_KERNEL32, getSysProcAddr(SYS_KERNEL32,

"GetLastError") "LoadLibraryA") "FreeLibrary") "GetProcAddress") "GetVersion")

var ForkLock sync.RWMutex

For testing: clients can set this flag to force creation of IPv6 sockets to return EAFNOSUPPORT.
var SocketDisableIPv6 bool

For testing: clients can set this flag to force creation of IPv6 sockets to return EAFNOSUPPORT.
var SocketDisableIPv6 bool

For testing: clients can set this flag to force creation of IPv6 sockets to return EAFNOSUPPORT.
var SocketDisableIPv6 bool

func Accept
func Accept(fd int) (nfd int, sa Sockaddr, errno int)

func Access
func Access(path string, mode int) (errno int)

func Acct
func Acct(path string) (errno int)

func Adjtime
func Adjtime(delta *Timeval, olddelta *Timeval) (errno int)

func Adjtimex
func Adjtimex(buf *Timex) (state int, errno int)

func AudioInit
func AudioInit(fmt int, nreq int, data *int) (errno int)

func AudioShutdown
func AudioShutdown() (errno int)

func AudioStream
func AudioStream(data *uint16, size *uintptr) (errno int)

func Bind
func Bind(fd int, sa Sockaddr) (errno int)

func Chdir
func Chdir(path string) (errno int)

func Chflags
func Chflags(path string, flags int) (errno int)

func Chmod
func Chmod(path string, mode int) (errno int)

func Chown
func Chown(path string, uid int, gid int) (errno int)

func Chroot
func Chroot(path string) (errno int)

func Clock
func Clock() (clock int)

func Close
func Close(fd int) (errno int)

func CloseOnExec
func CloseOnExec(fd int)

func CondBroadcast

func CondBroadcast(cv int) (errno int)

func CondCreate
func CondCreate() (cv int, errno int)

func CondSignal
func CondSignal(cv int) (errno int)

func CondTimedWaitAbs
func CondTimedWaitAbs(cv int, mutex int, abstime *Timespec) (errno int)

func CondWait
func CondWait(cv int, mutex int) (errno int)

func Connect
func Connect(fd int, sa Sockaddr) (errno int)

func Creat
func Creat(path string, mode int) (fd int, errno int)

func Dup
func Dup(oldfd int) (fd int, errno int)

func Dup2
func Dup2(oldfd int, newfd int) (fd int, errno int)

func EpollCreate
func EpollCreate(size int) (fd int, errno int)

func EpollCtl
func EpollCtl(epfd int, op int, fd int, event *EpollEvent) (errno int)

func EpollWait
func EpollWait(epfd int, events []EpollEvent, msec int) (n int, errno int)

func Errstr
func Errstr(errno int) string

func Exchangedata
func Exchangedata(path1 string, path2 string, options int) (errno int)

func Exec
func Exec(argv0 string, argv []string, envv []string) (err int) Ordinary exec.

func Exit
func Exit(code int)

func Faccessat
func Faccessat(dirfd int, path string, mode int, flags int) (errno int)

func Fallocate
func Fallocate(fd int, mode int, off int64, len int64) (errno int)

func Fchdir
func Fchdir(fd int) (errno int)

func Fchflags
func Fchflags(path string, flags int) (errno int)

func Fchmod
func Fchmod(fd int, mode int) (errno int)

func Fchmodat
func Fchmodat(dirfd int, path string, mode int, flags int) (errno int)

func Fchown
func Fchown(fd int, uid int, gid int) (errno int)

func Fchownat
func Fchownat(dirfd int, path string, uid int, gid int, flags int) (errno int)

func Fdatasync
func Fdatasync(fd int) (errno int)

func Flock
func Flock(fd int, how int) (errno int)

func ForkExec
func ForkExec(argv0 string, argv []string, envv []string, dir string, fd []int) (pid int, err int) Combination of fork and exec, careful to be thread safe.

func Fpathconf
func Fpathconf(fd int, name int) (val int, errno int)

func Fstat
func Fstat(fd int, stat *Stat_t) (errno int)

func Fstatfs
func Fstatfs(fd int, stat *Statfs_t) (errno int)

func Fsync
func Fsync(fd int) (errno int)

func Ftruncate
func Ftruncate(fd int, length int64) (errno int)

func Futimesat
func Futimesat(dirfd int, path string, tv []Timeval) (errno int) sys futimesat(dirfd int, path string, times *[2]Timeval) (errno int)

func GetLastError
func GetLastError() (lasterrno int)

func GetProcAddress
func GetProcAddress(module Module, procname string) (proc uint32, errno int)

func GetVersion
func GetVersion() (ver uint32, errno int)

func Getcwd
func Getcwd(buf []byte) (n int, errno int)

func Getdents
func Getdents(fd int, buf []byte) (n int, errno int)

func Getdirentries
func Getdirentries(fd int, buf []byte, basep *uintptr) (n int, errno int)

func Getdtablesize
func Getdtablesize() (size int)

func Getegid
func Getegid() (egid int)

func Geteuid
func Geteuid() (euid int)

func Getfsstat
func Getfsstat(buf []Statfs_t, flags int) (n int, errno int)

func Getgid
func Getgid() (gid int)

func Getgroups
func Getgroups() (gids []int, errno int)

func Getpagesize
func Getpagesize() int

func Getpgid
func Getpgid(pid int) (pgid int, errno int)

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, errno int)

func Getrlimit

func Getrlimit(resource int, rlim *Rlimit) (errno int)

func Getrusage
func Getrusage(who int, rusage *Rusage) (errno int)

func Getsid
func Getsid(pid int) (sid int, errno int)

func Gettid
func Gettid() (tid int)

func Gettimeofday
func Gettimeofday(tv *Timeval) (errno int) sys gettimeofday(tp *Timeval) (sec int32, usec int32, errno int)

func Getuid
func Getuid() (uid int)

func Getwd
func Getwd() (wd string, errno int) sys Getcwd(buf []byte) (n int, errno int)

func Ioperm
func Ioperm(from int, num int, on int) (errno int)

func Iopl
func Iopl(level int) (errno int)

func Issetugid
func Issetugid() (tainted bool)

func Kevent
func Kevent(kq int, changes, events []Kevent_t, timeout *Timespec) (n int, errno int)

func Kill
func Kill(pid int, sig int) (errno int)

func Klogctl
func Klogctl(typ int, buf []byte) (n int, errno int)

func Kqueue
func Kqueue() (fd int, errno int)

func Lchown
func Lchown(path string, uid int, gid int) (errno int)

func Link
func Link(oldpath string, newpath string) (errno int)

func Listen
func Listen(s int, backlog int) (errno int)

func Lstat
func Lstat(path string, stat *Stat_t) (errno int)

func Mkdir
func Mkdir(path string, mode int) (errno int)

func Mkdirat
func Mkdirat(dirfd int, path string, mode int) (errno int)

func Mkfifo
func Mkfifo(path string, mode int) (errno int)

func Mknod
func Mknod(path string, mode int, dev int) (errno int)

func Mknodat
func Mknodat(dirfd int, path string, mode int, dev int) (errno int)

func MultimediaInit
func MultimediaInit(subsys int) (errno int)

func MultimediaShutdown
func MultimediaShutdown() (errno int)

func MutexCreate
func MutexCreate() (mutex int, errno int)

func MutexLock
func MutexLock(mutex int) (errno int)

func MutexTryLock
func MutexTryLock(mutex int) (errno int)

func MutexUnlock
func MutexUnlock(mutex int) (errno int)

func Nanosleep
func Nanosleep(time *Timespec, leftover *Timespec) (errno int)

func Open

func Open(path string, mode int, perm int) (fd int, errno int)

func Openat
func Openat(dirfd int, path string, flags int, mode int) (fd int, errno int)

func Pathconf
func Pathconf(path string, name int) (val int, errno int)

func Pause
func Pause() (errno int)

func Pipe
func Pipe(p []int) (errno int) sys pipe(p *[2]_C_int) (errno int)

func PivotRoot
func PivotRoot(newroot string, putold string) (errno int)

func Pread
func Pread(fd int, p []byte, offset int64) (n int, errno int)

func PtraceAttach
func PtraceAttach(pid int) (errno int)

func PtraceCont
func PtraceCont(pid int, signal int) (errno int)

func PtraceDetach
func PtraceDetach(pid int) (errno int)

func PtraceForkExec

func PtraceForkExec(argv0 string, argv []string, envv []string, dir string, fd []int) (pid int, err int) PtraceForkExec is like ForkExec, but starts the child in a traced state.

func PtraceGetEventMsg
func PtraceGetEventMsg(pid int) (msg uint, errno int)

func PtraceGetRegs
func PtraceGetRegs(pid int, regsout *PtraceRegs) (errno int)

func PtracePeekData
func PtracePeekData(pid int, addr uintptr, out []byte) (count int, errno int)

func PtracePeekText
func PtracePeekText(pid int, addr uintptr, out []byte) (count int, errno int)

func PtracePokeData
func PtracePokeData(pid int, addr uintptr, data []byte) (count int, errno int)

func PtracePokeText
func PtracePokeText(pid int, addr uintptr, data []byte) (count int, errno int)

func PtraceSetOptions
func PtraceSetOptions(pid int, options int) (errno int)

func PtraceSetRegs
func PtraceSetRegs(pid int, regs *PtraceRegs) (errno int)

func PtraceSingleStep
func PtraceSingleStep(pid int) (errno int)

func Pwrite
func Pwrite(fd int, p []byte, offset int64) (n int, errno int)

func RawSyscall
func RawSyscall(trap, a1, a2, a3 uintptr) (r1, r2, err uintptr)

func Read
func Read(fd int, p []byte) (n int, errno int)

func Readlink
func Readlink(path string, buf []byte) (n int, errno int)

func Recvfrom
func Recvfrom(fd int, p []byte, flags int) (n int, from Sockaddr, errno int)

func Rename
func Rename(oldpath string, newpath string) (errno int)

func Renameat
func Renameat(olddirfd int, oldpath string, newdirfd int, newpath string) (errno int)

func Revoke
func Revoke(path string) (errno int)

func Rmdir
func Rmdir(path string) (errno int)

func Seek
func Seek(fd int, offset int64, whence int) (newoffset int64, errno int) Underlying system call writes to newoffset via pointer. Implemented in assembly to avoid allocation.

func Select
func Select(nfd int, r *FdSet, w *FdSet, e *FdSet, timeout *Timeval) (n int, errno int)

func SemCreate
func SemCreate() (sema int, errno int)

func SemPost
func SemPost(sema int) (errno int)

func SemWait
func SemWait(sema int) (errno int)

func Sendto
func Sendto(fd int, p []byte, flags int, to Sockaddr) (errno int)

func SetKevent
func SetKevent(k *Kevent_t, fd, mode, flags int)

func SetNonblock
func SetNonblock(fd int, nonblocking bool) (errno int)

func Setdomainname
func Setdomainname(p []byte) (errno int)

func Setegid
func Setegid(egid int) (errno int)

func Seteuid
func Seteuid(euid int) (errno int)

func Setfsgid
func Setfsgid(gid int) (errno int)

func Setfsuid
func Setfsuid(uid int) (errno int)

func Setgid
func Setgid(gid int) (errno int)

func Setgroups
func Setgroups(gids []int) (errno int)

func Sethostname
func Sethostname(p []byte) (errno int)

func Setlogin
func Setlogin(name string) (errno int)

func Setpgid
func Setpgid(pid int, pgid int) (errno int)

func Setpriority
func Setpriority(which int, who int, prio int) (errno int)

func Setprivexec
func Setprivexec(flag int) (errno int)

func Setregid
func Setregid(rgid int, egid int) (errno int)

func Setresgid

func Setresgid(rgid int, egid int, sgid int) (errno int)

func Setresuid
func Setresuid(ruid int, euid int, suid int) (errno int)

func Setreuid
func Setreuid(ruid int, euid int) (errno int)

func Setrlimit
func Setrlimit(resource int, rlim *Rlimit) (errno int)

func Setsid
func Setsid() (pid int)

func SetsockoptInt
func SetsockoptInt(fd, level, opt int, value int) (errno int)

func SetsockoptLinger
func SetsockoptLinger(fd, level, opt int, l *Linger) (errno int)

func SetsockoptTimeval
func SetsockoptTimeval(fd, level, opt int, tv *Timeval) (errno int)

func Settimeofday
func Settimeofday(tv *Timeval) (errno int)

func Setuid
func Setuid(uid int) (errno int)

func Shutdown
func Shutdown(s int, how int) (errno int)

func Sleep
func Sleep(nsec int64) (errno int)

func Socket
func Socket(domain, typ, proto int) (fd, errno int)

func Splice
func Splice(rfd int, roff *int64, wfd int, woff *int64, len int, flags int) (n int64, errno int)

func Stat
func Stat(path string, stat *Stat_t) (errno int)

func Statfs
func Statfs(path string, stat *Statfs_t) (errno int)

func StringArrayPtr
func StringArrayPtr(ss []string) []*byte Convert array of string to array of NUL-terminated byte pointer.

func StringBytePtr
func StringBytePtr(s string) *byte StringBytePtr returns a pointer to a NUL-terminated array of bytes containing the text of s.

func StringByteSlice
func StringByteSlice(s string) []byte StringByteSlice returns a NUL-terminated slice of bytes containing the text of s.

func Symlink
func Symlink(oldpath string, newpath string) (errno int)

func Sync
func Sync()

func SyncFileRange
func SyncFileRange(fd int, off int64, n int64, flags int) (errno int)

func Syscall
func Syscall(trap, a1, a2, a3 uintptr) (r1, r2, err uintptr)

func Syscall6
func Syscall6(trap, a1, a2, a3, a4, a5, a6 uintptr) (r1, r2, err uintptr)

func Sysctl
func Sysctl(name string) (value string, errno int)

func SysctlUint32
func SysctlUint32(name string) (value uint32, errno int)

func Sysinfo
func Sysinfo(info *Sysinfo_t) (errno int)

func Tee
func Tee(rfd int, wfd int, len int, flags int) (n int64, errno int)

func Tgkill
func Tgkill(tgid int, tid int, sig int) (errno int)

func Times
func Times(tms *Tms) (ticks uintptr, errno int)

func TimespecToNsec

func TimespecToNsec(ts Timespec) int64

func TimevalToNsec
func TimevalToNsec(tv Timeval) int64

func Truncate
func Truncate(path string, length int64) (errno int)

func Umask
func Umask(mask int) (oldmask int)

func Uname
func Uname(buf *Utsname) (errno int)

func Undelete
func Undelete(path string) (errno int)

func Unlink
func Unlink(path string) (errno int)

func Unlinkat
func Unlinkat(dirfd int, path string) (errno int)

func Unmount
func Unmount(path string, flags int) (errno int)

func Unshare
func Unshare(flags int) (errno int)

func Ustat
func Ustat(dev int, ubuf *Ustat_t) (errno int)

func Utime
func Utime(path string, buf *Utimbuf) (errno int)

func Utimes
func Utimes(path string, tv []Timeval) (errno int) sys utimes(path string, times *[2]Timeval) (errno int)

func VideoInit
func VideoInit(dx int, dy int) (errno int)

func VideoPollEvent
func VideoPollEvent(ev *byte) (errno int)

func VideoShutdown
func VideoShutdown() (errno int)

func VideoUpdate
func VideoUpdate(data *uint32) (errno int)

func Wait4
func Wait4(pid int, wstatus *WaitStatus, options int, rusage *Rusage) (wpid int, errno int) sys wait4(pid int, wstatus *_C_int, options int, rusage *Rusage) (wpid int, errno int)

func Write
func Write(fd int, p []byte) (n int, errno int)

type Bool
type Bool uint32

func FreeLibrary

func FreeLibrary(handle Module) (ok Bool, errno int)

type Cmsghdr
type Cmsghdr struct { Len uint32 Level int32 Type int32 }

type Dirent
type Dirent Ino Seekoff Reclen Namlen Type Name Pad0 } struct { uint64 uint64 uint16 uint16 uint8 [1024]int8 [3]byte

type EpollEvent
type EpollEvent struct { Events uint32 Fd int32 Pad int32 }

type Fbootstraptransfer_t
type Fbootstraptransfer_t struct { Offset int64 Length uint64 Buffer *byte }

type FdSet
type FdSet struct { Bits [32]int32 }

type Flock_t
type Flock_t struct { Start int64 Len int64 Pid int32 Type int16 Whence int16 }

type Fstore_t
type Fstore_t struct { Flags uint32 Posmode int32 Offset int64 Length int64 Bytesalloc int64 }

type Iovec
type Iovec struct { Base *byte Len uint64 }

type Kevent_t
type Kevent_t struct { Ident uint64 Filter int16 Flags uint16 Fflags uint32 Data int64 Udata *byte }

type Linger
type Linger struct { Onoff int32 Linger int32 }

type Log2phys_t
type Log2phys_t Flags Contigbytes Devoffset } struct { uint32 int64 int64

type Module
type Module uint32

func LoadLibrary
func LoadLibrary(libname string) (handle Module, errno int)

func LoadLibraryA
func LoadLibraryA(libname string) (handle Module, errno int)

type Msghdr
type Msghdr struct { Name *byte Namelen uint32 Pad0 [4]byte Iov *Iovec Iovlen int32 Pad1 [4]byte Control *byte Controllen uint32 Flags int32 }

type PtraceRegs

type PtraceRegs struct { Ebx int32 Ecx int32 Edx int32 Esi int32 Edi int32 Ebp int32 Eax int32 Ds uint16 X__ds uint16 Es uint16 X__es uint16 Fs uint16 X__fs uint16 Gs uint16 X__gs uint16 Orig_eax int32 Eip int32 Cs uint16 X__cs uint16 Eflags int32 Esp int32 Ss uint16 X__ss uint16 }

func (*PtraceRegs) PC
func (r *PtraceRegs) PC() uint64 TODO(kaib): add support for tracing

func (*PtraceRegs) SetPC


func (r *PtraceRegs) SetPC(pc uint64)

type Radvisory_t
type Radvisory_t struct { Offset int64 Count int32 Pad0 [4]byte }

type RawSockaddr
type RawSockaddr struct { Len uint8 Family uint8 Data [14]int8 }

type RawSockaddrAny
type RawSockaddrAny struct { Addr RawSockaddr Pad [92]int8 }

type RawSockaddrInet4
type RawSockaddrInet4 struct { Len uint8 Family uint8 Port uint16 Addr [4]byte /* in_addr */ Zero [8]int8 }

type RawSockaddrInet6
type RawSockaddrInet6 struct { Len uint8 Family uint8 Port uint16 Flowinfo uint32 Addr [16]byte /* in6_addr */ Scope_id uint32 }

type RawSockaddrUnix
type RawSockaddrUnix struct { Len uint8 Family uint8 Path [104]int8 }

type Rlimit
type Rlimit struct { Cur uint64 Max uint64 }

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 Sockaddr
type Sockaddr interface { // contains unexported methods }

func Getpeernam e
func Getpeername(fd int) (sa Sockaddr, errno int)

func Getsocknam e
func Getsockname(fd int) (sa Sockaddr, errno int)

type SockaddrInet4
type SockaddrInet4 struct { Port int Addr [4]byte // contains unexported fields }

type SockaddrInet6
type SockaddrInet6 struct { Port int Addr [16]byte // contains unexported fields }

type SockaddrUnix
type SockaddrUnix struct { Name string // contains unexported fields }

type Stat_t
type Stat_t struct { Dev int32 Mode uint16 Nlink uint16 Ino uint64 Uid uint32 Gid uint32 Rdev int32 Pad0 [4]byte Atimespec Timespec Mtimespec Timespec Ctimespec Timespec Birthtimespec Timespec Size int64 Blocks int64 Blksize int32 Flags uint32 Gen uint32 Lspare int32 Qspare [2]int64 }

type Statfs_t
type Statfs_t struct { Bsize uint32 Iosize int32 Blocks uint64 Bfree uint64 Bavail uint64 Files uint64 Ffree uint64 Fsid [8]byte /* fsid */ Owner uint32 Type uint32 Flags uint32 Fssubtype uint32 Fstypename [16]int8 Mntonname [1024]int8 Mntfromname [1024]int8 Reserved [8]uint32 }

type Sysinfo_t
type Sysinfo_t struct { Uptime int32 Loads [3]uint32 Totalram uint32 Freeram uint32 Sharedram uint32 Bufferram uint32 Totalswap uint32 Freeswap uint32 Procs uint16 Pad uint16 Totalhigh uint32 Freehigh uint32 Unit uint32 X_f [8]int8 }

type Time_t
type Time_t int32

func Tim e
func Time(t *Time_t) (tt Time_t, errno int)

type Timespec
type Timespec struct { Sec int64 Nsec int64 }

func NsecToTim espec


func NsecToTimespec(nsec int64) (ts Timespec)

type Timeval
type Timeval struct { Sec int64 Usec int32 Pad0 [4]byte }

func NsecToTim eval


func NsecToTimeval(nsec int64) (tv Timeval)

type Timex
type Timex struct { Modes uint32 Offset int32 Freq int32 Maxerror int32 Esterror int32 Status int32 Constant int32 Precision int32 Tolerance int32 Time Timeval Tick int32 Ppsfreq int32 Jitter int32 Shift int32 Stabil int32 Jitcnt int32 Calcnt int32 Errcnt int32 Stbcnt int32 Pad0 int32 Pad1 int32 Pad2 int32 Pad3 int32 Pad4 int32 Pad5 int32 Pad6 int32 Pad7 int32 Pad8 int32 Pad9 int32 Pad10 int32 Pad11 int32 }

type Tms
type Tms struct { Utime int32 Stime int32 Cutime int32 Cstime int32 }

type Ustat_t
type Ustat_t struct { Tfree int32 Tinode uint32 Fname [6]int8 Fpack [6]int8 }

type Utimbuf
type Utimbuf struct { Actime int32 Modtime int32 }

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) CoreDum p


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() int

func (WaitStatus) Signaled


func (w WaitStatus) Signaled() bool

func (WaitStatus) StopSignal


func (w WaitStatus) StopSignal() int

func (WaitStatus) Stopped

func (w WaitStatus) Stopped() bool

func (WaitStatus) TrapCause


func (w WaitStatus) TrapCause() int

Except as noted, this content is licensed under Creative Commons Attribution 3.0.

The Go Programming Language

Package syslog
func NewLogger type Priority type Writer func Dial func New func (*Writer) Close func (*Writer) Crit func (*Writer) Debug import "syslog" The syslog package provides a simple interface to the system log service. It can send messages to the syslog daemon using UNIX domain sockets, UDP, or TCP connections. Package files
sy slog.go

func (*Writer) Emerg func (*Writer) Err func (*Writer) Info func (*Writer) Notice func (*Writer) Warning func (*Writer) Write

func NewLogger
func NewLogger(p Priority, flag int) *log.Logger NewLogger provides an object that implements the full log.Logger interface, but sends messages to Syslog instead; flag is passed as is to Logger; priority will be used for all messages sent using this interface. All messages are logged with priority p.

type Priority
type Priority int

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 )

type Writer
A Writer is a connection to a syslog server.
type Writer struct { // contains unexported fields }

func Dial
func Dial(network, raddr string, priority Priority, prefix string) (w *Writer, err os.Error) Dial establishes a connection to a log daemon by connecting to address raddr on the network net. Each write to the returned writer sends a log message with the given priority and prefix.

func New
func New(priority Priority, prefix string) (w *Writer, err os.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) Close


func (w *Writer) Close() os.Error

func (*Writer) Crit


func (w *Writer) Crit(m string) (err os.Error) Crit logs a message using the LOG_CRIT priority.

func (*Writer) Debug


func (w *Writer) Debug(m string) (err os.Error) Debug logs a message using the LOG_DEBUG priority.

func (*Writer) Em erg


func (w *Writer) Emerg(m string) (err os.Error) Emerg logs a message using the LOG_EMERG priority.

func (*Writer) Err


func (w *Writer) Err(m string) (err os.Error) ERR logs a message using the LOG_ERR priority.

func (*Writer) Info


func (w *Writer) Info(m string) (err os.Error) Info logs a message using the LOG_INFO priority.

func (*Writer) Notice

func (w *Writer) Notice(m string) (err os.Error) Notice logs a message using the LOG_NOTICE priority.

func (*Writer) Warning


func (w *Writer) Warning(m string) (err os.Error) Warning logs a message using the LOG_WARNING priority.

func (*Writer) Write


func (w *Writer) Write(b []byte) (int, os.Error) Write sends a log message to the syslog daemon.

Except as noted, this content is licensed under Creative Commons Attribution 3.0.

The Go Programming Language

Package tabwriter
Constants type Writer func NewWriter func (*Writer) Flush func (*Writer) Init func (*Writer) Write import "tabwriter" The tabwriter package implements a write filter (tabwriter.Writer) that translates tabbed columns in input into properly aligned text. The package is using the Elastic Tabstops algorithm described at http://nickgravgaard.com/elastictabstops /index.html. Package files
tabwriter.go

Constants
Formatting can be controlled with these flags.
const ( // Ignore html tags and treat entities (starting with '&' // and ending in ';') as single characters (width = 1). FilterHTML uint = 1 << iota // Force right-alignment of cell content. // Default is left-alignment. AlignRight // Handle empty columns as if they were not present in // the input in the first place. DiscardEmptyColumns // Always use tabs for indentation columns (i.e., padding of // leading empty cells on the left) independent of padchar. TabIndent // Print a vertical bar ('|') between columns (after formatting). // Discarded colums appear as zero-width columns ("||"). Debug )

To escape a text segment, bracket it with Escape characters. For instance, the tab in this string "Ignore this tab: \xff\t\xff" does not terminate a cell and constitutes a single character of width one for formatting purposes.

The value 0xff was chosen because it cannot appear in a valid UTF-8 sequence.
const Escape = '\xff'

type Writer
A Writer is a filter that inserts padding around tab-delimited columns in its input to align them in the output. The Writer treats incoming bytes as UTF-8 encoded text consisting of cells terminated by (horizontal or vertical) tabs or line breaks (newline or formfeed characters). Cells in adjacent lines constitute a column. The Writer inserts padding as needed to make all cells in a column have the same width, effectively aligning the columns. It assumes that all characters have the same width except for tabs for which a tabwidth must be specified. Note that cells are tab-terminated, not tab-separated: trailing non-tab text at the end of a line does not form a column cell. If DiscardEmptyColumns is set, empty columns that are terminated entirely by vertical (or "soft") tabs are discarded. Columns terminated by horizontal (or "hard") tabs are not affected by this flag. A segment of text may be escaped by bracketing it with Escape characters. The tabwriter strips the Escape characters but otherwise passes escaped text segments through unchanged. In particular, it does not interpret any tabs or line breaks within the segment. The Writer assumes that all characters have the same width; this may not be true in some fonts, especially with certain UTF-8 characters. If a Writer is configured to filter HTML, HTML tags and entities are simply passed through. The widths of tags and entities are assumed to be zero (tags) and one (entities) for formatting purposes. The formfeed character ('\f') acts like a newline but it also terminates all columns in the current line (effectively calling Flush). Cells in the next line start new columns. Unless found inside an HTML tag or inside an escaped text segment, formfeed characters appear as newlines in the output. The Writer must buffer input internally, because proper spacing of one line may depend on the cells in future lines. Clients must call Flush when done calling Write.
type Writer struct { // contains unexported fields }

func New Writer


func NewWriter(output io.Writer, minwidth, tabwidth, padding int, padchar byte, flags uint) *Writer NewWriter allocates and initializes a new tabwriter.Writer. The parameters are the same as for the the Init function.

func (*Writer) Flush


func (b *Writer) Flush() os.Error Flush should be called after the last call to Write to ensure that any data buffered in the Writer is written to output. Any incomplete escape sequence at the end is simply considered complete for formatting purposes.

func (*Writer) Init

func (b *Writer) Init(output io.Writer, minwidth, tabwidth, padding int, padchar byte, flags uint) *Writer A Writer must be initialized with a call to Init. The first parameter (output) specifies the filter output. The remaining parameters control the formatting:
minwidth minimal cell width including any padding tabwidth width of tab characters (equivalent number of spaces) padding padding added to a cell before computing its width padchar ASCII char used for padding if padchar == '\t', the Writer will assume that the width of a '\t' in the formatted output is tabwidth, and cells are left-aligned independent of align_left (for correct-looking results, tabwidth must correspond to the tab width in the viewer displaying the result) flags formatting control

To format in tab-separated columns with a tab stop of 8:


b.Init(w, 8, 1, 8, '\t', 0);

To format in space-separated columns with at least 4 spaces between columns:


b.Init(w, 0, 4, 8, ' ', 0);

func (*Writer) Write


func (b *Writer) Write(buf []byte) (n int, err os.Error) Write writes buf to the writer b. The only errors returned are ones encountered while writing to the underlying output stream.

Except as noted, this content is licensed under Creative Commons Attribution 3.0.

The Go Programming Language

Package template
func HTMLEscape func HTMLFormatter func StringFormatter type Error func (*Error) String type FormatterMap type Template func MustParse func MustParseFile import "template" Data-driven templates for generating textual output such as HTML. See
http://code.google.com/p/json-template/wiki/Reference

func New func Parse func ParseFile func (*Template) Execute func (*Template) Parse func (*Template) SetDelims

for full documentation of the template language. A summary: Templates are executed by applying them to a data structure. Annotations in the template refer to elements of the data structure (typically a field of a struct or a key in a map) to control execution and derive values to be displayed. The template walks the structure as it executes and the "cursor" @ represents the value at the current location in the structure. Data items may be values or pointers; the interface hides the indirection. In the following, 'field' is one of several things, according to the data. - the name of a field of a struct (result = data.field) - the value stored in a map under that key (result = data[field]) - the result of invoking a niladic single-valued method with that name
(result = data.field())

Major constructs ({} are metacharacters; [] marks optional elements):


{# comment }

A one-line comment.
{.section field} XXX [ {.or} YYY ] {.end}

Set @ to the value of the field. It may be an explicit @ to stay at the same point in the data. If the field is nil or empty, execute YYY; otherwise execute XXX.
{.repeated section field} XXX [ {.alternates with} ZZZ ] [ {.or} YYY ] {.end}

Like .section, but field must be an array or slice. XXX is executed for each element. If the array is nil or empty, YYY is executed instead. If the {.alternates with} marker is present, ZZZ is executed between iterations of XXX.
{field} {field|formatter}

Insert the value of the field into the output. Field is first looked for in the cursor, as in .section and .repeated. If it is not found, the search continues in outer sections until the top level is reached. If a formatter is specified, it must be named in the formatter map passed to the template set up routines or in the default set ("html","str","") and is used to process the data for output. The formatter function has signature
func(wr io.Write, data interface{}, formatter string)

where wr is the destination for output, data is the field value, and formatter is its name at the invocation site. Package files
f ormat.go template.go

func HTMLEscape
func HTMLEscape(w io.Writer, s []byte) HTMLEscape writes to w the properly escaped HTML equivalent of the plain text data s.

func HTMLFormatter
func HTMLFormatter(w io.Writer, value interface{}, format string) HTMLFormatter formats arbitrary values for HTML

func StringFormatter
func StringFormatter(w io.Writer, value interface{}, format string) StringFormatter formats into the default string representation. It is stored under the name "str" and is the default formatter. You can override the default formatter by storing your default under the name "" in your custom formatter map.

type Error
Errors returned during parsing and execution. Users may extract the information and reformat if they desire.
type Error struct { Line int Msg string }

func (*Error) String


func (e *Error) String() string

type FormatterMap
FormatterMap is the type describing the mapping from formatter names to the functions that implement them.
type FormatterMap map[string]func(io.Writer, interface{}, string)

type Template
Template is the type that represents a template definition. It is unchanged after parsing.
type Template struct { // contains unexported fields }

func MustParse
func MustParse(s string, fmap FormatterMap) *Template MustParse is like Parse but panics if the template cannot be parsed.

func MustParseFile
func MustParseFile(filename string, fmap FormatterMap) *Template MustParseFile is like ParseFile but panics if the file cannot be read or the template cannot be parsed.

func New
func New(fmap FormatterMap) *Template New creates a new template with the specified formatter map (which may be nil) to define auxiliary functions for formatting variables.

func Parse
func Parse(s string, fmap FormatterMap) (t *Template, err os.Error) Parse creates a Template with default parameters (such as {} for metacharacters). The string s contains the template text while the formatter map fmap, which may be nil, defines auxiliary functions for formatting variables. The template is returned. If any errors occur, err will be non-nil.

func ParseFile
func ParseFile(filename string, fmap FormatterMap) (t *Template, err os.Error) ParseFile is a wrapper function that creates a Template with default parameters (such as {} for // metacharacters). The filename identfies a file containing the template text, while the formatter map fmap, which may be nil, defines auxiliary functions for formatting variables. The template is returned. If any errors occur, err will be non-nil.

func (*Tem plate) Execute


func (t *Template) Execute(data interface{}, wr io.Writer) os.Error Execute applies a parsed template to the specified data object, generating output to wr.

func (*Tem plate) Parse


func (t *Template) Parse(s string) os.Error Parse initializes a Template by parsing its definition. The string s contains the template text. If any errors occur, Parse returns the error.

func (*Tem plate) SetDelim s


func (t *Template) SetDelims(left, right string) SetDelims sets the left and right delimiters for operations in the template. They are validated during parsing. They could be validated here but it's better to keep the routine simple. The delimiters are very rarely invalid and Parse has the necessary error-handling interface already.

Except as noted, this content is licensed under Creative Commons Attribution 3.0.

The Go Programming Language

Package testing
Variables func Main func Match func MatchString func RunBenchmarks type B func (*B) ResetTimer func (*B) SetBytes func (*B) StartTimer func (*B) StopTimer type Benchmark type Regexp func CompileRegexp func MustCompile func (*Regexp) Execute func (*Regexp) ExecuteString func (*Regexp) Match import "testing" The testing package provides support for automated testing of Go packages. It is intended to be used in concert with the gotest utility, which automates execution of any function of the form
func TestXxx(*testing.T)

func (*Regexp) MatchSlices func (*Regexp) MatchString func (*Regexp) MatchStrings type T func (*T) Error func (*T) Errorf func (*T) Fail func (*T) FailNow func (*T) Failed func (*T) Fatal func (*T) Fatalf func (*T) Log func (*T) Logf type Test Subdirectories

where Xxx can be any alphanumeric string (but the first letter must not be in [a-z]) and serves to identify the test routine. These TestXxx routines should be declared within the package they are testing. Functions of the form
func BenchmarkXxx(*testing.B)

are considered benchmarks, and are executed by gotest when the -benchmarks flag is provided. A sample benchmark function looks like this:
func BenchmarkHello(b *testing.B) { for i := 0; i < b.N; i++ { fmt.Sprintf("hello") } }

The benchmark package will vary b.N until the benchmark function lasts long enough to be timed reliably. The output

testing.BenchmarkHello

500000

4076 ns/op

means that the loop ran 500000 times at a speed of 4076 ns per loop. If a benchmark needs some expensive setup before running, the timer may be stopped:
func BenchmarkBigLen(b *testing.B) { b.StopTimer(); big := NewBig(); b.StartTimer(); for i := 0; i < b.N; i++ { big.Len(); } }

Package files
benchmark.go regexp.go testing.go

Variables
Error codes returned by failures to parse an expression.
var ( ErrInternal ErrUnmatchedLpar ErrUnmatchedRpar ErrUnmatchedLbkt ErrUnmatchedRbkt ErrBadRange ErrExtraneousBackslash ErrBadClosure ErrBareClosure ErrBadBackslash )

= = = = = = = = = =

"internal error" "unmatched ''" "unmatched ''" "unmatched '['" "unmatched ']'" "bad range in character class" "extraneous backslash" "repeated closure **, ++, etc." "closure applies to nothing" "illegal backslash escape"

func Main
func Main(tests []Test) An internal function but exported because it is cross-package; part of the implementation of gotest.

func Match
func Match(pattern string, b []byte) (matched bool, error string) Match checks whether a textual regular expression matches a byte slice. More complicated queries need to use Compile and the full Regexp interface.

func MatchString

func MatchString(pattern string, s string) (matched bool, error string) MatchString checks whether a textual regular expression matches a string. More complicated queries need to use Compile and the full Regexp interface.

func RunBenchmarks
func RunBenchmarks(benchmarks []Benchmark) An internal function but exported because it is cross-package; part of the implementation of gotest.

type B
B is a type passed to Benchmark functions to manage benchmark timing and to specify the number of iterations to run.
type B struct { N int // contains unexported fields }

func (*B) ResetTim er


func (b *B) ResetTimer() ResetTimer stops the timer and sets the elapsed benchmark time to zero.

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) StartTim er


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) StopTim er


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 Benchmark
An internal type but exported because it is cross-package; part of the implementation of gotest.

type Benchmark struct { Name string F func(b *B) }

type Regexp
The representation of a compiled regular expression. The public interface is entirely through methods.
type Regexp struct { // contains unexported fields }

func Com pileRegexp


func CompileRegexp(str string) (regexp *Regexp, error string) CompileRegexp parses a regular expression and returns, if successful, a Regexp object that can be used to match against text.

func MustCom pile


func MustCompile(str string) *Regexp MustCompileRegexp is like CompileRegexp but panics if the expression cannot be parsed. It simplifies safe initialization of global variables holding compiled regular expressions.

func (*Regexp) Execute


func (re *Regexp) Execute(b []byte) (a []int) Execute matches the Regexp against the byte slice b. The return value is an array of integers, in pairs, identifying the positions of subslices matched by the expression.
b[a[0]:a[1]] is the subslice matched by the entire expression. b[a[2*i]:a[2*i+1]] for i > 0 is the subslice matched by the ith parenthesized subexpression.

A negative value means the subexpression did not match any element of the slice. An empty array means "no match".

func (*Regexp) ExecuteString


func (re *Regexp) ExecuteString(s string) (a []int) ExecuteString matches the Regexp against the string s. The return value is an array of integers, in pairs, identifying the positions of substrings matched by the expression.
s[a[0]:a[1]] is the substring matched by the entire expression. s[a[2*i]:a[2*i+1]] for i > 0 is the substring matched by the ith parenthesized subexpression.

A negative value means the subexpression did not match any element of the string. An empty array means "no match".

func (*Regexp) Match


func (re *Regexp) Match(b []byte) bool Match returns whether the Regexp matches the byte slice b. The return value is a boolean: true for match, false for no match.

func (*Regexp) MatchSlices


func (re *Regexp) MatchSlices(b []byte) (a [][]byte) MatchSlices matches the Regexp against the byte slice b. The return value is an array of subslices matched by the expression.
a[0] is the subslice matched by the entire expression. a[i] for i > 0 is the subslice matched by the ith parenthesized subexpression.

An empty array means no match.

func (*Regexp) MatchString


func (re *Regexp) MatchString(s string) bool MatchString returns whether the Regexp matches the string s. The return value is a boolean: true for match, false for no match.

func (*Regexp) MatchStrings


func (re *Regexp) MatchStrings(s string) (a []string) MatchStrings matches the Regexp against the string s. The return value is an array of strings matched by the expression.
a[0] is the substring matched by the entire expression. a[i] for i > 0 is the substring matched by the ith parenthesized subexpression.

An empty array means no match.

type T
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.
type T struct { // contains unexported fields }

func (*T) Error


func (t *T) Error(args ...interface{}) Error is equivalent to Log() followed by Fail().

func (*T) Errorf

func (t *T) Errorf(format string, args ...interface{}) Errorf is equivalent to Logf() followed by Fail().

func (*T) Fail


func (t *T) Fail() Fail marks the Test function as having failed but continues execution.

func (*T) FailNow


func (t *T) FailNow() FailNow marks the Test function as having failed and stops its execution. Execution will continue at the next Test.

func (*T) Failed


func (t *T) Failed() bool Failed returns whether the Test function has failed.

func (*T) Fatal


func (t *T) Fatal(args ...interface{}) Fatal is equivalent to Log() followed by FailNow().

func (*T) Fatalf


func (t *T) Fatalf(format string, args ...interface{}) Fatalf is equivalent to Logf() followed by FailNow().

func (*T) Log


func (t *T) Log(args ...interface{}) Log formats its arguments using default formatting, analogous to Print(), and records the text in the error log.

func (*T) Logf


func (t *T) Logf(format string, args ...interface{}) Log formats its arguments according to the format, analogous to Printf(), and records the text in the error log.

type Test
An internal type but exported because it is cross-package; part of the implementation of gotest.
type Test struct { Name string F func(*T) }

Subdirectories
Name .. iotest quick script Synopsis The iotest package implements Readers and Writers useful only for testing. This package implements utility functions to help with black box testing. This package aids in the testing of code that uses channels.

Except as noted, this content is licensed under Creative Commons Attribution 3.0.

The Go Programming Language

Package iotest
func DataErrReader func HalfReader func NewReadLogger func NewWriteLogger func OneByteReader func TruncateWriter import "testing/iotest" The iotest package implements Readers and Writers useful only for testing. Package files
logger.go reader.go writer.go

func DataErrReader
func DataErrReader(r io.Reader) io.Reader DataErrReader returns a Reader that returns the final error with the last data read, instead of by itself with zero bytes of 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.Stdout) each read to standard output, printing the prefix and the hexadecimal data written.

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.Stdout) each write to standard output, 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 TruncateWriter
func TruncateWriter(w io.Writer, n int64) io.Writer TruncateWriter returns a Writer that writes to w but stops silently after n bytes.

Except as noted, this content is licensed under Creative Commons Attribution 3.0.

The Go Programming Language

Package quick
func Check func CheckEqual func Value type CheckEqualError func (*CheckEqualError) String type CheckError func (*CheckError) String type Config type Generator type SetupError func (SetupError) String import "testing/quick" This package implements utility functions to help with black box testing. Package files
quick.go

func Check
func Check(function interface{}, config *Config) (err os.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 os.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: in order to create arbitrary values for structs, all the members must be public.

type CheckEqualError
A CheckEqualError is the result CheckEqual finding an error.
type CheckEqualError struct { CheckError Out1 []interface{} Out2 []interface{} }

func (*CheckEqualError) String


func (s *CheckEqualError) String() string

type CheckError
A CheckError is the result of Check finding an error.
type CheckError struct { Count int In []interface{} }

func (*CheckError) String


func (s *CheckError) String() string

type Config
A Config structure contains options for running a test.

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 float // 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, Values is a function which generates a slice of arbitrary // Values that are congruent with the arguments to the function being // tested. Otherwise, Values is used to generate the values. Values func([]reflect.Value, *rand.Rand) }

type Generator
A Generator can generate random values of its own type.
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 }

type SetupError
A SetupError is the result of an error in the way that check is being used, independent of the functions being tested.
type SetupError string

func (SetupError) String


func (s SetupError) String() string

Except as noted, this content is licensed under Creative Commons Attribution 3.0.

The Go Programming Language

Package script
func Perform type Close type Closed type Event func NewEvent type ReceivedUnexpected func (ReceivedUnexpected) String type Recv type RecvMatch type Send type SetupError func (SetupError) String import "testing/script" This package aids in the testing of code that uses channels. Package files
script.go

func Perform
func Perform(seed int64, events []*Event) (err os.Error) Given a set of Events, Perform repeatedly iterates over the set and finds the subset of ready Events (that is, all of their predecessors have occurred). From that subset, it pseudo-randomly selects an Event to perform. If the Event is a send event, the send occurs and Perform recalculates the ready set. If the event is a receive event, Perform waits for a value from any of the channels that are contained in any of the events. That value is then matched against the ready events. The first event that matches is considered to have occurred and Perform recalculates the ready set. Perform continues this until all Events have occurred. Note that uncollected goroutines may still be reading from any of the channels read from after Perform returns. For example, consider the problem of testing a function that reads values on one channel and echos them to two output channels. To test this we would create three events: a send event and two receive events. Each of the receive events must list the send event as a predecessor but there is no ordering between the receive events.
send := NewEvent("send", nil, Send{c, 1}); recv1 := NewEvent("recv 1", []*Event{send}, Recv{c, 1}); recv2 := NewEvent("recv 2", []*Event{send}, Recv{c, 1}); Perform(0, []*Event{send, recv1, recv2});

At first, only the send event would be in the ready set and thus Perform will send a value to the input channel. Now the two receive events are ready and Perform will match each of them against the values read from the output channels. It would be invalid to list one of the receive events as a predecessor of the other. At each receive step, all the receive channels are considered, thus Perform may see a value from a channel that is not in the current ready set and fail.

type Close
A Close action closes the given channel.
type Close struct { Channel interface{} }

type Closed
A Closed action matches if the given channel is closed. The closing is treated as an event, not a state, thus Closed will only match once for a given channel.
type Closed struct { Channel interface{} }

type Event
An Event is an element in a partially ordered set that either sends a value to a channel or expects a value from a channel.
type Event struct { // contains unexported fields }

func New Event


func NewEvent(name string, predecessors []*Event, action action) *Event

type ReceivedUnexpected
A ReceivedUnexpected error results if no active Events match a value received from a channel.
type ReceivedUnexpected struct { Value interface{} // contains unexported fields }

func (ReceivedUnexpected) String


func (r ReceivedUnexpected) String() string

type Recv
A Recv action reads a value from a channel and uses reflect.DeepMatch to compare it with an expected value.
type Recv struct { Channel interface{} Expected interface{} }

type RecvMatch
A RecvMatch action reads a value from a channel and calls a function to determine if the value matches.
type RecvMatch struct { Channel interface{} Match func(interface{}) bool }

type Send
A Send action sends a value to a channel. The value must match the type of the channel exactly unless the channel if of type chan interface{}.
type Send struct { Channel interface{} Value interface{} }

type SetupError
A SetupError results if there is a error with the configuration of a set of Events.
type SetupError string

func (SetupError) String


func (s SetupError) String() string

Except as noted, this content is licensed under Creative Commons Attribution 3.0.

The Go Programming Language

Package time
Constants func Nanoseconds func Seconds func Sleep func Tick type ParseError func (*ParseError) String type Ticker func NewTicker func (*Ticker) Stop type Time import "time" The time package provides functionality for measuring and displaying time. Package files
f ormat.go sleep.go tick.go time.go zoneinf o.go

func LocalTime func Parse func SecondsToLocalTime func SecondsToUTC func UTC func (*Time) Format func (*Time) Seconds func (*Time) String

Constants
These are predefined layouts for use in Time.Format. The standard time used in the layouts is:
Mon Jan 2 15:04:05 MST 2006 (MST is GMT-0700)

which is Unix time 1136243045. (Think of it as 01/02 03:04:05PM '06 -0700.) 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.
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 1504 MST" // RFC822 with Zulu time. RFC822Z = "02 Jan 06 1504 -0700" RFC850 = "Monday, 02-Jan-06 15:04:05 MST" RFC1123 = "Mon, 02 Jan 2006 15:04:05 MST" Kitchen = "3:04PM" // Special case: use Z to get the time zone formatted according to ISO 8601, // which is -0700 or Z for UTC ISO8601 = "2006-01-02T15:04:05Z" )

Days of the week.

const ( Sunday = iota Monday Tuesday Wednesday Thursday Friday Saturday )

func Nanoseconds
func Nanoseconds() int64 Nanoseconds reports the number of nanoseconds since the Unix epoch, January 1, 1970 00:00:00 UTC.

func Seconds
func Seconds() int64 Seconds reports the number of seconds since the Unix epoch, January 1, 1970 00:00:00 UTC.

func Sleep
func Sleep(ns int64) os.Error Sleep pauses the current goroutine for at least ns nanoseconds. Higher resolution sleeping may be provided by syscall.Nanosleep on some operating systems.

func Tick
func Tick(ns int64) <-chan int64 Tick is a convenience wrapper for NewTicker providing access to the ticking channel only. Useful for clients that have no need to shut down the ticker.

type ParseError
ParseError describes a problem parsing a time string.
type ParseError struct { Layout string Value string LayoutElem string ValueElem string Message string }

func (*ParseError) String

func (e *ParseError) String() string String is the string representation of a ParseError.

type Ticker
A Ticker holds a synchronous channel that delivers `ticks' of a clock at intervals.
type Ticker struct { C <-chan int64 // The channel on which the ticks are delivered. // contains unexported fields }

func New Ticker


func NewTicker(ns int64) *Ticker Ticker returns a new Ticker containing a channel that will send the time, in nanoseconds, every ns nanoseconds. It adjusts the intervals to make up for pauses in delivery of the ticks.

func (*Ticker) Stop


func (t *Ticker) Stop() Stop turns off a ticker. After Stop, no more ticks will be sent.

type Time
Time is the struct representing a parsed time value.
type Time struct { Year Month, Day Hour, Minute, Second Weekday ZoneOffset Zone }

int64 // int // int // int // int // string

2008 is 2008 Sep-17 is 9, 17 10:43:12 is 10, 43, 12 Sunday, Monday, ... seconds east of UTC

func LocalTim e
func LocalTime() *Time LocalTime returns the current time as a parsed Time value in the local time zone.

func Parse
func Parse(alayout, avalue string) (*Time, os.Error) Parse parses a formatted string and returns the time value it represents. The layout defines the format by showing the representation of a standard time, which is then used to describe the string to be parsed. Predefined layouts ANSIC, UnixDate, ISO8601 and others describe standard representations. Only those elements present in the value will be set in the returned time structure. Also, if the input string

represents an inconsistent time (such as having the wrong day of the week), the returned value will also be inconsistent. In any case, the elements of the returned time will be sane: hours in 0..23, minutes in 0..59, day of month in 0..31, etc.

func SecondsToLocalTim e
func SecondsToLocalTime(sec int64) *Time SecondsToLocalTime converts sec, in number of seconds since the Unix epoch, into a parsed Time value in the local time zone.

func SecondsToUTC
func SecondsToUTC(sec int64) *Time SecondsToUTC converts sec, in number of seconds since the Unix epoch, into a parsed Time value in the UTC time zone.

func UTC
func UTC() *Time UTC returns the current time as a parsed Time value in the UTC time zone.

func (*Tim e) Form at


func (t *Time) Format(layout string) string Format returns a textual representation of the time value formatted according to layout. The layout defines the format by showing the representation of a standard time, which is then used to describe the time to be formatted. Predefined layouts ANSIC, UnixDate, ISO8601 and others describe standard representations.

func (*Tim e) Seconds


func (t *Time) Seconds() int64 Seconds returns the number of seconds since January 1, 1970 represented by the parsed Time value.

func (*Tim e) String


func (t *Time) String() string String returns a Unix-style representation of the time value.

Except as noted, this content is licensed under Creative Commons Attribution 3.0.

The Go Programming Language

Package unicode
Constants Variables func Is func IsDigit func IsLetter func IsLower func IsSpace func IsTitle func IsUpper func To func ToLower func ToTitle func ToUpper type CaseRange type Range Other packages

import "unicode" This package provides data and functions to test some properties of Unicode code points. Package files
digit.go letter.go tables.go

Constants
const ( MaxRune = 0x10FFFF // Maximum valid Unicode code point. ReplacementChar = 0xFFFD // Represents invalid code points. )

Indices into the Delta arrays inside CaseRanges for case mapping.
const ( UpperCase = iota LowerCase TitleCase MaxCase )

If the Delta field of a CaseRange is UpperLower or LowerUpper, it means this CaseRange represents a sequence of the form (say) Upper Lower Upper Lower.
const ( UpperLower = MaxRune + 1 // (Cannot be a valid delta.) )

Version is the Unicode edition from which the tables are derived.
const Version = "5.2.0"

Variables
var ( Cc Cf Co Cs Digit Nd Letter Lm Lo Lower Ll Mc Me Mn Nl No Pc Pd Pe Pf Pi Po Ps Sc Sk Sm So Title Lt Upper Lu Zl Zp Zs ) = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = _Cc _Cf _Co _Cs _Nd _Nd letter _Lm _Lo _Ll _Ll _Mc _Me _Mn _Nl _No _Pc _Pd _Pe _Pf _Pi _Po _Ps _Sc _Sk _Sm _So _Lt _Lt _Lu _Lu _Zl _Zp _Zs // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // Cc is the set of Unicode characters in Cf is the set of Unicode characters in Co is the set of Unicode characters in Cs is the set of Unicode characters in Digit is the set of Unicode characters Nd is the set of Unicode characters in Letter is the set of Unicode letters. Lm is the set of Unicode characters in Lo is the set of Unicode characters in Lower is the set of Unicode lower case Ll is the set of Unicode characters in Mc is the set of Unicode characters in Me is the set of Unicode characters in Mn is the set of Unicode characters in Nl is the set of Unicode characters in No is the set of Unicode characters in Pc is the set of Unicode characters in Pd is the set of Unicode characters in Pe is the set of Unicode characters in Pf is the set of Unicode characters in Pi is the set of Unicode characters in Po is the set of Unicode characters in Ps is the set of Unicode characters in Sc is the set of Unicode characters in Sk is the set of Unicode characters in Sm is the set of Unicode characters in So is the set of Unicode characters in Title is the set of Unicode title case Lt is the set of Unicode characters in Upper is the set of Unicode upper case Lu is the set of Unicode characters in Zl is the set of Unicode characters in Zp is the set of Unicode characters in Zs is the set of Unicode characters in category category category category with the category category category letters. category category category category category category category category category category category category category category category category category letters. category letters. category category category category Cc. Cf. Co. Cs. "decimal digit" property. Nd. Lm. Lo. Ll. Mc. Me. Mn. Nl. No. Pc. Pd. Pe. Pf. Pi. Po. Ps. Sc. Sk. Sm. So. Lt. Lu. Zl. Zp. Zs.

var ( Arabic Armenian Avestan Balinese Bamum Bengali Bopomofo Braille Buginese Buhid Canadian_Aboriginal Carian Cham Cherokee Common Coptic Cuneiform Cypriot Cyrillic Deseret Devanagari Egyptian_Hieroglyphs Ethiopic Georgian Glagolitic Gothic Greek Gujarati Gurmukhi Han Hangul Hanunoo Hebrew Hiragana Imperial_Aramaic Inherited Inscriptional_Pahlavi Inscriptional_Parthian Javanese Kaithi Kannada Katakana Kayah_Li Kharoshthi Khmer Lao Latin Lepcha Limbu Linear_B Lisu Lycian Lydian Malayalam Meetei_Mayek Mongolian Myanmar New_Tai_Lue Nko Ogham Ol_Chiki Old_Italic Old_Persian Old_South_Arabian Old_Turkic

= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =

_Arabic _Armenian _Avestan _Balinese _Bamum _Bengali _Bopomofo _Braille _Buginese _Buhid _Canadian_Aboriginal _Carian _Cham _Cherokee _Common _Coptic _Cuneiform _Cypriot _Cyrillic _Deseret _Devanagari _Egyptian_Hieroglyphs _Ethiopic _Georgian _Glagolitic _Gothic _Greek _Gujarati _Gurmukhi _Han _Hangul _Hanunoo _Hebrew _Hiragana _Imperial_Aramaic _Inherited _Inscriptional_Pahlavi _Inscriptional_Parthian _Javanese _Kaithi _Kannada _Katakana _Kayah_Li _Kharoshthi _Khmer _Lao _Latin _Lepcha _Limbu _Linear_B _Lisu _Lycian _Lydian _Malayalam _Meetei_Mayek _Mongolian _Myanmar _New_Tai_Lue _Nko _Ogham _Ol_Chiki _Old_Italic _Old_Persian _Old_South_Arabian _Old_Turkic

// // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // //

Arabic is the set of Unicode characters in script Arabi Armenian is the set of Unicode characters in script Arm Avestan is the set of Unicode characters in script Aves Balinese is the set of Unicode characters in script Bal Bamum is the set of Unicode characters in script Bamum. Bengali is the set of Unicode characters in script Beng Bopomofo is the set of Unicode characters in script Bop Braille is the set of Unicode characters in script Brai Buginese is the set of Unicode characters in script Bug Buhid is the set of Unicode characters in script Buhid. Canadian_Aboriginal is the set of Unicode characters in Carian is the set of Unicode characters in script Caria Cham is the set of Unicode characters in script Cham. Cherokee is the set of Unicode characters in script Che Common is the set of Unicode characters in script Commo Coptic is the set of Unicode characters in script Copti Cuneiform is the set of Unicode characters in script Cu Cypriot is the set of Unicode characters in script Cypr Cyrillic is the set of Unicode characters in script Cyr Deseret is the set of Unicode characters in script Dese Devanagari is the set of Unicode characters in script D Egyptian_Hieroglyphs is the set of Unicode characters i Ethiopic is the set of Unicode characters in script Eth Georgian is the set of Unicode characters in script Geo Glagolitic is the set of Unicode characters in script G Gothic is the set of Unicode characters in script Gothi Greek is the set of Unicode characters in script Greek. Gujarati is the set of Unicode characters in script Guj Gurmukhi is the set of Unicode characters in script Gur Han is the set of Unicode characters in script Han. Hangul is the set of Unicode characters in script Hangu Hanunoo is the set of Unicode characters in script Hanu Hebrew is the set of Unicode characters in script Hebre Hiragana is the set of Unicode characters in script Hir Imperial_Aramaic is the set of Unicode characters in sc Inherited is the set of Unicode characters in script In Inscriptional_Pahlavi is the set of Unicode characters Inscriptional_Parthian is the set of Unicode characters Javanese is the set of Unicode characters in script Jav Kaithi is the set of Unicode characters in script Kaith Kannada is the set of Unicode characters in script Kann Katakana is the set of Unicode characters in script Kat Kayah_Li is the set of Unicode characters in script Kay Kharoshthi is the set of Unicode characters in script K Khmer is the set of Unicode characters in script Khmer. Lao is the set of Unicode characters in script Lao. Latin is the set of Unicode characters in script Latin. Lepcha is the set of Unicode characters in script Lepch Limbu is the set of Unicode characters in script Limbu. Linear_B is the set of Unicode characters in script Lin Lisu is the set of Unicode characters in script Lisu. Lycian is the set of Unicode characters in script Lycia Lydian is the set of Unicode characters in script Lydia Malayalam is the set of Unicode characters in script Ma Meetei_Mayek is the set of Unicode characters in script Mongolian is the set of Unicode characters in script Mo Myanmar is the set of Unicode characters in script Myan New_Tai_Lue is the set of Unicode characters in script Nko is the set of Unicode characters in script Nko. Ogham is the set of Unicode characters in script Ogham. Ol_Chiki is the set of Unicode characters in script Ol_ Old_Italic is the set of Unicode characters in script O Old_Persian is the set of Unicode characters in script Old_South_Arabian is the set of Unicode characters in s Old_Turkic is the set of Unicode characters in script O

var ( ASCII_Hex_Digit Bidi_Control Dash Deprecated Diacritic Extender Hex_Digit Hyphen IDS_Binary_Operator IDS_Trinary_Operator Ideographic Join_Control Logical_Order_Exception Noncharacter_Code_Point Other_Alphabetic Other_Default_Ignorable_Code_Point Other_Grapheme_Extend Other_ID_Continue Other_ID_Start Other_Lowercase Other_Math Other_Uppercase Pattern_Syntax Pattern_White_Space Quotation_Mark Radical STerm Soft_Dotted Terminal_Punctuation Unified_Ideograph Variation_Selector White_Space )

= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =

_ASCII_Hex_Digit _Bidi_Control _Dash _Deprecated _Diacritic _Extender _Hex_Digit _Hyphen _IDS_Binary_Operator _IDS_Trinary_Operator _Ideographic _Join_Control _Logical_Order_Exception _Noncharacter_Code_Point _Other_Alphabetic _Other_Default_Ignorable_Code_Point _Other_Grapheme_Extend _Other_ID_Continue _Other_ID_Start _Other_Lowercase _Other_Math _Other_Uppercase _Pattern_Syntax _Pattern_White_Space _Quotation_Mark _Radical _STerm _Soft_Dotted _Terminal_Punctuation _Unified_Ideograph _Variation_Selector _White_Space

// // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // //

ASCII_Hex_Digit is the set of U Bidi_Control is the set of Unic Dash is the set of Unicode char Deprecated is the set of Unicod Diacritic is the set of Unicode Extender is the set of Unicode Hex_Digit is the set of Unicode Hyphen is the set of Unicode ch IDS_Binary_Operator is the set IDS_Trinary_Operator is the set Ideographic is the set of Unico Join_Control is the set of Unic Logical_Order_Exception is the Noncharacter_Code_Point is the Other_Alphabetic is the set of Other_Default_Ignorable_Code_Po Other_Grapheme_Extend is the se Other_ID_Continue is the set of Other_ID_Start is the set of Un Other_Lowercase is the set of U Other_Math is the set of Unicod Other_Uppercase is the set of U Pattern_Syntax is the set of Un Pattern_White_Space is the set Quotation_Mark is the set of Un Radical is the set of Unicode c STerm is the set of Unicode cha Soft_Dotted is the set of Unico Terminal_Punctuation is the set Unified_Ideograph is the set of Variation_Selector is the set o White_Space is the set of Unico

CaseRanges is the table describing case mappings for all letters with non-self mappings.
var CaseRanges = _CaseRanges

Categories is the set of Unicode data tables.

var Categories = map[string][]Range{ "Lm": Lm, "Ll": Ll, "Me": Me, "Mc": Mc, "Mn": Mn, "Zl": Zl, "letter": letter, "Zp": Zp, "Zs": Zs, "Cs": Cs, "Co": Co, "Cf": Cf, "Cc": Cc, "Po": Po, "Pi": Pi, "Pf": Pf, "Pe": Pe, "Pd": Pd, "Pc": Pc, "Ps": Ps, "Nd": Nd, "Nl": Nl, "No": No, "So": So, "Sm": Sm, "Sk": Sk, "Sc": Sc, "Lu": Lu, "Lt": Lt, "Lo": Lo, }

Properties is the set of Unicode property tables.

var Properties = map[string][]Range{ "Pattern_Syntax": "Other_ID_Start": "Pattern_White_Space": "Other_Lowercase": "Soft_Dotted": "Hex_Digit": "ASCII_Hex_Digit": "Deprecated": "Terminal_Punctuation": "Quotation_Mark": "Other_ID_Continue": "Bidi_Control": "Variation_Selector": "Noncharacter_Code_Point": "Other_Math": "Unified_Ideograph": "Hyphen": "IDS_Binary_Operator": "Logical_Order_Exception": "Radical": "Other_Uppercase": "STerm": "Other_Alphabetic": "Diacritic": "Extender": "Join_Control": "Ideographic": "Dash": "IDS_Trinary_Operator": "Other_Grapheme_Extend": "Other_Default_Ignorable_Code_Point": "White_Space": }

Pattern_Syntax, Other_ID_Start, Pattern_White_Space, Other_Lowercase, Soft_Dotted, Hex_Digit, ASCII_Hex_Digit, Deprecated, Terminal_Punctuation, Quotation_Mark, Other_ID_Continue, Bidi_Control, Variation_Selector, Noncharacter_Code_Point, Other_Math, Unified_Ideograph, Hyphen, IDS_Binary_Operator, Logical_Order_Exception, Radical, Other_Uppercase, STerm, Other_Alphabetic, Diacritic, Extender, Join_Control, Ideographic, Dash, IDS_Trinary_Operator, Other_Grapheme_Extend, Other_Default_Ignorable_Code_Point, White_Space,

Scripts is the set of Unicode script tables.

var Scripts = map[string][]Range{ "Katakana": Katakana, "Malayalam": Malayalam, "Phags_Pa": Phags_Pa, "Inscriptional_Parthian": Inscriptional_Parthian, "Latin": Latin, "Inscriptional_Pahlavi": Inscriptional_Pahlavi, "Osmanya": Osmanya, "Khmer": Khmer, "Inherited": Inherited, "Telugu": Telugu, "Samaritan": Samaritan, "Bopomofo": Bopomofo, "Imperial_Aramaic": Imperial_Aramaic, "Kaithi": Kaithi, "Old_South_Arabian": Old_South_Arabian, "Kayah_Li": Kayah_Li, "New_Tai_Lue": New_Tai_Lue, "Tai_Le": Tai_Le, "Kharoshthi": Kharoshthi, "Common": Common, "Kannada": Kannada, "Old_Turkic": Old_Turkic, "Tamil": Tamil, "Tagalog": Tagalog, "Arabic": Arabic, "Tagbanwa": Tagbanwa, "Canadian_Aboriginal": Canadian_Aboriginal, "Tibetan": Tibetan, "Coptic": Coptic, "Hiragana": Hiragana, "Limbu": Limbu, "Egyptian_Hieroglyphs": Egyptian_Hieroglyphs, "Avestan": Avestan, "Myanmar": Myanmar, "Armenian": Armenian, "Sinhala": Sinhala, "Bengali": Bengali, "Greek": Greek, "Cham": Cham, "Hebrew": Hebrew, "Meetei_Mayek": Meetei_Mayek, "Saurashtra": Saurashtra, "Hangul": Hangul, "Runic": Runic, "Deseret": Deseret, "Lisu": Lisu, "Sundanese": Sundanese, "Glagolitic": Glagolitic, "Oriya": Oriya, "Buhid": Buhid, "Ethiopic": Ethiopic, "Javanese": Javanese, "Syloti_Nagri": Syloti_Nagri, "Vai": Vai, "Cherokee": Cherokee, "Ogham": Ogham, "Syriac": Syriac, "Gurmukhi": Gurmukhi, "Tai_Tham": Tai_Tham, "Ol_Chiki": Ol_Chiki, "Mongolian": Mongolian, "Hanunoo": Hanunoo, "Cypriot": Cypriot, "Buginese": Buginese, "Bamum": Bamum,

func Is
func Is(ranges []Range, rune int) bool Is tests whether rune is in the specified table of ranges.

func IsDigit
func IsDigit(rune int) bool IsDigit reports whether the rune is a decimal digit.

func IsLetter
func IsLetter(rune int) bool IsLetter reports whether the rune is a letter.

func IsLower
func IsLower(rune int) bool IsLower reports whether the rune is a lower case letter.

func IsSpace
func IsSpace(rune int) bool IsSpace reports whether the rune is a white space character.

func IsTitle
func IsTitle(rune int) bool IsTitle reports whether the rune is a title case letter.

func IsUpper
func IsUpper(rune int) bool IsUpper reports whether the rune is an upper case letter.

func To
func To(_case int, rune int) int To maps the rune to the specified case: UpperCase, LowerCase, or TitleCase.

func ToLower
func ToLower(rune int) int ToLower maps the rune to lower case.

func ToTitle
func ToTitle(rune int) int ToTitle maps the rune to title case.

func ToUpper
func ToUpper(rune int) int ToUpper maps the rune to upper case.

type CaseRange
The representation of a range of Unicode code points for 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 CaseRange struct { Lo int Hi int Delta d }

type Range
The representation of a range of Unicode code points. The range runs from Lo to Hi inclusive and has the specified stride.
type Range Lo Hi Stride } struct { int int int

Other packages
main

Except as noted, this content is licensed under Creative Commons Attribution 3.0.

The Go Programming Language

Package unsafe
func Alignof func Offsetof func Reflect func Sizeof func Typeof func Unreflect type ArbitraryType type Pointer func New func NewArray import "unsafe" The unsafe package contains operations that step around the type safety of Go programs. Package files
unsaf e.go

func Alignof
func Alignof(v ArbitraryType) int Alignof returns the alignment of the value v. It is the maximum value m such that the address of a variable with the type of v will always always be zero mod m. If v is of the form obj.f, it returns the alignment of field f within struct object obj.

func Offsetof
func Offsetof(v ArbitraryType) int Offsetof returns the offset within the struct of the field represented by v, which must be of the form struct_value.field. In other words, it returns the number of bytes between the start of the struct and the start of the field.

func Reflect
func Reflect(i interface{}) (typ interface{}, addr uintptr) Reflect unpacks an interface value into its type and the address of a copy of the internal value.

func Sizeof

func Sizeof(v ArbitraryType) int Sizeof returns the size in bytes occupied by the value v. The size is that of the "top level" of the value only. For instance, if v is a slice, it returns the size of the slice descriptor, not the size of the memory referenced by the slice.

func Typeof
func Typeof(i interface{}) (typ interface{}) Typeof returns the type of an interface value, a runtime.Type.

func Unreflect
func Unreflect(typ interface{}, addr uintptr) (ret interface{}) Unreflect inverts Reflect: Given a type and a pointer, it returns an empty interface value with those contents. The typ is assumed to contain a pointer to a runtime type; the type information in the interface{} is ignored, so that, for example, both *reflect.StructType and *runtime.StructType can be passed for typ.

type ArbitraryType
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 ArbitraryType int

type Pointer
Pointer represents a pointer to an arbitrary type. There are three special operations available for type Pointer that are not available for other types.
1) A pointer value of any type can be converted to a Pointer. 2) A uintptr can be converted to a Pointer. 3) 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.
type Pointer *ArbitraryType

func New
func New(typ interface{}) Pointer New allocates and returns a pointer to memory for a new value of the given type. The typ is assumed to hold a pointer to a runtime type. Callers should use reflect.MakeZero instead of invoking unsafe.New directly.

func New Array


func NewArray(typ interface{}, n int) Pointer NewArray allocates and returns a pointer to an array of n elements of the given type. The typ is assumed to hold a pointer to a runtime type. Callers should use reflect.MakeSlice instead of invoking unsafe.NewArray directly.

Except as noted, this content is licensed under Creative Commons Attribution 3.0.

The Go Programming Language

Package utf8
Constants func DecodeRune func DecodeRuneInString func EncodeRune func FullRune func FullRuneInString func RuneCount func RuneCountInString func RuneLen func RuneStart import "utf8" Functions and constants to support text encoded in UTF-8. This package calls a Unicode character a rune for brevity. Package files
utf 8.go

Constants
Numbers fundamental to the encoding.
const ( RuneError = unicode.ReplacementChar // the "error" Rune or "replacement character". RuneSelf = 0x80 // characters below Runeself are represented as themselves in a single UTFMax = 4 // maximum number of bytes of a UTF-8 encoded Unicode character. )

func DecodeRune
func DecodeRune(p []byte) (rune, size int) DecodeRune unpacks the first UTF-8 encoding in p and returns the rune and its width in bytes.

func DecodeRuneInString
func DecodeRuneInString(s string) (rune, size int) DecodeRuneInString is like DecodeRune but its input is a string.

func EncodeRune
func EncodeRune(rune int, p []byte) int EncodeRune writes into p (which must be large enough) the UTF-8 encoding of the rune. It returns the number of bytes written.

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.

func FullRuneInString
func FullRuneInString(s string) bool FullRuneInString is like FullRune but its input is a string.

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.

func RuneCountInString
func RuneCountInString(s string) (n int) RuneCountInString is like RuneCount but its input is a string.

func RuneLen
func RuneLen(rune int) int RuneLen returns the number of bytes required to encode the rune.

func RuneStart
func RuneStart(b byte) bool RuneStart reports whether the byte could be the first byte of an encoded rune. Second and subsequent bytes always have the top two bits set to 10.

Except as noted, this content is licensed under Creative Commons Attribution 3.0.

The Go Programming Language

Package websocket
Variables type Conn func Dial func (*Conn) Close func (*Conn) LocalAddr func (*Conn) Read func (*Conn) RemoteAddr func (*Conn) SetReadTimeout func (*Conn) SetTimeout func (*Conn) SetWriteTimeout import "websocket" The websocket package implements a client and server for the Web Socket protocol. The protocol is defined at http://tools.ietf.org/html/draft-hixie-thewebsocketprotocol Package files
client.go serv er.go websocket.go

func (*Conn) Write type Handler func (Handler) ServeHTTP type ProtocolError type WebSocketAddr func (WebSocketAddr) Network func (WebSocketAddr) String

Variables
var ( ErrBadStatus ErrNoUpgrade ErrBadUpgrade ErrNoWebSocketOrigin ErrBadWebSocketOrigin ErrNoWebSocketLocation ErrBadWebSocketLocation ErrNoWebSocketProtocol ErrBadWebSocketProtocol ) = = = = = = = = = &ProtocolError{"bad status"} &ProtocolError{"no upgrade"} &ProtocolError{"bad upgrade"} &ProtocolError{"no WebSocket-Origin"} &ProtocolError{"bad WebSocket-Origin"} &ProtocolError{"no WebSocket-Location"} &ProtocolError{"bad WebSocket-Location"} &ProtocolError{"no WebSocket-Protocol"} &ProtocolError{"bad WebSocket-Protocol"}

type Conn
Conn is a channel to communicate to a Web Socket. It implements the net.Conn interface.

type Conn struct { // The origin URI for the Web Socket. Origin string // The location URI for the Web Socket. Location string // The subprotocol for the Web Socket. Protocol string // contains unexported fields }

func Dial
func Dial(url, protocol, origin string) (ws *Conn, err os.Error) Dial opens a new client connection to a Web Socket. A trivial example client is: package main import (
"websocket" "strings"

) func main() {
ws, err := websocket.Dial("ws://localhost/ws", "", "http://localhost/"); if err != nil { panic("Dial: ", err.String()) } if _, err := ws.Write([]byte("hello, world!\n")); err != nil { panic("Write: ", err.String()) } var msg = make([]byte, 512); if n, err := ws.Read(msg); err != nil { panic("Read: ", err.String()) } // use msg[0:n]

func (*Conn) Close


func (ws *Conn) Close() os.Error Close implements the io.Closer interface for a Conn.

func (*Conn) LocalAddr


func (ws *Conn) LocalAddr() net.Addr LocalAddr returns the WebSocket Origin for the connection.

func (*Conn) Read


func (ws *Conn) Read(msg []byte) (n int, err os.Error)

Read implements the io.Reader interface for a Conn.

func (*Conn) Rem oteAddr


func (ws *Conn) RemoteAddr() net.Addr RemoteAddr returns the WebSocket locations for the connection.

func (*Conn) SetReadTim eout


func (ws *Conn) SetReadTimeout(nsec int64) os.Error SetReadTimeout sets the connection's network read timeout in nanoseconds.

func (*Conn) SetTim eout


func (ws *Conn) SetTimeout(nsec int64) os.Error SetTimeout sets the connection's network timeout in nanoseconds.

func (*Conn) SetWriteTim eout


func (ws *Conn) SetWriteTimeout(nsec int64) os.Error SeWritetTimeout sets the connection's network write timeout in nanoseconds.

func (*Conn) Write


func (ws *Conn) Write(msg []byte) (n int, err os.Error) Write implements the io.Writer interface for a Conn.

type Handler
Handler is an interface to a WebSocket. A trivial example server is: package main import (
"http" "io" "websocket"

) // Echo the data received on the Web Socket. func EchoServer(ws *websocket.Conn) {
io.Copy(ws, ws);

} func main() {

http.Handle("/echo", websocket.Handler(EchoServer)); err := http.ListenAndServe(":12345", nil); if err != nil { panic("ListenAndServe: ", err.String()) }

}
type Handler func(*Conn)

func (Handler) ServeHTTP


func (f Handler) ServeHTTP(c *http.Conn, req *http.Request) ServeHTTP implements the http.Handler interface for a Web Socket.

type ProtocolError
type ProtocolError struct { os.ErrorString }

type WebSocketAddr
WebSocketAddr is an implementation of net.Addr for Web Sockets.
type WebSocketAddr string

func (WebSocketAddr) Netw ork


func (addr WebSocketAddr) Network() string Network returns the network type for a Web Socket, "websocket".

func (WebSocketAddr) String


func (addr WebSocketAddr) String() string String returns the network address for a Web Socket.

Except as noted, this content is licensed under Creative Commons Attribution 3.0.

The Go Programming Language

Package xgb
Constants type AllocColorCellsReply type AllocColorPlanesReply type AllocColorReply type AllocNamedColorReply type Arc type ButtonPressEvent type ButtonReleaseEvent type Char2b type Charinfo type CirculateNotifyEvent type CirculateRequestEvent type ClientMessageData type ClientMessageEvent type Coloritem type ColormapNotifyEvent type ConfigureNotifyEvent type ConfigureRequestEvent type Conn func Dial func (*Conn) AllocColor func (*Conn) AllocColorCells func (*Conn) AllocColorCellsReply func (*Conn) AllocColorCellsRequest func (*Conn) AllocColorPlanes func (*Conn) AllocColorPlanesReply func (*Conn) AllocColorPlanesRequest func (*Conn) AllocColorReply func (*Conn) AllocColorRequest func (*Conn) AllocNamedColor func (*Conn) AllocNamedColorReply func (*Conn) AllocNamedColorRequest func (*Conn) AllowEvents func (*Conn) Bell func (*Conn) ChangeActivePointerGrab func (*Conn) ChangeGC func (*Conn) ChangeHosts func (*Conn) ChangeKeyboardControl func (*Conn) ChangeKeyboardMapping func (*Conn) ChangePointerControl func (*Conn) ChangeProperty func (*Conn) ChangeSaveSet func (*Conn) ChangeWindowAttributes func (*Conn) CirculateWindow func (*Conn) ClearArea func (*Conn) Close func (*Conn) NoOperation func (*Conn) OpenFont func (*Conn) PollForEvent func (*Conn) PolyArc func (*Conn) PolyFillArc func (*Conn) PolyFillRectangle func (*Conn) PolyLine func (*Conn) PolyPoint func (*Conn) PolyRectangle func (*Conn) PolySegment func (*Conn) PolyText16 func (*Conn) PolyText8 func (*Conn) PutImage func (*Conn) QueryBestSize func (*Conn) QueryBestSizeReply func (*Conn) QueryBestSizeRequest func (*Conn) QueryColors func (*Conn) QueryColorsReply func (*Conn) QueryColorsRequest func (*Conn) QueryExtension func (*Conn) QueryExtensionReply func (*Conn) QueryExtensionRequest func (*Conn) QueryFont func (*Conn) QueryFontReply func (*Conn) QueryFontRequest func (*Conn) QueryKeymap func (*Conn) QueryKeymapReply func (*Conn) QueryKeymapRequest func (*Conn) QueryPointer func (*Conn) QueryPointerReply func (*Conn) QueryPointerRequest func (*Conn) QueryTextExtents func (*Conn) QueryTextExtentsReply func (*Conn) QueryTextExtentsRequest func (*Conn) QueryTree func (*Conn) QueryTreeReply func (*Conn) QueryTreeRequest func (*Conn) RecolorCursor func (*Conn) ReparentWindow func (*Conn) RotateProperties func (*Conn) SendEvent func (*Conn) SetAccessControl func (*Conn) SetClipRectangles func (*Conn) SetCloseDownMode func (*Conn) SetDashes func (*Conn) SetFontPath

func (*Conn) CloseFont func (*Conn) ConfigureWindow func (*Conn) ConvertSelection func (*Conn) CopyArea func (*Conn) CopyColormapAndFree func (*Conn) CopyGC func (*Conn) CopyPlane func (*Conn) CreateColormap func (*Conn) CreateCursor func (*Conn) CreateGC func (*Conn) CreateGlyphCursor func (*Conn) CreatePixmap func (*Conn) CreateWindow func (*Conn) DefaultScreen func (*Conn) DeleteProperty func (*Conn) DestroySubwindows func (*Conn) DestroyWindow func (*Conn) FillPoly func (*Conn) ForceScreenSaver func (*Conn) FreeColormap func (*Conn) FreeColors func (*Conn) FreeCursor func (*Conn) FreeGC func (*Conn) FreePixmap func (*Conn) GetAtomName func (*Conn) GetAtomNameReply func (*Conn) GetAtomNameRequest func (*Conn) GetFontPath func (*Conn) GetFontPathReply func (*Conn) GetFontPathRequest func (*Conn) GetGeometry func (*Conn) GetGeometryReply func (*Conn) GetGeometryRequest func (*Conn) GetImage func (*Conn) GetImageReply func (*Conn) GetImageRequest func (*Conn) GetInputFocus func (*Conn) GetInputFocusReply func (*Conn) GetInputFocusRequest func (*Conn) GetKeyboardControl func (*Conn) GetKeyboardControlReply func (*Conn) GetKeyboardControlRequest func (*Conn) GetKeyboardMapping func (*Conn) GetKeyboardMappingReply func (*Conn) GetKeyboardMappingRequest func (*Conn) GetModifierMapping func (*Conn) GetModifierMappingReply func (*Conn) GetModifierMappingRequest func (*Conn) GetMotionEvents func (*Conn) GetMotionEventsReply func (*Conn) GetMotionEventsRequest func (*Conn) GetPointerControl func (*Conn) GetPointerControlReply func (*Conn) GetPointerControlRequest func (*Conn) GetPointerMapping

type type type type type type type type type type type type type type type type type type type type type type type type type type type type type type

func (*Conn) SetInputFocus func (*Conn) SetModifierMapping func (*Conn) SetModifierMappingReply func (*Conn) SetModifierMappingRequest func (*Conn) SetPointerMapping func (*Conn) SetPointerMappingReply func (*Conn) SetPointerMappingRequest func (*Conn) SetScreenSaver func (*Conn) SetSelectionOwner func (*Conn) StoreColors func (*Conn) StoreNamedColor func (*Conn) TranslateCoordinates func (*Conn) TranslateCoordinatesReply func (*Conn) TranslateCoordinatesRequest func (*Conn) UngrabButton func (*Conn) UngrabKey func (*Conn) UngrabKeyboard func (*Conn) UngrabPointer func (*Conn) UngrabServer func (*Conn) UninstallColormap func (*Conn) UnmapSubwindows func (*Conn) UnmapWindow func (*Conn) WaitForEvent func (*Conn) WarpPointer Cookie CreateNotifyEvent DepthInfo DestroyNotifyEvent EnterNotifyEvent Error func (*Error) String Event ExposeEvent FocusInEvent FocusOutEvent Fontprop Format GetAtomNameReply GetFontPathReply GetGeometryReply GetImageReply GetInputFocusReply GetKeyboardControlReply GetKeyboardMappingReply GetModifierMappingReply GetMotionEventsReply GetPointerControlReply GetPointerMappingReply GetPropertyReply GetScreenSaverReply GetSelectionOwnerReply GetWindowAttributesReply GrabKeyboardReply GrabPointerReply GraphicsExposureEvent

func (*Conn) GetPointerMappingReply func (*Conn) GetPointerMappingRequest func (*Conn) GetProperty func (*Conn) GetPropertyReply func (*Conn) GetPropertyRequest func (*Conn) GetScreenSaver func (*Conn) GetScreenSaverReply func (*Conn) GetScreenSaverRequest func (*Conn) GetSelectionOwner func (*Conn) GetSelectionOwnerReply func (*Conn) GetSelectionOwnerRequest func (*Conn) GetWindowAttributes func (*Conn) GetWindowAttributesReply func (*Conn) GetWindowAttributesRequest func (*Conn) GrabButton func (*Conn) GrabKey func (*Conn) GrabKeyboard func (*Conn) GrabKeyboardReply func (*Conn) GrabKeyboardRequest func (*Conn) GrabPointer func (*Conn) GrabPointerReply func (*Conn) GrabPointerRequest func (*Conn) GrabServer func (*Conn) ImageText16 func (*Conn) ImageText8 func (*Conn) InstallColormap func (*Conn) InternAtom func (*Conn) InternAtomReply func (*Conn) InternAtomRequest func (*Conn) KillClient func (*Conn) ListExtensions func (*Conn) ListExtensionsReply func (*Conn) ListExtensionsRequest func (*Conn) ListFonts func (*Conn) ListFontsReply func (*Conn) ListFontsRequest func (*Conn) ListFontsWithInfo func (*Conn) ListFontsWithInfoReply func (*Conn) ListFontsWithInfoRequest func (*Conn) ListHosts func (*Conn) ListHostsReply func (*Conn) ListHostsRequest func (*Conn) ListInstalledColormaps func (*Conn) ListInstalledColormapsReply func (*Conn) ListInstalledColormapsRequest func (*Conn) ListProperties func (*Conn) ListPropertiesReply func (*Conn) ListPropertiesRequest func (*Conn) LookupColor func (*Conn) LookupColorReply func (*Conn) LookupColorRequest func (*Conn) MapSubwindows func (*Conn) MapWindow func (*Conn) NewId

type GravityNotifyEvent type Host type Id type InternAtomReply type KeyPressEvent type KeyReleaseEvent type KeymapNotifyEvent type Keysym type LeaveNotifyEvent type ListExtensionsReply type ListFontsReply type ListFontsWithInfoReply type ListHostsReply type ListInstalledColormapsReply type ListPropertiesReply type LookupColorReply type MapNotifyEvent type MapRequestEvent type MappingNotifyEvent type MotionNotifyEvent type NoExposureEvent type Point type PropertyNotifyEvent type QueryBestSizeReply type QueryColorsReply type QueryExtensionReply type QueryFontReply type QueryKeymapReply type QueryPointerReply type QueryTextExtentsReply type QueryTreeReply type Rectangle type ReparentNotifyEvent type ResizeRequestEvent type Rgb type ScreenInfo type Segment type SelectionClearEvent type SelectionNotifyEvent type SelectionRequestEvent type SetModifierMappingReply type SetPointerMappingReply type SetupInfo type Str type Timecoord type Timestamp type TranslateCoordinatesReply type UnmapNotifyEvent type VisibilityNotifyEvent type VisualInfo Other packages

import "xgb" The XGB package implements the X11 core protocol. It is based on XCB: http://xcb.freedesktop.org/ Package files
auth.go xgb.go xproto.go

Constants
const ( VisualClassStaticGray VisualClassGrayScale VisualClassStaticColor VisualClassPseudoColor VisualClassTrueColor VisualClassDirectColor ) = = = = = = 0 1 2 3 4 5

const ( EventMaskNoEvent EventMaskKeyPress EventMaskKeyRelease EventMaskButtonPress EventMaskButtonRelease EventMaskEnterWindow EventMaskLeaveWindow EventMaskPointerMotion EventMaskPointerMotionHint EventMaskButton1Motion EventMaskButton2Motion EventMaskButton3Motion EventMaskButton4Motion EventMaskButton5Motion EventMaskButtonMotion EventMaskKeymapState EventMaskExposure EventMaskVisibilityChange EventMaskStructureNotify EventMaskResizeRedirect EventMaskSubstructureNotify EventMaskSubstructureRedirect EventMaskFocusChange EventMaskPropertyChange EventMaskColorMapChange EventMaskOwnerGrabButton )

= = = = = = = = = = = = = = = = = = = = = = = = = =

0 1 2 4 8 16 32 64 128 256 512 1024 2048 4096 8192 16384 32768 65536 131072 262144 524288 1048576 2097152 4194304 8388608 16777216

const ( BackingStoreNotUseful = 0 BackingStoreWhenMapped = 1 BackingStoreAlways = 2 )

const ( ImageOrderLSBFirst = 0 ImageOrderMSBFirst = 1 )

const ( ModMaskShift ModMaskLock ModMaskControl ModMask1 ModMask2 ModMask3 ModMask4 ModMask5 ModMaskAny )

= = = = = = = = =

1 2 4 8 16 32 64 128 32768

const ( KeyButMaskShift KeyButMaskLock KeyButMaskControl KeyButMaskMod1 KeyButMaskMod2 KeyButMaskMod3 KeyButMaskMod4 KeyButMaskMod5 KeyButMaskButton1 KeyButMaskButton2 KeyButMaskButton3 KeyButMaskButton4 KeyButMaskButton5 )

= = = = = = = = = = = = =

1 2 4 8 16 32 64 128 256 512 1024 2048 4096

const ( ButtonMask1 ButtonMask2 ButtonMask3 ButtonMask4 ButtonMask5 ButtonMaskAny )

= = = = = =

256 512 1024 2048 4096 32768

const ( MotionNormal = 0 MotionHint = 1 )

const ( NotifyDetailAncestor NotifyDetailVirtual NotifyDetailInferior NotifyDetailNonlinear NotifyDetailNonlinearVirtual NotifyDetailPointer NotifyDetailPointerRoot NotifyDetailNone )

= = = = = = = =

0 1 2 3 4 5 6 7

const ( NotifyModeNormal NotifyModeGrab NotifyModeUngrab NotifyModeWhileGrabbed )

= = = =

0 1 2 3

const ( VisibilityUnobscured = 0 VisibilityPartiallyObscured = 1 VisibilityFullyObscured = 2 )

const ( PlaceOnTop = 0 PlaceOnBottom = 1 )

const ( PropertyNewValue = 0 PropertyDelete = 1 )

const ( AtomNone AtomAny AtomPrimary AtomSecondary AtomArc AtomAtom AtomBitmap AtomCardinal AtomColormap AtomCursor AtomCutBuffer0 AtomCutBuffer1 AtomCutBuffer2 AtomCutBuffer3 AtomCutBuffer4 AtomCutBuffer5 AtomCutBuffer6 AtomCutBuffer7 AtomDrawable AtomFont AtomInteger AtomPixmap AtomPoint AtomRectangle AtomResourceManager AtomRgbColorMap AtomRgbBestMap AtomRgbBlueMap AtomRgbDefaultMap AtomRgbGrayMap AtomRgbGreenMap AtomRgbRedMap AtomString AtomVisualid AtomWindow AtomWmCommand AtomWmHints AtomWmClientMachine AtomWmIconName AtomWmIconSize AtomWmName AtomWmNormalHints AtomWmSizeHints AtomWmZoomHints AtomMinSpace AtomNormSpace AtomMaxSpace AtomEndSpace AtomSuperscriptX AtomSuperscriptY AtomSubscriptX AtomSubscriptY AtomUnderlinePosition AtomUnderlineThickness AtomStrikeoutAscent AtomStrikeoutDescent AtomItalicAngle AtomXHeight AtomQuadWidth AtomWeight AtomPointSize AtomResolution AtomCopyright AtomNotice AtomFontName

= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =

0 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63

const ( ColormapStateUninstalled = 0 ColormapStateInstalled = 1 )

const ( MappingModifier = 0 MappingKeyboard = 1 MappingPointer = 2 )

const ( WindowClassCopyFromParent = 0 WindowClassInputOutput = 1 WindowClassInputOnly = 2 )

const ( CWBackPixmap CWBackPixel CWBorderPixmap CWBorderPixel CWBitGravity CWWinGravity CWBackingStore CWBackingPlanes CWBackingPixel CWOverrideRedirect CWSaveUnder CWEventMask CWDontPropagate CWColormap CWCursor )

= = = = = = = = = = = = = = =

1 2 4 8 16 32 64 128 256 512 1024 2048 4096 8192 16384

const ( BackPixmapNone = 0 BackPixmapParentRelative = 1 )

const ( GravityBitForget GravityWinUnmap GravityNorthWest GravityNorth GravityNorthEast GravityWest GravityCenter GravityEast GravitySouthWest GravitySouth GravitySouthEast GravityStatic )

= = = = = = = = = = = =

0 0 1 2 3 4 5 6 7 8 9 10

const ( MapStateUnmapped = 0 MapStateUnviewable = 1 MapStateViewable = 2 )

const ( SetModeInsert = 0 SetModeDelete = 1 )

const ( ConfigWindowX ConfigWindowY ConfigWindowWidth ConfigWindowHeight ConfigWindowBorderWidth ConfigWindowSibling ConfigWindowStackMode )

= = = = = = =

1 2 4 8 16 32 64

const ( StackModeAbove StackModeBelow StackModeTopIf StackModeBottomIf StackModeOpposite )

= = = = =

0 1 2 3 4

const ( CirculateRaiseLowest = 0 CirculateLowerHighest = 1 )

const ( PropModeReplace = 0 PropModePrepend = 1 PropModeAppend = 2 )

const ( SendEventDestPointerWindow = 0 SendEventDestItemFocus = 1 )

const ( GrabModeSync = 0 GrabModeAsync = 1 )

const ( GrabStatusSuccess GrabStatusAlreadyGrabbed GrabStatusInvalidTime GrabStatusNotViewable GrabStatusFrozen )

= = = = =

0 1 2 3 4

const ( ButtonIndexAny ButtonIndex1 ButtonIndex2 ButtonIndex3 ButtonIndex4 ButtonIndex5 )

= = = = = =

0 1 2 3 4 5

const ( AllowAsyncPointer AllowSyncPointer AllowReplayPointer AllowAsyncKeyboard AllowSyncKeyboard AllowReplayKeyboard AllowAsyncBoth AllowSyncBoth )

= = = = = = = =

0 1 2 3 4 5 6 7

const ( InputFocusNone InputFocusPointerRoot InputFocusParent InputFocusFollowKeyboard )

= = = =

0 1 2 3

const ( FontDrawLeftToRight = 0 FontDrawRightToLeft = 1 )

const ( GCFunction GCPlaneMask GCForeground GCBackground GCLineWidth GCLineStyle GCCapStyle GCJoinStyle GCFillStyle GCFillRule GCTile GCStipple GCTileStippleOriginX GCTileStippleOriginY GCFont GCSubwindowMode GCGraphicsExposures GCClipOriginX GCClipOriginY GCClipMask GCDashOffset GCDashList GCArcMode )

= = = = = = = = = = = = = = = = = = = = = = =

1 2 4 8 16 32 64 128 256 512 1024 2048 4096 8192 16384 32768 65536 131072 262144 524288 1048576 2097152 4194304

const ( GXClear GXAnd GXAndReverse GXCopy GXAndInverted GXNoop GXXor GXOr GXNor GXEquiv GXInvert GXOrReverse GXCopyInverted GXOrInverted GXNand GXSet )

= = = = = = = = = = = = = = = =

0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15

const ( LineStyleSolid = 0 LineStyleOnOffDash = 1 LineStyleDoubleDash = 2 )

const ( CapStyleNotLast CapStyleButt CapStyleRound CapStyleProjecting )

= = = =

0 1 2 3

const ( JoinStyleMiter = 0 JoinStyleRound = 1 JoinStyleBevel = 2 )

const ( FillStyleSolid FillStyleTiled FillStyleStippled FillStyleOpaqueStippled )

= = = =

0 1 2 3

const ( FillRuleEvenOdd = 0 FillRuleWinding = 1 )

const ( SubwindowModeClipByChildren = 0 SubwindowModeIncludeInferiors = 1 )

const ( ArcModeChord = 0 ArcModePieSlice = 1 )

const ( ClipOrderingUnsorted ClipOrderingYSorted ClipOrderingYXSorted ClipOrderingYXBanded )

= = = =

0 1 2 3

const ( CoordModeOrigin = 0 CoordModePrevious = 1 )

const ( PolyShapeComplex = 0 PolyShapeNonconvex = 1 PolyShapeConvex = 2 )

const ( ImageFormatXYBitmap = 0 ImageFormatXYPixmap = 1 ImageFormatZPixmap = 2 )

const ( ColormapAllocNone = 0 ColormapAllocAll = 1 )

const ( ColorFlagRed = 1 ColorFlagGreen = 2 ColorFlagBlue = 4 )

const ( QueryShapeOfLargestCursor = 0 QueryShapeOfFastestTile = 1 QueryShapeOfFastestStipple = 2 )

const ( KBKeyClickPercent KBBellPercent KBBellPitch KBBellDuration KBLed KBLedMode KBKey KBAutoRepeatMode )

= = = = = = = =

1 2 4 8 16 32 64 128

const ( LedModeOff = 0 LedModeOn = 1 )

const ( AutoRepeatModeOff = 0 AutoRepeatModeOn = 1 AutoRepeatModeDefault = 2 )

const ( BlankingNotPreferred = 0 BlankingPreferred = 1 BlankingDefault = 2 )

const ( ExposuresNotAllowed = 0 ExposuresAllowed = 1 ExposuresDefault = 2 )

const ( HostModeInsert = 0 HostModeDelete = 1 )

const ( FamilyInternet FamilyDECnet FamilyChaos FamilyServerInterpreted FamilyInternet6 )

= = = = =

0 1 2 5 6

const ( AccessControlDisable = 0 AccessControlEnable = 1 )

const ( CloseDownDestroyAll = 0 CloseDownRetainPermanent = 1 CloseDownRetainTemporary = 2 )

const ( ScreenSaverReset = 0 ScreenSaverActive = 1 )

const ( MappingStatusSuccess = 0 MappingStatusBusy = 1 MappingStatusFailure = 2 )

const ( MapIndexShift MapIndexLock MapIndexControl MapIndex1 MapIndex2 MapIndex3 MapIndex4 MapIndex5 )

= = = = = = = =

0 1 2 3 4 5 6 7

const BadAccess = 10

const BadAlloc = 11

const BadAtom = 5

const BadColormap = 12

const BadCursor = 6

const BadDrawable = 9

const BadFont = 7

const BadGContext = 13

const BadIDChoice = 14

const BadImplementation = 17

const BadLength = 16

const BadMatch = 8

const BadName = 15

const BadPixmap = 4

const BadRequest = 1

const BadValue = 2

const BadWindow = 3

const ButtonPress = 4

const ButtonRelease = 5

const CirculateNotify = 26

const CirculateRequest = 27

const ClientMessage = 33

const ( ColormapNone = 0 )

const ColormapNotify = 32

const ConfigureNotify = 22

const ConfigureRequest = 23

const CreateNotify = 16

const ( CursorNone = 0 )

const DestroyNotify = 17

const EnterNotify = 7

const Expose = 12

const FocusIn = 9

const FocusOut = 10

const ( FontNone = 0 )

const ( GetPropertyTypeAny = 0 )

const ( GrabAny = 0 )

const GraphicsExposure = 13

const GravityNotify = 24

const KeyPress = 2

const KeyRelease = 3

const KeymapNotify = 11

const ( KillAllTemporary = 0 )

const LeaveNotify = 8

const MapNotify = 19

const MapRequest = 20

const MappingNotify = 34

const MotionNotify = 6

const NoExposure = 14

const ( PixmapNone = 0 )

const PropertyNotify = 28

const ReparentNotify = 21

const ResizeRequest = 25

const SelectionClear = 29

const SelectionNotify = 31

const SelectionRequest = 30

const ( TimeCurrentTime = 0 )

const UnmapNotify = 18

const VisibilityNotify = 15

const ( WindowNone = 0 )

type AllocColorCellsReply
type AllocColorCellsReply struct { PixelsLen uint16 MasksLen uint16 Pixels []uint32 Masks []uint32 }

type AllocColorPlanesReply
type AllocColorPlanesReply struct { PixelsLen uint16 RedMask uint32 GreenMask uint32 BlueMask uint32 Pixels []uint32 }

type AllocColorReply
type AllocColorReply struct { Red uint16 Green uint16 Blue uint16 Pixel uint32 }

type AllocNamedColorReply

type AllocNamedColorReply struct { Pixel uint32 ExactRed uint16 ExactGreen uint16 ExactBlue uint16 VisualRed uint16 VisualGreen uint16 VisualBlue uint16 }

type Arc
type Arc struct { X int16 Y int16 Width uint16 Height uint16 Angle1 int16 Angle2 int16 }

type ButtonPressEvent
type ButtonPressEvent struct { Detail byte Time Timestamp Root Id Event Id Child Id RootX int16 RootY int16 EventX int16 EventY int16 State uint16 SameScreen byte }

type ButtonReleaseEvent
type ButtonReleaseEvent ButtonPressEvent

type Char2b
type Char2b struct { Byte1 byte Byte2 byte }

type Charinfo
type Charinfo struct LeftSideBearing RightSideBearing CharacterWidth Ascent Descent Attributes } { int16 int16 int16 int16 int16 uint16

type CirculateNotifyEvent
type CirculateNotifyEvent struct { Event Id Window Id Place byte }

type CirculateRequestEvent
type CirculateRequestEvent CirculateNotifyEvent

type ClientMessageData
ClientMessageData holds the data from a client message, duplicated in three forms because Go doesn't have unions.
type ClientMessageData struct { Data8 [20]byte Data16 [10]uint16 Data32 [5]uint32 }

type ClientMessageEvent
type ClientMessageEvent struct { Format byte Window Id Type Id Data ClientMessageData }

type Coloritem

type Coloritem struct { Pixel uint32 Red uint16 Green uint16 Blue uint16 Flags byte }

type ColormapNotifyEvent
type ColormapNotifyEvent struct { Window Id Colormap Id New byte State byte }

type ConfigureNotifyEvent
type ConfigureNotifyEvent struct { Event Id Window Id AboveSibling Id X int16 Y int16 Width uint16 Height uint16 BorderWidth uint16 OverrideRedirect byte }

type ConfigureRequestEvent
type ConfigureRequestEvent struct { StackMode byte Parent Id Window Id Sibling Id X int16 Y int16 Width uint16 Height uint16 BorderWidth uint16 ValueMask uint16 }

type Conn

A Conn represents a connection to an X server. Only one goroutine should use a Conn's methods at a time.
type Conn struct { Setup SetupInfo // contains unexported fields }

func Dial
func Dial(display string) (*Conn, os.Error) Dial connects to the X server given in the 'display' string. If 'display' is empty it will be taken from os.Getenv("DISPLAY"). Examples:
Dial(":1") Dial("/tmp/launch-123/:0") Dial("hostname:2.1") Dial("tcp/hostname:1.0") // // // // connect connect connect connect to to to to net.Dial("unix", "", "/tmp/.X11-unix/X1") net.Dial("unix", "", "/tmp/launch-123/:0") net.Dial("tcp", "", "hostname:6002") net.Dial("tcp", "", "hostname:6001")

func (*Conn) AllocColor


func (c *Conn) AllocColor(Cmap Id, Red uint16, Green uint16, Blue uint16) (*AllocColorReply, os.Error)

func (*Conn) AllocColorCells


func (c *Conn) AllocColorCells(Contiguous byte, Cmap Id, Colors uint16, Planes uint16) (*AllocColorCellsReply, os.Error)

func (*Conn) AllocColorCellsReply


func (c *Conn) AllocColorCellsReply(cookie Cookie) (*AllocColorCellsReply, os.Error)

func (*Conn) AllocColorCellsRequest


func (c *Conn) AllocColorCellsRequest(Contiguous byte, Cmap Id, Colors uint16, Planes uint16) Cookie

func (*Conn) AllocColorPlanes


func (c *Conn) AllocColorPlanes(Contiguous byte, Cmap Id, Colors uint16, Reds uint16, Greens uint16, Blues uint16) (*AllocColorPlanesReply, os.Error)

func (*Conn) AllocColorPlanesReply


func (c *Conn) AllocColorPlanesReply(cookie Cookie) (*AllocColorPlanesReply, os.Error)

func (*Conn) AllocColorPlanesRequest


func (c *Conn) AllocColorPlanesRequest(Contiguous byte, Cmap Id, Colors uint16, Reds uint16, Greens uint16, Blues uint16) Cookie

func (*Conn) AllocColorReply


func (c *Conn) AllocColorReply(cookie Cookie) (*AllocColorReply, os.Error)

func (*Conn) AllocColorRequest


func (c *Conn) AllocColorRequest(Cmap Id, Red uint16, Green uint16, Blue uint16) Cookie

func (*Conn) AllocNam edColor


func (c *Conn) AllocNamedColor(Cmap Id, Name string) (*AllocNamedColorReply, os.Error)

func (*Conn) AllocNam edColorReply


func (c *Conn) AllocNamedColorReply(cookie Cookie) (*AllocNamedColorReply, os.Error)

func (*Conn) AllocNam edColorRequest


func (c *Conn) AllocNamedColorRequest(Cmap Id, Name string) Cookie

func (*Conn) Allow Events


func (c *Conn) AllowEvents(Mode byte, Time Timestamp)

func (*Conn) Bell


func (c *Conn) Bell(Percent int8)

func (*Conn) ChangeActivePointerGrab


func (c *Conn) ChangeActivePointerGrab(Cursor Id, Time Timestamp, EventMask uint16)

func (*Conn) ChangeGC


func (c *Conn) ChangeGC(Gc Id, ValueMask uint32, ValueList []uint32)

func (*Conn) ChangeHosts


func (c *Conn) ChangeHosts(Mode byte, Family byte, Address []byte)

func (*Conn) ChangeKeyboardControl


func (c *Conn) ChangeKeyboardControl(ValueMask uint32, ValueList []uint32)

func (*Conn) ChangeKeyboardMapping


func (c *Conn) ChangeKeyboardMapping(KeycodeCount byte, FirstKeycode byte, KeysymsPerKeycode byte, Keysyms []Keysym)

func (*Conn) ChangePointerControl


func (c *Conn) ChangePointerControl(AccelerationNumerator int16, AccelerationDenominator int16, Threshold int16, DoAcceleration byte, DoThreshold byte)

func (*Conn) ChangeProperty


func (c *Conn) ChangeProperty(Mode byte, Window Id, Property Id, Type Id, Format byte, Data []byte)

func (*Conn) ChangeSaveSet

func (c *Conn) ChangeSaveSet(Mode byte, Window Id)

func (*Conn) ChangeWindow Attributes


func (c *Conn) ChangeWindowAttributes(Window Id, ValueMask uint32, ValueList []uint32)

func (*Conn) CirculateWindow


func (c *Conn) CirculateWindow(Direction byte, Window Id)

func (*Conn) ClearArea


func (c *Conn) ClearArea(Exposures byte, Window Id, X int16, Y int16, Width uint16, Height uint16)

func (*Conn) Close


func (c *Conn) Close() Close closes the connection to the X server.

func (*Conn) CloseFont


func (c *Conn) CloseFont(Font Id)

func (*Conn) ConfigureWindow


func (c *Conn) ConfigureWindow(Window Id, ValueMask uint16, ValueList []uint32)

func (*Conn) ConvertSelection


func (c *Conn) ConvertSelection(Requestor Id, Selection Id, Target Id, Property Id, Time Timestamp)

func (*Conn) CopyArea


func (c *Conn) CopyArea(SrcDrawable Id, DstDrawable Id, Gc Id, SrcX int16, SrcY int16, DstX int16, DstY int16, Width uint16, Height uint16)

func (*Conn) CopyColorm apAndFree


func (c *Conn) CopyColormapAndFree(Mid Id, SrcCmap Id)

func (*Conn) CopyGC


func (c *Conn) CopyGC(SrcGc Id, DstGc Id, ValueMask uint32)

func (*Conn) CopyPlane


func (c *Conn) CopyPlane(SrcDrawable Id, DstDrawable Id, Gc Id, SrcX int16, SrcY int16, DstX int16, DstY int16, Width uint16, Height uint16, BitPlane uint32)

func (*Conn) CreateColorm ap


func (c *Conn) CreateColormap(Alloc byte, Mid Id, Window Id, Visual Id)

func (*Conn) CreateCursor


func (c *Conn) CreateCursor(Cid Id, Source Id, Mask Id, ForeRed uint16, ForeGreen uint16, ForeBlue uint16, BackRed uint16, BackGreen uint16, BackBlue uint16, X

uint16, Y uint16)

func (*Conn) CreateGC


func (c *Conn) CreateGC(Cid Id, Drawable Id, ValueMask uint32, ValueList []uint32)

func (*Conn) CreateGlyphCursor


func (c *Conn) CreateGlyphCursor(Cid Id, SourceFont Id, MaskFont Id, SourceChar uint16, MaskChar uint16, ForeRed uint16, ForeGreen uint16, ForeBlue uint16, BackRed uint16, BackGreen uint16, BackBlue uint16)

func (*Conn) CreatePixm ap


func (c *Conn) CreatePixmap(Depth byte, Pid Id, Drawable Id, Width uint16, Height uint16)

func (*Conn) CreateWindow


func (c *Conn) CreateWindow(Depth byte, Wid Id, Parent Id, X int16, Y int16, Width uint16, Height uint16, BorderWidth uint16, Class uint16, Visual Id, ValueMask uint32, ValueList []uint32)

func (*Conn) DefaultScreen


func (c *Conn) DefaultScreen() *ScreenInfo DefaultScreen returns the Screen info for the default screen, which is 0 or the one given in the display argument to Dial.

func (*Conn) DeleteProperty


func (c *Conn) DeleteProperty(Window Id, Property Id)

func (*Conn) DestroySubw indow s


func (c *Conn) DestroySubwindows(Window Id)

func (*Conn) DestroyWindow


func (c *Conn) DestroyWindow(Window Id)

func (*Conn) FillPoly


func (c *Conn) FillPoly(Drawable Id, Gc Id, Shape byte, CoordinateMode byte, Points []Point)

func (*Conn) ForceScreenSaver


func (c *Conn) ForceScreenSaver(Mode byte)

func (*Conn) FreeColorm ap


func (c *Conn) FreeColormap(Cmap Id)

func (*Conn) FreeColors


func (c *Conn) FreeColors(Cmap Id, PlaneMask uint32, Pixels []uint32)

func (*Conn) FreeCursor

func (c *Conn) FreeCursor(Cursor Id)

func (*Conn) FreeGC


func (c *Conn) FreeGC(Gc Id)

func (*Conn) FreePixm ap


func (c *Conn) FreePixmap(Pixmap Id)

func (*Conn) GetAtom Nam e


func (c *Conn) GetAtomName(Atom Id) (*GetAtomNameReply, os.Error)

func (*Conn) GetAtom Nam eReply


func (c *Conn) GetAtomNameReply(cookie Cookie) (*GetAtomNameReply, os.Error)

func (*Conn) GetAtom Nam eRequest


func (c *Conn) GetAtomNameRequest(Atom Id) Cookie

func (*Conn) GetFontPath


func (c *Conn) GetFontPath() (*GetFontPathReply, os.Error)

func (*Conn) GetFontPathReply


func (c *Conn) GetFontPathReply(cookie Cookie) (*GetFontPathReply, os.Error)

func (*Conn) GetFontPathRequest


func (c *Conn) GetFontPathRequest() Cookie

func (*Conn) GetGeom etry


func (c *Conn) GetGeometry(Drawable Id) (*GetGeometryReply, os.Error)

func (*Conn) GetGeom etryReply


func (c *Conn) GetGeometryReply(cookie Cookie) (*GetGeometryReply, os.Error)

func (*Conn) GetGeom etryRequest


func (c *Conn) GetGeometryRequest(Drawable Id) Cookie

func (*Conn) GetIm age


func (c *Conn) GetImage(Format byte, Drawable Id, X int16, Y int16, Width uint16, Height uint16, PlaneMask uint32) (*GetImageReply, os.Error)

func (*Conn) GetIm ageReply


func (c *Conn) GetImageReply(cookie Cookie) (*GetImageReply, os.Error)

func (*Conn) GetIm ageRequest


func (c *Conn) GetImageRequest(Format byte, Drawable Id, X int16, Y int16, Width uint16, Height uint16, PlaneMask uint32) Cookie

func (*Conn) GetInputFocus


func (c *Conn) GetInputFocus() (*GetInputFocusReply, os.Error)

func (*Conn) GetInputFocusReply


func (c *Conn) GetInputFocusReply(cookie Cookie) (*GetInputFocusReply, os.Error)

func (*Conn) GetInputFocusRequest


func (c *Conn) GetInputFocusRequest() Cookie

func (*Conn) GetKeyboardControl


func (c *Conn) GetKeyboardControl() (*GetKeyboardControlReply, os.Error)

func (*Conn) GetKeyboardControlReply


func (c *Conn) GetKeyboardControlReply(cookie Cookie) (*GetKeyboardControlReply, os.Error)

func (*Conn) GetKeyboardControlRequest


func (c *Conn) GetKeyboardControlRequest() Cookie

func (*Conn) GetKeyboardMapping


func (c *Conn) GetKeyboardMapping(FirstKeycode byte, Count byte) (*GetKeyboardMappingReply, os.Error)

func (*Conn) GetKeyboardMappingReply


func (c *Conn) GetKeyboardMappingReply(cookie Cookie) (*GetKeyboardMappingReply, os.Error)

func (*Conn) GetKeyboardMappingRequest


func (c *Conn) GetKeyboardMappingRequest(FirstKeycode byte, Count byte) Cookie

func (*Conn) GetModifierMapping


func (c *Conn) GetModifierMapping() (*GetModifierMappingReply, os.Error)

func (*Conn) GetModifierMappingReply


func (c *Conn) GetModifierMappingReply(cookie Cookie) (*GetModifierMappingReply, os.Error)

func (*Conn) GetModifierMappingRequest


func (c *Conn) GetModifierMappingRequest() Cookie

func (*Conn) GetMotionEvents


func (c *Conn) GetMotionEvents(Window Id, Start Timestamp, Stop Timestamp) (*GetMotionEventsReply, os.Error)

func (*Conn) GetMotionEventsReply


func (c *Conn) GetMotionEventsReply(cookie Cookie) (*GetMotionEventsReply, os.Error)

func (*Conn) GetMotionEventsRequest


func (c *Conn) GetMotionEventsRequest(Window Id, Start Timestamp, Stop Timestamp) Cookie

func (*Conn) GetPointerControl


func (c *Conn) GetPointerControl() (*GetPointerControlReply, os.Error)

func (*Conn) GetPointerControlReply


func (c *Conn) GetPointerControlReply(cookie Cookie) (*GetPointerControlReply, os.Error)

func (*Conn) GetPointerControlRequest


func (c *Conn) GetPointerControlRequest() Cookie

func (*Conn) GetPointerMapping


func (c *Conn) GetPointerMapping() (*GetPointerMappingReply, os.Error)

func (*Conn) GetPointerMappingReply


func (c *Conn) GetPointerMappingReply(cookie Cookie) (*GetPointerMappingReply, os.Error)

func (*Conn) GetPointerMappingRequest


func (c *Conn) GetPointerMappingRequest() Cookie

func (*Conn) GetProperty


func (c *Conn) GetProperty(Delete byte, Window Id, Property Id, Type Id, LongOffset uint32, LongLength uint32) (*GetPropertyReply, os.Error)

func (*Conn) GetPropertyReply


func (c *Conn) GetPropertyReply(cookie Cookie) (*GetPropertyReply, os.Error)

func (*Conn) GetPropertyRequest


func (c *Conn) GetPropertyRequest(Delete byte, Window Id, Property Id, Type Id, LongOffset uint32, LongLength uint32) Cookie

func (*Conn) GetScreenSaver


func (c *Conn) GetScreenSaver() (*GetScreenSaverReply, os.Error)

func (*Conn) GetScreenSaverReply


func (c *Conn) GetScreenSaverReply(cookie Cookie) (*GetScreenSaverReply, os.Error)

func (*Conn) GetScreenSaverRequest


func (c *Conn) GetScreenSaverRequest() Cookie

func (*Conn) GetSelectionOw ner


func (c *Conn) GetSelectionOwner(Selection Id) (*GetSelectionOwnerReply, os.Error)

func (*Conn) GetSelectionOw nerReply


func (c *Conn) GetSelectionOwnerReply(cookie Cookie) (*GetSelectionOwnerReply, os.Error)

func (*Conn) GetSelectionOw nerRequest


func (c *Conn) GetSelectionOwnerRequest(Selection Id) Cookie

func (*Conn) GetWindow Attributes


func (c *Conn) GetWindowAttributes(Window Id) (*GetWindowAttributesReply, os.Error)

func (*Conn) GetWindow AttributesReply


func (c *Conn) GetWindowAttributesReply(cookie Cookie) (*GetWindowAttributesReply, os.Error)

func (*Conn) GetWindow AttributesRequest


func (c *Conn) GetWindowAttributesRequest(Window Id) Cookie

func (*Conn) GrabButton


func (c *Conn) GrabButton(OwnerEvents byte, GrabWindow Id, EventMask uint16, PointerMode byte, KeyboardMode byte, ConfineTo Id, Cursor Id, Button byte, Modifiers uint16)

func (*Conn) GrabKey


func (c *Conn) GrabKey(OwnerEvents byte, GrabWindow Id, Modifiers uint16, Key byte, PointerMode byte, KeyboardMode byte)

func (*Conn) GrabKeyboard


func (c *Conn) GrabKeyboard(OwnerEvents byte, GrabWindow Id, Time Timestamp, PointerMode byte, KeyboardMode byte) (*GrabKeyboardReply, os.Error)

func (*Conn) GrabKeyboardReply


func (c *Conn) GrabKeyboardReply(cookie Cookie) (*GrabKeyboardReply, os.Error)

func (*Conn) GrabKeyboardRequest


func (c *Conn) GrabKeyboardRequest(OwnerEvents byte, GrabWindow Id, Time Timestamp, PointerMode byte, KeyboardMode byte) Cookie

func (*Conn) GrabPointer


func (c *Conn) GrabPointer(OwnerEvents byte, GrabWindow Id, EventMask uint16, PointerMode byte, KeyboardMode byte, ConfineTo Id, Cursor Id, Time Timestamp) (*GrabPointerReply, os.Error)

func (*Conn) GrabPointerReply


func (c *Conn) GrabPointerReply(cookie Cookie) (*GrabPointerReply, os.Error)

func (*Conn) GrabPointerRequest


func (c *Conn) GrabPointerRequest(OwnerEvents byte, GrabWindow Id, EventMask uint16,

PointerMode byte, KeyboardMode byte, ConfineTo Id, Cursor Id, Time Timestamp) Cookie

func (*Conn) GrabServer


func (c *Conn) GrabServer()

func (*Conn) Im ageText16


func (c *Conn) ImageText16(Drawable Id, Gc Id, X int16, Y int16, String []Char2b)

func (*Conn) Im ageText8


func (c *Conn) ImageText8(Drawable Id, Gc Id, X int16, Y int16, String []byte)

func (*Conn) InstallColorm ap


func (c *Conn) InstallColormap(Cmap Id)

func (*Conn) InternAtom


func (c *Conn) InternAtom(OnlyIfExists byte, Name string) (*InternAtomReply, os.Error)

func (*Conn) InternAtom Reply


func (c *Conn) InternAtomReply(cookie Cookie) (*InternAtomReply, os.Error)

func (*Conn) InternAtom Request


func (c *Conn) InternAtomRequest(OnlyIfExists byte, Name string) Cookie

func (*Conn) KillClient


func (c *Conn) KillClient(Resource uint32)

func (*Conn) ListExtensions


func (c *Conn) ListExtensions() (*ListExtensionsReply, os.Error)

func (*Conn) ListExtensionsReply


func (c *Conn) ListExtensionsReply(cookie Cookie) (*ListExtensionsReply, os.Error)

func (*Conn) ListExtensionsRequest


func (c *Conn) ListExtensionsRequest() Cookie

func (*Conn) ListFonts


func (c *Conn) ListFonts(MaxNames uint16, Pattern []byte) (*ListFontsReply, os.Error)

func (*Conn) ListFontsReply


func (c *Conn) ListFontsReply(cookie Cookie) (*ListFontsReply, os.Error)

func (*Conn) ListFontsRequest


func (c *Conn) ListFontsRequest(MaxNames uint16, Pattern []byte) Cookie

func (*Conn) ListFontsWithInfo


func (c *Conn) ListFontsWithInfo(MaxNames uint16, Pattern []byte) (*ListFontsWithInfoReply, os.Error)

func (*Conn) ListFontsWithInfoReply


func (c *Conn) ListFontsWithInfoReply(cookie Cookie) (*ListFontsWithInfoReply, os.Error)

func (*Conn) ListFontsWithInfoRequest


func (c *Conn) ListFontsWithInfoRequest(MaxNames uint16, Pattern []byte) Cookie

func (*Conn) ListHosts


func (c *Conn) ListHosts() (*ListHostsReply, os.Error)

func (*Conn) ListHostsReply


func (c *Conn) ListHostsReply(cookie Cookie) (*ListHostsReply, os.Error)

func (*Conn) ListHostsRequest


func (c *Conn) ListHostsRequest() Cookie

func (*Conn) ListInstalledColorm aps


func (c *Conn) ListInstalledColormaps(Window Id) (*ListInstalledColormapsReply, os.Error)

func (*Conn) ListInstalledColorm apsReply


func (c *Conn) ListInstalledColormapsReply(cookie Cookie) (*ListInstalledColormapsReply, os.Error)

func (*Conn) ListInstalledColorm apsRequest


func (c *Conn) ListInstalledColormapsRequest(Window Id) Cookie

func (*Conn) ListProperties


func (c *Conn) ListProperties(Window Id) (*ListPropertiesReply, os.Error)

func (*Conn) ListPropertiesReply


func (c *Conn) ListPropertiesReply(cookie Cookie) (*ListPropertiesReply, os.Error)

func (*Conn) ListPropertiesRequest


func (c *Conn) ListPropertiesRequest(Window Id) Cookie

func (*Conn) LookupColor


func (c *Conn) LookupColor(Cmap Id, Name string) (*LookupColorReply, os.Error)

func (*Conn) LookupColorReply


func (c *Conn) LookupColorReply(cookie Cookie) (*LookupColorReply, os.Error)

func (*Conn) LookupColorRequest


func (c *Conn) LookupColorRequest(Cmap Id, Name string) Cookie

func (*Conn) MapSubw indow s


func (c *Conn) MapSubwindows(Window Id)

func (*Conn) MapWindow


func (c *Conn) MapWindow(Window Id)

func (*Conn) New Id


func (c *Conn) NewId() Id NewID generates a new unused ID for use with requests like CreateWindow.

func (*Conn) NoOperation


func (c *Conn) NoOperation()

func (*Conn) OpenFont


func (c *Conn) OpenFont(Fid Id, Name string)

func (*Conn) PollForEvent


func (c *Conn) PollForEvent() (Event, os.Error) PollForEvent returns the next event from the server if one is available in the internal queue. It will not read from the connection, so you must call WaitForEvent to receive new events. Only use this function to empty the queue without blocking.

func (*Conn) PolyArc


func (c *Conn) PolyArc(Drawable Id, Gc Id, Arcs []Arc)

func (*Conn) PolyFillArc


func (c *Conn) PolyFillArc(Drawable Id, Gc Id, Arcs []Arc)

func (*Conn) PolyFillRectangle


func (c *Conn) PolyFillRectangle(Drawable Id, Gc Id, Rectangles []Rectangle)

func (*Conn) PolyLine


func (c *Conn) PolyLine(CoordinateMode byte, Drawable Id, Gc Id, Points []Point)

func (*Conn) PolyPoint


func (c *Conn) PolyPoint(CoordinateMode byte, Drawable Id, Gc Id, Points []Point)

func (*Conn) PolyRectangle


func (c *Conn) PolyRectangle(Drawable Id, Gc Id, Rectangles []Rectangle)

func (*Conn) PolySegm ent

func (c *Conn) PolySegment(Drawable Id, Gc Id, Segments []Segment)

func (*Conn) PolyText16


func (c *Conn) PolyText16(Drawable Id, Gc Id, X int16, Y int16, Items []byte)

func (*Conn) PolyText8


func (c *Conn) PolyText8(Drawable Id, Gc Id, X int16, Y int16, Items []byte)

func (*Conn) PutIm age


func (c *Conn) PutImage(Format byte, Drawable Id, Gc Id, Width uint16, Height uint16, DstX int16, DstY int16, LeftPad byte, Depth byte, Data []byte)

func (*Conn) QueryBestSize


func (c *Conn) QueryBestSize(Class byte, Drawable Id, Width uint16, Height uint16) (*QueryBestSizeReply, os.Error)

func (*Conn) QueryBestSizeReply


func (c *Conn) QueryBestSizeReply(cookie Cookie) (*QueryBestSizeReply, os.Error)

func (*Conn) QueryBestSizeRequest


func (c *Conn) QueryBestSizeRequest(Class byte, Drawable Id, Width uint16, Height uint16) Cookie

func (*Conn) QueryColors


func (c *Conn) QueryColors(Cmap Id, Pixels []uint32) (*QueryColorsReply, os.Error)

func (*Conn) QueryColorsReply


func (c *Conn) QueryColorsReply(cookie Cookie) (*QueryColorsReply, os.Error)

func (*Conn) QueryColorsRequest


func (c *Conn) QueryColorsRequest(Cmap Id, Pixels []uint32) Cookie

func (*Conn) QueryExtension


func (c *Conn) QueryExtension(Name string) (*QueryExtensionReply, os.Error)

func (*Conn) QueryExtensionReply


func (c *Conn) QueryExtensionReply(cookie Cookie) (*QueryExtensionReply, os.Error)

func (*Conn) QueryExtensionRequest


func (c *Conn) QueryExtensionRequest(Name string) Cookie

func (*Conn) QueryFont


func (c *Conn) QueryFont(Font Id) (*QueryFontReply, os.Error)

func (*Conn) QueryFontReply


func (c *Conn) QueryFontReply(cookie Cookie) (*QueryFontReply, os.Error)

func (*Conn) QueryFontRequest


func (c *Conn) QueryFontRequest(Font Id) Cookie

func (*Conn) QueryKeym ap


func (c *Conn) QueryKeymap() (*QueryKeymapReply, os.Error)

func (*Conn) QueryKeym apReply


func (c *Conn) QueryKeymapReply(cookie Cookie) (*QueryKeymapReply, os.Error)

func (*Conn) QueryKeym apRequest


func (c *Conn) QueryKeymapRequest() Cookie

func (*Conn) QueryPointer


func (c *Conn) QueryPointer(Window Id) (*QueryPointerReply, os.Error)

func (*Conn) QueryPointerReply


func (c *Conn) QueryPointerReply(cookie Cookie) (*QueryPointerReply, os.Error)

func (*Conn) QueryPointerRequest


func (c *Conn) QueryPointerRequest(Window Id) Cookie

func (*Conn) QueryTextExtents


func (c *Conn) QueryTextExtents(Font Id, String []Char2b) (*QueryTextExtentsReply, os.Error)

func (*Conn) QueryTextExtentsReply


func (c *Conn) QueryTextExtentsReply(cookie Cookie) (*QueryTextExtentsReply, os.Error)

func (*Conn) QueryTextExtentsRequest


func (c *Conn) QueryTextExtentsRequest(Font Id, String []Char2b) Cookie

func (*Conn) QueryTree


func (c *Conn) QueryTree(Window Id) (*QueryTreeReply, os.Error)

func (*Conn) QueryTreeReply


func (c *Conn) QueryTreeReply(cookie Cookie) (*QueryTreeReply, os.Error)

func (*Conn) QueryTreeRequest


func (c *Conn) QueryTreeRequest(Window Id) Cookie

func (*Conn) RecolorCursor


func (c *Conn) RecolorCursor(Cursor Id, ForeRed uint16, ForeGreen uint16, ForeBlue uint16, BackRed uint16, BackGreen uint16, BackBlue uint16)

func (*Conn) ReparentWindow

func (c *Conn) ReparentWindow(Window Id, Parent Id, X int16, Y int16)

func (*Conn) RotateProperties


func (c *Conn) RotateProperties(Window Id, Delta int16, Atoms []Id)

func (*Conn) SendEvent


func (c *Conn) SendEvent(Propagate byte, Destination Id, EventMask uint32, Event []byte)

func (*Conn) SetAccessControl


func (c *Conn) SetAccessControl(Mode byte)

func (*Conn) SetClipRectangles


func (c *Conn) SetClipRectangles(Ordering byte, Gc Id, ClipXOrigin int16, ClipYOrigin int16, Rectangles []Rectangle)

func (*Conn) SetCloseDow nMode


func (c *Conn) SetCloseDownMode(Mode byte)

func (*Conn) SetDashes


func (c *Conn) SetDashes(Gc Id, DashOffset uint16, Dashes []byte)

func (*Conn) SetFontPath


func (c *Conn) SetFontPath(FontQty uint16, Path []byte)

func (*Conn) SetInputFocus


func (c *Conn) SetInputFocus(RevertTo byte, Focus Id, Time Timestamp)

func (*Conn) SetModifierMapping


func (c *Conn) SetModifierMapping(KeycodesPerModifier byte, Keycodes []byte) (*SetModifierMappingReply, os.Error)

func (*Conn) SetModifierMappingReply


func (c *Conn) SetModifierMappingReply(cookie Cookie) (*SetModifierMappingReply, os.Error)

func (*Conn) SetModifierMappingRequest


func (c *Conn) SetModifierMappingRequest(KeycodesPerModifier byte, Keycodes []byte) Cookie

func (*Conn) SetPointerMapping


func (c *Conn) SetPointerMapping(Map []byte) (*SetPointerMappingReply, os.Error)

func (*Conn) SetPointerMappingReply


func (c *Conn) SetPointerMappingReply(cookie Cookie) (*SetPointerMappingReply, os.Error)

func (*Conn) SetPointerMappingRequest


func (c *Conn) SetPointerMappingRequest(Map []byte) Cookie

func (*Conn) SetScreenSaver


func (c *Conn) SetScreenSaver(Timeout int16, Interval int16, PreferBlanking byte, AllowExposures byte)

func (*Conn) SetSelectionOw ner


func (c *Conn) SetSelectionOwner(Owner Id, Selection Id, Time Timestamp)

func (*Conn) StoreColors


func (c *Conn) StoreColors(Cmap Id, Items []Coloritem)

func (*Conn) StoreNam edColor


func (c *Conn) StoreNamedColor(Flags byte, Cmap Id, Pixel uint32, Name string)

func (*Conn) TranslateCoordinates


func (c *Conn) TranslateCoordinates(SrcWindow Id, DstWindow Id, SrcX int16, SrcY int16) (*TranslateCoordinatesReply, os.Error)

func (*Conn) TranslateCoordinatesReply


func (c *Conn) TranslateCoordinatesReply(cookie Cookie) (*TranslateCoordinatesReply, os.Error)

func (*Conn) TranslateCoordinatesRequest


func (c *Conn) TranslateCoordinatesRequest(SrcWindow Id, DstWindow Id, SrcX int16, SrcY int16) Cookie

func (*Conn) UngrabButton


func (c *Conn) UngrabButton(Button byte, GrabWindow Id, Modifiers uint16)

func (*Conn) UngrabKey


func (c *Conn) UngrabKey(Key byte, GrabWindow Id, Modifiers uint16)

func (*Conn) UngrabKeyboard


func (c *Conn) UngrabKeyboard(Time Timestamp)

func (*Conn) UngrabPointer


func (c *Conn) UngrabPointer(Time Timestamp)

func (*Conn) UngrabServer


func (c *Conn) UngrabServer()

func (*Conn) UninstallColorm ap


func (c *Conn) UninstallColormap(Cmap Id)

func (*Conn) Unm apSubw indow s


func (c *Conn) UnmapSubwindows(Window Id)

func (*Conn) Unm apWindow


func (c *Conn) UnmapWindow(Window Id)

func (*Conn) WaitForEvent


func (c *Conn) WaitForEvent() (Event, os.Error) WaitForEvent returns the next event from the server. It will block until an event is available.

func (*Conn) WarpPointer


func (c *Conn) WarpPointer(SrcWindow Id, DstWindow Id, SrcX int16, SrcY int16, SrcWidth uint16, SrcHeight uint16, DstX int16, DstY int16)

type Cookie
Cookies are the sequence numbers used to pair replies up with their requests
type Cookie uint16

type CreateNotifyEvent
type CreateNotifyEvent struct { Parent Id Window Id X int16 Y int16 Width uint16 Height uint16 BorderWidth uint16 OverrideRedirect byte }

type DepthInfo
type DepthInfo Depth VisualsLen Visuals } struct { byte uint16 []VisualInfo

type DestroyNotifyEvent

type DestroyNotifyEvent struct { Event Id Window Id }

type EnterNotifyEvent
type EnterNotifyEvent struct { Detail byte Time Timestamp Root Id Event Id Child Id RootX int16 RootY int16 EventX int16 EventY int16 State uint16 Mode byte SameScreenFocus byte }

type Error
Error contains protocol errors returned to us by the X server.
type Error Detail Major Minor Cookie Id } struct { uint8 uint8 uint16 Cookie Id

func (*Error) String


func (e *Error) String() string

type Event
Event is an interface that can contain any of the events returned by the server. Use a type assertion switch to extract the Event structs.
type Event interface{}

type ExposeEvent

type ExposeEvent struct { Window Id X uint16 Y uint16 Width uint16 Height uint16 Count uint16 }

type FocusInEvent
type FocusInEvent struct { Detail byte Event Id Mode byte }

type FocusOutEvent
type FocusOutEvent FocusInEvent

type Fontprop
type Fontprop struct { Name Id Value uint32 }

type Format
type Format struct { Depth byte BitsPerPixel byte ScanlinePad byte }

type GetAtomNameReply
type GetAtomNameReply struct { NameLen uint16 Name []byte }

type GetFontPathReply
type GetFontPathReply struct { PathLen uint16 Path []Str }

type GetGeometryReply
type GetGeometryReply struct { Depth byte Root Id X int16 Y int16 Width uint16 Height uint16 BorderWidth uint16 }

type GetImageReply
type GetImageReply struct { Depth byte Length uint32 Visual Id Data []byte }

type GetInputFocusReply
type GetInputFocusReply struct { RevertTo byte Focus Id }

type GetKeyboardControlReply
type GetKeyboardControlReply struct { GlobalAutoRepeat byte LedMask uint32 KeyClickPercent byte BellPercent byte BellPitch uint16 BellDuration uint16 AutoRepeats [32]byte }

type GetKeyboardMappingReply
type GetKeyboardMappingReply struct { KeysymsPerKeycode byte Length uint32 Keysyms []Keysym }

type GetModifierMappingReply
type GetModifierMappingReply struct { KeycodesPerModifier byte Keycodes []byte }

type GetMotionEventsReply
type GetMotionEventsReply struct { EventsLen uint32 Events []Timecoord }

type GetPointerControlReply
type GetPointerControlReply AccelerationNumerator AccelerationDenominator Threshold } struct { uint16 uint16 uint16

type GetPointerMappingReply
type GetPointerMappingReply struct { MapLen byte Map []byte }

type GetPropertyReply

type GetPropertyReply struct { Format byte Type Id BytesAfter uint32 ValueLen uint32 Value []byte }

type GetScreenSaverReply
type GetScreenSaverReply struct { Timeout uint16 Interval uint16 PreferBlanking byte AllowExposures byte }

type GetSelectionOwnerReply
type GetSelectionOwnerReply struct { Owner Id }

type GetWindowAttributesReply
type GetWindowAttributesReply struct { BackingStore byte Visual Id Class uint16 BitGravity byte WinGravity byte BackingPlanes uint32 BackingPixel uint32 SaveUnder byte MapIsInstalled byte MapState byte OverrideRedirect byte Colormap Id AllEventMasks uint32 YourEventMask uint32 DoNotPropagateMask uint16 }

type GrabKeyboardReply

type GrabKeyboardReply struct { Status byte }

type GrabPointerReply
type GrabPointerReply struct { Status byte }

type GraphicsExposureEvent
type GraphicsExposureEvent struct { Drawable Id X uint16 Y uint16 Width uint16 Height uint16 MinorOpcode uint16 Count uint16 MajorOpcode byte }

type GravityNotifyEvent
type GravityNotifyEvent struct { Event Id Window Id X int16 Y int16 }

type Host
type Host struct { Family byte AddressLen uint16 Address []byte }

type Id
Id is used for all X identifiers, such as windows, pixmaps, and GCs.

type Id uint32

type InternAtomReply
type InternAtomReply struct { Atom Id }

type KeyPressEvent
type KeyPressEvent struct { Detail byte Time Timestamp Root Id Event Id Child Id RootX int16 RootY int16 EventX int16 EventY int16 State uint16 SameScreen byte }

type KeyReleaseEvent
type KeyReleaseEvent KeyPressEvent

type KeymapNotifyEvent
type KeymapNotifyEvent struct { Keys [31]byte }

type Keysym
type Keysym uint32

type LeaveNotifyEvent

type LeaveNotifyEvent EnterNotifyEvent

type ListExtensionsReply
type ListExtensionsReply struct { NamesLen byte Names []Str }

type ListFontsReply
type ListFontsReply struct { NamesLen uint16 Names []Str }

type ListFontsWithInfoReply
type ListFontsWithInfoReply struct { NameLen byte MinBounds Charinfo MaxBounds Charinfo MinCharOrByte2 uint16 MaxCharOrByte2 uint16 DefaultChar uint16 PropertiesLen uint16 DrawDirection byte MinByte1 byte MaxByte1 byte AllCharsExist byte FontAscent int16 FontDescent int16 RepliesHint uint32 Properties []Fontprop Name []byte }

type ListHostsReply
type ListHostsReply struct { Mode byte HostsLen uint16 Hosts []Host }

type ListInstalledColormapsReply
type ListInstalledColormapsReply struct { CmapsLen uint16 Cmaps []Id }

type ListPropertiesReply
type ListPropertiesReply struct { AtomsLen uint16 Atoms []Id }

type LookupColorReply
type LookupColorReply struct { ExactRed uint16 ExactGreen uint16 ExactBlue uint16 VisualRed uint16 VisualGreen uint16 VisualBlue uint16 }

type MapNotifyEvent
type MapNotifyEvent struct { Event Id Window Id OverrideRedirect byte }

type MapRequestEvent
type MapRequestEvent struct { Parent Id Window Id }

type MappingNotifyEvent

type MappingNotifyEvent struct { Request byte FirstKeycode byte Count byte }

type MotionNotifyEvent
type MotionNotifyEvent struct { Detail byte Time Timestamp Root Id Event Id Child Id RootX int16 RootY int16 EventX int16 EventY int16 State uint16 SameScreen byte }

type NoExposureEvent
type NoExposureEvent struct { Drawable Id MinorOpcode uint16 MajorOpcode byte }

type Point
type Point struct { X int16 Y int16 }

type PropertyNotifyEvent
type PropertyNotifyEvent struct { Window Id Atom Id Time Timestamp State byte }

type QueryBestSizeReply
type QueryBestSizeReply struct { Width uint16 Height uint16 }

type QueryColorsReply
type QueryColorsReply struct { ColorsLen uint16 Colors []Rgb }

type QueryExtensionReply
type QueryExtensionReply struct { Present byte MajorOpcode byte FirstEvent byte FirstError byte }

type QueryFontReply
type QueryFontReply struct { MinBounds Charinfo MaxBounds Charinfo MinCharOrByte2 uint16 MaxCharOrByte2 uint16 DefaultChar uint16 PropertiesLen uint16 DrawDirection byte MinByte1 byte MaxByte1 byte AllCharsExist byte FontAscent int16 FontDescent int16 CharInfosLen uint32 Properties []Fontprop CharInfos []Charinfo }

type QueryKeymapReply

type QueryKeymapReply struct { Keys [32]byte }

type QueryPointerReply
type QueryPointerReply struct { SameScreen byte Root Id Child Id RootX int16 RootY int16 WinX int16 WinY int16 Mask uint16 }

type QueryTextExtentsReply
type QueryTextExtentsReply struct { DrawDirection byte FontAscent int16 FontDescent int16 OverallAscent int16 OverallDescent int16 OverallWidth int32 OverallLeft int32 OverallRight int32 }

type QueryTreeReply
type QueryTreeReply struct { Root Id Parent Id ChildrenLen uint16 Children []Id }

type Rectangle
type Rectangle struct { X int16 Y int16 Width uint16 Height uint16 }

type ReparentNotifyEvent
type ReparentNotifyEvent struct { Event Id Window Id Parent Id X int16 Y int16 OverrideRedirect byte }

type ResizeRequestEvent
type ResizeRequestEvent struct { Window Id Width uint16 Height uint16 }

type Rgb
type Rgb struct { Red uint16 Green uint16 Blue uint16 }

type ScreenInfo
type ScreenInfo struct { Root Id DefaultColormap Id WhitePixel uint32 BlackPixel uint32 CurrentInputMasks uint32 WidthInPixels uint16 HeightInPixels uint16 WidthInMillimeters uint16 HeightInMillimeters uint16 MinInstalledMaps uint16 MaxInstalledMaps uint16 RootVisual Id BackingStores byte SaveUnders byte RootDepth byte AllowedDepthsLen byte AllowedDepths []DepthInfo }

type Segment
type Segment struct { X1 int16 Y1 int16 X2 int16 Y2 int16 }

type SelectionClearEvent
type SelectionClearEvent struct { Time Timestamp Owner Id Selection Id }

type SelectionNotifyEvent
type SelectionNotifyEvent struct { Time Timestamp Requestor Id Selection Id Target Id Property Id }

type SelectionRequestEvent
type SelectionRequestEvent struct { Time Timestamp Owner Id Requestor Id Selection Id Target Id Property Id }

type SetModifierMappingReply
type SetModifierMappingReply struct { Status byte }

type SetPointerMappingReply
type SetPointerMappingReply struct { Status byte }

type SetupInfo
type SetupInfo struct { Status ProtocolMajorVersion ProtocolMinorVersion Length ReleaseNumber ResourceIdBase ResourceIdMask MotionBufferSize VendorLen MaximumRequestLength RootsLen PixmapFormatsLen ImageByteOrder BitmapFormatBitOrder BitmapFormatScanlineUnit BitmapFormatScanlinePad MinKeycode MaxKeycode Vendor PixmapFormats Roots } byte uint16 uint16 uint16 uint32 uint32 uint32 uint32 uint16 uint16 byte byte byte byte byte byte byte byte []byte []Format []ScreenInfo

type Str
type Str struct { NameLen byte Name []byte }

type Timecoord
type Timecoord struct { Time Timestamp X int16 Y int16 }

type Timestamp

type Timestamp uint32

type TranslateCoordinatesReply
type TranslateCoordinatesReply struct { SameScreen byte Child Id DstX uint16 DstY uint16 }

type UnmapNotifyEvent
type UnmapNotifyEvent struct { Event Id Window Id FromConfigure byte }

type VisibilityNotifyEvent
type VisibilityNotifyEvent struct { Window Id State byte }

type VisualInfo
type VisualInfo struct { VisualId Id Class byte BitsPerRgbValue byte ColormapEntries uint16 RedMask uint32 GreenMask uint32 BlueMask uint32 }

Other packages
main

Except as noted, this content is licensed under Creative Commons Attribution 3.0.

The Go Programming Language

Package xml
Variables func Escape func Unmarshal type Attr type CharData func (CharData) Copy type Comment func (Comment) Copy type Directive func (Directive) Copy type EndElement type Name type Parser func NewParser func (*Parser) RawToken import "xml" Package xml implements a simple XML 1.0 parser that understands XML name spaces. Package files
read.go xml.go

func (*Parser) Skip func (*Parser) Token func (*Parser) Unmarshal type ProcInst func (ProcInst) Copy type StartElement type SyntaxError func (SyntaxError) String type Token type UnmarshalError func (UnmarshalError) String Bugs

Variables
HTMLAutoClose is the set of HTML elements that should be considered to close automatically.
var HTMLAutoClose = htmlAutoClose

HTMLEntity is an entity map containing translations for the standard HTML entity characters.
var HTMLEntity = htmlEntity

func Escape
func Escape(w io.Writer, s []byte) Escape writes to w the properly escaped XML equivalent of the plain text data s.

func Unmarshal

func Unmarshal(r io.Reader, val interface{}) os.Error Unmarshal parses an XML element from r and uses the reflect library to fill in an arbitrary struct, slice, or string pointed at by val. Well-formed data that does not fit into val is discarded. For example, given these definitions:
type Email struct { Where string "attr"; Addr string; } type Result struct { XMLName xml.Name "result"; Name string; Phone string; Email []Email; } result := Result{ Name: "name", Phone: "phone", Email: nil }

unmarshalling the XML input


<result> <email where="home"> <addr>gre@example.com</addr> </email> <email where='work'> <addr>gre@work.com</addr> </email> <name>Grace R. Emlin</name> <address>123 Main Street</address> </result>

via Unmarshal(r, &result) is equivalent to assigning


r = Result{ xml.Name{"", "result"}, "Grace R. Emlin", // name "phone", // no phone given []Email{ Email{ "home", "gre@example.com" }, Email{ "work", "gre@work.com" } } }

Note that the field r.Phone has not been modified and that the XML <address> element was discarded. Because Unmarshal uses the reflect package, it can only assign to upper case fields. Unmarshal uses a case-insensitive comparison to match XML element names to struct field names. Unmarshal maps an XML element to a struct using the following rules:

* 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 string of the form "tag" or "namespace-URL tag", the XML element must have the given tag (and, optionally, name space) or else Unmarshal returns an error. * If the XML element has an attribute whose name matches a struct field of type string with tag "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 a sub-element whose name matches a struct field whose tag is neither "attr" nor "chardata", Unmarshal maps the sub-element to that struct field. Otherwise, if the struct has a field named Any, unmarshal maps the sub-element to that struct field.

Unmarshal maps an XML element to a string or []byte by saving the concatenation of that elements character data in the string or []byte. 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 to a bool by setting it true if the string value is "true" or "1", or false otherwise. Unmarshal maps an XML element 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.

type Attr
An Attr represents an attribute in an XML element (Name=Value).
type Attr struct { Name Name Value string }

type CharData
A CharData represents XML character data (raw text), in which XML escape sequences have been replaced by the characters they represent.

type CharData []byte

func (CharData) Copy


func (c CharData) Copy() CharData

type Comment
A Comment represents an XML comment of the form <!--comment-->. The bytes do not include the <!-- and --> comment markers.
type Comment []byte

func (Com m ent) Copy


func (c Comment) Copy() Comment

type Directive
A Directive represents an XML directive of the form <!text>. The bytes do not include the <! and > markers.
type Directive []byte

func (Directive) Copy


func (d Directive) Copy() Directive

type EndElement
An EndElement represents an XML end element.
type EndElement struct { Name Name }

type Name
A Name represents an XML name (Local) annotated with a name space identifier (Space). In tokens returned by Parser.Token, the Space identifier is given as a canonical URL, not the short prefix used in the document being parsed.
type Name struct { Space, Local string }

type Parser
A Parser represents an XML parser reading a particular input stream. The parser assumes that its input is encoded in UTF-8.
type Parser 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: // // p.Strict = false; // p.AutoClose = HTMLAutoClose; // p.Entity = HTMLEntity // // creates a parser that can handle typical HTML. 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": "&", // "pos": "'", // "quot": `"`, // Entity map[string]string // contains unexported fields }

func New Parser


func NewParser(r io.Reader) *Parser NewParser creates a new XML parser reading from r.

func (*Parser) Raw Token


func (p *Parser) RawToken() (Token, os.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 (*Parser) Skip


func (p *Parser) Skip() os.Error

Have already read a start element. Read tokens until we find the end element. Token is taking care of making sure the end element matches the start element we saw.

func (*Parser) Token


func (p *Parser) Token() (t Token, err os.Error) Token returns the next XML token in the input stream. At the end of the input stream, Token returns nil, os.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 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, 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.

func (*Parser) Unm arshal


func (p *Parser) Unmarshal(val interface{}, start *StartElement) os.Error The Parser's Unmarshal method is like xml.Unmarshal except that it can be passed a pointer to the initial start element, useful when a client reads some raw XML tokens itself but also defers to Unmarshal for some elements. Passing a nil start element indicates that Unmarshal should read the token stream to find the start element.

type ProcInst
A ProcInst represents an XML processing instruction of the form <?target inst?>
type ProcInst struct { Target string Inst []byte }

func (ProcInst) Copy


func (p ProcInst) Copy() ProcInst

type StartElement
A StartElement represents an XML start element.

type StartElement struct { Name Name Attr []Attr }

type SyntaxError
A SyntaxError represents a syntax error in the XML input stream.
type SyntaxError string

func (SyntaxError) String


func (e SyntaxError) String() string

type Token
A Token is an interface holding one of the token types: StartElement, EndElement, CharData, Comment, ProcInst, or Directive.
type Token interface{}

type UnmarshalError
An UnmarshalError represents an error in the unmarshalling process.
type UnmarshalError string

func (Unm arshalError) String


func (e UnmarshalError) String() string

Bugs
Mapping between XML elements and data structures is inherently flawed: an XML element is an orderdependent 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.

Except as noted, this content is licensed under Creative Commons Attribution 3.0.

You might also like