Golang http StripPrefix Function

The http.StripPrefix function in Golang is part of the net/http package and is used to modify the URL path of an incoming HTTP request by removing a specified prefix before passing the request to another handler. This function is particularly useful when you want to serve static files or handle routes where the base path is not needed by the underlying handler.

Table of Contents

  1. Introduction
  2. http.StripPrefix Function Syntax
  3. Examples
    • Basic Usage
    • Serving Static Files with a Stripped Prefix
    • Combining http.StripPrefix with a File Server
  4. Real-World Use Case
  5. Conclusion

Introduction

The http.StripPrefix function allows you to remove a specific prefix from the URL path before forwarding the request to another handler. This is helpful in scenarios where the base path is not relevant to the actual resource being served or when you want to serve resources from a subdirectory without exposing the full path structure to the client.

http.StripPrefix Function Syntax

The syntax for the http.StripPrefix function is as follows:

func StripPrefix(prefix string, h http.Handler) http.Handler

Parameters:

  • prefix: A string representing the prefix to be stripped from the URL path.
  • h: An http.Handler that will handle the modified request after the prefix has been stripped.

Returns:

  • http.Handler: The function returns an http.Handler that processes the request after the specified prefix has been removed from the URL path.

Examples

Basic Usage

This example demonstrates how to use the http.StripPrefix function to remove a prefix from the URL path before passing the request to another handler.

Example

package main

import (
	"fmt"
	"net/http"
)

func main() {
	// Create a handler that handles the stripped path
	handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		fmt.Fprintf(w, "Path after stripping prefix: %s", r.URL.Path)
	})

	// Use http.StripPrefix to remove the "/static" prefix before passing the request to the handler
	http.Handle("/static/", http.StripPrefix("/static", handler))

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

Explanation:

  • The server listens on port 8080.
  • Requests with the path /static/anything will have /static stripped from the URL path before being handled.
  • The remaining path after the prefix is stripped is displayed to the client.

Example Request:

http://localhost:8080/static/hello

Response:

Path after stripping prefix: /hello

Serving Static Files with a Stripped Prefix

This example shows how to serve static files from a directory while stripping a prefix from the URL path.

Example

package main

import (
	"net/http"
)

func main() {
	// Serve files from the "public" directory with the "/assets" prefix stripped from the URL path
	fileServer := http.FileServer(http.Dir("public"))
	http.Handle("/assets/", http.StripPrefix("/assets", fileServer))

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

Explanation:

  • The server listens on port 8080.
  • Files in the public directory are served, but the /assets prefix is removed from the URL path before the file server handles the request.
  • For example, a request to /assets/css/styles.css will be served the file located at public/css/styles.css.

Example Directory Structure:

public/
└── css/
    └── styles.css

Example Request:

http://localhost:8080/assets/css/styles.css

Response:

  • The styles.css file is served, even though the client requested it with the /assets prefix.

Combining http.StripPrefix with a File Server

This example demonstrates how to combine http.StripPrefix with a file server to serve files from a specific directory structure.

Example

package main

import (
	"net/http"
)

func main() {
	// Serve files from the "static" directory after stripping the "/files" prefix
	http.Handle("/files/", http.StripPrefix("/files", http.FileServer(http.Dir("./static"))))

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

Explanation:

  • The server listens on port 8080.
  • Files in the static directory are served, but the /files prefix is removed from the URL path before the file server handles the request.
  • This setup allows you to serve files from a specific directory while keeping the URL structure clean.

Example Directory Structure:

static/
└── img/
    └── logo.png

Example Request:

http://localhost:8080/files/img/logo.png

Response:

  • The logo.png file is served, even though the client requested it with the /files prefix.

Real-World Use Case

Serving API Documentation

In a real-world application, you might want to serve API documentation files from a directory while keeping the URL structure clean by stripping a base path.

Example: Serving API Documentation

package main

import (
	"net/http"
)

func main() {
	// Serve API documentation from the "docs" directory after stripping the "/docs" prefix
	http.Handle("/docs/", http.StripPrefix("/docs", http.FileServer(http.Dir("./apidocs"))))

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

Explanation:

  • The server listens on port 8080.
  • API documentation files in the apidocs directory are served, but the /docs prefix is removed from the URL path.
  • This allows clients to access the documentation without needing to know the internal directory structure.

Conclusion

The http.StripPrefix function in Go is used for modifying URL paths before passing requests to another handler. Whether you're serving static files, routing requests, or building clean and maintainable URLs, http.StripPrefix provides a simple way to manage and manipulate URL prefixes in your web applications. By stripping unnecessary parts of the URL, you can create a more organized and user-friendly routing system for your web server.

Comments

Spring Boot 3 Paid Course Published for Free
on my Java Guides YouTube Channel

Subscribe to my YouTube Channel (165K+ subscribers):
Java Guides Channel

Top 10 My Udemy Courses with Huge Discount:
Udemy Courses - Ramesh Fadatare