In Go, leveraging the net/http package offers a straightforward approach for serving static HTML files. Execute the following steps:
Import the essential libraries:
import ( "net/http" )
Designate the static file's directory:
http.Handle("/", http.FileServer(http.Dir("./static")))
Consider that the static files reside in a directory named "static" within the project's root directory. If you desire a different directory, adjust the path accordingly.
Initialize the web server:
http.ListenAndServe(":3000", nil)
This will allow access to your HTML file by navigating to http://localhost:3000/ in your preferred browser.
Important Notes:
If you want to serve files from a URL different than "/", you can utilize the http.StripPrefix function:
http.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir("./public"))))
The above is the detailed content of How Can I Serve Static HTML Files Using Go's `net/http` Package?. For more information, please follow other related articles on the PHP Chinese website!