Add util.Config to api.Server and app.env variable for loglevel (#22)

This commit is contained in:
itsscb 2023-09-23 19:53:56 +02:00 committed by GitHub
parent bfb91cf3f7
commit 3d4b84fbe2
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
6 changed files with 23 additions and 7 deletions

View File

@ -123,7 +123,7 @@ func TestCreateAccountAPI(t *testing.T) {
store := mockdb.NewMockStore(ctrl)
tc.buildStubs(store)
server := NewServer(store)
server := NewServer(config, store)
recorder := httptest.NewRecorder()
// Marshal body data to JSON
@ -152,7 +152,7 @@ func TestGetAccountAPI(t *testing.T) {
Times(1).
Return(account, nil)
server := NewServer(store)
server := NewServer(config, store)
recorder := httptest.NewRecorder()
uri := fmt.Sprintf("/accounts/%d", account.ID)

View File

@ -5,9 +5,15 @@ import (
"testing"
"github.com/gin-gonic/gin"
"github.com/itsscb/df/util"
)
var config util.Config
func TestMain(m *testing.M) {
config = util.Config{
Environment: "production",
}
gin.SetMode(gin.TestMode)

View File

@ -6,22 +6,30 @@ import (
"github.com/gin-gonic/gin"
db "github.com/itsscb/df/db/sqlc"
"github.com/itsscb/df/util"
)
// Server serves HTTP requests for df service
type Server struct {
store db.Store
router *gin.Engine
config util.Config
}
// NewServer creates a new HTTP server and sets up routing
func NewServer(store db.Store) *Server {
func NewServer(config util.Config, store db.Store) *Server {
server := &Server{
store: store,
store: store,
config: config,
}
logLevel := slog.LevelError
if config.Environment == "development" {
logLevel = slog.LevelDebug
}
opts := slog.HandlerOptions{
Level: slog.LevelDebug,
Level: logLevel,
}
logger := slog.New(slog.NewJSONHandler(os.Stdout, &opts))
router := gin.New()

View File

@ -1,3 +1,4 @@
DB_SOURCE=postgresql://root:secret@localhost:5432/df?sslmode=disable
DB_DRIVER=postgres
SERVER_ADDRESS=0.0.0.0:8080
ENVIRONMENT=development

View File

@ -21,7 +21,7 @@ func main() {
}
store := db.NewStore(conn)
server := api.NewServer(store)
server := api.NewServer(config, store)
err = server.Start(config.ServerAddress)
if err != nil {

View File

@ -6,6 +6,7 @@ type Config struct {
DBSource string `mapstructure:"DB_SOURCE"`
DBDriver string `mapstructure:"DB_DRIVER"`
ServerAddress string `mapstructure:"SERVER_ADDRESS"`
Environment string `mapstructure:"ENVIRONMENT"`
}
func LoadConfig(path string) (config Config, err error) {