programming

12 Creating Static File Handler

In web applications, serving static files such as images, CSS files, or JavaScript from a public directory is often necessary. By using the julienschmidt/httprouter library, you can easily create a handler to serve static files. This article will walk you through the complete steps to implement a static file handler in a simple and efficient way using Golang.


Prerequisites

  1. Basic Understanding of Golang: You should have a fundamental understanding of Golang programming.

  2. Golang Installed: Ensure that Golang is installed on your machine.

  3. httprouter Library: You need to install this library. To do so, use the following command:

    go get github.com/julienschmidt/httprouter
    
  4. Public Folder: A directory to store your static files, for example, named public.


Step 1: Setting Up the Directory Structure

Create a simple project structure as follows:

project-root/
├── main.go
├── public/
│   ├── index.html
│   ├── style.css
│   ├── script.js
  • main.go: The main file to run the application.
  • public/: The folder containing static files to be accessed.

Step 2: Creating the main.go File

Open the main.go file and add the following code:

package main

import (
	"log"
	"net/http"
	"github.com/julienschmidt/httprouter"
)

func main() {
	router := httprouter.New()

	// Static file handler for the "public" folder
	router.ServeFiles("/static/*filepath", http.Dir("./public"))

	// Start the server
	log.Println("Server running at http://localhost:8080")
	log.Fatal(http.ListenAndServe(":8080", router))
}

Explanation:

  • router.ServeFiles: A built-in method from httprouter used to serve static files. The first parameter is the URL prefix (e.g., /static/*filepath), while the second parameter is the directory where the static files are stored (./public).
  • http.Dir("./public"): Directs the handler to read files from the public folder.
  • ListenAndServe: Starts the server on port 8080.

Step 3: Preparing Static Files

Create some files inside the public/ folder:

  1. public/index.html:

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Static Files</title>
        <link rel="stylesheet" href="/static/style.css">
    </head>
    <body>
        <h1>Welcome to Static Files in Golang!</h1>
        <script src="/static/script.js"></script>
    </body>
    </html>
    
  2. public/style.css:

    body {
        font-family: Arial, sans-serif;
        text-align: center;
        margin-top: 50px;
        background-color: #f4f4f9;
    }
    h1 {
        color: #333;
    }
    
  3. public/script.js:

    console.log("Static file loaded successfully!");
    

Step 4: Running the Application

Run the application using the following command:

go run main.go

The server will start at http://localhost:8080.

Testing

  1. Open your browser and visit:

    • http://localhost:8080/static/index.html: To open the HTML file.
    • http://localhost:8080/static/style.css: To view the CSS file.
    • http://localhost:8080/static/script.js: To view the JavaScript file.
  2. Ensure that the files are being accessed correctly and check for any errors in the browser console.


Step 5: Adding Headers to Static Files

To add headers to static file responses (such as security headers), you can create a simple middleware:

func WithHeaders(h http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Cache-Control", "max-age=3600")
		h.ServeHTTP(w, r)
	})
}

Then, use this middleware before the static file handler:

staticHandler := WithHeaders(http.StripPrefix("/static/", http.FileServer(http.Dir("./public"))))
router.Handler("GET", "/static/*filepath", staticHandler)

Explanation:

  • http.HandlerFunc: Wraps the handler to add headers to every response.
  • Cache-Control: Sets the cache time for static files to prevent the browser from reloading them on every request.

Conclusion

In this article, we implemented a static file handler using the httprouter library in Golang. By adding custom headers or middleware, you can enhance functionality according to your application’s needs.

Try extending this further by integrating dynamic endpoints or adding a logging system for static file responses. Happy coding!

comments powered by Disqus