package server import ( "fmt" "net/http" "strconv" "time" "weatherstation/internal/config" "weatherstation/internal/database" "weatherstation/pkg/types" "github.com/gin-gonic/gin" ) // StartGinServer 启动Gin Web服务器 func StartGinServer() error { // 设置Gin模式 gin.SetMode(gin.ReleaseMode) // 创建Gin引擎 r := gin.Default() // 加载HTML模板 r.LoadHTMLGlob("templates/*") // 静态文件服务 r.Static("/static", "./static") // 路由设置 r.GET("/", indexHandler) // API路由组 api := r.Group("/api") { api.GET("/system/status", systemStatusHandler) api.GET("/stations", getStationsHandler) api.GET("/data", getDataHandler) } // 获取配置的Web端口 port := config.GetConfig().Server.WebPort if port == 0 { port = 10003 // 默认端口 } // 启动服务器 fmt.Printf("Gin Web服务器启动,监听端口 %d...\n", port) return r.Run(fmt.Sprintf(":%d", port)) } // indexHandler 处理主页请求 func indexHandler(c *gin.Context) { data := types.PageData{ Title: "英卓气象站", ServerTime: time.Now().Format("2006-01-02 15:04:05"), OnlineDevices: database.GetOnlineDevicesCount(database.GetDB()), TiandituKey: "0c260b8a094a4e0bc507808812cefdac", } c.HTML(http.StatusOK, "index.html", data) } // systemStatusHandler 处理系统状态API请求 func systemStatusHandler(c *gin.Context) { status := types.SystemStatus{ OnlineDevices: database.GetOnlineDevicesCount(database.GetDB()), ServerTime: time.Now().Format("2006-01-02 15:04:05"), } c.JSON(http.StatusOK, status) } // getStationsHandler 处理获取站点列表API请求 func getStationsHandler(c *gin.Context) { stations, err := database.GetStations(database.GetDB()) if err != nil { c.JSON(http.StatusInternalServerError, gin.H{"error": "查询站点失败"}) return } // 为每个站点计算十进制ID for i := range stations { if len(stations[i].StationID) > 6 { hexID := stations[i].StationID[len(stations[i].StationID)-6:] if decimalID, err := strconv.ParseInt(hexID, 16, 64); err == nil { stations[i].DecimalID = strconv.FormatInt(decimalID, 10) } } } c.JSON(http.StatusOK, stations) } // getDataHandler 处理获取历史数据API请求 func getDataHandler(c *gin.Context) { // 获取查询参数 decimalID := c.Query("decimal_id") startTime := c.Query("start_time") endTime := c.Query("end_time") interval := c.Query("interval") // 将十进制ID转换为十六进制(补足6位) decimalNum, err := strconv.ParseInt(decimalID, 10, 64) if err != nil { c.JSON(http.StatusBadRequest, gin.H{"error": "无效的站点编号"}) return } hexID := fmt.Sprintf("%06X", decimalNum) stationID := fmt.Sprintf("RS485-%s", hexID) // 解析时间 start, err := time.Parse("2006-01-02 15:04:05", startTime) if err != nil { c.JSON(http.StatusBadRequest, gin.H{"error": "无效的开始时间"}) return } end, err := time.Parse("2006-01-02 15:04:05", endTime) if err != nil { c.JSON(http.StatusBadRequest, gin.H{"error": "无效的结束时间"}) return } // 获取数据 points, err := database.GetWeatherData(database.GetDB(), stationID, start, end, interval) if err != nil { c.JSON(http.StatusInternalServerError, gin.H{"error": "查询数据失败"}) return } c.JSON(http.StatusOK, points) }