Home > Backend Development > Golang > How to Serve Static CSS and JS Files in a Go Web Application?

How to Serve Static CSS and JS Files in a Go Web Application?

Mary-Kate Olsen
Release: 2024-12-14 00:34:16
Original
775 people have browsed it

How to Serve Static CSS and JS Files in a Go Web Application?

Serving CSS and JS in a Go Application

When working with the Go Writing Web Applications tutorial, it's common to encounter issues like serving CSS and JS files through the Go server. Here's how to resolve this issue:

In your main function, add the following line to handle static files:

http.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir("static"))))
Copy after login

This code serves the directory named "static" as a static file server, allowing you to access your CSS and JS files. You can place the files within the "static" directory.

In your HTML templates, ensure that you're referencing the CSS and JS files correctly by specifying the appropriate paths:

<link rel="stylesheet" href="/static/css/bootstrap.min.css">
<link rel="stylesheet" href="/static/css/bootstrap-theme.min.css">
<link rel="stylesheet" href="/static/css/custom.css">
Copy after login
<script src="/static/js/jquery.min.js"></script>
<script src="/static/js/bootstrap.min.js"></script>
Copy after login

With these modifications, your Go application should be able to serve CSS and JS files correctly.

The above is the detailed content of How to Serve Static CSS and JS Files in a Go Web Application?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template