struct
This commit is contained in:
3
.gitignore
vendored
Normal file
3
.gitignore
vendored
Normal file
@ -0,0 +1,3 @@
|
||||
.idea
|
||||
hr_receiver.iml
|
||||
main.go.bak
|
||||
6
config.yaml
Normal file
6
config.yaml
Normal file
@ -0,0 +1,6 @@
|
||||
database:
|
||||
host: localhost
|
||||
port: 5432
|
||||
user: postgres
|
||||
password: root
|
||||
name: training_db
|
||||
45
config/config.go
Normal file
45
config/config.go
Normal file
@ -0,0 +1,45 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"gorm.io/driver/postgres"
|
||||
)
|
||||
import (
|
||||
"github.com/spf13/viper"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
var DB *gorm.DB
|
||||
|
||||
type AppConfig struct {
|
||||
DB struct {
|
||||
Host string `yaml:"host"`
|
||||
Port string `yaml:"port"`
|
||||
User string `yaml:"user"`
|
||||
Password string `yaml:"password"`
|
||||
Name string `yaml:"name"`
|
||||
} `yaml:"database"`
|
||||
}
|
||||
|
||||
func InitConfig() {
|
||||
viper.AddConfigPath("./")
|
||||
viper.SetConfigName("config")
|
||||
viper.SetConfigType("yaml")
|
||||
if err := viper.ReadInConfig(); err != nil {
|
||||
panic("Failed to read config: " + err.Error())
|
||||
}
|
||||
}
|
||||
|
||||
func ConnectDB() {
|
||||
dsn := "host=" + viper.GetString("database.host") +
|
||||
" user=" + viper.GetString("database.user") +
|
||||
" password=" + viper.GetString("database.password") +
|
||||
" dbname=" + viper.GetString("database.name") +
|
||||
" port=" + viper.GetString("database.port") +
|
||||
" sslmode=disable"
|
||||
|
||||
var err error
|
||||
DB, err = gorm.Open(postgres.Open(dsn), &gorm.Config{})
|
||||
if err != nil {
|
||||
panic("Failed to connect database: " + err.Error())
|
||||
}
|
||||
}
|
||||
31
controllers/train.go
Normal file
31
controllers/train.go
Normal file
@ -0,0 +1,31 @@
|
||||
package controllers
|
||||
|
||||
import (
|
||||
"github.com/gin-gonic/gin"
|
||||
"hr_receiver/config"
|
||||
"hr_receiver/models"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
func ReceiveTrainingData(c *gin.Context) {
|
||||
var data models.TrainingData
|
||||
|
||||
if err := c.ShouldBindJSON(&data); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{
|
||||
"error": "Invalid request body: " + err.Error(),
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
if result := config.DB.Create(&data); result.Error != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{
|
||||
"error": "Failed to save data: " + result.Error.Error(),
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusCreated, gin.H{
|
||||
"message": "Data saved successfully",
|
||||
"id": data.ID,
|
||||
})
|
||||
}
|
||||
58
go.mod
Normal file
58
go.mod
Normal file
@ -0,0 +1,58 @@
|
||||
module hr_receiver
|
||||
|
||||
go 1.23.3
|
||||
|
||||
require (
|
||||
github.com/gin-gonic/gin v1.10.0
|
||||
github.com/lib/pq v1.10.9
|
||||
github.com/spf13/viper v1.20.0
|
||||
gorm.io/driver/postgres v1.5.11
|
||||
gorm.io/gorm v1.25.12
|
||||
)
|
||||
|
||||
require (
|
||||
github.com/bytedance/sonic v1.11.6 // indirect
|
||||
github.com/bytedance/sonic/loader v0.1.1 // indirect
|
||||
github.com/cloudwego/base64x v0.1.4 // indirect
|
||||
github.com/cloudwego/iasm v0.2.0 // indirect
|
||||
github.com/fsnotify/fsnotify v1.8.0 // indirect
|
||||
github.com/gabriel-vasile/mimetype v1.4.3 // indirect
|
||||
github.com/gin-contrib/sse v0.1.0 // indirect
|
||||
github.com/go-playground/locales v0.14.1 // indirect
|
||||
github.com/go-playground/universal-translator v0.18.1 // indirect
|
||||
github.com/go-playground/validator/v10 v10.20.0 // indirect
|
||||
github.com/go-viper/mapstructure/v2 v2.2.1 // indirect
|
||||
github.com/goccy/go-json v0.10.2 // indirect
|
||||
github.com/jackc/pgpassfile v1.0.0 // indirect
|
||||
github.com/jackc/pgservicefile v0.0.0-20221227161230-091c0ba34f0a // indirect
|
||||
github.com/jackc/pgx/v5 v5.5.5 // indirect
|
||||
github.com/jackc/puddle/v2 v2.2.1 // indirect
|
||||
github.com/jinzhu/inflection v1.0.0 // indirect
|
||||
github.com/jinzhu/now v1.1.5 // indirect
|
||||
github.com/json-iterator/go v1.1.12 // indirect
|
||||
github.com/klauspost/cpuid/v2 v2.2.7 // indirect
|
||||
github.com/leodido/go-urn v1.4.0 // indirect
|
||||
github.com/mattn/go-isatty v0.0.20 // indirect
|
||||
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
|
||||
github.com/modern-go/reflect2 v1.0.2 // indirect
|
||||
github.com/pelletier/go-toml/v2 v2.2.3 // indirect
|
||||
github.com/rogpeppe/go-internal v1.13.1 // indirect
|
||||
github.com/sagikazarmark/locafero v0.7.0 // indirect
|
||||
github.com/sourcegraph/conc v0.3.0 // indirect
|
||||
github.com/spf13/afero v1.12.0 // indirect
|
||||
github.com/spf13/cast v1.7.1 // indirect
|
||||
github.com/spf13/pflag v1.0.6 // indirect
|
||||
github.com/subosito/gotenv v1.6.0 // indirect
|
||||
github.com/twitchyliquid64/golang-asm v0.15.1 // indirect
|
||||
github.com/ugorji/go/codec v1.2.12 // indirect
|
||||
go.uber.org/atomic v1.9.0 // indirect
|
||||
go.uber.org/multierr v1.9.0 // indirect
|
||||
golang.org/x/arch v0.8.0 // indirect
|
||||
golang.org/x/crypto v0.32.0 // indirect
|
||||
golang.org/x/net v0.33.0 // indirect
|
||||
golang.org/x/sync v0.10.0 // indirect
|
||||
golang.org/x/sys v0.29.0 // indirect
|
||||
golang.org/x/text v0.21.0 // indirect
|
||||
google.golang.org/protobuf v1.36.1 // indirect
|
||||
gopkg.in/yaml.v3 v3.0.1 // indirect
|
||||
)
|
||||
136
go.sum
Normal file
136
go.sum
Normal file
@ -0,0 +1,136 @@
|
||||
github.com/bytedance/sonic v1.11.6 h1:oUp34TzMlL+OY1OUWxHqsdkgC/Zfc85zGqw9siXjrc0=
|
||||
github.com/bytedance/sonic v1.11.6/go.mod h1:LysEHSvpvDySVdC2f87zGWf6CIKJcAvqab1ZaiQtds4=
|
||||
github.com/bytedance/sonic/loader v0.1.1 h1:c+e5Pt1k/cy5wMveRDyk2X4B9hF4g7an8N3zCYjJFNM=
|
||||
github.com/bytedance/sonic/loader v0.1.1/go.mod h1:ncP89zfokxS5LZrJxl5z0UJcsk4M4yY2JpfqGeCtNLU=
|
||||
github.com/cloudwego/base64x v0.1.4 h1:jwCgWpFanWmN8xoIUHa2rtzmkd5J2plF/dnLS6Xd/0Y=
|
||||
github.com/cloudwego/base64x v0.1.4/go.mod h1:0zlkT4Wn5C6NdauXdJRhSKRlJvmclQ1hhJgA0rcu/8w=
|
||||
github.com/cloudwego/iasm v0.2.0 h1:1KNIy1I1H9hNNFEEH3DVnI4UujN+1zjpuk6gwHLTssg=
|
||||
github.com/cloudwego/iasm v0.2.0/go.mod h1:8rXZaNYT2n95jn+zTI1sDr+IgcD2GVs0nlbbQPiEFhY=
|
||||
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
|
||||
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/frankban/quicktest v1.14.6 h1:7Xjx+VpznH+oBnejlPUj8oUpdxnVs4f8XU8WnHkI4W8=
|
||||
github.com/frankban/quicktest v1.14.6/go.mod h1:4ptaffx2x8+WTWXmUCuVU6aPUX1/Mz7zb5vbUoiM6w0=
|
||||
github.com/fsnotify/fsnotify v1.8.0 h1:dAwr6QBTBZIkG8roQaJjGof0pp0EeF+tNV7YBP3F/8M=
|
||||
github.com/fsnotify/fsnotify v1.8.0/go.mod h1:8jBTzvmWwFyi3Pb8djgCCO5IBqzKJ/Jwo8TRcHyHii0=
|
||||
github.com/gabriel-vasile/mimetype v1.4.3 h1:in2uUcidCuFcDKtdcBxlR0rJ1+fsokWf+uqxgUFjbI0=
|
||||
github.com/gabriel-vasile/mimetype v1.4.3/go.mod h1:d8uq/6HKRL6CGdk+aubisF/M5GcPfT7nKyLpA0lbSSk=
|
||||
github.com/gin-contrib/sse v0.1.0 h1:Y/yl/+YNO8GZSjAhjMsSuLt29uWRFHdHYUb5lYOV9qE=
|
||||
github.com/gin-contrib/sse v0.1.0/go.mod h1:RHrZQHXnP2xjPF+u1gW/2HnVO7nvIa9PG3Gm+fLHvGI=
|
||||
github.com/gin-gonic/gin v1.10.0 h1:nTuyha1TYqgedzytsKYqna+DfLos46nTv2ygFy86HFU=
|
||||
github.com/gin-gonic/gin v1.10.0/go.mod h1:4PMNQiOhvDRa013RKVbsiNwoyezlm2rm0uX/T7kzp5Y=
|
||||
github.com/go-playground/assert/v2 v2.2.0 h1:JvknZsQTYeFEAhQwI4qEt9cyV5ONwRHC+lYKSsYSR8s=
|
||||
github.com/go-playground/assert/v2 v2.2.0/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4=
|
||||
github.com/go-playground/locales v0.14.1 h1:EWaQ/wswjilfKLTECiXz7Rh+3BjFhfDFKv/oXslEjJA=
|
||||
github.com/go-playground/locales v0.14.1/go.mod h1:hxrqLVvrK65+Rwrd5Fc6F2O76J/NuW9t0sjnWqG1slY=
|
||||
github.com/go-playground/universal-translator v0.18.1 h1:Bcnm0ZwsGyWbCzImXv+pAJnYK9S473LQFuzCbDbfSFY=
|
||||
github.com/go-playground/universal-translator v0.18.1/go.mod h1:xekY+UJKNuX9WP91TpwSH2VMlDf28Uj24BCp08ZFTUY=
|
||||
github.com/go-playground/validator/v10 v10.20.0 h1:K9ISHbSaI0lyB2eWMPJo+kOS/FBExVwjEviJTixqxL8=
|
||||
github.com/go-playground/validator/v10 v10.20.0/go.mod h1:dbuPbCMFw/DrkbEynArYaCwl3amGuJotoKCe95atGMM=
|
||||
github.com/go-viper/mapstructure/v2 v2.2.1 h1:ZAaOCxANMuZx5RCeg0mBdEZk7DZasvvZIxtHqx8aGss=
|
||||
github.com/go-viper/mapstructure/v2 v2.2.1/go.mod h1:oJDH3BJKyqBA2TXFhDsKDGDTlndYOZ6rGS0BRZIxGhM=
|
||||
github.com/goccy/go-json v0.10.2 h1:CrxCmQqYDkv1z7lO7Wbh2HN93uovUHgrECaO5ZrCXAU=
|
||||
github.com/goccy/go-json v0.10.2/go.mod h1:6MelG93GURQebXPDq3khkgXZkazVtN9CRI+MGFi0w8I=
|
||||
github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI=
|
||||
github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
|
||||
github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
|
||||
github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM=
|
||||
github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg=
|
||||
github.com/jackc/pgservicefile v0.0.0-20221227161230-091c0ba34f0a h1:bbPeKD0xmW/Y25WS6cokEszi5g+S0QxI/d45PkRi7Nk=
|
||||
github.com/jackc/pgservicefile v0.0.0-20221227161230-091c0ba34f0a/go.mod h1:5TJZWKEWniPve33vlWYSoGYefn3gLQRzjfDlhSJ9ZKM=
|
||||
github.com/jackc/pgx/v5 v5.5.5 h1:amBjrZVmksIdNjxGW/IiIMzxMKZFelXbUoPNb+8sjQw=
|
||||
github.com/jackc/pgx/v5 v5.5.5/go.mod h1:ez9gk+OAat140fv9ErkZDYFWmXLfV+++K0uAOiwgm1A=
|
||||
github.com/jackc/puddle/v2 v2.2.1 h1:RhxXJtFG022u4ibrCSMSiu5aOq1i77R3OHKNJj77OAk=
|
||||
github.com/jackc/puddle/v2 v2.2.1/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4=
|
||||
github.com/jinzhu/inflection v1.0.0 h1:K317FqzuhWc8YvSVlFMCCUb36O/S9MCKRDI7QkRKD/E=
|
||||
github.com/jinzhu/inflection v1.0.0/go.mod h1:h+uFLlag+Qp1Va5pdKtLDYj+kHp5pxUVkryuEj+Srlc=
|
||||
github.com/jinzhu/now v1.1.5 h1:/o9tlHleP7gOFmsnYNz3RGnqzefHA47wQpKrrdTIwXQ=
|
||||
github.com/jinzhu/now v1.1.5/go.mod h1:d3SSVoowX0Lcu0IBviAWJpolVfI5UJVZZ7cO71lE/z8=
|
||||
github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=
|
||||
github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=
|
||||
github.com/klauspost/cpuid/v2 v2.0.9/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg=
|
||||
github.com/klauspost/cpuid/v2 v2.2.7 h1:ZWSB3igEs+d0qvnxR/ZBzXVmxkgt8DdzP6m9pfuVLDM=
|
||||
github.com/klauspost/cpuid/v2 v2.2.7/go.mod h1:Lcz8mBdAVJIBVzewtcLocK12l3Y+JytZYpaMropDUws=
|
||||
github.com/knz/go-libedit v1.10.1/go.mod h1:MZTVkCWyz0oBc7JOWP3wNAzd002ZbM/5hgShxwh4x8M=
|
||||
github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=
|
||||
github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=
|
||||
github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
|
||||
github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
|
||||
github.com/leodido/go-urn v1.4.0 h1:WT9HwE9SGECu3lg4d/dIA+jxlljEa1/ffXKmRjqdmIQ=
|
||||
github.com/leodido/go-urn v1.4.0/go.mod h1:bvxc+MVxLKB4z00jd1z+Dvzr47oO32F/QSNjSBOlFxI=
|
||||
github.com/lib/pq v1.10.9 h1:YXG7RB+JIjhP29X+OtkiDnYaXQwpS4JEWq7dtCCRUEw=
|
||||
github.com/lib/pq v1.10.9/go.mod h1:AlVN5x4E4T544tWzH6hKfbfQvm3HdbOxrmggDNAPY9o=
|
||||
github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
|
||||
github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
|
||||
github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
|
||||
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg=
|
||||
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
|
||||
github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M=
|
||||
github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=
|
||||
github.com/pelletier/go-toml/v2 v2.2.3 h1:YmeHyLY8mFWbdkNWwpr+qIL2bEqT0o95WSdkNHvL12M=
|
||||
github.com/pelletier/go-toml/v2 v2.2.3/go.mod h1:MfCQTFTvCcUyyvvwm1+G6H/jORL20Xlb6rzQu9GuUkc=
|
||||
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
||||
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||
github.com/rogpeppe/go-internal v1.13.1 h1:KvO1DLK/DRN07sQ1LQKScxyZJuNnedQ5/wKSR38lUII=
|
||||
github.com/rogpeppe/go-internal v1.13.1/go.mod h1:uMEvuHeurkdAXX61udpOXGD/AzZDWNMNyH2VO9fmH0o=
|
||||
github.com/sagikazarmark/locafero v0.7.0 h1:5MqpDsTGNDhY8sGp0Aowyf0qKsPrhewaLSsFaodPcyo=
|
||||
github.com/sagikazarmark/locafero v0.7.0/go.mod h1:2za3Cg5rMaTMoG/2Ulr9AwtFaIppKXTRYnozin4aB5k=
|
||||
github.com/sourcegraph/conc v0.3.0 h1:OQTbbt6P72L20UqAkXXuLOj79LfEanQ+YQFNpLA9ySo=
|
||||
github.com/sourcegraph/conc v0.3.0/go.mod h1:Sdozi7LEKbFPqYX2/J+iBAM6HpqSLTASQIKqDmF7Mt0=
|
||||
github.com/spf13/afero v1.12.0 h1:UcOPyRBYczmFn6yvphxkn9ZEOY65cpwGKb5mL36mrqs=
|
||||
github.com/spf13/afero v1.12.0/go.mod h1:ZTlWwG4/ahT8W7T0WQ5uYmjI9duaLQGy3Q2OAl4sk/4=
|
||||
github.com/spf13/cast v1.7.1 h1:cuNEagBQEHWN1FnbGEjCXL2szYEXqfJPbP2HNUaca9Y=
|
||||
github.com/spf13/cast v1.7.1/go.mod h1:ancEpBxwJDODSW/UG4rDrAqiKolqNNh2DX3mk86cAdo=
|
||||
github.com/spf13/pflag v1.0.6 h1:jFzHGLGAlb3ruxLB8MhbI6A8+AQX/2eW4qeyNZXNp2o=
|
||||
github.com/spf13/pflag v1.0.6/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
|
||||
github.com/spf13/viper v1.20.0 h1:zrxIyR3RQIOsarIrgL8+sAvALXul9jeEPa06Y0Ph6vY=
|
||||
github.com/spf13/viper v1.20.0/go.mod h1:P9Mdzt1zoHIG8m2eZQinpiBjo6kCmZSKBClNNqjJvu4=
|
||||
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
||||
github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
|
||||
github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo=
|
||||
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
|
||||
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
||||
github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
||||
github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
|
||||
github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=
|
||||
github.com/stretchr/testify v1.10.0 h1:Xv5erBjTwe/5IxqUQTdXv5kgmIvbHo3QQyRwhJsOfJA=
|
||||
github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
|
||||
github.com/subosito/gotenv v1.6.0 h1:9NlTDc1FTs4qu0DDq7AEtTPNw6SVm7uBMsUCUjABIf8=
|
||||
github.com/subosito/gotenv v1.6.0/go.mod h1:Dk4QP5c2W3ibzajGcXpNraDfq2IrhjMIvMSWPKKo0FU=
|
||||
github.com/twitchyliquid64/golang-asm v0.15.1 h1:SU5vSMR7hnwNxj24w34ZyCi/FmDZTkS4MhqMhdFk5YI=
|
||||
github.com/twitchyliquid64/golang-asm v0.15.1/go.mod h1:a1lVb/DtPvCB8fslRZhAngC2+aY1QWCk3Cedj/Gdt08=
|
||||
github.com/ugorji/go/codec v1.2.12 h1:9LC83zGrHhuUA9l16C9AHXAqEV/2wBQ4nkvumAE65EE=
|
||||
github.com/ugorji/go/codec v1.2.12/go.mod h1:UNopzCgEMSXjBc6AOMqYvWC1ktqTAfzJZUZgYf6w6lg=
|
||||
go.uber.org/atomic v1.9.0 h1:ECmE8Bn/WFTYwEW/bpKD3M8VtR/zQVbavAoalC1PYyE=
|
||||
go.uber.org/atomic v1.9.0/go.mod h1:fEN4uk6kAWBTFdckzkM89CLk9XfWZrxpCo0nPH17wJc=
|
||||
go.uber.org/multierr v1.9.0 h1:7fIwc/ZtS0q++VgcfqFDxSBZVv/Xo49/SYnDFupUwlI=
|
||||
go.uber.org/multierr v1.9.0/go.mod h1:X2jQV1h+kxSjClGpnseKVIxpmcjrj7MNnI0bnlfKTVQ=
|
||||
golang.org/x/arch v0.0.0-20210923205945-b76863e36670/go.mod h1:5om86z9Hs0C8fWVUuoMHwpExlXzs5Tkyp9hOrfG7pp8=
|
||||
golang.org/x/arch v0.8.0 h1:3wRIsP3pM4yUptoR96otTUOXI367OS0+c9eeRi9doIc=
|
||||
golang.org/x/arch v0.8.0/go.mod h1:FEVrYAQjsQXMVJ1nsMoVVXPZg6p2JE2mx8psSWTDQys=
|
||||
golang.org/x/crypto v0.32.0 h1:euUpcYgM8WcP71gNpTqQCn6rC2t6ULUPiOzfWaXVVfc=
|
||||
golang.org/x/crypto v0.32.0/go.mod h1:ZnnJkOaASj8g0AjIduWNlq2NRxL0PlBrbKVyZ6V/Ugc=
|
||||
golang.org/x/net v0.33.0 h1:74SYHlV8BIgHIFC/LrYkOGIwL19eTYXQ5wc6TBuO36I=
|
||||
golang.org/x/net v0.33.0/go.mod h1:HXLR5J+9DxmrqMwG9qjGCxZ+zKXxBru04zlTvWlWuN4=
|
||||
golang.org/x/sync v0.10.0 h1:3NQrjDixjgGwUOCaF8w2+VYHv0Ve/vGYSbdkTa98gmQ=
|
||||
golang.org/x/sync v0.10.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=
|
||||
golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.29.0 h1:TPYlXGxvx1MGTn2GiZDhnjPA9wZzZeGKHHmKhHYvgaU=
|
||||
golang.org/x/sys v0.29.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
|
||||
golang.org/x/text v0.21.0 h1:zyQAAkrwaneQ066sspRyJaG9VNi/YJ1NfzcGB3hZ/qo=
|
||||
golang.org/x/text v0.21.0/go.mod h1:4IBbMaMmOPCJ8SecivzSH54+73PCFmPWxNTLm+vZkEQ=
|
||||
google.golang.org/protobuf v1.36.1 h1:yBPeRvTftaleIgM3PZ/WBIZ7XM/eEYAaEyCwvyjq/gk=
|
||||
google.golang.org/protobuf v1.36.1/go.mod h1:9fA7Ob0pmnwhb644+1+CVWFRbNajQ6iRojtC/QF5bRE=
|
||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=
|
||||
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=
|
||||
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
||||
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
gorm.io/driver/postgres v1.5.11 h1:ubBVAfbKEUld/twyKZ0IYn9rSQh448EdelLYk9Mv314=
|
||||
gorm.io/driver/postgres v1.5.11/go.mod h1:DX3GReXH+3FPWGrrgffdvCk3DQ1dwDPdmbenSkweRGI=
|
||||
gorm.io/gorm v1.25.12 h1:I0u8i2hWQItBq1WfE0o2+WuL9+8L21K9e2HHSTE/0f8=
|
||||
gorm.io/gorm v1.25.12/go.mod h1:xh7N7RHfYlNc5EmcI/El95gXusucDrQnHXe0+CgWcLQ=
|
||||
nullprogram.com/x/optparse v1.0.0/go.mod h1:KdyPE+Igbe0jQUrVfMqDMeJQIJZEuyV7pjYmp6pbG50=
|
||||
rsc.io/pdf v0.1.1/go.mod h1:n8OzWcQ6Sp37PL01nO98y4iUCRdTGarVfzxY20ICaU4=
|
||||
9
hr_receiver.iml
Normal file
9
hr_receiver.iml
Normal file
@ -0,0 +1,9 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<module type="WEB_MODULE" version="4">
|
||||
<component name="Go" enabled="true" />
|
||||
<component name="NewModuleRootManager" inherit-compiler-output="true">
|
||||
<exclude-output />
|
||||
<content url="file://$MODULE_DIR$" />
|
||||
<orderEntry type="sourceFolder" forTests="false" />
|
||||
</component>
|
||||
</module>
|
||||
22
main.go
Normal file
22
main.go
Normal file
@ -0,0 +1,22 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"hr_receiver/config"
|
||||
"hr_receiver/models"
|
||||
"hr_receiver/routes"
|
||||
)
|
||||
|
||||
func main() {
|
||||
// 初始化配置
|
||||
config.InitConfig()
|
||||
|
||||
// 连接数据库
|
||||
config.ConnectDB()
|
||||
|
||||
// 自动迁移模型
|
||||
config.DB.AutoMigrate(&models.TrainingData{})
|
||||
|
||||
// 启动服务
|
||||
r := routes.SetupRouter()
|
||||
r.Run(":8080")
|
||||
}
|
||||
516
main.go.bak
Normal file
516
main.go.bak
Normal file
@ -0,0 +1,516 @@
|
||||
// main.go
|
||||
package main
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
_ "fmt"
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/lib/pq"
|
||||
"gorm.io/driver/postgres"
|
||||
"gorm.io/gorm/clause"
|
||||
"log"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"regexp"
|
||||
"sort"
|
||||
"time"
|
||||
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// 调整后的结构体定义
|
||||
type CreateTrainingRequest struct {
|
||||
TID uint `json:"tid" binding:"required"`
|
||||
StartTime int64 `json:"startTime" binding:"required,min=1609459200000"` // 2021-01-01起
|
||||
EndTime int64 `json:"endTime" binding:"required,min=1609459200000"`
|
||||
Name string `json:"name" binding:"required"`
|
||||
MaxHeartRate int `json:"maxHeartRate" binding:"required,min=30,max=250"`
|
||||
Duration int `json:"duration" binding:"required"` // 单位:秒
|
||||
PeopleNum int `json:"peopleNum" binding:"required"`
|
||||
Evaluation string `json:"evaluation" binding:"required"`
|
||||
BeltAddrs []string `json:"beltAddrs" binding:"required"`
|
||||
}
|
||||
|
||||
type HeartRateUploadRequest struct {
|
||||
TrainID uint `json:"trainId" binding:"required"`
|
||||
Data []HeartRateData `json:"data" binding:"required,dive"`
|
||||
}
|
||||
|
||||
type HeartRateData struct {
|
||||
BeltAddr string `json:"beltAddr" binding:"required"`
|
||||
Timestamp int64 `json:"timestamp" binding:"required,min=1609459200000"`
|
||||
Value int `json:"value" binding:"required,min=30,max=250"`
|
||||
LastValue int `json:"lastValue" binding:"required,min=30,max=250"`
|
||||
}
|
||||
|
||||
// 数据库模型
|
||||
type TrainingRecord struct {
|
||||
TID uint `gorm:"primaryKey;column:tid" json:"tid"`
|
||||
StartTime time.Time `gorm:"not null" json:"-"`
|
||||
EndTime time.Time `gorm:"not null" json:"-"`
|
||||
Name string `gorm:"type:varchar(255);default:'训练'" json:"name"`
|
||||
MaxHeartRate int `gorm:"not null" json:"maxHeartRate"`
|
||||
Duration int `gorm:"not null" json:"duration"`
|
||||
PeopleNum int `gorm:"not null" json:"peopleNum"`
|
||||
Evaluation string `gorm:"type:varchar(255);default:'适中'" json:"evaluation"`
|
||||
BeltAddresses []string `gorm:"type:text[]" json:"beltAddrs"`
|
||||
|
||||
// 添加毫秒时间戳字段(仅用于JSON序列化)
|
||||
StartTimestamp int64 `gorm:"-" json:"startTime"`
|
||||
EndTimestamp int64 `gorm:"-" json:"endTime"`
|
||||
}
|
||||
|
||||
type HeartRate struct {
|
||||
Time time.Time `gorm:"primaryKey;type:timestamptz" json:"time"`
|
||||
TrainID uint `gorm:"primaryKey;index" json:"train_id"`
|
||||
BeltAddr string `gorm:"type:varchar(255);not null;index" json:"belt_addr"`
|
||||
Value int `gorm:"check:value BETWEEN 30 AND 250" json:"value"`
|
||||
LastValue int `gorm:"check:last_value BETWEEN 30 AND 250" json:"last_value"`
|
||||
}
|
||||
|
||||
// 统计分析响应结构
|
||||
type TrainingReport struct {
|
||||
TrainID uint `json:"train_id"`
|
||||
AvgHeartRate float64 `json:"avg_heart_rate"`
|
||||
MaxHeartRate int `json:"max_heart_rate"`
|
||||
DangerSeconds int `json:"danger_seconds"`
|
||||
BeltStats map[string]Stats `json:"belt_stats"`
|
||||
TimeSeries []TimePoint `json:"time_series,omitempty"`
|
||||
}
|
||||
|
||||
type Stats struct {
|
||||
Avg float64 `json:"avg"`
|
||||
Max int `json:"max"`
|
||||
DangerCount int `json:"danger_count"`
|
||||
}
|
||||
|
||||
type TimePoint struct {
|
||||
Time time.Time `json:"time"`
|
||||
AvgValue float64 `json:"avg_value"`
|
||||
DangerCount int `json:"danger_count"`
|
||||
}
|
||||
|
||||
// 实现自定义序列化逻辑
|
||||
func (t *TrainingRecord) AfterFind(tx *gorm.DB) (err error) {
|
||||
t.StartTimestamp = t.StartTime.UnixNano() / int64(time.Millisecond)
|
||||
t.EndTimestamp = t.EndTime.UnixNano() / int64(time.Millisecond)
|
||||
return
|
||||
}
|
||||
|
||||
func (t *TrainingRecord) BeforeCreate(tx *gorm.DB) (err error) {
|
||||
t.StartTime = time.Unix(0, t.StartTimestamp*int64(time.Millisecond)).UTC()
|
||||
t.EndTime = time.Unix(0, t.EndTimestamp*int64(time.Millisecond)).UTC()
|
||||
return
|
||||
}
|
||||
|
||||
// 更新处理函数
|
||||
//func createTraining(c *gin.Context) {
|
||||
// var req CreateTrainingRequest
|
||||
// if err := c.ShouldBindJSON(&req); err != nil {
|
||||
// c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
// return
|
||||
// }
|
||||
//
|
||||
// record := TrainingRecord{
|
||||
// TID: req.TID,
|
||||
// StartTimestamp: req.StartTime,
|
||||
// EndTimestamp: req.EndTime,
|
||||
// Name: req.Name,
|
||||
// MaxHeartRate: req.MaxHeartRate,
|
||||
// Duration: req.Duration,
|
||||
// PeopleNum: req.PeopleNum,
|
||||
// Evaluation: req.Evaluation,
|
||||
// BeltAddresses: req.BeltAddrs,
|
||||
// }
|
||||
//
|
||||
// if err := db.Create(&record).Error; err != nil {
|
||||
// if isDuplicateKeyError(err) {
|
||||
// c.JSON(http.StatusConflict, gin.H{"error": "训练记录已存在"})
|
||||
// return
|
||||
// }
|
||||
// c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
// return
|
||||
// }
|
||||
//
|
||||
// c.JSON(http.StatusCreated, record)
|
||||
//}
|
||||
|
||||
// 统一时间处理函数
|
||||
func parseTimestamp(ms int64) (time.Time, error) {
|
||||
if ms < 1609459200000 { // 2021-01-01 00:00:00 UTC
|
||||
return time.Time{}, fmt.Errorf("无效的时间戳")
|
||||
}
|
||||
return time.Unix(0, ms*int64(time.Millisecond)).UTC(), nil
|
||||
}
|
||||
|
||||
// 更新心率数据处理
|
||||
func processHeartRateData(req *HeartRateUploadRequest) ([]HeartRate, error) {
|
||||
var rates []HeartRate
|
||||
|
||||
for _, d := range req.Data {
|
||||
t, err := parseTimestamp(d.Timestamp)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("无效的时间戳: %d", d.Timestamp)
|
||||
}
|
||||
|
||||
rates = append(rates, HeartRate{
|
||||
TrainID: req.TrainID,
|
||||
BeltAddr: d.BeltAddr,
|
||||
Time: t,
|
||||
Value: d.Value,
|
||||
LastValue: d.LastValue,
|
||||
})
|
||||
}
|
||||
|
||||
// 按时间排序
|
||||
sort.Slice(rates, func(i, j int) bool {
|
||||
return rates[i].Time.Before(rates[j].Time)
|
||||
})
|
||||
|
||||
return rates, nil
|
||||
}
|
||||
|
||||
// 更新自动迁移逻辑
|
||||
func autoMigrate(db *gorm.DB) {
|
||||
db.Set("gorm:table_options", " comment '训练记录表'").AutoMigrate(&TrainingRecord{})
|
||||
db.Set("gorm:table_options", " comment '心率数据表'").AutoMigrate(&HeartRate{})
|
||||
|
||||
// 创建复合索引
|
||||
db.Exec(`
|
||||
CREATE INDEX IF NOT EXISTS idx_heart_rates_main
|
||||
ON heart_rates (train_id, belt_addr, time DESC)
|
||||
`)
|
||||
}
|
||||
|
||||
var db *gorm.DB
|
||||
|
||||
const (
|
||||
defaultDB = "postgres" // 用于创建新数据库的默认数据库
|
||||
)
|
||||
|
||||
func initDB() {
|
||||
// 解析原始DSN
|
||||
dsn := "host=localhost user=postgres password=root dbname=training port=5432 sslmode=disable"
|
||||
parsedDSN, err := url.Parse(dsn)
|
||||
if err != nil {
|
||||
log.Fatal("Invalid DSN:", err)
|
||||
}
|
||||
query := parsedDSN.Query()
|
||||
query.Set("dbname", defaultDB)
|
||||
query.Set("sslmode", "disable")
|
||||
query.Set("port", "5432")
|
||||
query.Set("host", "localhost")
|
||||
query.Set("user", "postgres")
|
||||
query.Set("password", "root")
|
||||
defaultDSN := fmt.Sprintf("host=%s user=%s password=%s dbname=%s port=%s sslmode=%s",
|
||||
query.Get("host"),
|
||||
query.Get("user"),
|
||||
query.Get("password"),
|
||||
query.Get("dbname"),
|
||||
query.Get("port"),
|
||||
query.Get("sslmode"),
|
||||
)
|
||||
//defaultDSNUrl, _ := url.Parse(defaultDSN)
|
||||
|
||||
// 提取数据库名称
|
||||
dbName := "training"
|
||||
|
||||
// 第一步:尝试连接目标数据库
|
||||
db, err := gorm.Open(postgres.Open(dsn), &gorm.Config{})
|
||||
if err != nil {
|
||||
// 检查是否是数据库不存在的错误(PostgreSQL错误码3D000)
|
||||
if isDatabaseNotExistError(err) {
|
||||
log.Printf("Database %q does not exist, attempting to create...", dbName)
|
||||
createDatabase(defaultDSN, dbName)
|
||||
} else {
|
||||
log.Fatal("Database connection failed:", err)
|
||||
}
|
||||
} else {
|
||||
log.Printf("Database %q already exists", dbName)
|
||||
sqlDB, _ := db.DB()
|
||||
sqlDB.Close()
|
||||
}
|
||||
|
||||
// 再次连接目标数据库
|
||||
db, err = gorm.Open(postgres.Open(dsn), &gorm.Config{
|
||||
CreateBatchSize: 1000,
|
||||
})
|
||||
if err != nil {
|
||||
log.Fatal("Final database connection failed:", err)
|
||||
}
|
||||
|
||||
// 自动迁移表结构
|
||||
autoMigrate(db)
|
||||
}
|
||||
|
||||
// 检查是否为数据库不存在错误
|
||||
func isDatabaseNotExistError(err error) bool {
|
||||
if err == nil {
|
||||
return false
|
||||
}
|
||||
errStr := err.Error()
|
||||
return containsErrorCode(errStr, "3D000")
|
||||
}
|
||||
|
||||
func containsErrorCode(errStr, code string) bool {
|
||||
// 使用正则表达式检查错误字符串中是否包含指定的错误码
|
||||
re := regexp.MustCompile(`\b` + code + `\b`)
|
||||
return re.MatchString(errStr)
|
||||
}
|
||||
|
||||
// 创建新数据库
|
||||
func createDatabase(parsedDSN string, dbName string) {
|
||||
// 使用默认数据库连接
|
||||
//parsedDSN.Path = "/" + defaultDB
|
||||
defaultDSN := parsedDSN
|
||||
|
||||
// 创建数据库
|
||||
db, err := gorm.Open(postgres.Open(defaultDSN), &gorm.Config{})
|
||||
if err != nil {
|
||||
log.Fatal("Connect to default database failed:", err)
|
||||
}
|
||||
|
||||
// 需要超级用户权限才能创建数据库
|
||||
createSQL := fmt.Sprintf("CREATE DATABASE \"%s\"", dbName)
|
||||
if err := db.Exec(createSQL).Error; err != nil {
|
||||
log.Fatal("Create database failed:", err)
|
||||
}
|
||||
|
||||
sqlDB, _ := db.DB()
|
||||
sqlDB.Close()
|
||||
log.Printf("Database %q created successfully", dbName)
|
||||
}
|
||||
|
||||
// 自动迁移表结构
|
||||
//func autoMigrate(db *gorm.DB) {
|
||||
// err := db.AutoMigrate(
|
||||
// &TrainingRecord{},
|
||||
// &HeartRate{},
|
||||
// )
|
||||
// if err != nil {
|
||||
// log.Fatal("Auto migrate failed:", err)
|
||||
// }
|
||||
//
|
||||
// // 添加索引(生产环境建议使用迁移工具)
|
||||
// db.Exec("CREATE INDEX IF NOT EXISTS idx_heart_rates_train_time ON heart_rates (train_id, time)")
|
||||
// log.Println("Database schema initialized successfully")
|
||||
//}
|
||||
|
||||
// ...(保持之前的import和结构体定义不变)
|
||||
//
|
||||
// func initDB() {
|
||||
// dsn := "host=localhost user=postgres password=root dbname=training port=5432 sslmode=disable"
|
||||
// var err error
|
||||
// db, err = gorm.Open(postgres.Open(dsn), &gorm.Config{
|
||||
// CreateBatchSize: 1000,
|
||||
// })
|
||||
// if err != nil {
|
||||
// log.Fatal("Failed to connect to database:", err)
|
||||
// }
|
||||
//
|
||||
// // 自动迁移(生产环境建议使用迁移工具)
|
||||
// db.AutoMigrate(&TrainingRecord{}, &HeartRate{})
|
||||
// }
|
||||
func setupRouter() *gin.Engine {
|
||||
r := gin.Default()
|
||||
|
||||
// 训练记录路由组
|
||||
trainingGroup := r.Group("/api/trainings")
|
||||
{
|
||||
trainingGroup.POST("create", createTraining)
|
||||
trainingGroup.POST("/:id/heart-rates", uploadHeartRates)
|
||||
//trainingGroup.GET("/:id/report", getTrainingReport)
|
||||
//trainingGroup.GET("/:id/time-series", getTimeSeriesData)
|
||||
}
|
||||
|
||||
return r
|
||||
}
|
||||
|
||||
// 更新处理函数
|
||||
func createTraining(c *gin.Context) {
|
||||
var req CreateTrainingRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
record := TrainingRecord{
|
||||
TID: req.TID,
|
||||
StartTimestamp: req.StartTime,
|
||||
EndTimestamp: req.EndTime,
|
||||
Name: req.Name,
|
||||
MaxHeartRate: req.MaxHeartRate,
|
||||
Duration: req.Duration,
|
||||
PeopleNum: req.PeopleNum,
|
||||
Evaluation: req.Evaluation,
|
||||
BeltAddresses: req.BeltAddrs,
|
||||
}
|
||||
|
||||
if err := db.Create(&record).Error; err != nil {
|
||||
if isDuplicateKeyError(err) {
|
||||
c.JSON(http.StatusConflict, gin.H{"error": "训练记录已存在"})
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusCreated, record)
|
||||
}
|
||||
|
||||
// 判断是否为唯一键冲突错误
|
||||
func isDuplicateKeyError(err error) bool {
|
||||
if err == nil {
|
||||
return false
|
||||
}
|
||||
|
||||
var pqErr *pq.Error
|
||||
if errors.As(err, &pqErr) {
|
||||
return pqErr.Code == "23505" // 唯一键冲突错误码
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
// 更新上传心率处理
|
||||
func uploadHeartRates(c *gin.Context) {
|
||||
var req HeartRateUploadRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
// 时区处理(接受时区参数,默认为UTC)
|
||||
loc := time.UTC
|
||||
if tz := c.Query("tz"); tz != "" {
|
||||
if l, err := time.LoadLocation(tz); err == nil {
|
||||
loc = l
|
||||
}
|
||||
}
|
||||
|
||||
heartRates := make([]HeartRate, 0, len(req.Data))
|
||||
for _, d := range req.Data {
|
||||
t, err := parseTimestamp(d.Timestamp)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{
|
||||
"error": fmt.Sprintf("invalid timestamp: %v", d.Timestamp),
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
// 转换为指定时区
|
||||
t = t.In(loc)
|
||||
|
||||
heartRates = append(heartRates, HeartRate{
|
||||
TrainID: req.TrainID,
|
||||
BeltAddr: d.BeltAddr,
|
||||
Time: t,
|
||||
Value: d.Value,
|
||||
LastValue: d.LastValue,
|
||||
})
|
||||
}
|
||||
|
||||
// 批量插入优化
|
||||
err := db.Clauses(
|
||||
clause.OnConflict{
|
||||
Columns: []clause.Column{{Name: "train_id"}, {Name: "time"}},
|
||||
DoNothing: true,
|
||||
},
|
||||
clause.Returning{},
|
||||
).CreateInBatches(heartRates, 1000).Error
|
||||
|
||||
if err != nil {
|
||||
log.Printf("Batch insert error: %v", err)
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "数据存储失败"})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusCreated, gin.H{
|
||||
"message": fmt.Sprintf("成功存储 %d 条心率数据", len(heartRates)),
|
||||
"timezone": loc.String(),
|
||||
})
|
||||
}
|
||||
|
||||
// 获取训练报告
|
||||
func getTrainingReport(c *gin.Context) {
|
||||
trainID := parseUint(c.Param("id"))
|
||||
threshold := c.DefaultQuery("threshold", "120") // 默认危险阈值120
|
||||
|
||||
var report TrainingReport
|
||||
report.BeltStats = make(map[string]Stats)
|
||||
|
||||
// 获取基础统计信息
|
||||
baseQuery := db.Model(&HeartRate{}).Where("train_id = ?", trainID)
|
||||
|
||||
// 整体平均和最大心率
|
||||
baseQuery.Select("AVG(value) as avg, MAX(value) as max").
|
||||
Row().Scan(&report.AvgHeartRate, &report.MaxHeartRate)
|
||||
|
||||
// 危险时长计算(假设5秒一个数据点)
|
||||
var dangerCount int64
|
||||
baseQuery.Where("value >= ?", threshold).Count(&dangerCount)
|
||||
report.DangerSeconds = int(dangerCount) * 5
|
||||
|
||||
// 各腰带统计
|
||||
rows, err := db.Model(&HeartRate{}).
|
||||
Select("belt_addr, AVG(value) as avg, MAX(value) as max, COUNT(*) filter (where value >= ?) as danger", threshold).
|
||||
Where("train_id = ?", trainID).
|
||||
Group("belt_addr").
|
||||
Rows()
|
||||
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
for rows.Next() {
|
||||
var addr string
|
||||
var stat Stats
|
||||
rows.Scan(&addr, &stat.Avg, &stat.Max, &stat.DangerCount)
|
||||
report.BeltStats[addr] = stat
|
||||
}
|
||||
|
||||
report.TrainID = trainID
|
||||
c.JSON(http.StatusOK, report)
|
||||
}
|
||||
|
||||
// 获取时间序列数据
|
||||
func getTimeSeriesData(c *gin.Context) {
|
||||
trainID := parseUint(c.Param("id"))
|
||||
interval := c.DefaultQuery("interval", "1m") // 默认1分钟间隔
|
||||
|
||||
var points []TimePoint
|
||||
err := db.Raw(`
|
||||
SELECT
|
||||
date_trunc(?, time) as time,
|
||||
AVG(value) as avg_value,
|
||||
COUNT(*) FILTER (WHERE value >= 120) as danger_count
|
||||
FROM heart_rates
|
||||
WHERE train_id = ?
|
||||
GROUP BY 1
|
||||
ORDER BY 1
|
||||
`, interval, trainID).Scan(&points).Error
|
||||
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, points)
|
||||
}
|
||||
|
||||
// 辅助函数:字符串转uint
|
||||
func parseUint(s string) uint {
|
||||
var n uint
|
||||
fmt.Sscanf(s, "%d", &n)
|
||||
return n
|
||||
}
|
||||
|
||||
// 补全main函数
|
||||
func main() {
|
||||
initDB()
|
||||
r := setupRouter()
|
||||
log.Fatal(r.Run(":8081"))
|
||||
}
|
||||
11
models/training.go
Normal file
11
models/training.go
Normal file
@ -0,0 +1,11 @@
|
||||
package models
|
||||
|
||||
import "gorm.io/gorm"
|
||||
|
||||
type TrainingData struct {
|
||||
gorm.Model
|
||||
Features string `gorm:"type:JSONB; not null" json:"features"`
|
||||
Label string `gorm:"type:varchar(255)" json:"label"`
|
||||
Probability float64 `gorm:"type:decimal(5,4)" json:"probability"`
|
||||
SessionID string `gorm:"index" json:"session_id"`
|
||||
}
|
||||
17
routes/routes.go
Normal file
17
routes/routes.go
Normal file
@ -0,0 +1,17 @@
|
||||
package routes
|
||||
|
||||
import (
|
||||
"github.com/gin-gonic/gin"
|
||||
"hr_receiver/controllers"
|
||||
)
|
||||
|
||||
func SetupRouter() *gin.Engine {
|
||||
r := gin.Default()
|
||||
|
||||
api := r.Group("/api/v1")
|
||||
{
|
||||
api.POST("/training", controllers.ReceiveTrainingData)
|
||||
}
|
||||
|
||||
return r
|
||||
}
|
||||
Reference in New Issue
Block a user