    <rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:sy="http://purl.org/rss/1.0/modules/syndication/" xmlns:admin="http://webns.net/mvcb/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:content="http://purl.org/rss/1.0/modules/content/">
     <channel>
        <title>ACCU  :: Hello World in Go</title>
        <link>https://members.accu.org/index.php/articles/2321</link>
        <description>Professionalism in Programming</description>
        <dc:language>en-us</dc:language> 
        <dc:creator>Administrator</dc:creator> 
        <admin:generatorAgent rdf:resource="http://www.xaraya.org" /> 
        <admin:errorReportsTo rdf:resource="mailto:webeditor@accu.org" />
       <sy:updatePeriod>hourly</sy:updatePeriod>
       <sy:updateFrequency>1</sy:updateFrequency>
       <docs>http://backend.userland.com/rss</docs>




<div class="xar-mod-head"><span class="xar-mod-title">Programming Topics + Overload Journal #136 - December 2016</span></div>

<table border="0" cellpadding="1" cellspacing="0">
    <tbody>
    <tr>
        <td valign="top">
            Browse in :
       </td>
       <td valign="top">

                                            <a href="https://members.accu.org/index.php/articles/">All</a>

                     &gt;                         <a href="https://members.accu.org/index.php/articles/c13/">Topics</a>

                     &gt;                         <a href="https://members.accu.org/index.php/articles/c65/">Programming</a>
<br />

                                            <a href="https://members.accu.org/index.php/articles/">All</a>

                     &gt;                         <a href="https://members.accu.org/index.php/articles/c76/">Journals</a>

                     &gt;                         <a href="https://members.accu.org/index.php/articles/c78/">Overload</a>

                     &gt;                         <a href="https://members.accu.org/index.php/articles/c368/">o136</a>
<br />

                                            <a href="https://members.accu.org/index.php/articles/c65-368/">Any of these categories</a>

                    -                        <a href="https://members.accu.org/index.php/articles/c65+368/">All of these categories</a>
<br />
</td>
   </tr>
   </tbody>
</table>




<div class="xar-error">
   <p>
 <strong>Note:</strong> when you create a new publication type,
the articles module will automatically use the templates
<em>user-display-[publicationtype].xt</em>
and <em>user-summary-[publicationtype].xt</em>.
If those templates do not exist when you try to preview or display a new article,
you'll get this warning :-)  Please place your own templates in themes/<em>yourtheme</em>/modules/articles . The templates will get the extension .xt there. </p>
</div>
<div class="xar-norm xar-standard-box-padding">
   <h1><strong>Title:</strong>&nbsp;Hello World in Go</h1>
<p><strong>Author:</strong>&nbsp;Martin Moene</p>
<p>
<strong>Date:</strong> 02 December 2016 20:47:03 +00:00 or Fri, 02 December 2016 20:47:03 +00:00</p>
<p><strong>Summary:</strong>&nbsp;Go provides a way to write efficient concurrent programs in a C-like language. Eleanor McHugh shares a &quot;Hello, world!&quot; tutorial.</p>
<p><strong>Body:</strong>&nbsp;<p>Itâ€™s a tradition in programming books to start with a canonical â€˜Hello Worldâ€™ example and whilst Iâ€™ve never felt the usual presentation is particularly enlightening, I know we can spice things up a little to provide useful insights into how we write Go programs.</p>

<p>Letâ€™s begin with the simplest Go program that will output text to the console (Listing 1).</p>

<table class="sidebartable">
	<tr>
		<td>
			<pre class="programlisting">
 1 package main
 2 func main() {
 3   println(&quot;hello world&quot;)
 4 }
			</pre>
		</td>
	</tr>
	<tr>
		<td class="title">Listing 1</td>
	</tr>
</table>

<p>The first thing to note is that every Go source file belongs to a package, with the main package defining an executable program whilst all other packages represent libraries.</p>

<pre class="programlisting">
  1 package main</pre>
  
<p>For the main package to be executable it needs to include a <code>main()</code> function, which will be called following program initialisation.</p>

