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, "添加成功"})
}
相关推荐
冰暮流星13 小时前
javascript之String方法介绍
开发语言·javascript·ecmascript
nianniannnn13 小时前
Qt QMessageBox知识点
开发语言·数据库·qt
故乡de云14 小时前
AWS 添加付款方式失败排查清单:卡片、银行风控与账号状态逐项定位
开发语言·php
J_yyy14 小时前
【Qt核心组件类框架】
开发语言·qt
运维行者_14 小时前
如何查看每个IP的带宽使用情况?NetFlow 技术实战指南
开发语言·网络·分布式·后端·架构·带宽
天天进步201514 小时前
Python全栈项目--基于深度学习的图像超分辨率系统
开发语言·python·深度学习
blevoice15 小时前
抖抖燃脂机单 AC6966B 主控调试踩坑:Type-C 整机供电喇叭无声排障
c语言·开发语言·单片机
小小晓.15 小时前
C++小白记:C风格字符串和数组用法
c语言·开发语言·c++
Helen_cai15 小时前
OpenHarmony 项目统一全局样式、尺寸、色彩主题封装 ThemeUtil(API23)
开发语言·前端·javascript·华为·harmonyos
郑州光合科技余经理15 小时前
家政O2O平台解析:从0搭建上门预约小程序解决方案
android·java·开发语言·前端·小程序·架构·php