middleware in golang

Golang : Creating a Logging Middleware for Your HTTP Server


Logging middleware is an essential part of any software system, as it provides visibility into the application's behavior and helps diagnose errors and performance issues. In a web application, logging can be particularly helpful to understand which endpoints are being called, what parameters are being passed, and how long requests take to complete. In this article, we will demonstrate how to create a logging middleware in Go that can be used to log incoming HTTP requests and responses. We will use a sample codebase to illustrate how the middleware can be integrated with an HTTP server.

This lecture demonstrates how to use middleware to log incoming HTTP requests in a Go server

The sample code provided imports the necessary packages for HTTP server creation, logging, and formatting. The reportLog function takes an http.HandlerFunc as input and returns a new http.HandlerFunc that logs the incoming request URL and then calls the original handler. The HelloHandler and HiHandler functions represent the HTTP handlers for the two endpoints that our server exposes.

package main

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

var Revision string

type fctHandler http.HandlerFunc

func reportLog(f fctHandler) fctHandler {
	return func(w http.ResponseWriter, r *http.Request) {
		log.Println(r.URL.Path)
		f(w, r)
	}
}

func HelloHandler(w http.ResponseWriter, r *http.Request) {
	fmt.Fprintln(w, "Hello freecoders!")
}

func HiHandler(w http.ResponseWriter, r *http.Request) {
	fmt.Fprintln(w, "Hi freecoders!")
}

func main() {
	http.HandleFunc("/hi", reportLog(HiHandler))
	http.HandleFunc("/hello", reportLog(HelloHandler))

	log.Fatal(http.ListenAndServe(":8080", nil))
}

In the main function, we register the reportLog middleware for both endpoints using the http.HandleFunc method.

This means that every incoming request to either endpoint will be logged before being passed to the corresponding handler. Finally, we start the HTTP server using the http.ListenAndServe method, which listens on port 8080.

You can get this code source project and many others on our github account: https://github.com/freecoder-dev/go-middleware

Conclusion

Creating a logging middleware in Go can help you understand the behavior of your web application and diagnose potential issues. By using a middleware, you can keep your logging concerns separate from your application logic, making your code more modular and easier to maintain. In this article, we demonstrated how to create a simple logging middleware in Go that can be used to log incoming HTTP requests. By following the example code, you can implement this middleware in your own Go web application and gain valuable insights into its behavior.

Default image
@freecoder

With 15+ years in low-level development, I'm passionate about crafting clean, maintainable code.
I believe in readable coding, rigorous testing, and concise solutions.

Articles: 22