modernize the codebase

Run the modernize linter across the codebase.
Change generated by running:

```
go run golang.org/x/tools/gopls/internal/analysis/modernize/cmd/modernize@latest -fix -test ./...
```

Ref:
https://pkg.go.dev/golang.org/x/tools/gopls/internal/analysis/modernize
This commit is contained in:
2025-09-23 09:13:29 +03:30
parent fc1502c4a0
commit 94694741a7
5 changed files with 33 additions and 38 deletions

View File

@@ -23,18 +23,18 @@ func main() {
// Configuration
config.Load,
// Database
database.Connect,
// Services
services.NewPostService,
services.NewImgKitHelper,
// Auth
auth.NewJwtTokenGenerator,
auth.NewGiteaOauth2Token,
// Handlers
handlers.NewAdminDashboardHandler,
handlers.NewApiEndpointHandler,
@@ -44,7 +44,7 @@ func main() {
fx.Invoke(
// Start background tasks
startBackgroundTasks,
// Setup and start server
server.SetupRouter,
),
@@ -62,49 +62,49 @@ func startBackgroundTasks(
lc.Append(fx.Hook{
OnStart: func(context.Context) error {
ticker := time.NewTicker(10 * time.Minute)
runFetchPosts := func() {
ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
defer cancel()
posts, err := postService.GetPostsFromApi(ctx, cfg.Tag, cfg.Instance)
if err != nil {
logger.Error("Failed to fetch posts", zap.Error(err))
return
}
existingPostIds := postService.GetExistingPostIds()
existingAccountIds := postService.GetExistingAccountIds()
newPosts := postService.GetNewPosts(existingPostIds, posts)
newAccounts := postService.GetNewAccounts(existingAccountIds, newPosts)
logger.Info("Fetched posts",
zap.Int("total", len(posts)),
zap.Int("existing", len(existingPostIds)),
zap.Int("new", len(newPosts)),
zap.Int("new_accounts", len(newAccounts)))
if len(newAccounts) > 0 {
count := postService.InsertNewAccounts(newAccounts)
logger.Info("Inserted accounts", zap.Int("count", count))
}
if len(newPosts) > 0 {
count := postService.InsertNewPosts(newPosts)
logger.Info("Inserted posts", zap.Int("count", count))
}
}
// Run initial fetch
go runFetchPosts()
// Start ticker
go func() {
for range ticker.C {
runFetchPosts()
}
}()
return nil
},
OnStop: func(context.Context) error {
@@ -129,6 +129,6 @@ func NewFXLogger() *FXLogger {
return &FXLogger{logger: logger}
}
func (l *FXLogger) Printf(str string, args ...interface{}) {
func (l *FXLogger) Printf(str string, args ...any) {
l.logger.Sugar().Infof(str, args...)
}
}

View File

@@ -2,6 +2,7 @@ package auth
import (
"CatsOfMastodonBotGo/internal/config"
"maps"
"strings"
"time"
@@ -17,16 +18,14 @@ func NewJwtTokenGenerator(cfg *config.Config) *JwtTokenGenerator {
return &JwtTokenGenerator{cfg: cfg}
}
func (j *JwtTokenGenerator) GenerateToken(claims map[string]interface{}) (string, error) {
func (j *JwtTokenGenerator) GenerateToken(claims map[string]any) (string, error) {
token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
"exp": time.Now().AddDate(0, 0, 1).Unix(),
"iat": time.Now().Unix(),
"iss": j.cfg.JwtIssuer,
"aud": j.cfg.JwtAudience,
})
for k, v := range claims {
token.Claims.(jwt.MapClaims)[k] = v
}
maps.Copy(token.Claims.(jwt.MapClaims), claims)
return token.SignedString([]byte(j.cfg.JwtSecret))
}
@@ -41,7 +40,7 @@ func (j *JwtTokenGenerator) GinMiddleware() gin.HandlerFunc {
}
tokenString := strings.TrimPrefix(authHeader, "Bearer ")
t, err := jwt.Parse(tokenString, func(t *jwt.Token) (interface{}, error) {
t, err := jwt.Parse(tokenString, func(t *jwt.Token) (any, error) {
if _, ok := t.Method.(*jwt.SigningMethodHMAC); !ok {
return nil, jwt.ErrSignatureInvalid
}
@@ -61,4 +60,4 @@ func (j *JwtTokenGenerator) GinMiddleware() gin.HandlerFunc {
c.Next()
}
}
}

View File

@@ -8,6 +8,7 @@ import (
"fmt"
"math/rand"
"net/http"
"slices"
"strings"
"gorm.io/gorm"
@@ -163,10 +164,5 @@ func (ps *PostService) GetMedia() domain.MediaAttachment {
}
func arrayContains(arr []string, str string) bool {
for _, a := range arr {
if a == str {
return true
}
}
return false
}
return slices.Contains(arr, str)
}

View File

@@ -28,7 +28,7 @@ func NewAdminDashboardHandler(
postService: postService,
jwt: jwt,
cfg: cfg,
imgKit: imgKit,
imgKit: imgKit,
}
}
@@ -61,8 +61,8 @@ func (adh *AdminDashboardHandler) RejectMedia(c *gin.Context) {
func (adh *AdminDashboardHandler) GetMedia(c *gin.Context) {
media := adh.postService.GetMedia()
// TODO: Fix this - we need to inject ImgKitHelper
media.PreviewUrl = adh.imgKit.GetPreviewUrl(media.RemoteUrl)
media.RemoteUrl = adh.imgKit.GetRemoteUrl(media.RemoteUrl)
media.PreviewUrl = adh.imgKit.GetPreviewUrl(media.RemoteUrl)
media.RemoteUrl = adh.imgKit.GetRemoteUrl(media.RemoteUrl)
c.JSON(http.StatusOK, media)
}
@@ -77,7 +77,7 @@ func (adh *AdminDashboardHandler) Login(c *gin.Context) {
}
if input.Password == adh.cfg.AdminPassword { // Its more than enough for this project
token, err := adh.jwt.GenerateToken(map[string]interface{}{"role": "admin"})
token, err := adh.jwt.GenerateToken(map[string]any{"role": "admin"})
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "Token generation failed"})
return
@@ -97,4 +97,4 @@ func (adh *AdminDashboardHandler) Login(c *gin.Context) {
// Expose the JWT middleware for use in routes
func (adh *AdminDashboardHandler) JWTMiddleware() gin.HandlerFunc {
return adh.jwt.GinMiddleware()
}
}

View File

@@ -10,9 +10,9 @@ import (
)
type OauthLoginHandler struct {
jwt *auth.JwtTokenGenerator
jwt *auth.JwtTokenGenerator
oauthHandler *auth.GiteaOAuth2Handler
cfg *config.Config
cfg *config.Config
}
func NewOauthLoginHandler(
@@ -55,7 +55,7 @@ func (olh *OauthLoginHandler) LoginWithGitea(c *gin.Context) {
// Check if the user's email is in the allowed list
for _, email := range olh.cfg.GiteaOauthAllowedEmails {
if email == userEmail {
token, err := olh.jwt.GenerateToken(map[string]interface{}{"role": "admin"})
token, err := olh.jwt.GenerateToken(map[string]any{"role": "admin"})
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "Token generation failed"})
return
@@ -70,4 +70,4 @@ func (olh *OauthLoginHandler) LoginWithGitea(c *gin.Context) {
c.JSON(401, gin.H{
"error": "oauth login failed or your email does not have access",
})
}
}