02_Go-1_02 简单实现用户登录API
main.go
package main import ( "net/http" "github.com/julienschmidt/httprouter" ) func RegisterHandlers() *httprouter.Router { // *Router路由指针 router := httprouter.New() // 使用POST方法注册一个适配/user路径的CreateUser函数 router.POST("/user", CreateUser) // 用户登录 router.POST("/user/:user_name", Login) // *Router作为参数传给ListenAndServe函数启动HTTP服务 return router } func main() { r := RegisterHandlers() http.ListenAndServe(":8000", r) }
handlers.go
package main import ( "io" "net/http" "github.com/julienschmidt/httprouter" ) // 创建用户 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) { // 通过这种方式获取参数 uname := p.ByName("user_name") io.WriteString(w, uname) }