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 小时前
R语言的数据库交互
开发语言·后端·golang
小萌新上大分3 小时前
SpringCloudGateWay
java·开发语言·后端·springcloud·springgateway·cloudalibaba·gateway网关
PacosonSWJTU4 小时前
python基础-13-处理excel电子表格
开发语言·python·excel
froginwe114 小时前
Perl 条件语句
开发语言
啥都鼓捣的小yao4 小时前
利用C++编写操作OpenCV常用操作
开发语言·c++·opencv
灼华十一4 小时前
Golang系列 - 内存对齐
开发语言·后端·golang
程序媛学姐4 小时前
SpringRabbitMQ消息模型:交换机类型与绑定关系
java·开发语言·spring
努力努力再努力wz5 小时前
【c++深入系列】:类与对象详解(中)
java·c语言·开发语言·c++·redis
Johnny_Cheung5 小时前
字符串、列表、元组、字典
开发语言·python