This is a creation in Article, where the information may have evolved or changed.
Objective
In order to make the route of Golang clearer, the code that makes the way is more readable, we use the MUX package to implement the route, and the original function is streamlined
This series of articles all the code here
Begin
The required packagegithub.com/gorilla/mux
We set the route configuration method when we start the HTTP service
func startHttp() { if err := http.ListenAndServe(":9090"nil { log.Fatal("ListenAndServe: ", err) }}
Configuration method
There are two ways to configure API package routing, one is the configuration of the API, the other is the configuration of static resources (no need to open a nginx for static resources)
func NewAPIMux() *mux.Router { r := mux.NewRouter() s := r.PathPrefix("/api").Subrouter() initUserApi(s) r.PathPrefix("/").Handler(http.StripPrefix("/", http.FileServer(http.Dir("web/")))) return r}
API configuration
The API configuration here is through the prefix function of the MUX, the beginning of the /api
request is considered an API request, and lead to the sub-route, which is the largest purpose of MUX
Let's take a look at Userapi's initialization method, and of course, it's best to write Userapi code in a separate file, such as User.go
func initUserApi(r *mux.Router) { s := r.PathPrefix("/user").Subrouter() s.HandleFunc("/list", UserListHandler) s.HandleFunc("/add", UserAddHandler)}func UserListHandler(w http.ResponseWriter, r *http.Request) { w.Write([]byte("user list"))}func UserAddHandler(w http.ResponseWriter, r *http.Request) { w.Write([]byte("user add"))}
Simple refining, matching /api/user
all requests under, and processing separately /api/user/list
and/api/user/add
Similarly, the same product,order can be written, the code will be very clear, simple refining,
Static file Configuration
r.PathPrefix("/").Handler(http.StripPrefix("/", http.FileServer(http.Dir("web/"))))
Well, as simple as this, all requests except the API are imported into the Web directory, processed in a static file, no longer need to start nginx,apache and so on to deal with
This is where I like to Golang, more to operate the business itself, instead of always knocking over duplicated code