go-echo学习笔记

go-echo学习笔记,包含了请求与响应,路由,参数解析,模版渲染,登录验证,日志,文件上传与下载,websocket通信。

文章目录

  • Part1 Get与Post
  • Part2 四种请求
  • Part3 提取参数
  • Part4 解析json与xml
  • Part5 json传输
  • Part6 模版渲染
  • Part7 模版参数传递
  • Part8 Cookie与Session
  • Part9 JWT
  • Part9 日志
  • Part10 文件上传与下载
  • Part 11 Websocket通信

Part1 Get与Post

主要内容包括登录网页,发送请求并进行处理

import ("github.com/labstack/echo""net/http"
)func main01() {e := echo.New()e.GET("/", func(c echo.Context) error {return c.String(http.StatusOK, "<h1>Hello, World</h1>")})e.Logger.Fatal(e.Start(":1323"))
}

Part2 四种请求

包含了PUT,DELETE PUT与GET,测试的时候需要结合Postman,其中请求时,静态路由要大于参数路由大于匹配路由。


import ("github.com/labstack/echo""net/http"
)func HelloFunc(c echo.Context) error {return c.String(http.StatusOK, "Hello, World!")
}func UserHandler(c echo.Context) error {return c.String(http.StatusOK, "UserHandler")
}func CreateProduct(c echo.Context) error {return c.String(http.StatusOK, "CreateProduct")
}
func FindProduct(c echo.Context) error {return c.String(http.StatusOK, "FindProduct")
}
func UpdateProduct(c echo.Context) error {return c.String(http.StatusOK, "UpdateProduct")
}
func DeleteProduct(c echo.Context) error {return c.String(http.StatusOK, "DeleteProduct")
}// 静态 > 参数 > 匹配路由
func main() {e := echo.New()e.GET("/", HelloFunc)r := e.Group("/api")r.GET("/user", UserHandler)//r.GET("/score", ScoreHandler)r.POST("/user", CreateProduct)r.DELETE("/user", DeleteProduct)r.PUT("/user", UpdateProduct)e.Logger.Fatal(e.Start(":1325"))e.GET("/product/1/price/*", func(c echo.Context) error {return c.String(http.StatusOK, "Product 1 price all")})e.GET("/product/:id", func(c echo.Context) error {return c.String(http.StatusOK, "Product "+c.Param("id"))})e.GET("/product/new", func(c echo.Context) error {return c.String(http.StatusOK, "Product new")})}

Part3 提取参数

在接收网页端的请求时,要对请求进行解析。如何解析是这个part的内容,表单发送过来的请求,REST请求,普通带问候的请求方式

package mainimport ("github.com/labstack/echo""net/http"
)func MyHandler(c echo.Context) error {p := new(Product)if err := c.Bind(p); err != nil {return c.String(http.StatusBadRequest, "bad request")}return c.JSON(http.StatusOK, p)
}func MyHandler2(c echo.Context) error {name := c.FormValue("name")return c.String(http.StatusOK, name)
}func MyHandler3(c echo.Context) error {name := c.QueryParam("name")return c.String(http.StatusOK, name)
}func MyHandler4(c echo.Context) error {name := c.Param("name")return c.String(http.StatusOK, name)
}type Product struct {Name  string `json:"name" form:"name" query:"name"`Price int    `json:"price" form:"price" query:"price"`
}func main() {e := echo.New()e.GET("/products", MyHandler)//在postman 中formdata进行请求e.GET("/products2", MyHandler2)//与products类似e.GET("/products3", MyHandler3)e.GET("/products4/:name", MyHandler4)e.Logger.Fatal(e.Start(":1328"))
}

Part4 解析json与xml

本part对json传输进行了详细的demo样例,json较为常用。


import ("encoding/json""github.com/labstack/echo""net/http"
)type Product struct {Name  string `json:"name" form:"name" query:"name"`Price int    `json:"price" form:"price" query:"price"`
}func main() {e := echo.New()e.GET("/", func(c echo.Context) error {return c.String(http.StatusOK, "Hello, World!")})e.GET("/html", func(c echo.Context) error {return c.HTML(http.StatusOK, "<h1>Hello, World!</h1>")})e.GET("/json", func(c echo.Context) error {p := &Product{Name:  "football",Price: 1000,}return c.JSON(http.StatusOK, p)})e.GET("/prettyjson", func(c echo.Context) error {p := &Product{Name:  "soccer",Price: 1000,}return c.JSONPretty(http.StatusOK, p, "  ")})e.GET("/streamjson", func(c echo.Context) error {p := &Product{Name:  "soccer",Price: 134,}c.Response().Header().Set("Content-Type", echo.MIMEApplicationXMLCharsetUTF8)c.Response().WriteHeader(http.StatusOK)return json.NewEncoder(c.Response()).Encode(p)})e.GET("/jsonblob", func(c echo.Context) error {p := &Product{Name:  "volley",Price: 120,}data, _ := json.Marshal(p)return c.JSONPBlob(http.StatusOK, "", data)})e.GET("/xml", func(c echo.Context) error {p := &Product{Name:  "basketball",Price: 120,}return c.XML(http.StatusOK, p)})e.GET("/png", func(c echo.Context) error {//return c.File("./public/left.png")return c.File("./public/test.html")})e.GET("blub", func(c echo.Context) error {data := []byte(`0306703,0035866,NO_ACTION,06/19/2006`)return c.Blob(http.StatusOK, "text/csv", data)})e.GET("null", func(c echo.Context) error {return c.NoContent(http.StatusOK)})e.Logger.Fatal(e.Start(":1330"))
}

Part5 json传输

package mainimport ("encoding/json""github.com/labstack/echo""net/http"
)type Product struct {Name  string `json:"name" form:"name" query:"name"`Price int    `json:"price" form:"price" query:"price"`
}func main() {e := echo.New()e.GET("/", func(c echo.Context) error {return c.String(http.StatusOK, "Hello, World!")})e.GET("/html", func(c echo.Context) error {return c.HTML(http.StatusOK, "<h1>Hello, World!</h1>")})e.GET("/json", func(c echo.Context) error {p := &Product{Name:  "football",Price: 1000,}return c.JSON(http.StatusOK, p)})e.GET("/prettyjson", func(c echo.Context) error {p := &Product{Name:  "soccer",Price: 1000,}return c.JSONPretty(http.StatusOK, p, "  ")})e.GET("/streamjson", func(c echo.Context) error {p := &Product{Name:  "soccer",Price: 134,}c.Response().Header().Set("Content-Type", echo.MIMEApplicationXMLCharsetUTF8)c.Response().WriteHeader(http.StatusOK)return json.NewEncoder(c.Response()).Encode(p)})e.GET("/jsonblob", func(c echo.Context) error {p := &Product{Name:  "volley",Price: 120,}data, _ := json.Marshal(p)return c.JSONPBlob(http.StatusOK, "", data)})e.GET("/xml", func(c echo.Context) error {p := &Product{Name:  "basketball",Price: 120,}return c.XML(http.StatusOK, p)})e.GET("/png", func(c echo.Context) error {//return c.File("./public/left.png")return c.File("./public/test.html")})e.GET("blub", func(c echo.Context) error {data := []byte(`0306703,0035866,NO_ACTION,06/19/2006`)return c.Blob(http.StatusOK, "text/csv", data)})e.GET("null", func(c echo.Context) error {return c.NoContent(http.StatusOK)})e.Logger.Fatal(e.Start(":1330"))
}

Part6 模版渲染


import ("github.com/labstack/echo""net/http"
)func main() {e := echo.New()e.GET("/", func(c echo.Context) error {return c.String(http.StatusOK, "Hello, World!")})e.GET("/index", func(c echo.Context) error {return c.File("assets/index.html")})e.Static("/static", "assets")e.Logger.Fatal(e.Start(":9090"))
}

Part7 模版参数传递


import ("github.com/labstack/echo""html/template""io""net/http"
)type Template struct {templates *template.Template
}func (t *Template) Render(w io.Writer,name string, data interface{}, c echo.Context) error {return t.templates.ExecuteTemplate(w, name, data)
}
func main() {e := echo.New()t := &Template{templates: template.Must(template.ParseGlob("public/view/*.html")),}e.Renderer = te.GET("/", func(c echo.Context) error {return c.Render(http.StatusOK, "index", "Hello, World!")})e.GET("/hello", func(c echo.Context) error {return c.Render(http.StatusOK, "hello", "World")})e.Logger.Fatal(e.Start(":1325"))
}

Part8 Cookie与Session


import ("fmt""github.com/gorilla/sessions""github.com/labstack/echo""github.com/labstack/echo-contrib/session""github.com/labstack/echo/v4""net/http""time"
)func WriteCookie(c echo.Context) error {cookie := new(http.Cookie)cookie.Name = "userName"cookie.Value = "cookieValue"cookie.Expires = time.Now().Add(time.Hour * 2)c.SetCookie(cookie)return c.String(http.StatusOK, "write a cookie")
}func ReadCookie(c echo.Context) error {cookie, err := c.Cookie("userName")if err != nil {return err}fmt.Println(cookie.Name)fmt.Println(cookie.Value)return c.String(http.StatusOK, "read cookie")
}func ReadAllCookie(c echo.Context) error {for _, cookie := range c.Cookies() {fmt.Println(cookie.Name)fmt.Println(cookie.Value)}return c.String(http.StatusOK, "read all cookie")
}func SessionHandler(c echo.Context) error {sess, _ := session.Get("session", c)sess.Options = &sessions.Options{Path:     "/",MaxAge:   86400 * 7,HttpOnly: true,}sess.Values["foo"] = "bar"sess.Save(c.Request(), c.Response())return c.String(http.StatusOK, "session handler")
}
func main() {e := echo.New()e.GET("/", func(c echo.Context) error {return c.String(http.StatusOK, "<h1>Hello, World</h1>")})e.GET("/writeCookie", WriteCookie)e.GET("/readCookie", ReadCookie)e.GET("/readAllCookie", ReadAllCookie)store := sessions.NewCookieStore([]byte("secret"))// 使用会话中间件e.Use(session.Middleware(store))//e.Use(session.Middleware(sessions.NewCookieStore([]byte("secret"))))e.GET("/session", SessionHandler)e.Logger.Fatal(e.Start(":1325"))
}

Part9 JWT

import ("github.com/dgrijalva/jwt-go""github.com/labstack/echo""github.com/labstack/echo/middleware""net/http""strconv""time"
)type User struct {Username string `json:"username"`Password string `json:"password"`
}const jwtSecret = "secret"type JwtCustomClaims struct {Name string `json:"name"`ID   int    `json:"id"`jwt.StandardClaims
}func Login(c echo.Context) error {u := new(User)if err := c.Bind(u); err != nil {return c.JSON(http.StatusOK, echo.Map{"errcode": 401,"errmsg":  "request error",})}if "pass" == u.Password && u.Username == "name" {claims := &JwtCustomClaims{Name: u.Username,ID:   12,StandardClaims: jwt.StandardClaims{ExpiresAt: time.Now().Add(time.Hour * 24).Unix()},}token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)t, err := token.SignedString([]byte(jwtSecret))if err != nil {return err}return c.JSON(http.StatusOK, echo.Map{"token":   t,"errcode": 200,"errmsg":  "success",})} else {return c.JSON(http.StatusOK, echo.Map{"errcode": -1,"errmsg":  "failed",})}
}
func main() {e := echo.New()e.GET("/", func(c echo.Context) error {return c.String(http.StatusOK, "<h1>Hello, World</h1>")})e.POST("/login", Login)r := e.Group("/api")r.Use(middleware.JWTWithConfig(middleware.JWTConfig{Claims:     &JwtCustomClaims{},SigningKey: []byte(jwtSecret),}))r.Use(func(next echo.HandlerFunc) echo.HandlerFunc {return func(c echo.Context) error {user := c.Get("user").(*jwt.Token)claims := user.Claims.(*JwtCustomClaims)c.Set("name", claims.Name)c.Set("uid", claims.ID)return next(c)}})r.GET("/getInfo", func(c echo.Context) error {name := c.Get("name").(string)id := c.Get("id").(int)return c.String(http.StatusOK, "name:"+name+"id:"+strconv.Itoa(id))})e.Logger.Fatal(e.Start(":1323"))
}

Part9 日志


import ("github.com/labstack/echo""github.com/labstack/echo/middleware""github.com/labstack/gommon/log""net/http"
)func main() {e := echo.New()e.Use(middleware.Logger())e.GET("/", func(c echo.Context) error {e.Logger.Debugf("这是格式化输出%s")e.Logger.Debugj(log.JSON{"aaa": "cccc"})e.Logger.Debug("aaaa")return c.String(http.StatusOK, "<h1>Hello, World</h1>")})e.Logger.SetLevel(log.INFO)e.GET("/info", func(c echo.Context) error {e.Logger.Infof("这是格式化输出%s")e.Logger.Infoj(log.JSON{"aaa": "cccc"})e.Logger.Info("aaaa")return c.String(http.StatusOK, "INFO PAGE!")})e.Logger.Fatal(e.Start(":1323"))}

Part10 文件上传与下载


import ("github.com/labstack/echo""io""net/http""os"
)func upload(c echo.Context) error {file, err := c.FormFile("filename")if err != nil {return err}src, err := file.Open()if err != nil {return err}defer src.Close()dst, err := os.Create("upload/" + file.Filename)if err != nil {return err}defer dst.Close()if _, err = io.Copy(dst, src); err != nil {return err}return c.String(http.StatusOK, "upload success")
}
func multiUpload(c echo.Context) error {form, err := c.MultipartForm()if err != nil {return err}files := form.File["files"]for _, file := range files {src, err := file.Open()if err != nil {return err}defer src.Close()dst, err := os.Create("upload/" + file.Filename)if err != nil {return err}defer dst.Close()if _, err = io.Copy(dst, src); err != nil {return err}}return c.String(http.StatusOK, "upload success")}
func main() {e := echo.New()e.GET("/", func(c echo.Context) error {return c.Attachment("attachment.txt", "attachment.txt")})e.GET("/index", func(c echo.Context) error {return c.File("./multiUpload.html")})e.POST("/upload", upload)e.POST("/multiUpload", multiUpload)e.Logger.Fatal(e.Start(":1335"))
}

Part 11 Websocket通信

package mainimport ("fmt""github.com/gorilla/websocket""github.com/labstack/echo""github.com/labstack/echo/middleware"
)var upgrader = websocket.Upgrader{}func hello(c echo.Context) error {ws, err := upgrader.Upgrade(c.Response(), c.Request(), nil)if err != nil {return err}defer ws.Close()for {err := ws.WriteMessage(websocket.TextMessage, []byte("hello world"))if err != nil {c.Logger().Error(err)}_, msg, err := ws.ReadMessage()if err != nil {c.Logger().Error(err)}fmt.Printf("%s\n", msg)}
}
func main() {e := echo.New()e.Use(middleware.Logger())e.Use(middleware.Recover())e.Static("/", "./public")e.GET("/", func(c echo.Context) error {return c.File("./public/webtest.html")})e.GET("/ws", hello)e.Logger.Fatal(e.Start(":1330"))
}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/diannao/67232.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

mqtt详细介绍及集成到springboot

mqtt详细介绍及集成到springboot 1.mqtt发布/订阅消息参数详细介绍2. mqtt客户端连接参数介绍3. docker-compose搭建mqtt服务端4. springboot集成mqtt实现发布订阅5. 测试注意事项 1.mqtt发布/订阅消息参数详细介绍 1.1. qosQoS0 &#xff0c;Sender 发送的一条消息&#xff0…

【linux命令】ip命令使用

1、设置网口IP 方法1&#xff1a;通过IP设置网口ip 添加静态IP&#xff1a; ip addr add 1.1.1.1/24 dev eth0 删除ip: ip addr del 1.1.1.1/24 dev eth0 方法2&#xff1a;nmtui 配置IP另外方法&#xff1a; nmtui 2、添加路由 添加路由&#xff1a; ip route add 目标网…

基于springboot的租房网站系统

作者&#xff1a;学姐 开发技术&#xff1a;SpringBoot、SSM、Vue、MySQL、JSP、ElementUI、Python、小程序等 文末获取“源码数据库万字文档PPT”&#xff0c;支持远程部署调试、运行安装。 项目包含&#xff1a; 完整源码数据库功能演示视频万字文档PPT 项目编码&#xff1…

自动化办公|xlwings简介

xlwings 是一个开源的 Python 库&#xff0c;旨在实现 Python 与 Microsoft Excel 的无缝集成。它允许用户使用 Python 脚本自动化 Excel 操作&#xff0c;读取和写入数据&#xff0c;执行宏&#xff0c;甚至调用 VBA 脚本。这使得数据分析、报告生成和其他与 Excel 相关的任务…

《零基础Go语言算法实战》【题目 4-8】用 Go 语言设计一个遵循最近最少使用(LRU)缓存约束的数据结构

《零基础Go语言算法实战》 【题目 4-8】用 Go 语言设计一个遵循最近最少使用&#xff08;LRU&#xff09;缓存约束的数据结构 实现 LRUCache 类。 ● LRUCache(int capacity) &#xff1a;初始化具有正大小容量的 LRU 缓存。 ● int get(int key) &#xff1a;如果 key 存在…

Sonatype Nexus OSS 构建私有docker 仓库

1.Docker Engine 配置 {"builder": {"gc": {"defaultKeepStorage": "20GB","enabled": true}},"dns": ["8.8.8.8","114.114.114.114"],"experimental": false,"features"…

lqb.key按键全套

#include "stc15.h" #define FOSC 11059200L //#define T1MS (65536-FOSC/1000) //1T模式 #define T1MS (65536-FOSC/12/1000) //12T模式typedef unsigned char u8; typedef unsigned int u16; typedef unsigned long u32;#define LY 1 //…

概率函数,累计分布函数

四. 累计分布函数 1. 累计分布函数&#xff08;CDF, Cumulative Distribution Function&#xff09; 累计分布函数是用来描述随机变量取值小于或等于某个给定值的概率。它适用于离散型和连续型随机变量&#xff0c;并且能够通过概率质量函数&#xff08;PMF&#xff09;或概率…

Docker中编码和时区设置不生效问题排查

一、编码不生效排查 在 docker-compose.yml 中设置了环境变量&#xff0c;但进入 Docker 容器后 LANG 仍然显示为 zh_CN.UTF-8&#xff0c;按照以下步骤进行排查和修复&#xff1a; 1. 确保设置正确 确保你的 docker-compose.yml 文件中环境变量设置没有拼写错误&#xff0c;示…

CSS 样式 margin:0 auto; 详细解读

一、基本语法 margin 属性是用于设置元素的外边距&#xff0c;它可以接受一个、两个、三个或四个值。 margin:0 auto 是一种简洁的写法&#xff0c;其中包含了两个值。 二、值的含义 第一个值 0 表示元素的上下外边距为 0。这意味着该元素的顶部和底部与相邻元素或父元素之间…

【线性代数】行列式的性质

行列式性质定理讲义 一、行列式的基本性质 性质 1&#xff1a;行列互换 对于任意一个 n n n \times n nn 的方阵 A A A&#xff0c;其行列式 ∣ A ∣ |A| ∣A∣ 满足&#xff1a; ∣ A ∣ ∣ A T ∣ |A| |A^T| ∣A∣∣AT∣ 其中&#xff0c; A T A^T AT 是 A A A 的…

python创建pdf水印,希望根据文本长度调整水印字体大小,避免超出页面

为了根据文本长度动态调整水印字体大小&#xff0c;可以先测量文本长度&#xff0c;然后根据页面宽度和高度动态计算合适的字体大小。以下是修改后的代码&#xff1a; from reportlab.pdfgen import canvas from reportlab.lib.pagesizes import letter from reportlab.pdfbas…

Flutter项目适配鸿蒙

Flutter项目适配鸿蒙 前言Flutter项目适配鸿蒙新工程直接支持ohos构建新项目编译运行 适配已有的Flutter项目 前言 目前市面上使用Flutter技术站的app不在少数&#xff0c;对于Flutter的项目&#xff0c;可能更多的是想直接兼容Harmonyos&#xff0c;而不是直接在重新开发一个…

链家房价数据爬虫和机器学习数据可视化预测

完整源码项目包获取→点击文章末尾名片&#xff01;

【20250113】基于肌肉形变测量的连续步态相位估计算法,可自适应步行速度和地形坡度...

【基本信息】 论文标题&#xff1a;Continuous Gait Phase Estimation by Muscle Deformations with Speed and Ramp Adaptability 发表期刊&#xff1a;IEEE Sensors Journal 发表时间&#xff1a;2024年5月30日 【访问链接】 论文链接&#xff1a;https://ieeexplore.ieee.or…

AudioGPT全新的 音频内容理解与生成系统

AudioGPT全新的 音频内容理解与生成系统 ChatGPT、GPT-4等大型语言模型 (LLM) 在语言理解、生成、交互和推理方面表现出的非凡能力,引起了学界和业界的极大关注,也让人们看到了LLM在构建通用人工智能 (AGI) 系统方面的潜力。 现有的GPT模型具有极高的语言生成能力,是目前最…

【全套】基于分类算法的学业警示预测信息管理系统

【全套】基于分类算法的学业警示预测信息管理系统 【摘 要】 随着网络技术的发展基于分类算法的学业警示预测信息管理系统是一种新的管理方式&#xff0c;同时也是现代学业预测信息管理的基础&#xff0c;利用互联网的时代与实际情况相结合来改变过去传统的学业预测信息管理中…

小程序组件 —— 31 事件系统 - 事件绑定和事件对象

小程序中绑定事件和网页开发中绑定事件几乎一致&#xff0c;只不过在小程序不能通过 on 的方式绑定事件&#xff0c;也没有 click 等事件&#xff0c;小程序中绑定事件使用 bind 方法&#xff0c;click 事件也需要使用 tap 事件来进行代替&#xff0c;绑定事件的方式有两种&…

使用中间件自动化部署java应用

为了实现你在 IntelliJ IDEA 中打包项目并通过工具推送到两个 Docker 服务器&#xff08;172.168.0.1 和 172.168.0.12&#xff09;&#xff0c;并在推送后自动或手动重启容器&#xff0c;我们可以按照以下步骤进行操作&#xff1a; 在 IntelliJ IDEA 中配置 Maven 或 Gradle 打…

邮箱发送验证码(nodemailer)

邮箱发送验证码 打开SMTP 服务使用 Node.js 邮件发送模块&#xff08;nodemailer&#xff09;封装验证码组件 开发中经常会遇到需要验证码&#xff0c;不过手机验证码需要money&#xff0c;不到必要就不必花费&#xff0c;所以可以使用邮箱发送验证码 打开SMTP 服务 根据自己想…