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, "添加成功"})
}
相关推荐
执风挽^1 小时前
Python基础编程题2
开发语言·python·算法·visual studio code
Z9fish1 小时前
sse哈工大C语言编程练习20
c语言·开发语言·算法
萧鼎1 小时前
Python 包管理的“超音速”革命:全面上手 uv 工具链
开发语言·python·uv
源代码•宸2 小时前
大厂技术岗面试之谈薪资
经验分享·后端·面试·职场和发展·golang·大厂·职级水平的薪资
Anastasiozzzz2 小时前
Java Lambda 揭秘:从匿名内部类到底层原理的深度解析
java·开发语言
刘琦沛在进步2 小时前
【C / C++】引用和函数重载的介绍
c语言·开发语言·c++
机器视觉的发动机2 小时前
AI算力中心的能耗挑战与未来破局之路
开发语言·人工智能·自动化·视觉检测·机器视觉
HyperAI超神经2 小时前
在线教程|DeepSeek-OCR 2公式/表格解析同步改善,以低视觉token成本实现近4%的性能跃迁
开发语言·人工智能·深度学习·神经网络·机器学习·ocr·创业创新
R_.L2 小时前
【QT】常用控件(按钮类控件、显示类控件、输入类控件、多元素控件、容器类控件、布局管理器)
开发语言·qt
Zach_yuan3 小时前
自定义协议:实现网络计算器
linux·服务器·开发语言·网络