8
8
This document demonstrates the development of a simple Go package and
9
introduces the <a href="/cmd/go/">go command</a>, the standard way to fetch,
9
introduces the <a href="/cmd/go/">go tool</a>, the standard way to fetch,
10
10
build, and install Go packages and commands.
14
<h2 id="GOPATH">Code organization</h2>
16
<h3><code>GOPATH</code> and workspaces</h3>
19
One of Go's design goals is to make writing software easier. To that end, the
20
<code>go</code> command doesn't use Makefiles or other configuration files to
21
guide program construction. Instead, it uses the source code to find
22
dependencies and determine build conditions. This means your source code and
23
build scripts are always in sync; they are one and the same.
27
The one thing you must do is set a <code>GOPATH</code> environment variable.
28
<code>GOPATH</code> tells the <code>go</code> command (and other related tools)
29
where to find and install the Go packages on your system.
33
<code>GOPATH</code> is a list of paths. It shares the syntax of your system's
34
<code>PATH</code> environment variable. A typical <code>GOPATH</code> on
35
a Unix system might look like this:
39
GOPATH=/home/user/ext:/home/user/mygo
43
(On a Windows system use semicolons as the path separator instead of colons.)
47
Each path in the list (in this case <code>/home/user/ext</code> or
48
<code>/home/user/mygo</code>) specifies the location of a <i>workspace</i>.
49
A workspace contains Go source files and their associated package objects, and
50
command executables. It has a prescribed structure of three subdirectories:
14
The <code>go</code> tool requires you to organize your code in a specific
15
way. Please read this document carefully.
16
It explains the simplest way to get up and running with your Go installation.
20
A similar explanation is available as a
21
<a href="http://www.youtube.com/watch?v=XCsL89YtqCs">screencast</a>.
25
<h2 id="Organization">Code organization</h2>
27
<h3 id="Workspaces">Workspaces</h3>
30
The <code>go</code> tool is designed to work with open source code maintained
31
in public repositories. Although you don't need to publish your code, the model
32
for how the environment is set up works the same whether you do or not.
36
Go code must be kept inside a <i>workspace</i>.
37
A workspace is a directory hierarchy with three directories at its root:
54
<li><code>src</code> contains Go source files,
55
<li><code>pkg</code> contains compiled package objects, and
41
<li><code>src</code> contains Go source files organized into packages (one package per directory),
42
<li><code>pkg</code> contains package objects, and
56
43
<li><code>bin</code> contains executable commands.
60
Subdirectories of the <code>src</code> directory hold independent packages, and
61
all source files (<code>.go</code>, <code>.c</code>, <code>.h</code>, and
62
<code>.s</code>) in each subdirectory are elements of that subdirectory's
67
When building a program that imports the package "<code>widget</code>" the
68
<code>go</code> command looks for <code>src/pkg/widget</code> inside the Go root,
69
and then—if the package source isn't found there—it searches
70
for <code>src/widget</code> inside each workspace in order.
74
Multiple workspaces can offer some flexibility and convenience, but for now
75
we'll concern ourselves with only a single workspace.
79
Let's work through a simple example. First, create a <code>$HOME/mygo</code>
80
directory and its <code>src</code> subdirectory:
84
$ mkdir -p $HOME/mygo/src # create a place to put source code
88
Next, set it as the <code>GOPATH</code>. You should also add the
89
<code>bin</code> subdirectory to your <code>PATH</code> environment variable so
90
that you can run the commands therein without specifying their full path.
91
To do this, add the following lines to <code>$HOME/.profile</code> (or
96
export GOPATH=$HOME/mygo
97
export PATH=$PATH:$HOME/mygo/bin
101
<h3>Import paths</h3>
104
The standard packages are given short import paths such as <code>"fmt"</code>
105
and <code>"net/http"</code> for convenience.
106
For your own projects, it is important to choose a base import path that is
107
unlikely to collide with future additions to the standard library or other
112
The best way to choose an import path is to use the location of your version
114
For instance, if your source repository is at <code>example.com</code>
115
or <code>code.google.com/p/example</code>, you should begin your package
116
paths with that URL, as in "<code>example.com/foo/bar</code>" or
117
"<code>code.google.com/p/example/foo/bar</code>".
118
Using this convention, the <code>go</code> command can automatically check out and
119
build the source code by its import path alone.
123
If you don't intend to install your code in this way, you should at
124
least use a unique prefix like "<code>widgets/</code>", as in
125
"<code>widgets/foo/bar</code>". A good rule is to use a prefix such as your
126
company or project name, since it is unlikely to be used by another group.
130
We'll use <code>example/</code> as our base import path:
134
$ mkdir -p $GOPATH/src/example
138
<h3>Package names</h3>
141
The first statement in a Go source file should be
47
The <code>go</code> tool builds source packages and installs the resulting
48
binaries to the <code>pkg</code> and <code>bin</code> directories.
52
The <code>src</code> subdirectory typically contains multiple version control
53
repositories (such as for Git or Mercurial) that track the development of one
54
or more source packages.
58
To give you an idea of how a workspace looks in practice, here's an example:
63
streak # command executable
64
todo # command executable
67
code.google.com/p/goauth2/
68
oauth.a # package object
70
task.a # package object
72
code.google.com/p/goauth2/
73
.hg/ # mercurial repository metadata
75
oauth.go # package source
76
oauth_test.go # test source
79
.git/ # git repository metadata
80
oauth.go # command source
81
streak.go # command source
83
.git/ # git repository metadata
85
task.go # package source
86
todo.go # command source
90
This workspace contains three repositories (<code>goauth2</code>,
91
<code>streak</code>, and <code>todo</code>) comprising two commands
92
(<code>streak</code> and <code>todo</code>) and two libraries
93
(<code>oauth</code> and <code>task</code>).
97
Commands and libraries are built from different kinds of source packages.
98
We will discuss the distinction <a href="#PackageNames">later</a>.
102
<h3 id="GOPATH">The <code>GOPATH</code> environment variable</h3>
105
The <code>GOPATH</code> environment variable specifies the location of your
106
workspace. It is likely the only environment variable you'll need to set
107
when developing Go code.
111
To get started, create a workspace directory and set <code>GOPATH</code>
112
accordingly. Your workspace can be located wherever you like, but we'll use
113
<code>$HOME/go</code> in this document. Note that this must <b>not</b> be the
114
same path as your Go installation.
118
$ <b>mkdir $HOME/go</b>
119
$ <b>export GOPATH=$HOME/go</b>
123
For convenience, add the workspace's <code>bin</code> subdirectory
124
to your <code>PATH</code>:
128
$ <b>export PATH=$PATH:$GOPATH/bin</b>
132
<h3 id="PackagePaths">Package paths</h3>
135
The packages from the standard library are given short paths such as
136
<code>"fmt"</code> and <code>"net/http"</code>.
137
For your own packages, you must choose a base path that is unlikely to
138
collide with future additions to the standard library or other external
143
If you keep your code in a source repository somewhere, then you should use the
144
root of that source repository as your base path.
145
For instance, if you have a <a href="https://github.com/">GitHub</a> account at
146
<code>github.com/user</code>, that should be your base path.
150
Note that you don't need to publish your code to a remote repository before you
151
can build it. It's just a good habit to organize your code as if you will
152
publish it someday. In practice you can choose any arbitrary path name,
153
as long as it is unique to the standard library and greater Go ecosystem.
157
We'll use <code>github.com/user</code> as our base path. Create a directory
158
inside your workspace in which to keep source code:
162
$ <b>mkdir -p $GOPATH/src/github.com/user</b>
166
<h3 id="Command">Your first program</h3>
169
To compile and run a simple program, first choose a package path (we'll use
170
<code>github.com/user/hello</code>) and create a corresponding package directory
171
inside your workspace:
175
$ <b>mkdir $GOPATH/src/github.com/user/hello</b>
179
Next, create a file named <code>hello.go</code> inside that directory,
180
containing the following Go code.
189
fmt.Printf("Hello, world.\n")
194
Now you can build and install that program with the <code>go</code> tool:
198
$ <b>go install github.com/user/hello</b>
202
Note that you can run this command from anywhere on your system. The
203
<code>go</code> tool finds the source code by looking for the
204
<code>github.com/user/hello</code> package inside the workspace specified by
209
You can also omit the package path if you run <code>go install</code> from the
214
$ <b>cd $GOPATH/src/github.com/user/hello</b>
219
This command builds the <code>hello</code> command, producing an executable
220
binary. It then installs that binary to the workspace's <code>bin</code>
221
directory as <code>hello</code> (or, under Windows, <code>hello.exe</code>).
222
In our example, that will be <code>$GOPATH/bin/hello</code>, which is
223
<code>$HOME/go/bin/hello</code>.
227
The <code>go</code> tool will only print output when an error occurs, so if
228
these commands produce no output they have executed successfully.
232
You can now run the program by typing its full path at the command line:
236
$ <b>$GOPATH/bin/hello</b>
241
Or, as you have added <code>$GOPATH/bin</code> to your <code>PATH</code>,
242
just type the binary name:
251
If you're using a source control system, now would be a good time to initialize
252
a repository, add the files, and commit your first change. Again, this step is
253
optional: you do not need to use source control to write Go code.
257
$ <b>cd $GOPATH/src/github.com/user/hello</b>
259
Initialized empty Git repository in /home/user/go/src/github.com/user/hello/.git/
260
$ <b>git add hello.go</b>
261
$ <b>git commit -m "initial commit"</b>
262
[master (root-commit) 0b4507d] initial commit
263
1 file changed, 1 insertion(+)
264
create mode 100644 hello.go
268
Pushing the code to a remote repository is left as an exercise for the reader.
272
<h3 id="Library">Your first library</h3>
275
Let's write a library and use it from the <code>hello</code> program.
279
Again, the first step is to choose a package path (we'll use
280
<code>github.com/user/newmath</code>) and create the package directory:
284
$ <b>mkdir $GOPATH/src/github.com/user/newmath</b>
288
Next, create a file named <code>sqrt.go</code> in that directory with the
293
// Package newmath is a trivial example package.
296
// Sqrt returns an approximation to the square root of x.
297
func Sqrt(x float64) float64 {
299
for i := 0; i < 1000; i++ {
300
z -= (z*z - x) / (2 * x)
307
Now, test that the package compiles with <code>go build</code>:
311
$ <b>go build github.com/user/newmath</b>
315
Or, if you are working in the package's source directory, just:
323
This won't produce an output file. To do that, you must use <code>go
324
install</code>, which places the package object inside the <code>pkg</code>
325
directory of the workspace.
329
After confirming that the <code>newmath</code> package builds,
330
modify your original <code>hello.go</code> (which is in
331
<code>$GOPATH/src/github.com/user/hello</code>) to use it:
340
<b>"github.com/user/newmath"</b>
344
fmt.Printf("Hello, world. <b>Sqrt(2) = %v\n", newmath.Sqrt(2)</b>)
349
Whenever the <code>go</code> tool installs a package or binary, it also
350
installs whatever dependencies it has. So when you install the <code>hello</code>
355
$ <b>go install github.com/user/hello</b>
359
the <code>newmath</code> package will be installed as well, automatically.
363
Running the new version of the program, you should see some numerical output:
368
Hello, world. Sqrt(2) = 1.414213562373095
372
After the steps above, your workspace should look like this:
377
hello # command executable
379
linux_amd64/ # this will reflect your OS and architecture
381
newmath.a # package object
385
hello.go # command source
387
sqrt.go # package source
391
Note that <code>go install</code> placed the <code>newmath.a</code> object in a
392
directory inside <code>pkg/linux_amd64</code> that mirrors its source
394
This is so that future invocations of the <code>go</code> tool can find the
395
package object and avoid recompiling the package unnecessarily.
396
The <code>linux_amd64</code> part is there to aid in cross-compilation,
397
and will reflect the operating system and architecture of your system.
401
Go command executables are statically linked; the package objects need not
402
be present to run Go programs.
406
<h3 id="PackageNames">Package names</h3>
409
The first statement in a Go source file must be
154
422
Go's convention is that the package name is the last element of the
155
423
import path: the package imported as "<code>crypto/rot13</code>"
156
424
should be named <code>rot13</code>.
428
Executable commands must always use <code>package main</code>.
157
432
There is no requirement that package names be unique
158
433
across all packages linked into a single binary,
159
434
only that the import paths (their full file names) be unique.
163
Create a new package under <code>example</code> called <code>newmath</code>:
167
$ cd $GOPATH/src/example
172
Then create a file named <code>$GOPATH/src/example/newmath/sqrt.go</code>
173
containing the following Go code:
177
// Package newmath is a trivial example package.
180
// Sqrt returns an approximation to the square root of x.
181
func Sqrt(x float64) float64 {
182
// This is a terrible implementation.
183
// Real code should import "math" and use math.Sqrt.
185
for i := 0; i < 1000; i++ {
186
z -= (z*z - x) / (2 * x)
193
This package is imported by the path name of the directory it's in, starting
194
after the <code>src</code> component:
198
import "example/newmath"
202
438
See <a href="/doc/effective_go.html#names">Effective Go</a> to learn more about
203
439
Go's naming conventions.
207
<h2>Building and installing</h2>
210
The <code>go</code> command comprises several subcommands, the most central being
211
<code>install</code>. Running <code>go install <i>importpath</i></code> builds
212
and installs a package and its dependencies.
216
To "install a package" means to write the package object or executable command
217
to the <code>pkg</code> or <code>bin</code> subdirectory of the workspace in
218
which the source resides.
221
<h3>Building a package</h3>
224
To build and install the <code>newmath</code> package, type
228
$ go install example/newmath
232
This command will produce no output if the package and its dependencies
233
are built and installed correctly.
237
As a convenience, the <code>go</code> command will assume the current directory
238
if no import path is specified on the command line. This sequence of commands
239
has the same effect as the one above:
243
$ cd $GOPATH/src/example/newmath
248
The resulting workspace directory tree (assuming we're running Linux on a 64-bit
249
system) looks like this:
256
newmath.a # package object
260
sqrt.go # package source
264
<h3>Building a command</h3>
267
The <code>go</code> command treats code belonging to <code>package main</code> as
268
an executable command and installs the package binary to the
269
<code>GOPATH</code>'s <code>bin</code> subdirectory.
273
Add a command named <code>hello</code> to the source tree.
274
First create the <code>example/hello</code> directory:
278
$ cd $GOPATH/src/example
283
Then create the file <code>$GOPATH/src/example/hello/hello.go</code>
284
containing the following Go code.
288
// Hello is a trivial example of a main package.
297
fmt.Printf("Hello, world. Sqrt(2) = %v\n", newmath.Sqrt(2))
302
Next, run <code>go install</code>, which builds and installs the binary to
303
<code>$GOPATH/bin</code> (or <code>$GOBIN</code>, if set; to simplify
304
presentation, this document assumes <code>GOBIN</code> is unset):
308
$ go install example/hello
312
To run the program, invoke it by name as you would any other command:
317
Hello, world. Sqrt(2) = 1.414213562373095
321
If you added <code>$HOME/mygo/bin</code> to your <code>PATH</code>, you may omit
322
the path to the executable:
327
Hello, world. Sqrt(2) = 1.414213562373095
331
The workspace directory tree now looks like this:
336
hello # command executable
340
newmath.a # package object
344
hello.go # command source
346
sqrt.go # package source
350
The <code>go</code> command also provides a <code>build</code> command, which is
351
like <code>install</code> except it builds all objects in a temporary directory
352
and does not install them under <code>pkg</code> or <code>bin</code>.
353
When building a command an executable named after the last element of the
354
import path is written to the current directory. When building a package,
355
<code>go build</code> serves merely to test that the package and its
356
dependencies can be built. (The resulting package object is thrown away.)
360
443
<h2 id="Testing">Testing</h2>