go_test1
package main
import (
"github.com/gin-gonic/gin"
"net/http"
)
type Article struct {
Id int `json:"id"`
Title string `json:"title"`
}
func main() {
// 定义路由
r := gin.Default()
// 返回字符串
r.GET("/", func(context *gin.Context) {
context.String(200, "内容:%v", "你好gin")
})
// 返回json
r.GET("/json", func(context *gin.Context) {
context.JSON(200, map[string]interface{}{
"姓名": "张艺卓",
"电话": "12345678910",
})
})
// 返回json
r.GET("/json2", func(context *gin.Context) {
// type H map[string]any, any是interface{}的缩写
context.JSON(200, gin.H{
"姓名": "孟子恒",
"电话": "12345678910",
})
})
// 返回结构体
r.GET("/json3", func(context *gin.Context) {
// 大写才能被包外访问
var a = &Article{
Id: 1,
Title: "斗罗大陆",
}
context.JSON(200, a)
})
// jsonp,可给params传入callback回调函数,用于处理跨域请求
// http://localhost:8080/jsonp?callback=xxx
r.GET("/jsonp", func(context *gin.Context) {
// 大写才能被包外访问
var a = &Article{
Id: 1,
Title: "斗罗大陆-jsonp",
}
context.JSONP(200, a)
})
// xml
r.GET("/xml", func(context *gin.Context) {
//context.XML(http.StatusOK, map[string]interface{}{ // 不知道为啥不显示
// "isTrue": true,
// "content": "我是xml",
//})
context.XML(http.StatusOK, gin.H{ // 显示ok
"isTrue": true,
"content": "我是xml",
})
})
// html
r.LoadHTMLGlob("templates/*") // 配置模板路径
r.GET("/html", func(context *gin.Context) {
context.HTML(200, "index.html", gin.H{
"name": "张艺卓",
"mobile ": "12345678910",
})
})
r.Run()
}
作者:cloud-2-jane
出处:https://www.cnblogs.com/cloud-2-jane/p/18502634
版权:本作品采用「署名-非商业性使用-相同方式共享 4.0 国际」许可协议进行许可。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
· Pantheons:用 TypeScript 打造主流大模型对话的一站式集成库