gorilla/muxs可以很方便的幫助我們實現(xiàn)了路由和middlerware
但是如果endpoint較少且無需驗證token,則無需使用
Development環(huán)境: Mac
安裝之前血巍,開啟go module
$ vim ~/.bash_profile
確保go module開啟
export GOPATH=$HOME/Documents/GoWorkSpace
export GO111MODULE=on
在你的工程根目錄下(例如$GOPATH/src/github.com/YOURCOMPANY/PROJECTNAME)鹿鳖,運行
$ go mod init
安裝
// -u 意味著最新版本
go get -u github.com/gorilla/mux
依賴包會下載到$GOPATH/pkg/mod/目錄下,該中方式比較像Gradle
示例代碼
package main
import (
"fmt"
"log"
"net/http"
"github.com/gorilla/mux"
)
func handler(w http.ResponseWriter, r *http.Request) {
// fmt.Fprintf(w, "Hi there, I love %s!", r.URL.Path[1:])
fmt.Fprintf(w, `{"alive": true}`)
}
func ArticlesCategoryHandler(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
w.WriteHeader(http.StatusOK)
fmt.Fprintf(w, "Category: %v\n", vars["category"])
}
func main() {
r := mux.NewRouter()
r.Methods("GET", "POST")
s := r.PathPrefix("/products").Subrouter()
s.HandleFunc("/", handler)
s.HandleFunc("/products/{key}", handler)
s.HandleFunc("/articles/{category}", ArticlesCategoryHandler)
http.Handle("/", s)
log.Fatal(http.ListenAndServe(":3060", nil))
}
調試
在vscode中敌完,debug并在瀏覽器中輸入http://localhost:3060/products/articles/tests就可以進行測試了