Add run configs. Add redis for cache. Add cache-get in player-list.

This commit is contained in:
MaxJa4
2024-01-20 17:47:39 +01:00
parent 9e3e2723d3
commit 069d76520e
10 changed files with 124 additions and 9 deletions

19
.idea/runConfigurations/Redis.xml generated Normal file
View File

@@ -0,0 +1,19 @@
<component name="ProjectRunConfigurationManager">
<configuration default="false" name="Redis" type="docker-deploy" factoryName="docker-image" server-name="Docker">
<deployment type="docker-image">
<settings>
<option name="imageTag" value="redis:alpine" />
<option name="containerName" value="redis-isc" />
<option name="portBindings">
<list>
<DockerPortBindingImpl>
<option name="containerPort" value="6379" />
<option name="hostPort" value="6379" />
</DockerPortBindingImpl>
</list>
</option>
</settings>
</deployment>
<method v="2" />
</configuration>
</component>

View File

@@ -0,0 +1,14 @@
<component name="ProjectRunConfigurationManager">
<configuration default="false" name="Release-Build Win" type="GoApplicationRunConfiguration" factoryName="Go Application">
<module name="InfantrySkillCalculator" />
<working_directory value="$PROJECT_DIR$" />
<go_parameters value="-ldflags &quot;-s -w&quot;" />
<kind value="PACKAGE" />
<package value="InfantrySkillCalculator" />
<directory value="$PROJECT_DIR$" />
<filePath value="$PROJECT_DIR$" />
<output_directory value="$PROJECT_DIR$" />
<option name="run" value="false" />
<method v="2" />
</configuration>
</component>

View File

@@ -0,0 +1,13 @@
<component name="ProjectRunConfigurationManager">
<configuration default="false" name="go build InfantrySkillCalculator" type="GoApplicationRunConfiguration" factoryName="Go Application">
<module name="InfantrySkillCalculator" />
<working_directory value="$PROJECT_DIR$" />
<kind value="PACKAGE" />
<package value="InfantrySkillCalculator" />
<directory value="$PROJECT_DIR$" />
<filePath value="$PROJECT_DIR$/main.go" />
<method v="2">
<option name="RunConfigurationTask" enabled="true" run_configuration_name="Redis" run_configuration_type="docker-deploy" />
</method>
</configuration>
</component>

View File

@@ -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
func GetCacheByPlayerID(c *gin.Context) {
var cache models.PlayerCache
var ctx = context.Background()
if err := FindCacheGin(&cache, c).Error; err != nil {
// GetCacheByPlayerID GET /cache/:player_id?game_id=TAG
func GetCacheByPlayerID(c *gin.Context) {
playerId := utils.StringToUint(c.Param("player_id"))
gameId := utils.StringToUint(c.Request.URL.Query().Get("game_id"))
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

View File

@@ -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")

7
go.mod
View File

@@ -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

12
go.sum
View File

@@ -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=

View File

@@ -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)

View File

@@ -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())
}
}

View File

@@ -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)
}