青春纸盒子

文: 芦苇

你喜欢我笑的样子

我靠上了落寞的窗子

晚风吹起了我的袖子

明月沾湿了你的眸子


转身,你走出了两个人的圈子

树影婆娑,整座院子


挽起袖子

回头,把揽你忧伤一地的影子

装进,青春,这纸盒子


更多代码请关注我的微信小程序: "ecoder"

luwei0915

导航

03_Go-1_03 实现基本的API请求框架

1. 当前目录结构

 

 2. API请求流程

2.1 main.go 进入

 1 package main
 2 
 3 import (
 4     "net/http"
 5 
 6     "github.com/julienschmidt/httprouter"
 7 )
 8 
 9 func RegisterHandlers() *httprouter.Router {
10     // *Router路由指针
11     router := httprouter.New()
12 
13     // 使用POST方法注册一个适配/user路径的CreateUser函数
14     router.POST("/user", CreateUser)
15 
16     // 用户登录
17     router.POST("/user/:user_name", Login)
18 
19     // *Router作为参数传给ListenAndServe函数启动HTTP服务
20     return router
21 }
22 
23 func main() {
24     r := RegisterHandlers()
25     http.ListenAndServe(":8000", r)
26 }
27 
28 /*
29 
30 API请求流程:
31     1. handler
32     2. validatin
33         a. request 是否合法
34         b. user 是否存在
35     3. 逻辑处理
36     4. response
37 
38 */

2.2 handlers.go 处理

 1 package main
 2 
 3 import (
 4     "io"
 5     "net/http"
 6 
 7     "github.com/julienschmidt/httprouter"
 8 )
 9 
10 // 创建用户
11 func CreateUser(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
12     io.WriteString(w, "Create User Handler")
13 }
14 
15 // 用户登录
16 func Login(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
17     // 通过这种方式获取参数
18     uname := p.ByName("user_name")
19     io.WriteString(w, uname)
20 }

2.3 api.go 用户校验-数据库

 1 package dbops
 2 
 3 import "database/sql"
 4 
 5 // 内部方法
 6 func openConn() *sql.DB {
 7 
 8 }
 9 
10 // 用户注册
11 func AddUserCrendential(loginName string, pwd string) error {
12 
13 }
14 
15 // 用户登录
16 func GetUserCredential(loginName string) (string, error) {
17 
18 }

2.4 apidef.go 用户校验-用户模型

1 package defs
2 
3 // 定义用户数据模型
4 type UserCredential struct {
5     UserName string `json:"user_name`
6     UserPwd  string `json:"user_pwd"`
7 }

2.5 errors.go 请求校验-错误类型

 1 package defs
 2 
 3 type Err struct {
 4     Error     string `json:"error"`
 5     ErrorCode string `json:"error_code"`
 6 }
 7 
 8 type ErroResponse struct {
 9     HttpSc int
10     Error  Err
11 }
12 
13 var (
14 
15     // request 传进来的参数无法解析
16     ErrorRequestBodyParseFailed = ErroResponse{
17         HttpSc: 400,
18         Error: Err{
19             Error:     "Request body is not correct",
20             ErrorCode: "001",
21         },
22     }
23 
24     // 用户不存在
25     ErrorNotAuthUser = ErroResponse{
26         HttpSc: 401,
27         Error: Err{
28             Error:     "User authentication failed",
29             ErrorCode: "002",
30         },
31     }
32 )

2.6 response.go 最终返回

 1 package main
 2 
 3 import "net/http"
 4 
 5 func sendErrorResponse(w http.ResponseWriter) {
 6 
 7 }
 8 
 9 func sendNormalResponse(w http.ResponseWriter) {
10 
11 }

 

posted on 2021-12-13 09:46  芦苇の  阅读(101)  评论(0编辑  收藏  举报