Home >Backend Development >Golang >How Can I Serve Static Assets (CSS & JS) in My Go Web Application?

How Can I Serve Static Assets (CSS & JS) in My Go Web Application?

Susan Sarandon
Susan SarandonOriginal
2024-12-20 02:23:08654browse

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:

  • Ensure that the "static" directory is present in your project and contains the required CSS and JS files.
  • Adjust the "/static/..." path in the http.Handle function to match your desired static asset location.
  • The handlers you provided for "/view/", "/edit/", "/save/", and "/index/" are registered normally and do not affect static asset serving.

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn