Skip to content

Commit

Permalink
Refactor code structure and configuration handling
Browse files Browse the repository at this point in the history
  • Loading branch information
funnyzak committed Feb 6, 2024
1 parent 689141d commit 604b925
Show file tree
Hide file tree
Showing 9 changed files with 83 additions and 72 deletions.
34 changes: 7 additions & 27 deletions cmd/main.go
Original file line number Diff line number Diff line change
@@ -1,14 +1,8 @@
package main

import (
"fmt"
"go-gin/cmd/webserver"
"go-gin/internal/config"
"go-gin/internal/log"
"go-gin/model"

config_utils "go-gin/pkg/config"
logger "go-gin/pkg/logger"
"go-gin/service/singleton"

flag "github.com/spf13/pflag"
)
Expand All @@ -27,27 +21,13 @@ func main() {
flag.Parse()
flag.Lookup("config").NoOptDefVal = "config"

initConfig(webServerCliParam.ConfigName)
initLog(config.Instance)

webserver.ServerWeb(config.Instance)
}

func initConfig(name string) {
_config, err := config_utils.ReadViperConfig(name, "yaml", []string{".", "./config", "../"})
if err != nil {
panic(fmt.Errorf("unable to read config: %s", err))
}
singleton.InitConfig(webServerCliParam.ConfigName)
singleton.InitLog(singleton.Config)
initService()

if err := _config.Unmarshal(&config.Instance); err != nil {
panic(fmt.Errorf("unable to unmarshal config: %s", err))
}
webserver.ServerWeb(singleton.Config)
}

