美文网首页
Go gorilla/mux学习心得 - 安装

Go gorilla/mux学习心得 - 安装

作者: 账房先生2016 | 来源:发表于2019-08-07 14:26 被阅读0次

    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学习心得 - 安装

          本文链接:https://www.haomeiwen.com/subject/wczidctx.html