go gin 响应数据

go gin 响应数据

go 复制代码
package main

import (
	"fmt"
	"github.com/gin-gonic/gin"
)

type UserInfo struct {
	UserName string `json:"user_name"`
	Age      int    `json:"age"`
	Password string `json:"-"`
}

func JsonTest(ctx *gin.Context) {

	a := UserInfo{"张三", 20, "123"}
	ctx.JSON(200, a)
}

func Query1(c *gin.Context) {
	id := c.Query("id")
	c.String(200, id+"ces")
}

func main() {
	fmt.Println("测试")

	router := gin.Default()

	router.GET("/index", func(ctx *gin.Context) {
		ctx.String(200, "Hello World~!")
	})

	router.GET("/json", JsonTest)

	router.GET("/query", Query1)

	router.Run(":8080")
}
go 复制代码
package main

import (
	"encoding/json"
	"fmt"

	"github.com/gin-gonic/gin"
)

type ArticleModel struct {
	Title string `json:"title"`
	Content string    `json:"content"`
}

type Response struct {
	Code int `json:"code"`
	Data any `json:"data"`
	Msg string `json:"msg"`
}

func _getList(c *gin.Context) {
	articleList := []ArticleModel{
		{"go语言入门", "这篇文章是讲解go的"},
		{"python语言入门", "这篇文章是讲解python的"},
		{"JavaScript语言入门", "这篇文章是讲解JavaScript的"},
	}
	// c.JSON(200, articleList)
	c.JSON(200, Response{0, articleList, "成功"})
}

func _getDetail(c *gin.Context) {
	a := c.Param("id")
	fmt.Println(c.Param("id"))
	article := ArticleModel{
		"go语言入门", "这篇文章是讲解go的" + a,
	}
	c.JSON(200, Response{0, article, "成功"})
}



/* 
GET     /articles      文章列表
GET     /articles/:id  文章详情
POST    /articles      添加文章
PUT     /articles/:id  修改某一篇文章
DELETE  /articles/:id  删除某一篇文章
*/

func main() {
	fmt.Println("测试")

	router := gin.Default()

	router.GET("/articles", _getList)
	router.GET("/articles/:id", _getDetail)
	router.POST("/articles", _create)



	router.Run(":8080")
}



func _bindJson(c *gin.Context, obj any) (err error) {
	body, _ := c.GetRawData()
	contentType := c.GetHeader("Content-Type")
	switch contentType {
	case "application/json":
		err = json.Unmarshal(body, &obj)
		if err != nil {
			fmt.Println(err.Error())
			return err
		}
	}
	return nil
}

func _create(c *gin.Context) {
	var article ArticleModel
	err := _bindJson(c, &article)
	if err != nil{
		fmt.Println(err)
		return
	}
	fmt.Println(article)
	c.JSON(200, Response{0, article, "添加成功"})
}
相关推荐
倔强青铜33 小时前
苦练Python第18天:Python异常处理锦囊
开发语言·python
u_topian4 小时前
【个人笔记】Qt使用的一些易错问题
开发语言·笔记·qt
珊瑚里的鱼4 小时前
LeetCode 692题解 | 前K个高频单词
开发语言·c++·算法·leetcode·职场和发展·学习方法
AI+程序员在路上4 小时前
QTextCodec的功能及其在Qt5及Qt6中的演变
开发语言·c++·qt
xingshanchang4 小时前
Matlab的命令行窗口内容的记录-利用diary记录日志/保存命令窗口输出
开发语言·matlab
Risehuxyc4 小时前
C++卸载了会影响电脑正常使用吗?解析C++运行库的作用与卸载后果
开发语言·c++
AI视觉网奇4 小时前
git 访问 github
运维·开发语言·docker
不知道叫什么呀5 小时前
【C】vector和array的区别
java·c语言·开发语言·aigc
liulilittle5 小时前
.NET ExpandoObject 技术原理解析
开发语言·网络·windows·c#·.net·net·动态编程
wan_da_ren5 小时前
JVM监控及诊断工具-GUI篇
java·开发语言·jvm·后端