Hosting Static HTML Files with a Go Web Server
Serving static HTML files is a fundamental aspect of web development. In Go, this task is easily accomplished using the net/http package. Here's how you can do it:
In your code:
package main import ( "net/http" ) func main() { // Specify the folder containing the static HTML files staticDir := "./static" // Serve static files using the built-in FileServer handler http.Handle("/", http.FileServer(http.Dir(staticDir))) // Start listening for HTTP requests on port 3000 http.ListenAndServe(":3000", nil) }
This code mounts a file server that serves files from the specified staticDir at the root URL (/).
Serving Files from a Different URL
If you want to serve static files from a URL other than the root, you can use the http.StripPrefix function. For example, to serve files from the /static URL:
staticDir := "./public" http.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir(staticDir))))
This code will make files from the ./public directory accessible at localhost:3000/static.
By hosting static HTML files using this method, you can easily modify the HTML outside of the Go program, making it simple to maintain and update your web content.
The above is the detailed content of How Can I Serve Static HTML Files Using a Go Web Server?. For more information, please follow other related articles on the PHP Chinese website!