Friday, 3 January 2014

Creating a simple web server in Golang

No modern programming language would be complete without the ability to interact over the internet. Go has this in spades, and since there's nothing more satisfying than getting a web page up and running, we are going to code up a simple web server in Go:
package main

import ("fmt"
        "net/http")

func main() {
    http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
        fmt.Fprintf(w, "Hello Web")
        })

    http.ListenAndServe(":8080", nil)
}
Save this code as "server.go" and then run it by opening a command prompt and typing:
go run server.go
You command prompt will pause. Open a browser and enter the location as:
http://localhost:8080
Your browser should return a page that says "Hello Web". Congratulations, you've just written your first web server in Golang.

Importing multiple packages

One of the new things we've done in our simple server is to import a second package. The net/http package allows us to work with the http protocol and listen for requests and serve responses. Importing multiple packages is pretty simple. There are various ways to do so, but the syntax above works fine - include your packages, one per line and surround the entire block of imports with parentheses.

Passing functions as arguments

The net/http package allows us to capture requests and route them with the HandleFunc - this function takes two parameters - the first, the url to handle and the second, a function which will be called when we hit the server on the specified url. This takes advantage of Go's first class functions which we explored a little before.

Listening"

The http.ListenAndServe function tells go that to "listen" on a particular port - we've specified ":8080", hence our url becomes "http://localhost:8080". Unlike our previous snippets of code, which exited once they had finished executing, our web server will run until we specifically interrupt it (or it hits a nasty error). To exit our program, pull up the command prompt where you typed "go run server.go" and hit Ctrl-C.

Thursday, 2 January 2014

First class functions or passing arguments to functions in Golang - refactor

Last time, we learned how to pass arguments to functions in Go. We even managed to pass a function as an argument illustrating Go's First-Class Functions. We ended up with a small piece of code as follows:
package main
 
import "fmt"
 
func goodbye(aFunc func(words string) string) {
    fmt.Println(aFunc("Goodbye"))
}
 
func hello(aFunc func(words string) string) {
    fmt.Println(aFunc("Hello"))
}

func main() {
    var x = func(words string) string {
        return words + " world"
    }
    hello(x)
    goodbye(x)
 
}
We have two functions that take as an argument, another function. You will notice that both func goodbye and func hello have the same signature for their single argument. This kind of duplication is crying out for a refactor, and that's exactly what we are going to do. Instead of declaring the function signature as an argument (aFunc func(words string) string), we are going to create a type with that function signature. To declare a type in Go, we simply use the type keyword. Our function that will be used as an argument can be declared like this:
type myOwnFunction func(words string) string
We can then use our newly defined type. For example, our goodbye function can be re-written to use our new type:
func goodbye(aFunc myOwnFunction) {
    fmt.Println(aFunc ("Goodbye"))
}
Similarly, our hello function:
func hello(aFunc myOwnFunction) {
    fmt.Println(aFunc ("Hello"))
}
The rest of our code can remain untouched. A complete listing of our refactored code now looks like this:
package main
 
import "fmt"

type myOwnFunction func(words string) string
 
func goodbye(aFunc myOwnFunction) {
    fmt.Println(aFunc ("Goodbye"))
}
 
func hello(aFunc myOwnFunction) {
    fmt.Println(aFunc ("Hello"))
}
 
func main() {
    var x = func(words string) string {
        return words + " world"
    }
    hello(x)
    goodbye(x)
 
}

Wednesday, 25 December 2013

Passing arguments to functions in Golang

Functions wouldn't be much use if we couldn't pass parameters to them. Rewriting our previous example, we might decide to create a function that takes a string as it's single argument.
package main

import "fmt"

func saySomething(somethingToSay string) {
    fmt.Println(somethingToSay)
}

func main() {
    saySomething("Hello")
    saySomething("world")
}
We've declared a function saySomething that takes a single argument. The argument is a string type and is called somethingToSay. We then use our new function, calling it twice from our main func to output:
Hello
wordl
Go also provides first class functions. This means we can pass a function as an argument into another function. For example:
package main

import "fmt"

func hello(aFunc func(words string) string) {
    fmt.Println(aFunc("Hello"))
}


func main() {

    var x = func(words string) string {
        return words + " world"
    }
    hello(x)

}
Again, all our program does is print
Hello world
, though in a roundabout way. We've defined a function hello which accepts as its argument another function - note that the argument defines the signature of the function we expect to receive - in this case, a function that takes one string argument and returns a string. Moving into our main function, we define x to be a function that will append " world" onto whatever string is passed in. This is rather convoluted, but illustrates the point. Now, if we fancy, we can define a goodbye function as well - to wit:
package main

