Home >Backend Development >Golang >How to Serve Static HTML Files with a Go Web Server?
Serving Static HTML Files with a Go Web Server
For serving static HTML files like index.html, Go's net/http package provides an elegant solution. Here's how it's done:
package main import ( "net/http" ) func main() { http.Handle("/", http.FileServer(http.Dir("./static"))) http.ListenAndServe(":3000", nil) }
This code assumes your static files are stored in a directory called "static" in the project's root. By calling the FileServer() function and passing it the directory containing your HTML files, you instruct the web server to serve those files as is.
When you visit http://localhost:3000/, the index.html file from the static directory will be rendered. Other files in that directory can also be accessed directly by modifying the URL.
Serving Files from a Different URL
If you prefer to serve your static files from a specific URL, such as http://localhost:3000/static, you can utilize the StripPrefix() function:
package main import ( "net/http" ) func main() { http.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir("./public")))) http.ListenAndServe(":3000", nil) }
This code sets up a handler that strips "/static/" from the request URL before serving files from the "public" directory. As a result, files from the public directory will be accessible at http://localhost:3000/static/.
The above is the detailed content of How to Serve Static HTML Files with a Go Web Server?. For more information, please follow other related articles on the PHP Chinese website!