Create Golang HTTP Server in 15 Lines

UY

Umesh Yadav / September 22nd, 2020

3 min read444 words

Golang has quickly become an industry standard for creating and maintaining high scale web services. It has an inbuilt package net/http to create an HTTP server. This package reduces the barrier of creating the server.

This post will help get your first HTTP server up and running in golang with bare minimum code.

This tutorial assumes that you have golang installed and setup ready with you. If don't have one you can refer here

Creating the Handler#

One of the most important concepts in net/http is Handlers. Handlers are nothing but the functions implementing http.Handler interface. You can imagine them as the unit which handles the operations on request and returns the appropriate response. Let me show you how does it look like.

go

type Handler interface {
ServeHTTP(ResponseWriter, *Request)
}

So in order to write an HTTP handler, we will implement the golang's handler interface.

go

func index(w http.ResponseWriter, r *http.Request) {
io.WriteString(w, "welcome to golang world!")
}

In the above example, you can see the handler function take a http.ResponseWriter and http.Request. The http.Request represents your request contents like headers, body, etc. The http.ResponseWriter used to write back the response from the server.

Registering the Router and Staring the Server#

Golang has HandlerFunc which can be used to register the routes. It registers these routes on the default router in net/http package, if you want you can create your own router. It takes the route path and handler function(which we just wrote above).

Now finally we use http.ListenAndServe to serve our HTTP server. It takes two arguments first one is the address on which it listens, we have passed it :8080 so it listens on localhost:8080, the second argument takes a router which in our case is nil because we have mounted our routes on the default router. If you want you can pass your own custom router.

go

func main() {
http.HandleFunc("/", index)
print("Starting Server at port :8080")
log.Fatal(http.ListenAndServe(":8080", nil))
}

Here is the full code

go

package main
import (
"io"
"log"
"net/http"
)
func index(w http.ResponseWriter, r *http.Request) {
io.WriteString(w, "welcome to golang world!")
}
func main() {
http.HandleFunc("/", index)
print("Starting Server at port :8080")
log.Fatal(http.ListenAndServe(":8080", nil))
}

Now run the server and hit the endpoint to see the output.

bash

$ go run main.go
Starting Server at port :8080
$ curl localhost:8080/
welcome to golang world!

Conclusion#

Golang is a great language with modern web services. It provides you with sufficient building blocks to run your Http server. One of the best things about Golang is you can take these language blocks and built a simple solution for yourself.

Umesh's Newsletter

Subscribe to get my latest blogs delivered straight into your inbox