1.[]byte
engine.GET("/hellobyte", func(context *gin.Context) {
fullpath:="请求路径:"+context.FullPath()
fmt.Println(fullpath)
context.Writer.Write([]byte(fullpath))
})
2.string
engine.GET("/hellostring", func(context *gin.Context) {
fullpath:="请求路径:"+context.FullPath()
fmt.Println(fullpath)
context.Writer.WriteString(fullpath)
})
3.JSON
(1).map类型
//gin框架中的context包含的JSON方法可以将结构体类型的数据转换为JSON格式的结构化数据,然后返回给客户端。
engine.GET("/hellojson", func(context *gin.Context) {
fullpath:="请求路径:"+context.FullPath()
fmt.Println(fullpath)
context.JSON(200,map[string]interface{}{//将传回的数据类型转换为JSON格式,显示在浏览器上
"code": 1,
"message":"OK",//当code为0时,message可能为错误信息
"data":fullpath,
})
})
(2)struct类型
首先定义一个结构体
type Response struct {
Code int
Message string
Data interface{}
}
具体的实现:
engine.GET("/jsonstruct", func(context *gin.Context) {
fullpath:="请求路径:"+context.FullPath()
fmt.Println(fullpath)
resp:=Response{Code: 1,Message: "OK",Data: fullpath}
context.JSON(200,&resp)//第二个参数为 interface{},需要取地址
})
通过浏览器上的更多工具-开发者工具
4.html后续用到可在学习
5.加载动态图片,是在html上进行展示的,后续用到可在进行学习
完整代码如下:
package main
import (
"fmt"
"github.com/gin-gonic/gin"
)
func main(){
engine:=gin.Default()
engine.GET("/hellobyte", func(context *gin.Context) {
fullpath:="请求路径:"+context.FullPath()
fmt.Println(fullpath)
context.Writer.Write([]byte(fullpath))
})
engine.GET("/hellostring", func(context *gin.Context) {
fullpath:="请求路径:"+context.FullPath()
fmt.Println(fullpath)
context.Writer.WriteString(fullpath)
})
//gin框架中的context包含的JSON方法可以将结构体类型的数据转换为JSON格式的结构化数据,然后返回给客户端。
engine.GET("/hellojson", func(context *gin.Context) {
fullpath:="请求路径:"+context.FullPath()
fmt.Println(fullpath)
context.JSON(200,map[string]interface{}{//将传回的数据类型转换为JSON格式,显示在浏览器上
"code": 1,
"message":"OK",//当code为0时,message可能为错误信息
"data":fullpath,
})
})
engine.GET("/jsonstruct", func(context *gin.Context) {
fullpath:="请求路径:"+context.FullPath()
fmt.Println(fullpath)
resp:=Response{Code: 1,Message: "OK",Data: fullpath}
context.JSON(200,&resp)//第二个参数为 interface{},需要取地址
})
engine.Run()
}
type Response struct {
Code int
Message string
Data interface{}
}