重构: 将API配置提取到config模块并优化错误处理

- 将硬编码的API配置移到config模块,支持环境变量配置
- 添加API Key验证和配置检查
- 添加图片上传大小限制(10MB)
- 移除不必要的注释,简化代码
- 改进错误处理和日志记录
This commit is contained in:
lafay
2026-03-16 13:02:57 +08:00
parent 9addc89a66
commit ed1d252fab
3 changed files with 22 additions and 17 deletions

10
main.go
View File

@@ -97,7 +97,6 @@ func runHTTPServer() {
// 课表图片识别接口
r.POST("/recognize", func(c *gin.Context) {
// 读取上传的图片文件
file, header, err := c.Request.FormFile("image")
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "请上传图片文件", "details": err.Error()})
@@ -107,24 +106,25 @@ func runHTTPServer() {
log.Printf("收到图片上传: %s, 大小: %d bytes", header.Filename, header.Size)
// 读取图片数据
if header.Size > 10*1024*1024 {
c.JSON(http.StatusBadRequest, gin.H{"error": "图片文件过大", "max_size": "10MB"})
return
}
imageData, err := io.ReadAll(file)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "读取图片失败", "details": err.Error()})
return
}
// 调用识别模块
courses, err := recognizer.RecognizeFromBytes(imageData)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "识别失败", "details": err.Error()})
return
}
// 打印识别结果
recognizer.PrintCourses(courses)
// 保存到JSON文件
err = recognizer.SaveToJSON(courses, "schedule_result.json")
if err != nil {
log.Printf("保存JSON失败: %v", err)