gin框架02

gin 路由

1、基本路由
gin框架中采用的路由库是基于httprouter做的
地址为:GitHub - julienschmidt/httprouter: A high performance HTTP request router that scales well
2、Restful风格的API
gin支持Restful风格的API
即Representational State Transfer的缩写。直接翻译的意思是“表现层状态转化”,是一种互联网应用程序的API设计理念:URL定位资源,用HTTP描述操作。

1获取文件
2添加
3修改
4删除


restful.png

default
使用new路由,默认用了两个中间件Logger(),recover()。


01.png

GET - 从指定的资源请求数据。
POST - 向指定的资源提交要被处理的数据。

API参数

可以通过Context的Param获取API参数


api.png

URL参数

url1.png
url.png
package main

import (
    "fmt"
    "github.com/gin-gonic/gin"
    "net/http"
)
// gin的Hellowork

func main() {
    // 1. 创建路由器
    r := gin.Default()
    //  2. 绑定路由规则,执行函数
    // gin.Context,封装了request和respones
    r.POST("/from", func(c *gin.Context) {
        // 表单参数设置默认值
        type1 := c.DefaultPostForm("type","alert")
        // 接收其他的
        username := c.PostForm("username")
        password := c.PostForm("password")
        // 多选框
        hobbys := c.PostFormArray("hobby")
        c.String(http.StatusOK,
            fmt.Sprintf("type is %s,username is %s ,password is %s,hobby is %s \n",
                type1,username,password,hobbys))
    })
    // 3.监听端口,默认8080
    r.Run(":8000")

}

表单参数

表单参数.png
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>登录</title>
</head>
<body>
<form action="http://127.0.0.1:8000/from" method="post" enctype="application/x-www-form-urlencoded">
    用户名:<input type="text" name="username">
    <br>
    密&nbsp&nbsp码:<input type="password" name="password">
    兴&nbsp&nbsp趣:
    <input type="checkbox" value="run" name="hobby">跑步
    <input type="checkbox" value="game" name="hobby">游戏
    <input type="checkbox" value="money" name="hobby">金钱
    <br>
    <input type="submit" value="登录">
</form>
</body>
</html>

结果我是随便输入的


结果.png
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
禁止转载,如需转载请通过简信或评论联系作者。

相关阅读更多精彩内容

友情链接更多精彩内容