import "fmt"

func goodbye(aFunc func(words string) string) {
    fmt.Println(aFunc("Goodbye"))
}

func hello(aFunc func(words string) string) {
    fmt.Println(aFunc("Hello"))
}


func main() {

    var x = func(words string) string {
        return words + " world"
    }
    hello(x)
    goodbye(x)

}
Now our program outputs the following:
Hello world
Goodbye world
Now our code is ripe for a refactor - we have duplicate argument definitions, which we can code out - but we will leave that to another post.

Monday, 23 December 2013

Variables in golang

Declaring a variable in Go is a matter of using the var keyword. Let's follow on from our last piece of code and create a string, assign a value to it and then print it out.
package main

import "fmt"

func helloWorld() {
    var x string
    x = "Hello world"
    fmt.Println(x)
}
 
func main() {
    helloWorld()
}
Again, nothing spectacular here - we are simply printing out "Hello world", however, it illustrates simple variable declaration and assignment.
var x string
declares a variable for us and lets the compiler know we want it to be of type string. Next, we assign the string "Hello world" to variable x
x = "Hello world"
and finally, we print it out - just as we did before. Go is statically typed and compiled, however Go does borrow a little from dynamically typed languages by exposing a syntax that removes the need to name the variable's type. The Go compiler's ability to infer types allows us to short-cut our variable declarations. To wit, we can re-write our helloWorld function as follows:
func helloWorld() {
    x := "Hello world
    fmt.Println(x)
}
When we compile our code, Go will use type inference to assign a type to our variable for us. We are left with the security of a strongly typed language while still having the convenience of a more dynamically typed syntax. One more for the road; if you prefer to explicitly type your variable, but still enjoy assigning them immediately, the following variant of our helloWorld function will see you right:
func helloWorld() {
    var x string = "Hello world"
    fmt.Println(x)
}

Sunday, 22 December 2013

Creating a function in golang

Our first piece of code had only one function - main. Let's create a new function in our code and call it from within the main function.
package main

import "fmt"

func helloWorld() {
    fmt.Println("Hello World")
}

func main() {
    helloWorld()
}
This piece of code does the same thing as our first hello world in go from the end user experience. The big difference is we are calling a function. Declaring a new function in go is simple - use the func keyword to begin declaring your function. Then, as in many other languages, include a pair of parentheses. Our hellWorld function takes no arguments at the moment so we leave the parentheses empty. Similarly, helloWorld doesn't return anything, so we can forget about giving our function a return type for the moment. Golang has some C inspired syntax so functions are enclosed in curly braces. The rest of the hellWorld function should look familiar since we are simply calling printing some text to standard out as we did before. Calling a function is equally familiar to anyone with some coding under their belt - as demonstrated in main above where we call our newly defined helloWorld func.

Friday, 20 December 2013

Dissecting Hello World in Go

In the first post, we wrote a simple hello world application in go. Let's examine it a bit and figure out what all the moving parts are. For reference, here's the code again:
package main
 
import "fmt"
 
func main() {
    fmt.Println("Hello World from Golang")
}
We begin our code with the
package main
command. Packages are exactly what they sound like - discreet pieces of code with a name. You can think of the package command as wrapping up your code into a little bundle so it is ready to be delivered and used by another piece of code. Specifying
package main
tells the compiler that this is the entry point of your code. Our import statement allows us to access other packages - it pulls in or imports other bits of code. Here we import the "fmt" package. This package allows us to create formatted input and output. The setup out of the way, we get to the meat and potatoes our
main
function - as the name suggest, main is the function that will get executed. It is the master control point for us to instruct the computer using golang. Our functionality here relies on the fmt.Println function - this prints a line of text to the standard output of the computer (your screen most likely) and appends a new line. And that's it. One super simple go program

Tuesday, 10 December 2013

Hello World from Golang

Every journey into code begins with "Hello World". I don't know why, but that's what we do. It's a safe way of checking that you've got your language installed correctly and can at least run the most basic of basics - that of outputting something (in this case, some text) to the user. Golang, being C-Syntax inspired language, should look fairly familiar to pretty much anyone in the computer sciences. A nice simple Hello World application can be written as follows:
package main

import "fmt"

func main() {
    fmt.Println("Hello World from Golang")
}
Saving the above code as 'hello.go' and then typing the following on the command line:
go run hello.go
should net you a lovely little message:
Hello World from Golang