Use of Golang HTTP Handler Explained with Examples

Robin
Updated on November 22, 2023

An HTTP handler is an interface in Go that specifies a ServeHTTP() method. We use this type to process routes in our web server.

An object that implements this interface can handle HTTP requests. When our Golang server receives an HTTP request to a specific route that is using a handler, our server will execute the ServeHTTP() method of that handler.

          package main

import (
	"fmt"
	"net/http"
)

// MyHandler is a custom HTTP handler
type MyHandler struct{}

// ServeHTTP implements the http.Handler interface
func (h *MyHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	fmt.Fprint(w, "Hello, this is my custom handler!")
}

func main() {
	// Creating an instance of MyHandler
	myHandler := &MyHandler{}

	// Registering the handler with the default ServeMux (multiplexer)
	http.Handle("/", myHandler)

	// Starting the HTTP server on port 8080
	http.ListenAndServe(":8000", nil)
}

        

HTTP Handler Syntax

The http.Handler interface has only one method. When you add this method to any of your types, they will become handlers.

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

        

This means you can convert any type an HTTP handler by adding the ServHTTP() method to it.

It takes the response writer and a request object as its arguments. While implementing this interface, you have to follow this exact syntax.


Implementing http.Handler Interface

I have a MyHandler struct type. I want to implement the http.Handler interface to this type.

Therefore, I am adding the ServeHTTP() method to this MyHandler struct.

          // MyHandler is a custom HTTP handler
type MyHandler struct{}

// ServeHTTP implements the http.Handler interface
func (h *MyHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	fmt.Fprint(w, "Hello, this is my custom handler!")
}
        

Inside this method, you can write our code to handle a request and send a response. I am writing a string to the response writer.


Creating an Instance of Our HTTP Handler

Initializes a new instance of the MyHandler struct and holds it to a variable.

Here the myHandler variable holds the memory address of that newly created MyHandler object. You can pass this to any route handler.

          // Creating an instance of MyHandler
myHandler := &MyHandler{}
        

Using Handler in a Server Route

To use an HTTP handler in a Go server route, you have to call http.Handle() method. It accepts two parameters.

The first parameter is the route you want to handle and the second parameter is the instance of your custom handler type.

          package main

import (
	"fmt"
	"net/http"
)

// MyHandler is a custom HTTP handler
type MyHandler struct{}

// ServeHTTP implements the http.Handler interface
func (h *MyHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	fmt.Fprint(w, "Hello, this is my custom handler!")
}

func main() {
	// Creating an instance of MyHandler
	myHandler := &MyHandler{}

	// Registering the handler with the default ServeMux (multiplexer)
	http.Handle("/", myHandler)

	// Starting the HTTP server on port 8080
	http.ListenAndServe(":8000", nil)
}

        

In this case, I am calling the http.Handle() with "/" to handle requests for the root path and myHandler variable.

When you start your server (go run main.go) and visit http://localhost:8000 route, it will execute the ServeHTTP() method from the myHanlder instance.

That's how you can implement the http.Handler interface to your types and use them in your route handlers.

Also Read: What is HTTP HandlerFunc in Go? Complete Guide with Examples

Related Posts