Home >Backend Development >Golang >How Can I Serve Static Assets (CSS & JS) in My Go Web Application?
Serving Static Assets with Go
As you mentioned in the Go Writing Web Applications tutorial, you are encountering difficulties serving CSS and JS in your Go application. Let's delve into the issue and provide a solution.
Problem:
When running the Go server, the CSS and JS assets are inaccessible, despite working correctly when the static page is accessed directly.
Solution:
To resolve this issue, you need to configure your Go application to handle and serve static assets. Here's an updated version of your main function:
func main() { http.HandleFunc("/view/", makeHandler(viewHandler)) http.HandleFunc("/edit/", makeHandler(editHandler)) http.HandleFunc("/save/", makeHandler(saveHandler)) http.HandleFunc("/index/", makeHandler(indexHandler)) http.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir("static")))) http.ListenAndServe(":8080", nil) }
In this code, we use the http.Handle function to map the "/static/" path to a handler that serves files from the "static" directory. The http.FileServer constructor creates a handler that serves files from a given directory, and http.StripPrefix strips the "/static/" prefix from the requested path before serving the file.
By configuring your application this way, you instruct the server to serve CSS and JS files from the "static" directory when a request is made to "/static/css/..." or "/static/js/...".
Additional Notes:
The above is the detailed content of How Can I Serve Static Assets (CSS & JS) in My Go Web Application?. For more information, please follow other related articles on the PHP Chinese website!