利用httprouter 实现两个简单Api
2018-08-26 本文已影响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)
}