Software Development

Creating HTTP Server in Go

In this post, we will create a simple HTTP server in Go following some simple steps. Before starting, let me give you a brief introduction about Go.

What is Go?

Go is an open source programming language which is case sensitive and statically-typed with syntax similar to that of C language created at Google in 2007. It compiles very quickly, supports concurrency at the language level and provides garbage collection, type safety, dynamic-typing capability, many advanced built-in types such as variable length arrays and key-value maps though there is no support for generic programming, type inheritance, method or operator overloading, pointer arithmetic and assertions.

Now, let’s start with setting up the environment to run our first HTTP Server, following below steps:

Step 1: Download and extract Go in any directory, for me it’s golang under directory /Users/ArpitAggarwal/ as follows:

$ mkdir golang
$ cd golang
$ wget https://storage.googleapis.com/golang/go1.8.3.darwin-amd64.tar.gz
$ tar -xvzf go1.8.3.darwin-amd64.tar.gz

Step 2: Update Path with GOROOT, GOPATH and GOBIN, as follows:

$ export GOROOT=/Users/ArpitAggarwal/golang/go
$ export GOPATH=$GOROOT/src
$ export GOBIN=$GOROOT/bin
$ export PATH=$PATH:$GOPATH:$GOBIN

GOROOT refers to the go installation directory.
GOPATH refers to our go workspace directory or where go build is done.
GOBIN refers to the directory where go generate executable binaries.

Step 3: Verify if GOPATH is set properly on Bash, executing following command:

$ env | grep -E "^GO"

Step 4: Create a directory inside workspace to keep source code:

$ mkdir -p $GOPATH/github.com/arpitaggarwal

Step 5: Move to directory we created in previous step and create a file named webserver.go inside it, as follows:

$ cd $GOPATH/github.com/arpitaggarwal
$ touch webserver.go

Copy following Go code:

package main

import (
	"fmt"
	"log"
	"net/http"
)

func helloWorld(w http.ResponseWriter, r *http.Request) {
	fmt.Fprintf(w, "Hello World!") // send data to client side
}

func main() {
	http.HandleFunc("/", helloWorld)         // set router
	err := http.ListenAndServe(":8080", nil) // set listen port
	if err != nil {
		log.Fatal("Error while starting GO http server on port - 8080 : ", err) //log error and exit in case of error at server boot up
	}
}

Let’s understand what does each line mean.

package main – It defines the package name of the program.

import (“fmt”, “log” “net/http”) – is a preprocessor command which tells the Go compiler to include all files from fmt, log and net/http package.

func helloWorld(w http.ResponseWriter, r *http.Request) – is a go function.

main() – is the main function where the program execution begins.

Step 6: Install webserver.go using go tool, as follows:

$ go install $GOPATH/github.com/arpitaggarwal/webserver.go

Above command compile webserver.go and generate executable binary file of it in $GOROOT/bin or GOBIN.

Step 7: Run webserver moving to golang directory, as follows:

$ cd golang
$ ./go/bin/webserver

Now, opening http://localhost:8080/ in browser or executing command:

curl http://localhost:8080

will show us “Hello World!” as response.

Step 8: Optionally we can run binary file in background using nohup command, as follows:

$ cd golang
$ nohup ./go/bin/webserver &;

Complete source code is hosted on github

Reference: Creating HTTP Server in Go from our JCG partner Arpit Aggarwal at the Arpit Aggarwal blog.

Arpit Aggarwal

Arpit is a Consultant at Xebia India. He has been designing and building J2EE applications since more than 6 years. He is fond of Object Oriented and lover of Functional programming. You can read more of his writings at aggarwalarpit.wordpress.com
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments
Back to top button