From 069d76520e2edc3073d0ce70e35335bdab9f5c7a Mon Sep 17 00:00:00 2001 From: MaxJa4 <74194322+MaxJa4@users.noreply.github.com> Date: Sat, 20 Jan 2024 17:47:39 +0100 Subject: [PATCH] Add run configs. Add redis for cache. Add cache-get in player-list. --- .idea/runConfigurations/Redis.xml | 19 ++++++++++++ .idea/runConfigurations/Release_Build_Win.xml | 14 +++++++++ .../go_build_InfantrySkillCalculator.xml | 13 ++++++++ controllers/cache_controller.go | 30 +++++++++++++++---- controllers/player_controller.go | 12 ++++++-- go.mod | 7 +++-- go.sum | 12 ++++++++ main.go | 3 ++ models/setup.go | 18 +++++++++++ utils/conv.go | 5 ++++ 10 files changed, 124 insertions(+), 9 deletions(-) create mode 100644 .idea/runConfigurations/Redis.xml create mode 100644 .idea/runConfigurations/Release_Build_Win.xml create mode 100644 .idea/runConfigurations/go_build_InfantrySkillCalculator.xml diff --git a/.idea/runConfigurations/Redis.xml b/.idea/runConfigurations/Redis.xml new file mode 100644 index 0000000..b91b9ae --- /dev/null +++ b/.idea/runConfigurations/Redis.xml @@ -0,0 +1,19 @@ + + + + + + + + + + \ No newline at end of file diff --git a/.idea/runConfigurations/Release_Build_Win.xml b/.idea/runConfigurations/Release_Build_Win.xml new file mode 100644 index 0000000..bc0edee --- /dev/null +++ b/.idea/runConfigurations/Release_Build_Win.xml @@ -0,0 +1,14 @@ + + + + + + + + + + + + \ No newline at end of file diff --git a/.idea/runConfigurations/go_build_InfantrySkillCalculator.xml b/.idea/runConfigurations/go_build_InfantrySkillCalculator.xml new file mode 100644 index 0000000..e6e046b --- /dev/null +++ b/.idea/runConfigurations/go_build_InfantrySkillCalculator.xml @@ -0,0 +1,13 @@ + + + + + + + + + + + + \ No newline at end of file diff --git a/controllers/cache_controller.go b/controllers/cache_controller.go index 2ac4e63..08da605 100644 --- a/controllers/cache_controller.go +++ b/controllers/cache_controller.go @@ -3,7 +3,11 @@ package controllers import ( "InfantrySkillCalculator/models" "InfantrySkillCalculator/utils" + "context" + "errors" + "fmt" "github.com/gin-gonic/gin" + "github.com/redis/go-redis/v9" "gorm.io/gorm" "gorm.io/gorm/clause" "net/http" @@ -22,16 +26,32 @@ type UpdateCacheInput struct { Score float32 `json:"score" gorm:"default:-1.0"` } -// GetCacheByPlayerID GET /cache/:id?game=TAG +var ctx = context.Background() + +// GetCacheByPlayerID GET /cache/:player_id?game_id=TAG func GetCacheByPlayerID(c *gin.Context) { - var cache models.PlayerCache + playerId := utils.StringToUint(c.Param("player_id")) + gameId := utils.StringToUint(c.Request.URL.Query().Get("game_id")) - if err := FindCacheGin(&cache, c).Error; err != nil { + val, err := GetCacheByPlayerIDGorm(playerId, gameId) + if err != nil { c.JSON(http.StatusBadRequest, gin.H{"error": "Record not found!"}) - return + } else { + c.JSON(http.StatusOK, val) } +} - c.JSON(http.StatusOK, cache) +func GetCacheByPlayerIDGorm(playerId uint, gameId uint) (float32, error) { + key := fmt.Sprintf("player:%d:game:%d", playerId, gameId) + + val, err := models.Cache.Get(ctx, key).Result() + if errors.Is(err, redis.Nil) { + return -1.0, nil // cache miss + } else if err != nil { + return -1.0, err // cache error + } else { + return utils.StringToFloat(val), nil // cache hit + } } // AddCache POST /cache diff --git a/controllers/player_controller.go b/controllers/player_controller.go index 3ae23f1..8946346 100644 --- a/controllers/player_controller.go +++ b/controllers/player_controller.go @@ -34,7 +34,9 @@ func GetAllPlayers(c *gin.Context) { func GetPlayersByClanHTML(c *gin.Context) { var players []models.Player clanId := c.Request.URL.Query().Get("clan_id") - if err := models.DB.Where("clan_id = ?", utils.StringToUint(clanId)).Find(&players).Error; err != nil { + if err := models.DB. + Where("clan_id = ?", utils.StringToUint(clanId)). + Find(&players).Error; err != nil { return } @@ -46,7 +48,13 @@ func GetPlayersByClanHTML(c *gin.Context) { var htmlOptions string for _, player := range players { - htmlOptions += fmt.Sprintf(playerItem, player.Name, "----", player.ID, player.ID) + var score string + if val, err := GetCacheByPlayerIDGorm(player.ID, 0); err != nil { + score = "----" + } else { + score = utils.FloatToString(val) + } + htmlOptions += fmt.Sprintf(playerItem, player.Name, score, player.ID, player.ID) } c.Header("Content-Type", "text/html") diff --git a/go.mod b/go.mod index 511a4ca..d6a9aee 100644 --- a/go.mod +++ b/go.mod @@ -4,13 +4,18 @@ go 1.21 require ( github.com/gin-gonic/gin v1.9.1 + github.com/gorilla/sessions v1.2.2 + github.com/redis/go-redis/v9 v9.4.0 + golang.org/x/crypto v0.9.0 gorm.io/driver/sqlite v1.5.4 gorm.io/gorm v1.25.5 ) require ( github.com/bytedance/sonic v1.9.1 // indirect + github.com/cespare/xxhash/v2 v2.2.0 // indirect github.com/chenzhuoyu/base64x v0.0.0-20221115062448-fe3a3abad311 // indirect + github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f // indirect github.com/gabriel-vasile/mimetype v1.4.2 // indirect github.com/gin-contrib/sse v0.1.0 // indirect github.com/go-playground/locales v0.14.1 // indirect @@ -18,7 +23,6 @@ require ( github.com/go-playground/validator/v10 v10.14.0 // indirect github.com/goccy/go-json v0.10.2 // indirect github.com/gorilla/securecookie v1.1.2 // indirect - github.com/gorilla/sessions v1.2.2 // 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 @@ -32,7 +36,6 @@ require ( github.com/twitchyliquid64/golang-asm v0.15.1 // indirect github.com/ugorji/go/codec v1.2.11 // indirect golang.org/x/arch v0.3.0 // indirect - golang.org/x/crypto v0.9.0 // indirect golang.org/x/net v0.10.0 // indirect golang.org/x/sys v0.8.0 // indirect golang.org/x/text v0.9.0 // indirect diff --git a/go.sum b/go.sum index 1452acb..6ef2ffc 100644 --- a/go.sum +++ b/go.sum @@ -1,12 +1,20 @@ +github.com/bsm/ginkgo/v2 v2.12.0 h1:Ny8MWAHyOepLGlLKYmXG4IEkioBysk6GpaRTLC8zwWs= +github.com/bsm/ginkgo/v2 v2.12.0/go.mod h1:SwYbGRRDovPVboqFv0tPTcG1sN61LM1Z4ARdbAV9g4c= +github.com/bsm/gomega v1.27.10 h1:yeMWxP2pV2fG3FgAODIY8EiRE3dy0aeFYt4l7wh6yKA= +github.com/bsm/gomega v1.27.10/go.mod h1:JyEr/xRbxbtgWNi8tIEVPUYZ5Dzef52k01W3YH0H+O0= github.com/bytedance/sonic v1.5.0/go.mod h1:ED5hyg4y6t3/9Ku1R6dU/4KyJ48DZ4jPhfY1O2AihPM= github.com/bytedance/sonic v1.9.1 h1:6iJ6NqdoxCDr6mbY8h18oSO+cShGSMRGCEo7F2h0x8s= github.com/bytedance/sonic v1.9.1/go.mod h1:i736AoUSYt75HyZLoJW9ERYxcy6eaN6h4BZXU064P/U= +github.com/cespare/xxhash/v2 v2.2.0 h1:DC2CZ1Ep5Y4k3ZQ899DldepgrayRUGE6BBZ/cd9Cj44= +github.com/cespare/xxhash/v2 v2.2.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= github.com/chenzhuoyu/base64x v0.0.0-20211019084208-fb5309c8db06/go.mod h1:DH46F32mSOjUmXrMHnKwZdA8wcEefY7UVqBKYGjpdQY= github.com/chenzhuoyu/base64x v0.0.0-20221115062448-fe3a3abad311 h1:qSGYFH7+jGhDF8vLC+iwCD4WpbV1EBDSzWkJODFLams= github.com/chenzhuoyu/base64x v0.0.0-20221115062448-fe3a3abad311/go.mod h1:b583jCggY9gE99b6G5LEC39OIiVsWj+R97kbl5odCEk= 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/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f h1:lO4WD4F/rVNCu3HqELle0jiPLLBs70cWOduZpkS1E78= +github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f/go.mod h1:cuUVRXasLTGF7a8hSLbxyZXjz+1KgoB3wDUb6vlszIc= github.com/gabriel-vasile/mimetype v1.4.2 h1:w5qFW6JKBz9Y393Y4q372O9A7cUSequkh1Q7OhCmWKU= github.com/gabriel-vasile/mimetype v1.4.2/go.mod h1:zApsH/mKG4w07erKIaJPFiX0Tsq9BFQgN3qGY5GnNgA= github.com/gin-contrib/sse v0.1.0 h1:Y/yl/+YNO8GZSjAhjMsSuLt29uWRFHdHYUb5lYOV9qE= @@ -27,6 +35,8 @@ github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaS github.com/google/go-cmp v0.5.5 h1:Khx7svrCpmxxtHBq5j2mp/xVjsi8hQMfNLvJFAlrGgU= github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= +github.com/google/gofuzz v1.2.0 h1:xRy4A+RhZaiKjJ1bPfwQ8sedCA+YS2YcCHW6ec7JMi0= +github.com/google/gofuzz v1.2.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= github.com/gorilla/securecookie v1.1.2 h1:YCIWL56dvtr73r6715mJs5ZvhtnY73hBvEF8kXD8ePA= github.com/gorilla/securecookie v1.1.2/go.mod h1:NfCASbcHqRSY+3a8tlWJwsQap2VX5pwzwo4h3eOamfo= github.com/gorilla/sessions v1.2.2 h1:lqzMYz6bOfvn2WriPUjNByzeXIlVzURcPmgMczkmTjY= @@ -55,6 +65,8 @@ github.com/pelletier/go-toml/v2 v2.0.8 h1:0ctb6s9mE31h0/lhu+J6OPmVeDxJn+kYnJc2jZ github.com/pelletier/go-toml/v2 v2.0.8/go.mod h1:vuYfssBdrU2XDZ9bYydBu6t+6a6PYNcZljzZR9VXg+4= 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/redis/go-redis/v9 v9.4.0 h1:Yzoz33UZw9I/mFhx4MNrB6Fk+XHO1VukNcCa1+lwyKk= +github.com/redis/go-redis/v9 v9.4.0/go.mod h1:hdY0cQFCN4fnSYT6TkisLufl/4W5UIXyv0b/CLO2V2M= 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= diff --git a/main.go b/main.go index 013211a..0e66da0 100644 --- a/main.go +++ b/main.go @@ -70,6 +70,7 @@ func main() { admin.Use(AdminAuthRequired()) models.ConnectDatabase() + models.ConnectCache() f, _ := os.OpenFile("isc_rest.log", os.O_RDWR|os.O_APPEND|os.O_CREATE, 0660) utils.GinWriter = io.MultiWriter(f, os.Stdout) @@ -111,6 +112,8 @@ func main() { protected.PATCH("/player/:id", controllers.UpdatePlayerByID) protected.DELETE("/player/:id", controllers.DeletePlayerByID) + protected.GET("/cache/:player_id", controllers.GetCacheByPlayerID) + protected.GET("/game", controllers.GetGames) protected.GET("/game_html", controllers.GetGamesHTML) diff --git a/models/setup.go b/models/setup.go index 1ee3e91..0ff3f48 100644 --- a/models/setup.go +++ b/models/setup.go @@ -2,6 +2,8 @@ package models import ( "InfantrySkillCalculator/utils" + "context" + "github.com/redis/go-redis/v9" "gorm.io/driver/sqlite" "gorm.io/gorm" "gorm.io/gorm/logger" @@ -9,6 +11,8 @@ import ( ) var DB *gorm.DB +var ctx = context.Background() +var Cache *redis.Client func ConnectDatabase() { database, err := gorm.Open(sqlite.Open("isc_data.db"), &gorm.Config{ @@ -71,3 +75,17 @@ func ConnectDatabase() { DB = database } + +func ConnectCache() { + Cache = redis.NewClient(&redis.Options{ + Addr: "127.0.0.1:6379", + Password: "", + DB: 0, + }) + + _, err := Cache.Ping(ctx).Result() + if err != nil { + Cache = nil + log.Fatal("Failed to connect to Redis! " + err.Error()) + } +} diff --git a/utils/conv.go b/utils/conv.go index ee7494e..04ed85f 100644 --- a/utils/conv.go +++ b/utils/conv.go @@ -17,3 +17,8 @@ func StringToUint(val string) uint { func FloatToString(val float32) string { return fmt.Sprintf("%f", val) } + +func StringToFloat(val string) float32 { + res, _ := strconv.ParseFloat(val, 32) + return float32(res) +}