Home >Backend Development >Golang >Why Am I Getting a 404 Error When Serving CSS Files in My Go Web Application?

Why Am I Getting a 404 Error When Serving CSS Files in My Go Web Application?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-23 20:05:21306browse

Why Am I Getting a 404 Error When Serving CSS Files in My Go Web Application?

Issue: 404 Page Not Found While Rendering CSS in Go

When attempting to use CSS files in a Go web application, users may encounter a 404 error, indicating that the CSS file cannot be located. This issue arises despite following the instructions from the provided documentation.

Relevant Directory Structure and Code:

The relevant directory structure is as follows:

src/
  |__ css/somefilename.css
  |__ server/server.go

The code in server.go includes:

http.Handle("/css/", http.StripPrefix("/css/", http.FileServer(http.Dir("css"))))

In the HTML template src/templates/layout.html, the CSS file is referenced as:

<link rel="stylesheet" type="text/css" href="../css/css490.css" />

Source of the Issue and Resolution:

The error occurs because the path provided to the FileServer directory is not an absolute path. Relative paths in Go are resolved to the working directory from which the application is run.

To resolve the issue, users can ensure that the application is run from the correct working directory, typically specified in the command line argument when running the program. Alternatively, the absolute path to the CSS directory can be explicitly provided in the FileServer function.

For example, if the working directory is src, then running go run server/server.go will resolve the path correctly and the CSS file will be accessible at localhost:8080/css/. However, running go run server.go from the src/server folder will result in a 404 error. To fix this in the后者, users can modify the code to use the absolute path:

http.Handle("/css/", http.StripPrefix("/css/", http.FileServer(http.Dir("/src/css"))))

By specifying the full path to the CSS directory, the program can locate the CSS file regardless of the working directory from which it is run.

The above is the detailed content of Why Am I Getting a 404 Error When Serving CSS Files 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