refactor: 优化POST请求处理逻辑,移除不必要的依赖和调试代码

This commit is contained in:
liyp 2024-08-02 21:02:42 +08:00
parent c498d12a9b
commit 966742551d

35
main.go
View file

@ -5,7 +5,6 @@ import (
"fmt" "fmt"
"go-bot/config" "go-bot/config"
"go-bot/utils" "go-bot/utils"
"io"
"log" "log"
"net" "net"
"net/http" "net/http"
@ -13,7 +12,6 @@ import (
"time" "time"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
"github.com/goccy/go-json"
_ "github.com/mattn/go-sqlite3" _ "github.com/mattn/go-sqlite3"
) )
@ -52,24 +50,27 @@ func insertMessage(db *sql.DB, data map[string]interface{}) error {
// handlePost 处理 POST 请求 // handlePost 处理 POST 请求
func handlePost(c *gin.Context) { 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 { if err != nil {
// 请求体数据读取失败 c.JSON(400, gin.H{"error": gin.H{
c.JSON(http.StatusBadRequest, gin.H{"error": "Error reading request body"}) "message": "Request must be proper JSON",
"type": "invalid_request_error",
"param": nil,
"code": err.Error(),
}})
return 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") db, err := sql.Open("sqlite3", "./data.db")
if err != nil { if err != nil {
@ -108,7 +109,7 @@ func handlePost(c *gin.Context) {
// 调用路由处理函数 // 调用路由处理函数
if data["post_type"] == "message" || data["post_type"] == "message_sent" { if data["post_type"] == "message" || data["post_type"] == "message_sent" {
utils.Router(data) 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 { if !ok {
log.Fatal("加载配置失败!") log.Fatal("加载配置失败!")
} }
gin.SetMode(gin.ReleaseMode)
r := gin.Default() r := gin.Default()
r.POST("/", handlePost) r.POST("/", handlePost)
fmt.Println("Server listening on", APIURL, "...") fmt.Println("Server listening on", APIURL, "...")