Introduction
When building web applications with Go, you may need to serve static files such as images, CSS files, or JavaScript files from your web server. Go provides a simple and efficient way to handle static files using the net/http package.
Setting Up a Static File Server in Go
In this section, we will walk through the steps to set up a simple static file server in Go. We'll use the http.FileServer and http.StripPrefix functions to serve files from a directory.
package main
import (
"net/http"
"log"
)
func main() {
// Serve files from the "static" directory
fileServer := http.FileServer(http.Dir("./static"))
// Strip the "/static/" prefix when looking for files
http.Handle("/static/", http.StripPrefix("/static", fileServer))
// Start the server on port 8080
log.Println("Starting server on :8080")
if err := http.ListenAndServe(":8080", nil); err != nil {
log.Fatal(err)
}
}
Code Walkthrough
- fileServer := http.FileServer(http.Dir("./static")): This line initializes a file server handler that will serve files from the
./staticdirectory. - http.Handle("/static/", http.StripPrefix("/static", fileServer)): This sets up the HTTP route so that any request to
/static/...will serve files relative to the./staticdirectory. - http.ListenAndServe(":8080", nil): This function starts the HTTP server on port 8080, with the file server serving requests.
Testing the Static File Server
First, create a directory named static and add some files you want to serve. For example, you could add an index.html file. The directory structure may look like this:
/static
├── index.html
└── styles.css
Now run your Go application and open your browser. Enter http://localhost:8080/static/index.html, and you should see the contents of your index.html file. Similarly, enter http://localhost:8080/static/styles.css to access the CSS file.
Customizing with Middleware
You may want to add logging or serve files only when a specific condition is met. This can be done by wrapping your file server handler with a custom middleware function.
package main
import (
"fmt"
"net/http"
"log"
)
func loggingMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
log.Println("Request received:", r.URL.Path)
next.ServeHTTP(w, r)
})
}
func main() {
fileServer := http.FileServer(http.Dir("./static"))
http.Handle("/static/", loggingMiddleware(http.StripPrefix("/static", fileServer)))
log.Println("Starting server on :8080")
if err := http.ListenAndServe(":8080", nil); err != nil {
log.Fatal(err)
}
}
In this updated code, every request to the server will be logged to the console with the route accessed.
Conclusion
Serving static files in Go is straightforward with the http package. By understanding the basics of handlers and middleware, you can easily extend this functionality to fit more complex requirements. Use this guide as a foundation and integrate these principles into your own projects.