func initLog(config *config.Config) {
logPath := config.Log.Path
if logPath == "" {
logPath = model.DefaultLogPath
}
log.ZLog = logger.NewLogger(config.Log.Level, logPath)
func initService() {
singleton.InitSingleton()
}
29 changes: 14 additions & 15 deletions cmd/webserver/controller/auth.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,8 @@ import (
"github.com/gin-gonic/gin"
"github.com/golang-jwt/jwt/v5"

"go-gin/internal/config"
"go-gin/internal/log"
"go-gin/model"
"go-gin/service/singleton"

api_utils "go-gin/internal/api"
)
Expand All @@ -20,21 +19,21 @@ func Login(c *gin.Context) {
// get the body of the POST request
err := c.BindJSON(&creds)
if err != nil {
log.ZLog.Error().Msgf("Error binding JSON: %v", err)
singleton.Log.Error().Msgf("Error binding JSON: %v", err)
api_utils.ResponseError(c, http.StatusBadRequest, "Invalid JSON")
return
}

users := config.Instance.Users
users := singleton.Config.Users
expectedPassword, ok := users[creds.Username]

if !ok || expectedPassword != creds.Password {
log.ZLog.Error().Msgf("Invalid credentials: %v", creds)
singleton.Log.Error().Msgf("Invalid credentials: %v", creds)
api_utils.ResponseError(c, http.StatusUnauthorized, "Invalid credentials")
return
}

expirationTime := time.Now().Add(time.Duration(config.Instance.JWT.Expiration) * time.Minute)
expirationTime := time.Now().Add(time.Duration(singleton.Config.JWT.Expiration) * time.Minute)
claims := &model.Claims{
Username: creds.Username,
RegisteredClaims: jwt.RegisteredClaims{
Expand All @@ -44,9 +43,9 @@ func Login(c *gin.Context) {
}

token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
tokenString, err := token.SignedString([]byte(config.Instance.JWT.Secret))
tokenString, err := token.SignedString([]byte(singleton.Config.JWT.Secret))
if err != nil {
log.ZLog.Error().Msgf("Error signing token: %v", err)
singleton.Log.Error().Msgf("Error signing token: %v", err)
api_utils.ResponseError(c, http.StatusInternalServerError, "Error signing token")
return
}
Expand All @@ -59,7 +58,7 @@ func Refresh(c *gin.Context) {
tokenString, err := api_utils.GetTokenString(c)

if err != nil {
log.ZLog.Error().Msgf("Error getting token: %v", err)
singleton.Log.Error().Msgf("Error getting token: %v", err)
c.JSON(http.StatusUnauthorized, &model.ErrorResponse{
Code: http.StatusUnauthorized,
Message: "Unauthorized",
Expand All @@ -69,28 +68,28 @@ func Refresh(c *gin.Context) {

claims := &model.Claims{}
token, err := jwt.ParseWithClaims(tokenString, claims, func(token *jwt.Token) (interface{}, error) {
return []byte(config.Instance.JWT.Secret), nil
return []byte(singleton.Config.JWT.Secret), nil
})
if err != nil {
log.ZLog.Error().Msgf("Error parsing token: %v", err)
singleton.Log.Error().Msgf("Error parsing token: %v", err)
api_utils.ResponseError(c, http.StatusUnauthorized, "Unauthorized")
return
}
if !token.Valid {
log.ZLog.Error().Msgf("Invalid token")
singleton.Log.Error().Msgf("Invalid token")
c.JSON(http.StatusUnauthorized, &model.ErrorResponse{
Code: http.StatusUnauthorized,
Message: "Invalid token",
})
return
}

expirationTime := time.Now().Add(time.Duration(config.Instance.JWT.Expiration) * time.Minute)
expirationTime := time.Now().Add(time.Duration(singleton.Config.JWT.Expiration) * time.Minute)
claims.ExpiresAt = jwt.NewNumericDate(expirationTime)
token = jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
tokenString, err = token.SignedString([]byte(config.Instance.JWT.Secret))
tokenString, err = token.SignedString([]byte(singleton.Config.JWT.Secret))
if err != nil {
log.ZLog.Error().Msgf("Error signing token: %v", err)
singleton.Log.Error().Msgf("Error signing token: %v", err)
api_utils.ResponseError(c, http.StatusInternalServerError, "Error signing token")
return
}
Expand Down
7 changes: 3 additions & 4 deletions cmd/webserver/controller/share.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,16 +5,15 @@ import (
"net/http"
"os"

"go-gin/internal/config"

"github.com/gin-gonic/gin"

api_utils "go-gin/internal/api"
"go-gin/service/singleton"
)

func GetCreation(c *gin.Context) {
share_num := c.Param("share_num")
creation_file := fmt.Sprintf("%s/creation/%s.png", config.Instance.Upload.Dir, share_num)
creation_file := fmt.Sprintf("%s/creation/%s.png", singleton.Config.Upload.Dir, share_num)
// Check if the file exists
if _, err := os.Stat(creation_file); os.IsNotExist(err) {
api_utils.ResponseError(c, http.StatusNotFound, "Creation not found")
Expand All @@ -26,7 +25,7 @@ func GetCreation(c *gin.Context) {
"creation/share",
gin.H{
"share_num": share_num,
"config": config.Instance,
"config": singleton.Config,
},
)
}
6 changes: 3 additions & 3 deletions cmd/webserver/controller/user.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,8 @@ import (
"net/http"
"strings"

"go-gin/internal/config"
"go-gin/pkg/utils"
"go-gin/service/singleton"

"github.com/gin-gonic/gin"

Expand All @@ -24,10 +24,10 @@ func UploadCreation(c *gin.Context) {
return
}
new_id := utils.GenHexStr(32)
c.SaveUploadedFile(file, fmt.Sprintf("%s/creation/%s.png", config.Instance.Upload.Dir, new_id))
c.SaveUploadedFile(file, fmt.Sprintf("%s/creation/%s.png", singleton.Config.Upload.Dir, new_id))

api_utils.Response(c, gin.H{
"creation_id": new_id,
"share_url": fmt.Sprintf("%s/share/creation/%s", config.Instance.Server.BaseUrl, new_id),
"share_url": fmt.Sprintf("%s/share/creation/%s", singleton.Config.Server.BaseUrl, new_id),
})
}
11 changes: 5 additions & 6 deletions cmd/webserver/middleware/auth.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,8 @@ package middleware
import (
"net/http"

"go-gin/internal/config"
"go-gin/internal/log"
"go-gin/model"
"go-gin/service/singleton"

"github.com/gin-gonic/gin"
"github.com/golang-jwt/jwt/v5"
Expand All @@ -18,21 +17,21 @@ func AuthHanlder() gin.HandlerFunc {
tokenString, err := api_utils.GetTokenString(c)

if err != nil {
log.ZLog.Error().Msgf("Error getting token: %v", err)
singleton.Log.Error().Msgf("Error getting token: %v", err)
api_utils.ResponseError(c, http.StatusUnauthorized, "Unauthorized")
return
}
claims := &model.Claims{}
token, err := jwt.ParseWithClaims(tokenString, claims, func(token *jwt.Token) (interface{}, error) {
return []byte(config.Instance.JWT.Secret), nil
return []byte(singleton.Config.JWT.Secret), nil
})
if err != nil {
log.ZLog.Error().Msgf("Error parsing token: %v", err)
singleton.Log.Error().Msgf("Error parsing token: %v", err)
api_utils.ResponseError(c, http.StatusUnauthorized, "Unauthorized")
return
}
if !token.Valid {
log.ZLog.Error().Msgf("Invalid token")
singleton.Log.Error().Msgf("Invalid token")
api_utils.ResponseError(c, http.StatusUnauthorized, "Invalid token")
return
}
Expand Down
11 changes: 5 additions & 6 deletions cmd/webserver/middleware/logging.go
Original file line number Diff line number Diff line change
@@ -1,26 +1,25 @@
package middleware

import (
"go-gin/service/singleton"
"time"

"go-gin/internal/log"

"github.com/gin-gonic/gin"
)

func LoggingHandler() gin.HandlerFunc {
return func(c *gin.Context) {
t := time.Now()

log.ZLog.Info().Msgf("Request Info:\nMethod: %s\nHost: %s\nURL: %s",
singleton.Log.Info().Msgf("Request Info:\nMethod: %s\nHost: %s\nURL: %s",
c.Request.Method, c.Request.Host, c.Request.URL)
log.ZLog.Debug().Msgf("Request Header:\n%v", c.Request.Header)
singleton.Log.Debug().Msgf("Request Header:\n%v", c.Request.Header)

c.Next()

latency := time.Since(t)
log.ZLog.Info().Msgf("Response Time: %s\nStatus: %d",
singleton.Log.Info().Msgf("Response Time: %s\nStatus: %d",
latency.String(), c.Writer.Status())
log.ZLog.Debug().Msgf("Response Header:\n%v", c.Writer.Header())
singleton.Log.Debug().Msgf("Response Header:\n%v", c.Writer.Header())
}
}
8 changes: 4 additions & 4 deletions cmd/webserver/router.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,9 @@ import (
"go-gin/cmd/webserver/controller"
"go-gin/cmd/webserver/middleware"
"go-gin/internal/config"
"go-gin/internal/log"
"go-gin/internal/tmpl"
"go-gin/resource"
"go-gin/service/singleton"

"github.com/gin-gonic/gin"
)
Expand All @@ -33,7 +33,7 @@ func NewRoute(config *config.Config) *gin.Engine {
func serveStatic(r *gin.Engine) {
staticFs, err := fs.Sub(resource.StaticFS, "static")
if err != nil {
log.ZLog.Fatal().Err(err).Msg("Error parsing static files")
singleton.Log.Fatal().Err(err).Msg("Error parsing static files")
panic(err)
}
r.StaticFS("/static", http.FS(staticFs))
Expand All @@ -45,7 +45,7 @@ func loadTemplates(r *gin.Engine) {
var err error
new_tmpl, err = new_tmpl.ParseFS(resource.TemplateFS, "template/**/*.html", "template/*.html")
if err != nil {
log.ZLog.Fatal().Err(err).Msg("Error parsing templates")
singleton.Log.Fatal().Err(err).Msg("Error parsing templates")
panic(err)
}
r.SetHTMLTemplate(new_tmpl)
Expand All @@ -55,7 +55,7 @@ func routers(r *gin.Engine) {
// Logging middleware
r.Use(middleware.LoggingHandler())
// Rate limit middleware
r.Use(middleware.RateLimiterHandler(config.Instance.RateLimit.Max))
r.Use(middleware.RateLimiterHandler(singleton.Config.RateLimit.Max))

r.POST("/login", controller.Login)
userGroup := r.Group("/v1/user")
Expand Down
7 changes: 0 additions & 7 deletions internal/log/log.go

This file was deleted.

42 changes: 42 additions & 0 deletions service/singleton/singleton.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
package singleton

import (
"fmt"
"go-gin/internal/config"
"go-gin/model"

config_utils "go-gin/pkg/config"
logger "go-gin/pkg/logger"

"github.com/rs/zerolog"
"gorm.io/gorm"
)

var (
Config *config.Config
Log *zerolog.Logger
DB *gorm.DB
)

func InitSingleton() {
// TOO: init db
}

func InitConfig(name string) {
_config, err := config_utils.ReadViperConfig(name, "yaml", []string{".", "./config", "../"})
if err != nil {
panic(fmt.Errorf("unable to read config: %s", err))
}

if err := _config.Unmarshal(&Config); err != nil {
panic(fmt.Errorf("unable to unmarshal config: %s", err))
}
}

func InitLog(config *config.Config) {
logPath := config.Log.Path
if logPath == "" {
logPath = model.DefaultLogPath
}
Log = logger.NewLogger(config.Log.Level, logPath)
}

0 comments on commit 604b925

Please sign in to comment.