解决响应中带有反斜杠转义符&返回的json无法格式化的问题
package main
import (
"encoding/json"
"net/http"
"github.com/gin-gonic/gin"
"gorm.io/gorm"
)
// 模型定义
type Cookie struct {
gorm.Model
CookieJson json.RawMessage `gorm:"type:json" json:"cookie_json"`
}
// 服务层
type CookieService struct{}
func (service CookieService) GetCookieJsonById(id string) (json.RawMessage, error) {
var cookie Cookie
if err := model.DB.First(&cookie, "id = ?", id).Error; err != nil {
return nil, err
}
return cookie.CookieJson, nil
}
// 控制器层
func GetCookieJsonById(c *gin.Context) {
id := c.Query("id")
service := CookieService{}
cookieJsonData, err := service.GetCookieJsonById(id)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
c.Data(http.StatusOK, "application/json", cookieJsonData)
}
func main() {
// 初始化Gin引擎
r := gin.Default()
// 注册路由
r.GET("/cookie", GetCookieJsonById)
// 启动端口
r.Run(":8080")
}