Golang Http Server Example

Golang offers directly in its standard library a package which can be used to work with http protocol.

The net/http package. In this post we are going to explore the capabilities of the net/http package and how we can use it to run our own http server.
One of the first function we want to have a look at is http.HandleFunc

func HandleFunc(pattern string, handler func(ResponseWriter, *Request))

and ListenAndServe which listen on the given tcp address and then calls the handler, which is tipically left as nil

func ListenAndServe(addr string, handler Handler) error

It appears to be clear that we can easily create our first http handler by using ListenAndServe and HandleFunc as follows


package main

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

func main() {
        goodMorningHandler := func(w http.ResponseWriter, req *http.Request) {
                fmt.Fprintf(w, "Good morning! You are using verb: %s, URL: %s\n", req.Method, req.URL)
        }
        http.HandleFunc("/goodmorning", goodMorningHandler)
        log.Fatal(http.ListenAndServe(":1234", nil))
}

In the following example we just saw how to create a http server which handles http requests based on the requested URI path.
Let’s now try out our simple http server and see what we get as response

➜  ~ curl -v http://localhost:1234/goodmorning
*   Trying ::1...
* TCP_NODELAY set
* Connected to localhost (::1) port 1234 (#0)
> GET /goodmorning HTTP/1.1
> Host: localhost:1234
> User-Agent: curl/7.54.0
> Accept: */*
> 
< HTTP/1.1 200 OK
< Content-Length: 57
< Content-Type: text/plain; charset=utf-8
< 
Good morning! You are using verb: GET, URL: /goodmorning
* Connection #0 to host localhost left intact
Join the Golang Developers Community on Golang Cafe