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, "添加成功"})
}
相关推荐
another heaven2 小时前
【Qt VS2022调试时无法查看QString等Qt变量信息】解决方法
开发语言·qt
A黄俊辉A2 小时前
axios+ts封装
开发语言·前端·javascript
杨福瑞3 小时前
C语⾔内存函数
c语言·开发语言
eqwaak03 小时前
科技信息差(9.12)
开发语言·python·科技·量子计算
axban3 小时前
QT M/V架构开发实战:QStringListModel介绍
开发语言·数据库·qt
刘媚-海外3 小时前
Go语言开发AI应用
开发语言·人工智能·golang·go
勇敢牛牛_3 小时前
使用Rust实现服务配置/注册中心
开发语言·后端·rust·注册中心·配置中心
catchadmin3 小时前
PHP serialize 序列化完全指南
android·开发语言·php
deepwater_zone3 小时前
Go语言核心技术
后端·golang
hzzzzzo04 小时前
微服务网关全解析:从入门到实践
java·开发语言·微服务