How do I serve static files securely?

In this guide, we will explore how to serve static files securely using the Go programming language. This is important for protecting against various web vulnerabilities.

Example of Serving Static Files Securely

package main import ( "log" "net/http" "path/filepath" ) func main() { fs := http.FileServer(http.Dir("./static")) // Specify the directory for static files http.Handle("/static/", http.StripPrefix("/static/", fs)) // Serve files found in the static directory // Restrict access to certain file types (additional security measures) http.HandleFunc("/static/", func(w http.ResponseWriter, r *http.Request) { ext := filepath.Ext(r.URL.Path) if ext != ".css" && ext != ".js" && ext != ".png" && ext != ".jpg" { http.Error(w, "Forbidden", http.StatusForbidden) return } fs.ServeHTTP(w, r) // Serve the file }) log.Println("Server is running on :8080") log.Fatal(http.ListenAndServe(":8080", nil)) // Start the server }

Go static files secure serving web security Go programming