Go gorilla/mux学习心得 - 安装

gorilla/muxs可以很方便的帮助我们实现了路由和middlerware
但是如果endpoint较少且无需验证token,则无需使用

Development环境: 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就可以进行测试了

你可能感兴趣的:(Go gorilla/mux学习心得 - 安装)