运维八一 运维八一
首页
运维杂记
编程浅尝
周积跬步
专栏
生活
关于
收藏
  • 分类
  • 标签
  • 归档
Source (opens new window)

运维八一

运维,运维!
首页
运维杂记
编程浅尝
周积跬步
专栏
生活
关于
收藏
  • 分类
  • 标签
  • 归档
Source (opens new window)
  • Go

    • 前言

    • Go基础知识

    • Go基本语法

    • 实战项目:简单web服务

    • 基本数据类型

    • 内置运算符

    • 分支和循环

    • 函数 function

    • 结构体 struct

    • 方法 method

    • 实战项目:跟踪函数调用链

    • 接口 interface

    • 并发 concurrency

    • 指针

    • 实战项目:实现轻量级线程池

    • 实战项目:实现TCP服务器

    • go常用包

    • Gin框架

      • gin入门
      • gin工作流程
      • gin中间件
      • gin路由
      • gin请求
      • 数据绑定和校验
      • 响应返回
        • 路由分发
        • Cookie和Session
        • gin项目结构
        • GORM入门
        • 一对多关联查询
      • go随记

    • Python

    • Shell

    • Java

    • Vue

    • 前端

    • 编程浅尝
    • Go
    • Gin框架
    lyndon
    2022-06-27
    目录

    响应返回

    # 1. 响应返回

    各种数据格式的响应:json、结构体、XML、YAML,类似于java的properties、ProtoBuf

    main.go

    package main
    
    import (
    	"github.com/gin-gonic/gin"
    	"github.com/gin-gonic/gin/testdata/protoexample"
    )
    
    // 多种响应方式
    func main() {
    	// 1.创建路由
    	// 默认使用了2个中间件Logger(), Recovery()
    	r := gin.Default()
    	// 1.json
    	r.GET("/someJSON", func(c *gin.Context) {
    		c.JSON(200, gin.H{"message": "someJSON", "status": 200})
    	})
    	// 2. 结构体响应
    	r.GET("/someStruct", func(c *gin.Context) {
    		var msg struct {
    			Name    string
    			Message string
    			Number  int
    		}
    		msg.Name = "root"
    		msg.Message = "message"
    		msg.Number = 123
    		c.JSON(200, msg)
    	})
    	// 3.XML
    	r.GET("/someXML", func(c *gin.Context) {
    		c.XML(200, gin.H{"message": "abc"})
    	})
    	// 4.YAML响应
    	r.GET("/someYAML", func(c *gin.Context) {
    		c.YAML(200, gin.H{"name": "zhangsan"})
    	})
    	// 5.protobuf格式,谷歌开发的高效存储读取的工具
    	// 数组?切片?如果自己构建一个传输格式,应该是什么格式?
    	r.GET("/someProtoBuf", func(c *gin.Context) {
    		reps := []int64{int64(1), int64(2)}
    		// 定义数据
    		label := "label"
    		// 传protobuf格式数据
    		data := &protoexample.Test{
    			Label: &label,
    			Reps:  reps,
    		}
    		c.ProtoBuf(200, data)
    	})
    
    	r.Run(":8000")
    }
    
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52

    # 1.1 string响应

    package main
    import (
    	"fmt"
    	"net/http"
    	"github.com/gin-gonic/gin"
    )
    func main() {
    	r := gin.Default()
    	r.GET("/response/", ResponseStringHandler)
    	fmt.Println("http://127.0.0.1:8000/response/")
    	r.Run(":8000")
    }
    func ResponseStringHandler(c *gin.Context) {
    	c.String(http.StatusOK, "返回简单字符串")
    }
    
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15

    # 1.2 JSON响应

    package main
    import (
    	"fmt"
    	"net/http"
    	"github.com/gin-gonic/gin"
    )
    func main() {
    	r := gin.Default()
    	r.GET("/response/", ResponseJsonHandler)
    	fmt.Println("http://127.0.0.1:8000/response/")
    	r.Run(":8000")
    }
    func ResponseJsonHandler(c *gin.Context) {
    	type Data struct {
    		Msg string `json:"msg"`
    		Code int `json:"code"`
    	}
    	d := Data{
    		Msg: "Json数据",
    		Code: 1001,
    	}
    	c.JSON(http.StatusOK, d)
    	//// 也可以直接使用 gin.H返回 json数据
    	//c.JSON(http.StatusOK, gin.H{
    	// "msg": "success",
    	//})
    }
    
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27

    # 1.3 结构体响应

    http://localhost:8000/someStruct

    {"Name":"root","Message":"message","Number":123}
    
    1

    # 1.4 XML响应

    http://localhost:8000/someXML

    This XML file does not appear to have any style information associated with it. The document tree is shown below.
    <map>
    <message>abc</message>
    </map>
    
    1
    2
    3
    4

    # 1.5 YAML响应

    http://localhost:8000/someYAML

    name: zhangsan
    
    1

    # 1.6 重定向

    package main
    
    import (
        "net/http"
        "github.com/gin-gonic/gin"
    )
    
    func main() {
        r := gin.Default()
        r.GET("/index", func(c *gin.Context) {
            c.Redirect(http.StatusMovedPermanently, "http://v5blog.cn")
        })
        r.Run()
    }
    
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14

    # 1.7 同步异步

    • goroutine机制可以方便地实现异步处理
    • 另外,在启动新的goroutine时,不应该使用原始上下文,必须使用它的只读副本
    package main
    
    import (
        "log"
        "time"
        "github.com/gin-gonic/gin"
    )
    
    func main() {
        // 1.创建路由
        // 默认使用了2个中间件Logger(), Recovery()
        r := gin.Default()
        // 1.异步
        r.GET("/long_async", func(c *gin.Context) {
            // 需要搞一个副本
            copyContext := c.Copy()
            // 异步处理
            go func() {
                time.Sleep(3 * time.Second)
                log.Println("异步执行:" + copyContext.Request.URL.Path)
            }()
        })
        // 2.同步
        r.GET("/long_sync", func(c *gin.Context) {
            time.Sleep(3 * time.Second)
            log.Println("同步执行:" + c.Request.URL.Path)
        })
    
        r.Run(":8000")
    }
    
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30

    # 1.8 HTML模板渲染

    • gin支持加载HTML模板, 然后根据模板参数进行配置并返回相应的数据,本质上就是字符串替换
    • LoadHTMLGlob()方法可以加载模板文件

    项目结构

    img

    当我们渲染的HTML文件中引用了静态文件时,我们只需要按照以下方式在渲染页面前调用gin.Static方法即可。

    func main() {
    	r := gin.Default()
    	r.Static("/static", "./static")
    	r.LoadHTMLGlob("templates/**/*")
       // ...
    	r.Run(":8080")
    }
    
    1
    2
    3
    4
    5
    6
    7

    main.go

    package main
    
    import (
    	"github.com/gin-gonic/gin"
    	"net/http"
    )
    
    func main() {
    	r := gin.Default()
    	r.LoadHTMLGlob("tem/**/*")
    	r.GET("/index", func(c *gin.Context) {
    		c.HTML(http.StatusOK, "user/index.html", gin.H{"title": "我的博客:", "address": "v5blog.cn"})
    	})
    	r.Run()
    }
    
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15

    tem/public/header.html

    {{define "public/header"}}
    <!DOCTYPE html>
    <html lang="en">
    <head>
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <meta http-equiv="X-UA-Compatible" content="ie=edge">
      <title>{{.title}}</title>
    </head>
    <body>
      <h1>header</h1>
    </body>
    </html>
    {{end}}
    
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14

    tem/public/footer.html

    {{define "public/footer"}}
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
    </head>
    <body>
        <h1>footer</h1>
    </body>
    </html>
    {{ end }}
    
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12

    tem/user/index.html

    {{ define "user/index.html" }}
    {{template "public/header" .}}
    博客地址:{{.address}}
    {{template "public/footer" .}}
    {{ end }}
    
    1
    2
    3
    4
    5
    上次更新: 2022/06/27, 00:59:36
    数据绑定和校验
    路由分发

    ← 数据绑定和校验 路由分发→

    最近更新
    01
    ctr和crictl显示镜像不一致
    03-13
    02
    alpine镜像集成常用数据库客户端
    03-13
    03
    create-cluster
    02-26
    更多文章>
    Theme by Vdoing | Copyright © 2015-2024 op81.com
    苏ICP备18041258号-2
    • 跟随系统
    • 浅色模式
    • 深色模式
    • 阅读模式