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.
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
}
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?