From 966742551d32f103ec47ad54eb51372ce8b9cc3d Mon Sep 17 00:00:00 2001 From: liyp Date: Fri, 2 Aug 2024 21:02:42 +0800 Subject: [PATCH] =?UTF-8?q?refactor:=20=E4=BC=98=E5=8C=96POST=E8=AF=B7?= =?UTF-8?q?=E6=B1=82=E5=A4=84=E7=90=86=E9=80=BB=E8=BE=91=EF=BC=8C=E7=A7=BB?= =?UTF-8?q?=E9=99=A4=E4=B8=8D=E5=BF=85=E8=A6=81=E7=9A=84=E4=BE=9D=E8=B5=96?= =?UTF-8?q?=E5=92=8C=E8=B0=83=E8=AF=95=E4=BB=A3=E7=A0=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- main.go | 35 +++++++++++++++++++---------------- 1 file changed, 19 insertions(+), 16 deletions(-) diff --git a/main.go b/main.go index 3808538..09184df 100644 --- a/main.go +++ b/main.go @@ -5,7 +5,6 @@ import ( "fmt" "go-bot/config" "go-bot/utils" - "io" "log" "net" "net/http" @@ -13,7 +12,6 @@ import ( "time" "github.com/gin-gonic/gin" - "github.com/goccy/go-json" _ "github.com/mattn/go-sqlite3" ) @@ -52,24 +50,27 @@ func insertMessage(db *sql.DB, data map[string]interface{}) error { // handlePost 处理 POST 请求 func handlePost(c *gin.Context) { + // 从请求体中读取数据 - body, err := io.ReadAll(c.Request.Body) + // body, err := io.ReadAll(c.Request.Body) + // if err != nil { + // // 请求体数据读取失败 + // c.JSON(http.StatusBadRequest, gin.H{"error": "Error reading request body"}) + // return + // } + // 将 JSON 数据解析为 map 类型 + var data map[string]interface{} + err := c.BindJSON(&data) if err != nil { - // 请求体数据读取失败 - c.JSON(http.StatusBadRequest, gin.H{"error": "Error reading request body"}) + c.JSON(400, gin.H{"error": gin.H{ + "message": "Request must be proper JSON", + "type": "invalid_request_error", + "param": nil, + "code": err.Error(), + }}) return } - // 将 JSON 数据解析为 map 类型 - var data map[string]interface{} - err = json.Unmarshal(body, &data) - if err != nil { - // JSON 数据解析失败 - c.JSON(http.StatusBadRequest, gin.H{"error": "Error decoding JSON"}) - return - } - // 输出解析后的 JSON 数据 - fmt.Printf("data: %s\n\n", string(body)) // 打开数据库 db, err := sql.Open("sqlite3", "./data.db") if err != nil { @@ -108,7 +109,7 @@ func handlePost(c *gin.Context) { // 调用路由处理函数 if data["post_type"] == "message" || data["post_type"] == "message_sent" { utils.Router(data) - c.JSON(http.StatusOK, gin.H{"message": "JSON data received successfully!"}) + c.JSON(http.StatusOK, gin.H{"message": data}) } } @@ -118,8 +119,10 @@ func main() { if !ok { log.Fatal("加载配置失败!") } + gin.SetMode(gin.ReleaseMode) r := gin.Default() + r.POST("/", handlePost) fmt.Println("Server listening on", APIURL, "...")