Hello World Server in Golang

I’m back from vacation and it’s time to work again on side projects! I’ve been working for a while on an idea and wanted to use Golang for it. To help me sharpen my skills on this language, I’ll be sharing periodically some simple code snippets I’m using in my project. Today is a hello world HTTP server.

Here’s our code:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
// In Golang we always need to set a package name
// The main package is special as it's a reserved name for the starting point
// of a Golang project
// Other package names are expected to be used as libraries
package main

// Here we're importing dependencies from the standard library
import (
	"fmt"
	"log"
	"net/http"
)

// Our function handler receives w as a http.ResponseWriter (writable stream)
func handler(w http.ResponseWriter, r *http.Request) {
	// We write a string in that stream
	fmt.Fprintf(w, "Hello Yacine!")
}

// The main function, like the main package, is considered as the starting point
// of a Golang project
func main() {
	// Our router is answering the requests on the URL path /
	http.HandleFunc("/", handler)

	// log.Fatal close the current program with an exit code 1 when the given
	// parameter is crashing
	// http.ListenAndServe opens a HTTP server on the given port.
	// If no router is given as second parameter (nil), the default router will
	// handle all the requests (http.DefaultServeMux)
	log.Fatal(http.ListenAndServe(":8080", nil))
}

Any thoughts or comments? Ping me on Twitter @yrezgui