<pre class="programlisting">
  2 func main() {</pre>
  
<p>Notice that unlike C/C++, the <code>main()</code> function neither takes parameters nor has a return value. Whenever a program should interact with command-line parameters or return a value on termination, these tasks are handled using functions in the standard package library. Weâ€™ll examine command-line parameters when developing <code>Echo</code>.</p>

<p>Finally letâ€™s look at our payload.</p>

<pre class="programlisting">
  3 println(&quot;hello world&quot;)</pre>
  
<p>The <code>println()</code> function is one of a small set of built-in generic functions defined in the language specification and which in this case is usually used to assist debugging, whilst <code>&quot;hello world&quot;</code> is a value comprising an immutable string of characters in utf-8 format.</p>

<p>We can now run our program from the command-line (Terminal on MacOS X or Command Prompt on Windows) with the command</p>

<pre class="programlisting">
  $ go run 01.go
  hello world</pre>

<h2>Packages</h2>

<p>Now weâ€™re going to apply a technique which I plan to use throughout my book by taking this simple task and developing increasingly complex ways of expressing it in Go. This runs counter to how experienced programmers usually develop code but I feel this makes for a very effective way to introduce features of Go in rapid succession and have used it with some success during presentations and workshops.</p>

<p>There are a number of ways we can artificially complicate our hello world example and by the time weâ€™ve finished I hope to have demonstrated all the features you can expect to see in the global scope of a Go package. Our first change is to remove the built-in <code>println()</code> function and replace it with something intended for production code (see Listing 2).</p>

<table class="sidebartable">
	<tr>
		<td>
			<pre class="programlisting">
 1 package main
 2 import &quot;fmt&quot;
 3 func main() {
 4   fmt.Println(&quot;hello world&quot;)
 5 }
			</pre>
		</td>
	</tr>
	<tr>
		<td class="title">Listing 2</td>
	</tr>
</table>

<p>The structure of our program remains essentially the same, but weâ€™ve introduced two new features.</p>

<pre class="programlisting">
  2 import &quot;fmt&quot;</pre>
  
<p>The <code>import</code> statement is a reference to the <code>fmt</code> package, one of many packages defined in Goâ€™s standard runtime library. A <code>package</code> is a library which provides a group of related functions and data types we can use in our programs. In this case, <code>fmt</code> provides functions and types associated with formatting text for printing and displaying it on a console or in the command shell.</p>

<pre class="programlisting">
  4 fmt.Println(&quot;hello world&quot;)</pre>
  
<p>One of the functions provided by <code>fmt</code> is <code>Println()</code>, which takes one or more parameters and prints them to the console with a carriage return appended. Go assumes that any identifier starting with a capital letter is part of the public interface of a package whilst identifiers starting with any other letter or symbol are private to the package.</p>

<p>In production code we might choose to simplify matters a little by importing the <code>fmt</code> namespace into the namespace of the current source file, which requires we change our <code>import</code> statement.</p>

<pre class="programlisting">
  2 import . &quot;fmt&quot;</pre>
  
<p>And this consequently allows the explicit package reference to be removed from the <code>Println()</code> function call.</p>

<pre class="programlisting">
  4 Println(&quot;hello world&quot;)</pre>
  
<p>In this case we notice little gain; however, in later examples weâ€™ll use this feature extensively to keep our code legible (Listing 3).</p>

<table class="sidebartable">
	<tr>
		<td>
			<pre class="programlisting">
 1 package main
 2 import . &quot;fmt&quot;
 3 func main() {
 4   Println(&quot;hello world&quot;)
 5 }
			</pre>
		</td>
	</tr>
	<tr>
		<td class="title">Listing 3</td>
	</tr>
</table>

<p>One aspect of imports that weâ€™ve not yet looked at is Goâ€™s built-in support for code hosted on a variety of popular social code-sharing sites such as GitHub and Google Code. Donâ€™t worry, weâ€™ll get to this in later chapters of my book.</p>


<h2>Constants</h2>

<p>A significant proportion of Go codebases feature identifiers whose values will not change during the runtime execution of a program and our â€˜Hello Worldâ€™ example is no different (Listing 4), so weâ€™re going to factor these out.</p>

<table class="sidebartable">
	<tr>
		<td>
			<pre class="programlisting">
 1 package main
 2 import . &quot;fmt&quot;
 3 const Hello = &quot;hello&quot;
 4 const world = &quot;world&quot;
 5 func main() {
 6   Println(Hello, world)
 7 }
			</pre>
		</td>
	</tr>
	<tr>
		<td class="title">Listing 4</td>
	</tr>
</table>

<p>Here weâ€™ve introduced two constants: <code>Hello</code> and <code>world</code>. Each identifier is assigned its value during compilation, and that value cannot be changed at runtime. As the identifier <code>Hello</code> starts with a capital letter the associated constant is visible to other packages â€“ though this isnâ€™t relevant in the context of a <code>main</code> package â€“ whilst the identifier <code>world</code> starts with a lowercase letter and is only accessible within the <code>main</code> package.</p>

<p>We donâ€™t need to specify the type of these constants as the Go compiler identifies them both as strings.</p>

<p>Another neat trick in Goâ€™s armoury is multiple assignment so letâ€™s see how this looks (see Listing 5).</p>

<table class="sidebartable">
	<tr>
		<td>
			<pre class="programlisting">
 1 package main
 2 import . &quot;fmt&quot;
 3 const Hello, world = &quot;hello&quot;, &quot;world&quot;
 4 func main() {
 5   Println(Hello, world)
 6 }
			</pre>
		</td>
	</tr>
	<tr>
		<td class="title">Listing 5</td>
	</tr>
</table>

<p>This is compact, but I personally find it too cluttered and prefer the more general form (Listing 6).</p>

<table class="sidebartable">
	<tr>
		<td>
			<pre class="programlisting">
 1 package main
 2 import . &quot;fmt&quot;
 3 const (
 4   Hello = &quot;hello&quot;
 5   world =  &quot;world&quot;
 6 )
 7 func main() {
 8   Println(Hello, world)
 9 }
			</pre>
		</td>
	</tr>
	<tr>
		<td class="title">Listing 6</td>
	</tr>
</table>

<p>Because the <code>Println()</code> function is <em>variadic</em> (i.e. can take a varible number of parameters) we can pass it both constants and it will print them on the same line, separate by whitespace. <code>fmt</code> also provides the <code>Printf()</code> function which gives precise control over how its parameters are displayed using a format specifier which will be familiar to seasoned C/C++ programmers.</p>

<pre class="programlisting">
  8 Printf(&quot;%v %v\n&quot;, Hello, world)</pre>
  
<p><code>fmt</code> defines a number of % replacement terms which can be used to determine how a particular parameter will be displayed. Of these <code>%v</code> is the most generally used as it allows the formatting to be specified by the type of the parameter. Weâ€™ll discuss this in depth when we look at user-defined types, but in this case it will simply replace a <code>%v</code> with the corresponding string.</p>

<p>When parsing strings the Go compiler recognises a number of <em>escape sequences</em> which are available to mark tabs, new lines and specific unicode characters. In this case we use <code>\n</code> to mark a new line (Listing 7).</p>

<table class="sidebartable">
	<tr>
		<td>
			<pre class="programlisting">
 1 package main
 2 import . &quot;fmt&quot;
 3 const (
 4   Hello = &quot;hello&quot;
 5   world =  &quot;world&quot;
 6 )
 7 func main() {
 8   Printf(&quot;%v %v\n&quot;, Hello, world)
 9 }
			</pre>
		</td>
	</tr>
	<tr>
		<td class="title">Listing 7</td>
	</tr>
</table>

<h2>Variables</h2>

<p>Constants are useful for referring to values which shouldnâ€™t change at runtime; however, most of the time when weâ€™re referencing values in an imperative language like Go we need the freedom to change these values. We associate values which will change with variables. What follows is a simple variation of our Hello World program which allows the value of <code>world</code> to be changed at runtime by creating a new value and assigning it to the <code>world</code> variable (Listing 8).</p>

<table class="sidebartable">
	<tr>
		<td>
			<pre class="programlisting">
 1 package main
 2 import . &quot;fmt&quot;
 3 const Hello = &quot;hello&quot;
 4 var world = &quot;world&quot;
 5 func main() {
 6   world += &quot;!&quot;
 7   Println(Hello, world)
 8 }
			</pre>
		</td>
	</tr>
	<tr>
		<td class="title">Listing 8</td>
	</tr>
</table>

<p>There are two important changes here. Firstly weâ€™ve introduced syntax for declaring a variable and assigning a value to it. Once more Goâ€™s ability to infer type allows us assign a <code>string</code> value to the variable <code>world</code> without explicitly specifying the type.</p>

<pre class="programlisting">
  4 var world = &quot;world&quot;</pre>
  
<p>However if we wish to be more explicit we can be.</p>

<pre class="programlisting">
  4 var world string = &quot;world&quot;</pre>
  
<p>Having defined <code>world</code> as a variable in the global scope we can modify its value in <code>main()</code>, and in this case we choose to append an exclamation mark. Strings in Go are immutable values so following the assignment <code>world</code> will reference a new value.</p>

<pre class="programlisting">
  6 world += &quot;!&quot;</pre>
  
<p>To add some extra interest, Iâ€™ve chosen to use an <em>augmented assignment</em> operator. These are a syntactic convenience popular in many languages which allow the value contained in a variable to be modified and the resulting value then assigned to the same variable.</p>

<p>I donâ€™t intend to expend much effort discussing scope in Go. The point of my book is to experiment and learn by playing with code, referring to the comprehensive language specification available from Google when you need to know the technicalities of a given point. However, to illustrate the difference between <em>global</em> and <em>local</em> scope weâ€™ll modify this program further (see Listing 9).</p>

<table class="sidebartable">
	<tr>
		<td>
			<pre class="programlisting">
 1 package main
 2 import . &quot;fmt&quot;
 3 
 4 const Hello = &quot;hello&quot;
 5 var world = &quot;world&quot;
 6 
 7 func main() {
 8   world := world + &quot;!&quot;
 9   Println(Hello, world)
10 }
			</pre>
		</td>
	</tr>
	<tr>
		<td class="title">Listing 9</td>
	</tr>
</table>

<p>Here weâ€™ve introduced a new <em>local</em> variable <code>world</code> within <code>main()</code> which takes its value from an operation concatenating the value of the <em>global</em> <code>world</code> variable with an exclamation mark. Within <code>main()</code>, any subsequent reference to <code>world</code> will always access the <em>local</em> version of the variable without affecting the <em>global</em> <code>world</code> variable. This is known as <em>shadowing</em>.</p>

<p>The <code>:=</code> operator marks an assignment declaration in which the type of the expression is inferred from the type of the value being assigned. If we chose to declare the local variable separately from the assignment weâ€™d have to give it a different name to avoid a compilation error (Listing 10).</p>

<table class="sidebartable">
	<tr>
		<td>
			<pre class="programlisting">
 1 package main
 2 import . &quot;fmt&quot;
 3 const Hello = &quot;hello&quot;
 4 var world = &quot;world&quot;
 5 func main() {
 6   var w string
 7   w = world + &quot;!&quot;
 8   Println(Hello, w)
 9 }
			</pre>
		</td>
	</tr>
	<tr>
		<td class="title">Listing 10</td>
	</tr>
</table>

<p>Another thing to note in this example is that when <code>w</code> is declared itâ€™s also initialised to the zero value, which in the case of <code>string</code> happens to be <code>&quot;&quot;</code>. This is a <code>string</code> containing no characters.</p>

<p>In fact, all variables in Go are initialised to the zero value for their type when theyâ€™re declared and this eliminates an entire category of initialisation bugs which could otherwise be difficult to identify.</p>

<h2>Functions</h2>

<p>Having looked at how to reference values in Go and how to use the <code>Println()</code> function to display them, itâ€™s only natural to wonder how we can implement our own functions. Obviously weâ€™ve already implemented <code>main()</code> which hints at whatâ€™s involved, but <code>main()</code> is something of a special case as it exist to allow a Go program to execute and it neither requires any parameters nor produces any values to be used elsewhere in the program. (See Listing 11.)</p>

<table class="sidebartable">
	<tr>
		<td>
			<pre class="programlisting">
 1 package main
 2 import . &quot;fmt&quot;
 3 const Hello = &quot;hello&quot;
 4 func main() {
 5   Println(Hello, world())
 6 }
 7 func world() string {
 8   return &quot;world&quot;
 9 }
			</pre>
		</td>
	</tr>
	<tr>
		<td class="title">Listing 11</td>
	</tr>
</table>

<p>In this example weâ€™ve introduced <code>world()</code>, a function which to the outside world has the same operational purpose as the variable of the same name that we used in the previous section.</p>

<p>The empty brackets <code>()</code> indicate that there are no parameters passed into the function when itâ€™s called, whilst <code>string</code> tells us that a single value is returned and itâ€™s of type <code>string</code>. Anywhere that a valid Go program would expect a <code>string</code> value we can instead place a call to <code>world()</code> and the value returned will satisfy the compiler. The use of <code>return</code> is required by the language specification whenever a function specifies return values, and in this case it tells the compiler that the value of <code>world() </code>is the string <code>&quot;world&quot;</code>.</p>

<p>Go is unusual in that its syntax allows a function to return more than one value and as such each function takes two sets of <code>()</code>, the first for parameters and the second for results. We could therefore write our function in long form as</p>

<pre class="programlisting">
  7 func world() (string) {
  8   return &quot;world&quot;
  9 }</pre>
  
<p>In this next example we use a somewhat richer function signature, passing the parameter <code>name</code> which is a string value into the function <code>message()</code>, and assigning the functionâ€™s return value to <code>message</code> which is a variable declared and available throughout the function. (See Listing 12.)</p>

<table class="sidebartable">
	<tr>
		<td>
			<pre class="programlisting">
 1 package main
 2 import &quot;fmt&quot;
 3 func main() {
 4   fmt.Println(message(&quot;world&quot;))
 5 }
 6 func message(name string) (message string) {
 7   message = fmt.Sprintf(&quot;hello %v&quot;, name)
 8   return message
 9 }
			</pre>
		</td>
	</tr>
	<tr>
		<td class="title">Listing 12</td>
	</tr>
</table>

<p>As with <code>world()</code>, the <code>message()</code> function can be used anywhere that the Go compiler expects to find a string value. However, where <code>world()</code> simply returned a predetermined value, <code>message()</code> performs a calculation using the <code>Sprintf()</code> function and returns its result.</p>

<p><code>Sprintf()</code> is similar to <code>Printf()</code> which we met when discussing constants, only rather than create a string according to a format and displaying it in the terminal it instead returns this string as a value which we can assign to a variable or use as a parameter in another function call such as <code>Println()</code>.</p>

<p>Because weâ€™ve explicitly named the return value, we donâ€™t need to reference it in the return statement as each of the named return values is implied. (See Listing 13.)</p>

<table class="sidebartable">
	<tr>
		<td>
			<pre class="programlisting">
 1 package main
 2 import . &quot;fmt&quot;
 3 func main() {
 4   Println(message(&quot;world&quot;))
 5 }
 6 func message(name string) (message string) {
 7   message = Sprintf(&quot;hello %v&quot;, name)
 8   return
 9 }
			</pre>
		</td>
	</tr>
	<tr>
		<td class="title">Listing 13</td>
	</tr>
</table>

<p>If we compare the <code>main()</code> and <code>message()</code> functions (Listing 14), we notice that <code>main()</code> doesnâ€™t have a <code>return</code> statement. Likewise if we define our own functions without return values we can omit the <code>return</code> statement, though later weâ€™ll meet examples where weâ€™d still use a <code>return</code> statement to prematurely exit a function.</p>

<table class="sidebartable">
	<tr>
		<td>
			<pre class="programlisting">
 1 package main
 2 import . &quot;fmt&quot;
 3 func main() {
 4   greet(&quot;world&quot;)
 5 }
 6 func greet(name string) {
 7   Println(&quot;hello&quot;, name)
 8 }
			</pre>
		</td>
	</tr>
	<tr>
		<td class="title">Listing 14</td>
	</tr>
</table>

<p>In Listing 15, weâ€™ll see what a function which uses multiple return values looks like.</p>

<table class="sidebartable">
	<tr>
		<td>
			<pre class="programlisting">
 1 package main
 2 import . &quot;fmt&quot;
 3 func main() {
 4   Println(message())
 5 }
 6 func message() (string, string) {
 7   return &quot;hello&quot;, &quot;world&quot;
 8 }
			</pre>
		</td>
	</tr>
	<tr>
		<td class="title">Listing 15</td>
	</tr>
</table>

<p>Because <code>message()</code> returns two values we can use it in any context where at least two parameters can be consumed. <code>Println()</code> happens to be a <em>variadic</em> function, which weâ€™ll explain in a moment, and takes zero or more parameters so it happily consumes both of the values <code>message() </code>returns.</p>

<p>For our final example (Listing 16) weâ€™re going to implement our own <em>variadic</em> function.</p>

<table class="sidebartable">
	<tr>
		<td>
			<pre class="programlisting">
 1 package main
 2 import . &quot;fmt&quot;
 3 func main() {
 4   print(&quot;Hello&quot;, &quot;world&quot;)
 5 }
 6 func print(v ...interface{}) {
 7   Println(v...)
 8 }
			</pre>
		</td>
	</tr>
	<tr>
		<td class="title">Listing 16</td>
	</tr>
</table>

<p>We have three interesting things going on here which need explaining. Firstly Iâ€™ve introduced a new type, <code>interface{}</code>, which acts as a proxy for any other type in a Go program. Weâ€™ll discuss the details of this shortly but for now itâ€™s enough to know that anywhere an <code>interface{}</code> is accepted we can provide a <code>string</code>.</p>

<p>In the function signature we use <code>v â€¦interface{}</code> to declare a parameter <code>v</code> which takes any number of values. These are received by <code>print()</code> as a sequence of values and the subsequent call to <code>Println(vâ€¦)</code> uses this same sequence as this is the sequence expected by <code>Println()</code>.</p>

<p>So why did we use <code>â€¦interface{}</code> in defining our parameters instead of the more obvious <code>â€¦string</code>? The <code>Println()</code> function is itself defined as <code>Println(â€¦interface{})</code> so to provide a sequence of values en masse we likewise need to use <code>â€¦interface{}</code> in the type signature of our function. Otherwise weâ€™d have to create a <code>[]interface{}</code> (a <code>slice</code> of <code>interface{}</code> values, a concept weâ€™ll cover in detail in a later chapter of my book) and copy each individual element into it before passing it into <code>Println()</code>.</p>

<h2>Encapsulation</h2>

<p>In this tutorial, weâ€™ll for the most part be using Goâ€™s primitive types and types defined in various standard packages without any comment on their structure; however, a key aspect of modern programming languages is the encapsulation of related data into structured types and Go supports this via the <code>struct</code> type. A <code>struct</code> describes an area of allocated memory which is subdivided into slots for holding named values, where each named value has its own type. A typical example of a <code>struct</code> in action would be Listing 17, which gives:</p>

<table class="sidebartable">
	<tr>
		<td>
			<pre class="programlisting">
 1 package main
 2 import &quot;fmt&quot;
 3 type Message struct {
 4   X string
 5   y *string
 6 }
 7 func (v Message) Print() {
 8   if v.y != nil {
 9     fmt.Println(v.X, *v.y)
10   } else {
11     fmt.Println(v.X)
12   }
13 }
14 func (v *Message) Store(x, y string) {
15   v.X = x
16   v.y = &amp;y
17 }
18 func main() {
19   m := &amp;Message{}
20   m.Print()
21   m.Store(&quot;Hello&quot;, &quot;world&quot;)
22   m.Print()
23 }
			</pre>
		</td>
	</tr>
	<tr>
		<td class="title">Listing 17</td>
	</tr>
</table>

<pre class="programlisting">
  $ go run 17.go
  Hello world</pre>
  
<p>Here weâ€™ve defined a struct <code>Message</code> which contains two values: <code>X</code> and <code>y</code>. Go uses a very simple rule for deciding if an identifier is visible outside of the package in which itâ€™s defined which applies to both package-level constants and variables, and <code>type</code> names, methods and fields. If the identifier starts with a capital letter itâ€™s visible outside the package, otherwise itâ€™s private to the package.</p>

<p>The Go language spec guarantees that all variables will be initialised to the zero value for their type. For a <code>struct</code> type this means that every field will be initialised to an appropriate zero value. Therefore when we declare a value of type <code>Message</code> the Go runtime will initialise all of its elements to their zero value (in this case a zero-length string and a nil pointer respectively), and likewise if we create a <code>Message</code> value using a literal</p>

<pre class="programlisting">
  19   m := &amp;Message{}</pre>
  
<p>Having declared a <code>struct</code> type we can declare any number of <code>method</code> functions which will operate on this type. In this case weâ€™ve introduced <code>Print()</code> which is called on a <code>Message</code> value to display it in the terminal, and <code>Store()</code> which is called on a pointer to a <code>Message</code> value to change its contents. The reason <code>Store()</code> applies to a pointer is that we want to be able to change the contents of the <code>Message</code> and have these changes persist. If we define the method to work directly on the value these changes wonâ€™t be propagated outside the methodâ€™s scope. To test this for yourself, make the following change to the program:</p>

<pre class="programlisting">
  14 func (v Message) Store(x, y string) {</pre>
  
<p>If youâ€™re familiar with functional programming then the ability to use values immutably this way will doubtless spark all kinds of interesting ideas.</p>

<p>Thereâ€™s another <code>struct</code> trick I want to show off before we move on and thatâ€™s <em>type embedding</em> using an anonymous field. Goâ€™s design has upset quite a few people with an inheritance-based view of object orientation because it lacks inheritance; however, thanks to <em>type embedding</em> weâ€™re able to compose types which act as proxies to the <em>methods</em> provided by anonymous fields. As with most things, an example (Listing 18) will make this much clearer.</p>

<table class="sidebartable">
	<tr>
		<td>
			<pre class="programlisting">
 1 package main
 2 import &quot;fmt&quot;
 3 type HelloWorld struct {}
 4 func (h HelloWorld) String() string {
 5   return &quot;Hello world&quot;
 6 }
 7 type Message struct {
 8   HelloWorld
 9 }
10 func main() {
11   m := &amp;Message{}
12   fmt.Println(m.HelloWorld.String())
13   fmt.Println(m.String())
14   fmt.Println(m)
15 }
			</pre>
		</td>
	</tr>
	<tr>
		<td class="title">Listing 18</td>
	</tr>
</table>

<pre class="programlisting">
  $ go run 18.go
  Hello world
  Hello world
  Hello world</pre>
  
<p>Here weâ€™re declaring a type <code>HelloWorld</code> which in this case is just an empty <code>struct</code>, but which in reality could be any declared type. <code>HelloWorld</code> defines a <code>String()</code> method which can be called on any <code>HelloWorld</code> value. We then declare a type <code>Message</code> which embeds the <code>HelloWorld</code> type by defining an anonymous field of the <code>HelloWorld</code> type. Wherever we encounter a value of type <code>Message</code> and wish to call <code>String()</code> on its embedded <code>HelloWorld</code> value we can do so by calling <code>String()</code> directly on the value, calling <code>String()</code> on the <code>Message</code> value, or in this case by allowing <code>fmt.Println()</code> to match it with the <code>fmt.Stringer</code> interface.</p>

<p>Any declared type can be embedded, so in Listing 19, weâ€™re going to base <code>HelloWorld</code> on the primitive <code>bool</code> boolean type to prove the point.</p>

<table class="sidebartable">
	<tr>
		<td>
			<pre class="programlisting">
 1 package main
 2 import &quot;fmt&quot;
 3 type HelloWorld bool
 4 func (h HelloWorld) String() (r string) {
 5   if h {
 6     r = &quot;Hello world&quot;
 7   }
 8   return
 9 }
10 type Message struct {
11   HelloWorld
12 }
13 func main() {
14   m := &amp;Message{ HelloWorld: true }
15   fmt.Println(m)
16   m.HelloWorld = false
17   fmt.Println(m)
18   m.HelloWorld = true
19   fmt.Println(m)
20 }
			</pre>
		</td>
	</tr>
	<tr>
		<td class="title">Listing 19</td>
	</tr>
</table>

<p>In our final example (Listing 20) weâ€™ve declared the <code>Hello</code> type and embedded it in <code>Message</code>, then weâ€™ve implemented a new <code>String()</code> method which allows a <code>Message</code> value more control over how itâ€™s printed.</p>

<table class="sidebartable">
	<tr>
		<td>
			<pre class="programlisting">
 1 package main
 2 import &quot;fmt&quot;
 3 type Hello struct {}
 4 func (h Hello) String() string {
 5   return &quot;Hello&quot;
 6 }
 7 type Message struct {
 8   *Hello
 9   World string
10 }
11 func (v Message) String() (r string) {
12   if v.Hello == nil {
13     r = v.World
14   } else {
15     r = fmt.Sprintf(&quot;%v %v&quot;, v.Hello, v.World)
16   }
17   return
18 }
19 func main() {
20   m := &amp;Message{}
21   fmt.Println(m)
22   m.Hello = new(Hello)
23   fmt.Println(m)
24   m.World = &quot;world&quot;
25   fmt.Println(m)
26 }
			</pre>
		</td>
	</tr>
	<tr>
		<td class="title">Listing 20</td>
	</tr>
</table>

<pre class="programlisting">
  $ go run 20.go
  Hello
  Hello world</pre>
  
<p>In all these examples weâ€™ve made liberal use of the <code>*</code> and <code>&amp;</code> operators. An explanation is in order.</p>

<p>Go is a systems programming language, and this means that a Go program has direct access to the memory of the platform itâ€™s running on. This requires that Go has a means of referring to specific addresses in memory and of accessing their contents indirectly. The <code>&amp;</code> operator is prepended to the name of a variable or to a value literal when we wish to discover its address in memory, which we refer to as a pointer. To do anything with the pointer returned by the <code>&amp;</code> operator we need to be able to declare a pointer variable which we do by prepending a type name with the <code>*</code> operator. An example (Listing 21) will probably make this description somewhat clearer, and we get:</p>

<table class="sidebartable">
	<tr>
		<td>
			<pre class="programlisting">
 1 package main
 2 import . &quot;fmt&quot;
 3 type Text string
 4 func main() {
 5   var name Text = &quot;Ellie&quot;
 6   var pointer_to_name *Text
 7   pointer_to_name = &amp;name
 8   Printf(&quot;name = %v stored at %v\n&quot;, name,
     pointer_to_name)
 9   Printf(&quot;pointer_to_name references %v\n&quot;,
     *pointer_to_name)
10 }
			</pre>
		</td>
	</tr>
	<tr>
		<td class="title">Listing 21</td>
	</tr>
</table>

<pre class="programlisting">
  $ go run 21.go
  name = Ellie stored at 0x208178170
  pointer_to_name references Ellie</pre>
  
<p>Go allows user-defined types to declare methods on either a <em>value type</em> or a <em>pointer to a value type</em>. When methods operate on a <em>value type</em> the value manipulated remains immutable to the rest of the program (essentially the method operates on a copy of the value) whilst with a <em>pointer to a value type</em> any changes to the value are apparent throughout the program. This has far-reaching implications which weâ€™ll explore in later chapters.</p>

<h2>Generalisation</h2>

<p>Encapsulation is of huge benefit when writing complex programs and it also enables one of the more powerful features of Goâ€™s type system, the <code>interface</code>. An <code>interface</code> is similar to a <code>struct</code> in that it combines one or more elements but rather than defining a type in terms of the data items it contains, an <code>interface</code> defines it in terms of a set of method signatures which it must implement.</p>

<p>As none of the primitive types (<code>int</code>, <code>string</code>, etc.) have methods they match the empty <code>interface (interface{})</code> as do all other types, a property used frequently in Go programs to create generic containers.</p>

<p>Once declared, an interface can be used just like any other declared type, allowing functions and variables to operate with unknown types based solely on their required behaviour. Goâ€™s type inference system will then recognise compliant values as instances of the interface, allowing us to write generalised code with little fuss.</p>

<p>In Listing 22, weâ€™re going to introduce a simple <code>interface</code> (by far the most common kind) which matches any type with a <code>func String() string</code> method signature. </p>

<table class="sidebartable">
	<tr>
		<td>
			<pre class="programlisting">
 1 package main
 2 import &quot;fmt&quot;
 3 type Stringer interface {
 4   String() string
 5 }
 6 type Hello struct {}
 7 func (h Hello) String() string {
 8   return &quot;Hello&quot;
 9 }
10 type World struct {}
11 func (w *World) String() string {
12   return &quot;world&quot;
13 }
14 type Message struct {
15   X Stringer
16   Y Stringer
17 }
18 func (v Message) String() (r string) {
19   switch {
20   case v.X == nil &amp;&amp; v.Y == nil:
21   case v.X == nil:
22     r = v.Y.String()
23   case v.Y == nil:
24     r = v.X.String()
25   default:
26     r = fmt.Sprintf(&quot;%v %v&quot;, v.X, v.Y)
27   }
28   return 
29 }
30 func main() {
31   m := &amp;Message{}
32   fmt.Println(m)
33   m.X = new(Hello)
34   fmt.Println(m)
35   m.Y = new(World)
36   fmt.Println(m)
37   m.Y = m.X
38   fmt.Println(m)
39   m = &amp;Message{ X: new(World), Y: new(Hello) }
40   fmt.Println(m)
41   m.X, m.Y = m.Y, m.X
42   fmt.Println(m)
43 }
			</pre>
		</td>
	</tr>
	<tr>
		<td class="title">Listing 22</td>
	</tr>
</table>

<pre class="programlisting">
  $ go run 22.go
  Hello
  Hello world
  Hello Hello
  world Hello
  Hello world</pre>
  
<p>This <code>interface</code> is copied directly from <code>fmt.Stringer</code>, so we can simplify our code a little by using that interface instead:</p>

<pre class="programlisting">
  11 type Message struct {
  12   X fmt.Stringer
  13   Y fmt.Stringer
  14 }</pre>
  
<p>As Go is strongly typed <code>interface</code> values contain both a pointer to the value contained in the <code>interface</code>, and the <em>concrete</em> type of the stored value. This allows us to perform type assertions to confirm that the value inside an <code>interface</code> matches a particular concrete type (see Listing 23).</p>

<table class="sidebartable">
	<tr>
		<td>
			<pre class="programlisting">
 1 package main
 2 import &quot;fmt&quot;
 3 type Hello struct {}
 4 func (h Hello) String() string {
 5   return &quot;Hello&quot;
 6 }
 7 type World struct {}
 8 func (w *World) String() string {
 9   return &quot;world&quot;
10 }
11 type Message struct {
12   X fmt.Stringer
13   Y fmt.Stringer
14 }
15 func (v Message) IsGreeting() (ok bool) {
16   if _, ok = v.X.(*Hello); !ok {
17     _, ok = v.Y.(*Hello)
18   }
19   return 
20 }
21 func main() {
22   m := &amp;Message{}
23   fmt.Println(m.IsGreeting())
24   m.X = new(Hello)
25   fmt.Println(m.IsGreeting())
26   m.Y = new(World)
27   fmt.Println(m.IsGreeting())
28   m.Y = m.X
29   fmt.Println(m.IsGreeting())
30   m = &amp;Message{ X: new(World), Y: new(Hello) }
31   fmt.Println(m.IsGreeting())
32   m.X, m.Y = m.Y, m.X
33   fmt.Println(m.IsGreeting())
34 }
			</pre>
		</td>
	</tr>
	<tr>
		<td class="title">Listing 23</td>
	</tr>
</table>

<pre class="programlisting">
  go run 23.go
  false
  true
  true
  true
  true
  true</pre>
  
<p>Here weâ€™ve replaced <code>Message</code>â€™s <code>String()</code> method with <code>IsGreeting()</code>, a predicate which uses a pair of <em>type assertions</em> to tell us whether or not one of <code>Message</code>â€™s data fields contains a value of concrete type <code>Hello</code>.</p>

<p>So far in these examples weâ€™ve been using pointers to <code>Hello</code> and <code>World</code> so the <code>interface</code> variables are storing pointers to pointers to these values (i.e. <code>**Hello</code> and <code>**World</code>) rather than pointers to the values themselves (i.e. <code>*Hello</code> and <code>*World</code>). In the case of <code>World</code> we have to do this to comply with the <code>fmt.Stringer</code> interface because <code>String()</code> is defined for <code>*World</code> and if we modify <code>main</code> to assign a <code>World</code> value to either field (see Listing 24) weâ€™ll get a compile-time error:</p>

<table class="sidebartable">
	<tr>
		<td>
			<pre class="programlisting">
29 func main() {
30   m := &amp;Message{}
31   fmt.Println(m.IsGreeting())
32   m.X = Hello{}
33   fmt.Println(m.IsGreeting())
34   m.X = new(Hello)
35   fmt.Println(m.IsGreeting())
36   m.X = World{}
37 }
			</pre>
		</td>
	</tr>
	<tr>
		<td class="title">Listing 24</td>
	</tr>
</table>

<pre class="programlisting">
  $ go run 24.go
  # command-line-arguments
  ./24.go:36: cannot use World literal (type World)  as type fmt.Stringer in assignment:
  World does not implement fmt.Stringer (String  method has pointer receiver)</pre>
  
<p>The final thing to mention about <code>interface</code>s is that they support embedding of other <code>interface</code>s. This allows us to compose a new, more restrictive <code>interface</code> based on one or more existing <code>interface</code>s. Rather than demonstrate this with an example, weâ€™re going to look at code lifted directly from the standard <strong>io</strong> package which does this (Listing 25).</p>

<table class="sidebartable">
	<tr>
		<td>
			<pre class="programlisting">
67 type Reader interface {
68   Read(p []byte) (n int, err error)
69 }
78 type Writer interface {
79   Write(p []byte) (n int, err error)
80 }
106 type ReadWriter interface {
107   Reader
108   Writer
109 }
			</pre>
		</td>
	</tr>
	<tr>
		<td class="title">Listing 25</td>
	</tr>
</table>

<p>Here <strong>io</strong> is declaring three interfaces, the <code>Reader</code> and <code>Writer</code>, which are independent of each other, and the <code>ReadWriter</code> which combines both. Any time we declare a variable, field or function parameter in terms of a <code>ReaderWriter</code>, we know we can use both the <code>Read()</code> and <code>Write()</code> methods to manipulate it.</p>

<h2>Startup</h2>

<p>One of the less-discussed aspects of computer programs is the need to initialise many of them to a pre-determined state before they begin executing. Whilst this is probably the worst place to start discussing what to many people may appear to be advanced topics, one of my goals in this chapter is to cover all of the structural elements that weâ€™ll meet when we examine more complex programs.</p>

<p>Every Go package may contain one or more <code>init()</code> functions specifying actions that should be taken during program initialisation. This is the one case Iâ€™m aware of where multiple declarations of the same identifier can occur without either resulting in a compilation error or the shadowing of a variable. In the following example we use the <code>init()</code> function to assign a value to our <code>world</code> variable (Listing 26).</p>

<table class="sidebartable">
	<tr>
		<td>
			<pre class="programlisting">
 1 package main
 2 import . &quot;fmt&quot;
 3 const Hello = &quot;hello&quot;
 4 var world  string
 5 func init() {
 6   world = &quot;world&quot;
 7 }
 8 func main() {
 9   Println(Hello, world)
10 }
			</pre>
		</td>
	</tr>
	<tr>
		<td class="title">Listing 26</td>
	</tr>
</table>

<p>However, the <code>init()</code> function can contain any valid Go code, allowing us to place the whole of our program in <code>init()</code> and leaving <code>main()</code> as a stub to convince the compiler that this is indeed a valid Go program (Listing 27).</p>

<table class="sidebartable">
	<tr>
		<td>
			<pre class="programlisting">
 1 package main
 2 import . &quot;fmt&quot;
 3 
 4 const Hello = &quot;hello&quot;
 5 var world  string
 6 
 7 func init() {
 8   world = &quot;world&quot;
 9   Println(Hello, world)
10 }
11 
12 func main() {}
			</pre>
		</td>
	</tr>
	<tr>
		<td class="title">Listing 27</td>
	</tr>
</table>

<p>When there are multiple <code>init()</code> functions, the order in which theyâ€™re executed is indeterminate so in general itâ€™s best not to do this unless you can be certain the <code>init()</code> functions donâ€™t interact in any way. Listing 28 happens to work as expected on my development computer but an implementation of Go could just as easily arrange it to run in reverse order or even leave deciding the order of execution until runtime.</p>

<table class="sidebartable">
	<tr>
		<td>
			<pre class="programlisting">
 1 package main
 2 import . &quot;fmt&quot;
 3 const Hello = &quot;hello&quot;
 4 var world  string
 5 func init() {
 6   Print(Hello, &quot; &quot;)
 7   world = &quot;world&quot;
 8 }
 9 func init() {
10   Printf(&quot;%v\n&quot;, world)
11 }
12 func main() {}
			</pre>
		</td>
	</tr>
	<tr>
		<td class="title">Listing 28</td>
	</tr>
</table>

<h2>HTTP</h2>

<p>So far our treatment of Hello World has followed the traditional route of printing a preset message to the console. Anyone would think we were living in the fuddy-duddy mainframe era of the 1970s instead of the shiny 21st Century, when web and mobile applications rule the world.</p>

<p>Turning Hello World into a web application is surprisingly simple, as Listing 29 demonstrates.</p>

<table class="sidebartable">
	<tr>
		<td>
			<pre class="programlisting">
 1 package main
 2 import (
 3   . &quot;fmt&quot;
 4   &quot;net/http&quot;
 5 )
 6 const MESSAGE = &quot;hello world&quot;
 7 const ADDRESS = &quot;:1024&quot;
 8 func main() {
 9   http.HandleFunc(&quot;/hello&quot;, Hello)
10   if e := http.ListenAndServe(ADDRESS, nil);
     e != nil {
11     Println(e)
12   }
13 }
14 func Hello(w http.ResponseWriter,
   r *http.Request) {
15   w.Header().Set(&quot;Content-Type&quot;, &quot;text/plain&quot;)
16   Fprintf(w, MESSAGE)
17 }
			</pre>
		</td>
	</tr>
	<tr>
		<td class="title">Listing 29</td>
	</tr>
</table>

<p>Our web server is now listening on localhost port 1024 (usually the first non-privileged port on most Unix-like operating systems) and if we visit the url http://localhost:1024/hello with a web browser our server will return Hello World in the response body.</p>

<table class="sidebartable">
	<tr>
		<td><img src="http://accu.org/content/images/journals/ol136/McHugh/McHugh-01.png" /></td>
	</tr>
	<tr>
		<td class="title">Figure 1</td>
	</tr>
</table>

<p>The first thing to note is that the <code>net/http</code> package provides a fully-functional web server which requires very little configuration. All we have to do to get our content to the browser is define a <code>handler</code>, which in this case is a function to call whenever an <code>http.Request</code> is received, and then launch a server to listen on the desired address with <code>http.ListenAndServe()</code>. <code>http.ListenAndServe</code> returns an error if itâ€™s unable to launch the server for some reason, which in this case we print to the console.</p>

<p>Weâ€™re going to import the <code>net/http</code> package into the current namespace and assume our code wonâ€™t encounter any runtime errors to make the simplicity even more apparent (Listing 30). If you run into any problems whilst trying the examples which follow, reinserting the <code>if</code> statement will allow you to figure out whatâ€™s going on.</p>

<table class="sidebartable">
	<tr>
		<td>
			<pre class="programlisting">
 1 package main
 2 import (
 3   . &quot;fmt&quot;
 4   . &quot;net/http&quot;
 5 )
 6 const MESSAGE = &quot;hello world&quot;
 7 const ADDRESS = &quot;:1024&quot;
 8 func main() {
 9   HandleFunc(&quot;/hello&quot;, Hello)
10   ListenAndServe(ADDRESS, nil)
11 }
12 func Hello(w ResponseWriter, r *Request) {
13   w.Header().Set(&quot;Content-Type&quot;, &quot;text/plain&quot;)
14   Fprintf(w, MESSAGE)
15 }
			</pre>
		</td>
	</tr>
	<tr>
		<td class="title">Listing 30</td>
	</tr>
</table>

<p><code>HandleFunc()</code> registers a URL in the web server as the trigger for a function, so when a web request targets the URL the associated function will be executed to generate the result. The specified handler function is passed both a <code>ResponseWriter</code> to send output to the web client and the <code>Request</code> which is being replied to. The <code>ResponseWriter</code> is a file handle so we can use the <code>fmt.Fprint()</code> family of file-writing functions to create the response body.</p>

<p>Finally we launch the server using <code>ListenAndServe()</code>, which will block for as long as the server is active, returning an error if there is one to report.</p>

<p>In this example (Listing 30) Iâ€™ve declared a function <code>Hello</code> and by referring to this in the call to <code>HandleFunc()</code> this becomes the function which is registered. However, Go also allows us to define functions anonymously where we wish to use a function value, as demonstrated in the following variation on our theme.</p>

<p>Functions are first-class values in Go and in Listing 31 <code>HandleFunc()</code> is passed an anonymous function value which is created at runtime.</p>

<table class="sidebartable">
	<tr>
		<td>
			<pre class="programlisting">
 1 package main
 2 import (
 3   . &quot;fmt&quot;
 4   . &quot;net/http&quot;
 5 )
 6 const MESSAGE = &quot;hello world&quot;
 7 const ADDRESS = &quot;:1024&quot;
 8 func main() {
 9   HandleFunc(&quot;/hello&quot;, func(w ResponseWriter,
     r *Request) {
10     w.Header().Set(&quot;Content-Type&quot;,
       &quot;text/plain&quot;)
11     Fprintf(w, MESSAGE)
12   })
13   ListenAndServe(ADDRESS, nil)
14 }
			</pre>
		</td>
	</tr>
	<tr>
		<td class="title">Listing 31</td>
	</tr>
</table>

<p>This value is a closure so it can also access variables in the lexical scope in which itâ€™s defined. Weâ€™ll treat closures in greater depth later in my book, but for now Listing 32 is an example which demonstrates their basic premise by defining a variable <code>message</code>s in <code>main()</code> and then accessing it from within the anonymous function.</p>

<table class="sidebartable">
	<tr>
		<td>
			<pre class="programlisting">
 1 package main
 2 import (
 3   . &quot;fmt&quot;
 4   . &quot;net/http&quot;
 5 )
 6 const ADDRESS = &quot;:1024&quot;
 7 func main() {
 8   message := &quot;hello world&quot;
 9   HandleFunc(&quot;/hello&quot;, func(w ResponseWriter,
     r *Request) {
10     w.Header().Set(&quot;Content-Type&quot;,
       &quot;text/plain&quot;)
11     Fprintf(w, message)
12   })
13   ListenAndServe(ADDRESS, nil)
14 }
			</pre>
		</td>
	</tr>
	<tr>
		<td class="title">Listing 32</td>
	</tr>
</table>

<p>This is only a very brief taster of whatâ€™s possible using <code>net/http</code> so weâ€™ll conclude by serving our hello world web application over an SSL connection (see Listing 33).</p>

<table class="sidebartable">
	<tr>
		<td>
			<pre class="programlisting">
 1 package main
 2 import (
 3   . &quot;fmt&quot;
 4   . &quot;net/http&quot;
 5 )
 6 const SECURE_ADDRESS = &quot;:1025&quot;
 7 func main() {
 8   message := &quot;hello world&quot;
 9   HandleFunc(&quot;/hello&quot;, func(w ResponseWriter,
     r *Request) {
10     w.Header().Set(&quot;Content-Type&quot;,
       &quot;text/plain&quot;)
11     Fprintf(w, message)
12   })
13   ListenAndServeTLS(SECURE_ADDRESS, &quot;cert.pem&quot;,
     &quot;key.pem&quot;, nil)
			</pre>
		</td>
	</tr>
	<tr>
		<td class="title">Listing 33</td>
	</tr>
</table>

<p>Before we run this program we first need to generate a certificate and a public key, which we can do using <code>crypto/tls/generate_cert.go</code> in the standard package library.</p>

<pre class="programlisting">
  $ go run $GOROOT/src/pkg/crypto/tls/  generate_cert.go -ca=true -host=&quot;localhost&quot;
  2014/05/16 20:41:53 written cert.pem
  2014/05/16 20:41:53 written key.pem
  $ go run 33.go</pre>

<table class="sidebartable">
	<tr>
		<td><img src="http://accu.org/content/images/journals/ol136/McHugh/McHugh-02.png" /></td>
	</tr>
	<tr>
		<td class="title">Figure 2</td>
	</tr>
</table>  
  
<p>This is a self-signed certificate, and not all modern web browsers like these. Firefox will refuse to connect on the grounds the certificate is inadequate and not being a Firefox user Iâ€™ve not devoted much effort to solving this. Meanwhile both Chrome and Safari will prompt the user to confirm the certificate is trusted. I have no idea how Internet Explorer behaves. For production applications youâ€™ll need a certificate from a recognised Certificate Authority. Traditionally this would be purchased from a company such as Thawte for a fixed period but with the increasing emphasis on securing the web a number of major networking companies have banded together to launch Letâ€™s Encrypt. Itâ€™s a free CA issuing short-duration certificates for SSL/TLS with support for automated renewal.</p>

<p>If youâ€™re anything like me (and you have my sympathy if you are) then the next thought to idle through your mind will be a fairly obvious question: given that we can serve our content over both HTTP and HTTPS connections, how do we do both from the same program?</p>

<p>To answer this we have to know a little â€“ but not a lot â€“ about how to model concurrency in a Go program. The go keyword marks a goroutine which is a lightweight thread scheduled by the Go runtime. How this is implemented under the hood doesnâ€™t matter, all we need to know is that when a goroutine is launched it takes a function call and creates a separate thread of execution for it. In Listing 34, weâ€™re going to launch a goroutine to run the HTTP server then run the HTTPS server in the main flow of execution.</p>

<table class="sidebartable">
	<tr>
		<td>
			<pre class="programlisting">
 1 package main
 2 import (
 3   . &quot;fmt&quot;
 4   . &quot;net/http&quot;
 5 )
 6 const ADDRESS = &quot;:1024&quot;
 7 const SECURE_ADDRESS = &quot;:1025&quot;
 8 func main() {
 9   message := &quot;hello world&quot;
10   HandleFunc(&quot;/hello&quot;, func(w ResponseWriter,
     r *Request) {
11     w.Header().Set(&quot;Content-Type&quot;,
       &quot;text/plain&quot;)
12     Fprintf(w, message)
13   })
14   go func() {
15     ListenAndServe(ADDRESS, nil)
16   }()
17   ListenAndServeTLS(SECURE_ADDRESS, &quot;cert.pem&quot;,
     &quot;key.pem&quot;, nil)
18 }
			</pre>
		</td>
	</tr>
	<tr>
		<td class="title">Listing 34</td>
	</tr>
</table>

<p>When I first wrote this code it actually used two goroutines, one for each server. Unfortunately no matter how busy any particular goroutine is, when the <code>main()</code> function returns our program will exit and our web servers will terminate. So I tried the primitive approach we all know and love from C (see Listing 35).</p>

<table class="sidebartable">
	<tr>
		<td>
			<pre class="programlisting">
 8 func main() {
 9   message := &quot;hello world&quot;
10   HandleFunc(&quot;/hello&quot;, func(w ResponseWriter,
     r *Request) {
11     w.Header().Set(&quot;Content-Type&quot;,
       &quot;text/plain&quot;)
12     Fprintf(w, message)
13   })
14   go func() {
15     ListenAndServe(ADDRESS, nil)
16   }()
17   go func() {
18     ListenAndServeTLS(SECURE_ADDRESS,
       &quot;cert.pem&quot;, &quot;key.pem&quot;, nil)
19   }()
20   for {}
21 } 
			</pre>
		</td>
	</tr>
	<tr>
		<td class="title">Listing 35</td>
	</tr>
</table>

<p>Here weâ€™re using an infinite <code>for</code> loop to prevent program termination: itâ€™s inelegant, but this is a small program and dirty hacks have their appeal. Whilst semantically correct this unfortunately doesnâ€™t work either because of the way goroutines are scheduled: the infinite loop can potentially starve the thread scheduler and prevent the other goroutines from running.</p>

<pre class="programlisting">
  $ go version
  go version go1.3 darwin/amd64</pre>
  
<p>In any event an infinite loop is a nasty, unnecessary hack as Go allows concurrent elements of a program to communicate with each other via <em>channels</em>, allowing us to rewrite our code as in Listing 36.</p>

<table class="sidebartable">
	<tr>
		<td>
			<pre class="programlisting">
 1 package main
 2 import (
 3   . &quot;fmt&quot;
 4   . &quot;net/http&quot;
 5 )
 7 const ADDRESS = &quot;:1024&quot;
 8 const SECURE_ADDRESS = &quot;:1025&quot;
 9 func main() {
10   message := &quot;hello world&quot;
11   HandleFunc(&quot;/hello&quot;, func(w ResponseWriter,
     r *Request) {
12     w.Header().Set(&quot;Content-Type&quot;, 
       &quot;text/plain&quot;)
13     Fprintf(w, message)
14   })
15   done := make(chan bool)
16   go func() {
17     ListenAndServe(ADDRESS, nil)
18     done &lt;- true
19   }()
20   ListenAndServeTLS(SECURE_ADDRESS, &quot;cert.pem&quot;,
     &quot;key.pem&quot;, nil)
21   &lt;- done
22 }
			</pre>
		</td>
	</tr>
	<tr>
		<td class="title">Listing 36</td>
	</tr>
</table>

<p>For the next pair of examples weâ€™re going to use two separate goroutines to run our HTTP and HTTPS servers, yet again coordinating program termination with a shared channel. In Listing 37, weâ€™ll launch both of the goroutines from the <code>main()</code> function, which is a fairly typical code pattern.</p>

<table class="sidebartable">
	<tr>
		<td>
			<pre class="programlisting">
 1 package main
 2 import (
 3   . &quot;fmt&quot;
 4   . &quot;net/http&quot;
 5 )
 6 const ADDRESS = &quot;:1024&quot;
 7 const SECURE_ADDRESS = &quot;:1025&quot;
 8 func main() {
 9   message := &quot;hello world&quot;
10   HandleFunc(&quot;/hello&quot;, func(w ResponseWriter,
     r *Request) {
11     w.Header().Set(&quot;Content-Type&quot;,
       &quot;text/plain&quot;)
12     Fprintf(w, message)
13   })
14   done := make(chan bool)
15   go func() {
16     ListenAndServe(ADDRESS, nil)
17     done &lt;- true
18   }()
19   go func () {
20     ListenAndServeTLS(SECURE_ADDRESS,
       &quot;cert.pem&quot;, &quot;key.pem&quot;, nil)
21     done &lt;- true
22   }()
23   &lt;- done
24   &lt;- done
25 }
			</pre>
		</td>
	</tr>
	<tr>
		<td class="title">Listing 37</td>
	</tr>
</table>

<p>For our second deviation (Listing 38), weâ€™re going to launch a goroutine from <code>main()</code> which will run our HTTPS server and this will launch the second goroutine which manages our HTTP server.</p>

<table class="sidebartable">
	<tr>
		<td>
			<pre class="programlisting">
 1 package main
 2 import (
 3   . &quot;fmt&quot;
 4   . &quot;net/http&quot;
 5 )
 6 const ADDRESS = &quot;:1024&quot;
 7 const SECURE_ADDRESS = &quot;:1025&quot;
 8 func main() {
 9   message := &quot;hello world&quot;
10   HandleFunc(&quot;/hello&quot;, func(w ResponseWriter,
     r *Request) {
11     w.Header().Set(&quot;Content-Type&quot;,
       &quot;text/plain&quot;)
12     Fprintf(w, message)
13   })
14   done := make(chan bool)
15   go func () {
16     go func() {
17       ListenAndServe(ADDRESS, nil)
18       done &lt;- true
19     }()
20     ListenAndServeTLS(SECURE_ADDRESS,
       &quot;cert.pem&quot;, &quot;key.pem&quot;, nil)
21     done &lt;- true
22   }()
23   &lt;- done
24   &lt;- done
25 }
			</pre>
		</td>
	</tr>
	<tr>
		<td class="title">Listing 38</td>
	</tr>
</table>

<p>Thereâ€™s a certain amount of fragile repetition in this code as we have to remember to explicitly create a channel, and then to send and receive on it multiple times to coordinate execution. As Go provides first-order functions (i.e. allows us to refer to functions the same way we refer to data, assigning instances of them to variables and passing them around as parameters to other functions), we can refactor the server launch code as in Listing 39.</p>

<table class="sidebartable">
	<tr>
		<td>
			<pre class="programlisting">
 1 package main
 2 import (
 3   . &quot;fmt&quot;
 4   . &quot;net/http&quot;
 5 )
 6 const ADDRESS = &quot;:1024&quot;
 7 const SECURE_ADDRESS = &quot;:1025&quot;
 8 func main() {
 9   message := &quot;hello world&quot;
10   HandleFunc(&quot;/hello&quot;, func(w ResponseWriter,
     r *Request) {
11     w.Header().Set(&quot;Content-Type&quot;,
       &quot;text/plain&quot;)
12     Fprintf(w, message)
13   })
14   Spawn(
15     func() { ListenAndServeTLS(SECURE_ADDRESS,
       &quot;cert.pem&quot;, &quot;key.pem&quot;, nil) },
16   func() { ListenAndServe(ADDRESS, nil) },
17     )
18 }
19 func Spawn(f ...func()) {
20   done := make(chan bool)
21   for _, s := range f {
22     go func() {
23       s()
24       done &lt;- true
25     }()
26   }
27   for l := len(f); l &gt; 0; l-- {
28     &lt;- done
29   }
30 }
			</pre>
		</td>
	</tr>
	<tr>
		<td class="title">Listing 39</td>
	</tr>
</table>

<p>However, this doesnâ€™t work as expected, so letâ€™s see if we can get any further insight</p>

<pre class="programlisting">
 $ go vet 39.go
 39.go:23: range variable s captured by func literal
 exit status 1</pre>
 
<p>Running <code>go</code> with the <code>vet</code> command runs a set of heuristics against our source code to check for common errors which wouldnâ€™t be caught during compilation. In this case weâ€™re being warned about this code</p>

<pre class="programlisting">
  21 for _, s := range f {
  22   go func() {
  23     s()
  24     done &lt;- true
  25   }()
  26 }</pre>
  
<p>Here weâ€™re using a closure so it refers to the variable <code>s</code> in the <code>for</code>...<code>range</code> statement, and as the value of <code>s</code> changes on each successive iteration, so this is reflected in the call <code>s()</code>.</p>

<p>To demonstrate this, weâ€™ll try a variant where we introduce a delay on each loop iteration much greater than the time taken to launch the goroutine (see Listing 40).</p>

<table class="sidebartable">
	<tr>
		<td>
			<pre class="programlisting">
 1 package main
 2 import (
 3   . &quot;fmt&quot;
 4   . &quot;net/http&quot;
 5   &quot;time&quot;
 6 )
 7 const ADDRESS = &quot;:1024&quot;
 8 const SECURE_ADDRESS = &quot;:1025&quot;
 9 func main() {
10   message := &quot;hello world&quot;
11   HandleFunc(&quot;/hello&quot;, func(w ResponseWriter,
     r *Request) {
12     w.Header().Set(&quot;Content-Type&quot;, 
       &quot;text/plain&quot;)
13     Fprintf(w, message)
14   })
15   Spawn(
16     func() { ListenAndServeTLS(SECURE_ADDRESS,
       &quot;cert.pem&quot;, &quot;key.pem&quot;, nil) },
17     func() { ListenAndServe(ADDRESS, nil) },
18   )
19 }
20 func Spawn(f ...func()) {
21   done := make(chan bool)
22   for _, s := range f {
23     go func() {
24       s()
25       done &lt;- true
26     }()
27     time.Sleep(time.Second)
28   }
29   for l := len(f); l &gt; 0; l-- {
30     &lt;- done
31   }
32 }
			</pre>
		</td>
	</tr>
	<tr>
		<td class="title">Listing 40</td>
	</tr>
</table>

<p>When we run this we get the behaviour we expect with both HTTP and HTTPS servers running on their respective ports and responding to browser traffic. However, this is hardly an elegant or practical solution and thereâ€™s a much better way of achieving the same effect (Listing 41).</p>

<table class="sidebartable">
	<tr>
		<td>
			<pre class="programlisting">
26   for _, s := range f {
27     go func(server func()) {
28       server()
29       done &lt;- true
30     }(s)
31   }
			</pre>
		</td>
	</tr>
	<tr>
		<td class="title">Listing 41</td>
	</tr>
</table>

<p>By accepting the parameter <code>server</code> to the goroutineâ€™s closure we can pass in the value of <code>s</code> and capture it so that on successive iterations of the range our goroutines use the correct value.</p>

<p><code>Spawn()</code> is an example of how powerful Goâ€™s support for first-class functions can be, allowing us to run any arbitrary piece of code and wait for it to signal completion. Itâ€™s also a <em>variadic</em> function, taking as many or as few functions as desired and setting each of them up correctly.</p>

<p>If we now reach for the standard library we discover that another alternative is to use a <code>sync.WaitGroup</code> to keep track of how many active goroutines we have in our program and only terminate the program when theyâ€™ve all completed their work. Yet again this allows us to run both servers in separate goroutines and manage termination correctly. (See Listing 42.)</p>

<table class="sidebartable">
	<tr>
		<td>
			<pre class="programlisting">
 1 package main
 2 import (
 3   . &quot;fmt&quot;
 4   . &quot;net/http&quot;
 5   &quot;sync&quot;
 6 )
 7 const ADDRESS = &quot;:1024&quot;
 8 const SECURE_ADDRESS = &quot;:1025&quot;
 9 func main() {
10   message := &quot;hello world&quot;
11   HandleFunc(&quot;/hello&quot;, func(w ResponseWriter,
     r *Request) {
12     w.Header().Set(&quot;Content-Type&quot;,
       &quot;text/plain&quot;)
13     Fprintf(w, message)
14   })
15   var servers sync.WaitGroup
16   servers.Add(1)
17   go func() {
18     defer servers.Done()
19     ListenAndServe(ADDRESS, nil)
20   }()
21   servers.Add(1)
22   go func() {
23     defer servers.Done()
24     ListenAndServeTLS(SECURE_ADDRESS,
       &quot;cert.pem&quot;, &quot;key.pem&quot;, nil)
25   }()
26   servers.Wait()
27 }
			</pre>
		</td>
	</tr>
	<tr>
		<td class="title">Listing 42</td>
	</tr>
</table>

<p>As thereâ€™s a certain amount of redundancy in this, letâ€™s refactor a little by packaging server initiation into a new <code>Launch()</code> function. <code>Launch()</code> takes a parameter-less function and wraps this in a <code>closure</code> which will be launched as a goroutine in a separate thread of execution. Our <code>sync.WaitGroup</code> variable servers has been turned into a global variable to simplify the function signature of <code>Launch()</code>. When we call <code>Launch()</code> weâ€™re freed from the need to manually increment servers prior to goroutine startup, and we use a defer statement to automatically call <code>servers.Done()</code> when the goroutine terminates even in the event that the goroutine crashes. See Listing 43.</p>

<table class="sidebartable">
	<tr>
		<td>
			<pre class="programlisting">
 1 package main
 2 import (
 3   . &quot;fmt&quot;
 4   . &quot;net/http&quot;
 5   &quot;sync&quot;
 6 )
 7 const ADDRESS = &quot;:1024&quot;
 8 const SECURE_ADDRESS = &quot;:1025&quot;
 9 
10 var servers sync.WaitGroup
11 func main() {
12   message := &quot;hello world&quot;
13   HandleFunc(&quot;/hello&quot;, func(w ResponseWriter,
     r *Request) {
14     w.Header().Set(&quot;Content-Type&quot;,
       &quot;text/plain&quot;)
15     Fprintf(w, message)
16   })
17   Launch(func() {
18     ListenAndServe(ADDRESS, nil)
19   })
20   Launch(func() {
21     ListenAndServeTLS(SECURE_ADDRESS,
       &quot;cert.pem&quot;, &quot;key.pem&quot;, nil)
22   })
23   servers.Wait()
24 }
25 func Launch(f func()) {
26   servers.Add(1)
27   go func() {
28     defer servers.Done()
29     f()
30   }()
31 }
			</pre>
		</td>
	</tr>
	<tr>
		<td class="title">Listing 43</td>
	</tr>
</table>

<table class="sidebartable">
	<tr>
		<td>
			<p>This is an extract from A Go Developerâ€™s Notebook, a living eBook about Go and programming.</p>
			<p>Living eBooks are purchased once and freely updated when the author has something new to say.</p>
			<p>You can purchase your copy at <a href="http://leanpub.com/GoNotebook">http://leanpub.com/GoNotebook</a></p>
		</td>
	</tr>
</table>
</p>
<p><strong>Notes:</strong>&nbsp;</p>
<p><em>More fields may be available via dynamicdata ..</em></p>
</div>
</channel>
</rss>
