美文网首页
利用httprouter 实现两个简单Api

利用httprouter 实现两个简单Api

作者: 会长__ | 来源:发表于2018-08-26 22:19 被阅读259次

    1.安装httprouter

    go get github.com/julienschmidt/httprouter
    手册

    .代码

    main.go

    package main
    
    import (
        "net/http"
        "github.com/julienschmidt/httprouter"
    )
    
    func RegisterHandlers() *httprouter.Router  {
        router := httprouter.New()
    
        router.POST("/user", CreateUser)
    
        router.POST("/user/:user_name", Login)
        return router
    }
    
    func main()  {
        registerHandler := RegisterHandlers()
        http.ListenAndServe(":8000", registerHandler)
    }
    

    Handlers.go

    package main
    
    import (
        "github.com/julienschmidt/httprouter"
        "net/http"
        "io"
    )
    
    func CreateUser(w http.ResponseWriter, r *http.Request, p httprouter.Params)  {
        io.WriteString(w, "create User Handler")
    }
    
    func Login(w http.ResponseWriter, r *http.Request, p httprouter.Params)  {
        userName := p.ByName("user_name")
    
        io.WriteString(w, userName)
    }
    

    3.测试

    image.png image.png

    相关文章

      网友评论

          本文标题:利用httprouter 实现两个简单Api

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