Files
gpt-test/backend/main.go
2024-02-26 14:44:22 +08:00

89 lines
2.5 KiB
Go
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// 本文件功能为根据分页参数从数据库(用了gorm)中查询gpt对话历史记录并通过http返回给前端json
package main
import (
"encoding/json"
"fmt"
"gorm.io/driver/postgres"
"gorm.io/gorm"
"log"
"net/http"
"strconv"
)
type Request struct {
gorm.Model
Ip string // 来访者IP
Url string // 请求的URL
Stream bool // 是否是流式请求
APIModel string // 使用的 openapi 模型
TokenKey string `json:"TokenKey"` // api key
ResponseCode int // 返回的状态码
Error string `json:"Error"` // 错误信息
RequestData string `json:"RequestData"` // 请求内容
ResponseData string `json:"ResponseData"` // 返回内容
CompletionDuration int64 `json:"duration"` // 请求耗时
}
func main() {
dsn := "host=172.17.0.2 user=postgres password=mysecretpassword dbname=openai port=5432 sslmode=disable TimeZone=Asia/Shanghai"
db, err := gorm.Open(postgres.Open(dsn), &gorm.Config{})
if err != nil {
log.Fatalf("Error open db: %v", err)
}
db.AutoMigrate(&Request{})
http.HandleFunc("/requests/api", func(w http.ResponseWriter, r *http.Request) {
// 获取参数
page, _ := strconv.Atoi(r.URL.Query().Get("page")) // 页数
pageSize, _ := strconv.Atoi(r.URL.Query().Get("size")) // 分页大小
// 参数小于零置为1
if page <= 0 {
page = 1
}
if pageSize <= 0 {
pageSize = 10
}
// 计算偏移量
offset := (page - 1) * pageSize
var requests []Request
// 根据偏移量查记录
db.Offset(offset).Limit(pageSize).Find(&requests)
w.Header().Set("Content-Type", "application/json")
// 计算总数
var totalRecords int64
db.Model(&Request{}).Count(&totalRecords)
// 计算总页数
totalPages := (totalRecords + int64(pageSize) - 1) / int64(pageSize)
// 返回的分页数据
pagination := map[string]interface{}{
"page": page,
"pageSize": pageSize,
"totalRecords": totalRecords,
"totalPages": totalPages,
}
fmt.Println(requests)
// 返回的数据
responseDataWithPagination, err := json.Marshal(map[string]interface{}{
"data": requests,
"pagination": pagination,
})
if err != nil {
http.Error(w, "Failed to marshal JSON", http.StatusInternalServerError)
return
}
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Methods", "GET, OPTIONS")
w.WriteHeader(http.StatusOK)
w.Write(responseDataWithPagination)
})
http.ListenAndServe(":3002", nil)
}