Tuesday, March 5, 2019

Writing the simplest HTTP server in Go

To write a very simple, HTTP server in Go, that serves just a single static page, you just need to do the following.

  • Import the net/http package
  • start listening on a port of your choice using http's ListenAndServe
  • server requests using a HTTP ResponseWriter.

Here is the code for this:-
package main
import (
"net/http"
"log"
)

func viewHandler(w http.ResponseWriter, r *http.Request) {
    w.Write([]byte("Hello there..."))
}

func main() {
    http.HandleFunc("/", viewHandler)
    log.Fatal(http.ListenAndServe(":8087",nil))
}
Using http.HandleFunc we choose to handle incoming requests on '/' path using the viewHandler function. After this, we start a ListenAndServe() function to start handling incoming HTTP requests on 8087.

Go ahead and build this and then run the exe. Your server has started. Now, open the browser and goto http://localhost:8087/

You should see a 'hello there...'.

Go has a pretty powerful HTTP library that allows you to do a lot of things. We shall explore more in the future.


No comments:

Post a Comment