rodrigosaito.com

home

Hello World Webserver in Go

01 May 2015

Go standard library has a lot of useful packages to create a webserver and it's very well built so you can use it in production, I will write a series of posts about the net/http package. In this tutorial I will show how to create a Hello World Webserver in Go.

Let's start by creating a Hello World using the net/http package, create a file named main.go:

 1 package main
 2 
 3 import (
 4   "fmt"
 5   "net/http"
 6 )
 7 
 8 func handler(w http.ResponseWriter, r *http.Request) {
 9   fmt.Fprintf(w, "Hello")
10 }
11 
12 func main() {
13   http.HandleFunc("/", handler)
14   http.ListenAndServe(":8080", nil)
15 }

Here are some exaplanations about this code:

The handler function must receive the following parameters: an http.ResponseWriter and a pointer to http.Request, where http.ResponseWriter is the object used to write all the data to the Response.

Now we can run our Hello World example and see if everything works as expected:

$ go run main.go

And we can test it:

$ curl -i http://localhost:8080
HTTP/1.1 200 OK
Content-Length: 5
Content-Type: text/plain; charset=utf-8

Hello