How to use Go language to implement routing static file service
Overview:
In Web development, static file service is a very common and important function. It is usually used to serve static resources of a website, such as HTML, CSS, JavaScript, images, etc. This article will introduce how to use Go language to implement a simple routed static file service and provide specific code examples.
- myapp - main.go - static - index.html
Among them, main.go is our main code file, and the static directory is used to store static files, such as index.html.
go get -u github.com/gorilla/mux
Import the gorilla/mux package at the beginning of the main.go code:
package main import ( "net/http" "github.com/gorilla/mux" )
func main() { router := mux.NewRouter() router.PathPrefix("/static/").Handler(http.StripPrefix("/static/", http.FileServer(http.Dir("static")))) http.Handle("/", router) http.ListenAndServe(":8080", nil) }
In the above code, router.PathPrefix("/static/") specifies the URL prefix that matches the static file, http.StripPrefix(" /static/", http.FileServer(http.Dir("static"))) is used to process requests for static files and remove the "/static/" prefix in the URL. http.Handle("/", router) is used to hand over the request to the router for processing. Finally, http.ListenAndServe(":8080", nil) is used to start the web server and listen for requests from port 8080.
go run main.go
The server will start on the local port 8080. Now, we can visit http://localhost:8080/static/index.html in the browser to view the index.html file.
Summary:
This article introduces how to use Go language to implement a simple routing static file service. We use the gorilla/mux package to implement the routing function and provide static file services through the http.FileServer function. Through the guidance of this article, you can quickly set up a static file service and use it for your website. In actual development, you can further expand and optimize this static file service to meet your specific needs.
The above is the detailed content of How to use Go language to implement routing static file service. For more information, please follow other related articles on the PHP Chinese website!