Hello World Server in Golang

October 2, 2019

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 some simple code snippets periodically I’m using in my project. Today is a hello world HTTP server.

Here’s our code:

// In Golang we always need to set a package name
// The main package is unique 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