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"
"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, "...")