Golang Web Server Hello World

2017-09-25

An example of rendering "Hello World!" using golang as a web server with it's built in "net/http" package.

package main

import (
  "log"
  "net/http"
)

func main() {
  mux := http.NewServeMux()

  server := &http.Server{
    Addr:    ":8080",
    Handler: mux,
  }

  mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
    w.Write([]byte("Hello World!"))
  })

  log.Fatal(server.ListenAndServe())
}

Hello World!

That is perhaps a little more than strictly necessary for the most basic web server hello world, but I think it's a more useful example which you can build on.

package main

The first golang file is always package main. It has a function main() which will be run when you type go run hello_world.go.

import (
  "log"
  "net/http"
)

Import the packages "log" and "net/http" from golang's standard library.

func main() {

Define the main function which will be executed when this program is run.

  mux := http.NewServeMux()

Mux is an abbreviation for multiplexing. In our context it is what we register our url paths on, giving it functions to call for each. We create a new http.ServeMux and assign it to the variable mux.

  server := &http.Server{
    Addr:    ":8080",
    Handler: mux,
  }

Create a server listening on port 8080 and using the mux we created earlier to handle web requests.

  mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
    w.Write([]byte("Hello World!"))
  })

We register the path "/" on our mux and give it a function to respond to requests with. Now when our server gets a request for the path "/" it will call this function to write the response.

  log.Fatal(server.ListenAndServe())

Start the server and log any errors if the server returns one.