Skip to content

Commit

Permalink
Fixes after review
Browse files Browse the repository at this point in the history
  • Loading branch information
UnicoYal committed Sep 23, 2024
1 parent 4306f7f commit f5d08ad
Show file tree
Hide file tree
Showing 9 changed files with 104 additions and 74 deletions.
4 changes: 2 additions & 2 deletions cmd/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,10 @@ import (
)

func main() {
a, ctx, err := app.New()
a, err := app.New()
if err != nil {
log.Fatalf(err.Error())
}

a.Run(ctx)
a.Run()
}
56 changes: 53 additions & 3 deletions config/config.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,11 @@
package config

import "time"
import (
"fmt"
"time"

"github.com/spf13/viper"
)

type Config struct {
Listener Listener `yaml:"listener"`
Expand All @@ -24,6 +29,51 @@ type Listener struct {
IdleTimeout time.Duration `yaml:"idle_timeout"`
}

func NewConfig() *Config {
return &Config{}
func New() (*Config, error) {
err := setupViper()
if err != nil {
return nil, fmt.Errorf("config creation error: %w", err)
}

listner := Listener{
Address: viper.GetString("listener.address"),
Port: viper.GetInt("listener.port"),
Timeout: viper.GetDuration("listener.timeout"),
IdleTimeout: viper.GetDuration("listener.idle_timeout"),
}

postgres := Postgres{
Host: viper.GetString("postgres.host"),
Port: viper.GetInt("postgres.port"),
User: viper.GetString("postgres.user"),
Password: viper.GetString("postgres.password"),
Name: viper.GetString("postgres.name"),
}

return &Config{
Listener: listner,
Postgres: postgres,
}, nil
}

func setupViper() error {
viper.SetConfigName(".env")
viper.SetConfigType("env")
viper.AddConfigPath(".")

err := viper.ReadInConfig()
if err != nil {
return fmt.Errorf("failed to read .env file: %v", err)
}

viper.SetConfigName("config")
viper.SetConfigType("yml")
viper.AddConfigPath(viper.GetString("VIPER_CFG_PATH"))

err = viper.MergeInConfig()
if err != nil {
return fmt.Errorf("failed to read config.yml file: %v", err)
}

return nil
}
18 changes: 0 additions & 18 deletions config/context.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,27 +2,9 @@ package config

import (
"context"
"fmt"
"os"
"path/filepath"

"github.com/spf13/viper"
"gopkg.in/yaml.v3"
)

func WrapContext(cfg *Config) (context.Context, error) {
filename, _ := filepath.Abs(viper.GetString("CFG_PATH"))
data, err := os.ReadFile(filename)

if err != nil {
return nil, fmt.Errorf("failed to open env: %w", err)
}

err = yaml.Unmarshal(data, cfg)
if err != nil {
return nil, fmt.Errorf("cannot unmarshall config.yml: %w", err)
}

return context.WithValue(context.Background(), ConfigContextKey{}, cfg), nil
}

Expand Down
12 changes: 6 additions & 6 deletions docker-compose.yml
Original file line number Diff line number Diff line change
Expand Up @@ -11,29 +11,29 @@ services:
ports:
- 8080:8080
networks:
- netflix
- cassette-world
redis:
image: 'redis:latest'
command: redis-server
volumes:
- redis:/data
networks:
- netflix
- cassette-world
db:
image: postgres:latest
container_name: db
environment:
- "POSTGRES_DB=netflix"
- "POSTGRES_DB=cassette-world"
- "POSTGRES_USER=test"
- "POSTGRES_PASSWORD=test"
volumes:
- ./dev/SQL:/docker-entrypoint-initdb.d/
- "postgres_volume:/var/lib/postgresql/data"
networks:
- netflix
- cassette-world

networks:
netflix:
cassette-world:
default:
external:
name: netflix # Не забыть создать сеть перед деплоем
name: cassette-world # Не забыть создать сеть перед деплоем
51 changes: 18 additions & 33 deletions internal/app/app.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@ import (
"net/http"

_ "github.com/lib/pq"
"github.com/spf13/viper"

"github.com/go-park-mail-ru/2024_2_GOATS/config"
"github.com/go-park-mail-ru/2024_2_GOATS/internal/app/api"
Expand All @@ -20,30 +19,38 @@ import (

type App struct {
Database *sql.DB
Context context.Context
}

func New() (*App, context.Context, error) {
setupViper()
ctx, err := config.WrapContext(config.NewConfig())
func New() (*App, error) {
cfg, err := config.New()
if err != nil {
return nil, nil, err
return nil, fmt.Errorf("error initialize app cfg: %w", err)
}

ctx, err := config.WrapContext(cfg)
if err != nil {
return nil, fmt.Errorf("error wrap app context: %w", err)
}

db, err := db.SetupDatabase(ctx)
if err != nil {
return nil, nil, err
return nil, fmt.Errorf("error initialize database: %w", err)
}

return &App{Database: db}, ctx, nil
return &App{
Database: db,
Context: ctx,
}, nil
}

func (a *App) Run(ctx context.Context) {
func (a *App) Run() {
repoLayer := repository.NewRepository(a.Database)
srvLayer := service.NewService(repoLayer)
apiLayer := api.NewImplementation(ctx, srvLayer)
mux := router.Setup(ctx, apiLayer)
apiLayer := api.NewImplementation(a.Context, srvLayer)
mux := router.Setup(a.Context, apiLayer)

ctxValues := config.FromContext(ctx)
ctxValues := config.FromContext(a.Context)

srv := &http.Server{
Addr: fmt.Sprintf(":%d", ctxValues.Listener.Port),
Expand All @@ -59,25 +66,3 @@ func (a *App) Run(ctx context.Context) {
log.Fatalf(err.Error())
}
}

func setupViper() {
viper.SetConfigName(".env")
viper.SetConfigType("env")
viper.AddConfigPath(".")

err := viper.ReadInConfig()
if err != nil {
fmt.Printf("Failed to read .env file: %v\n", err)
return
}

viper.SetConfigName("config")
viper.SetConfigType("yml")
viper.AddConfigPath(viper.GetString("VIPER_CFG_PATH"))

err = viper.MergeInConfig()
if err != nil {
fmt.Printf("Failed to read config.yml file: %v\n", err)
return
}
}
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package handler
package auth

import (
"context"
Expand All @@ -17,9 +17,3 @@ func Register(ctx context.Context, api *api.Implementation, next http.Handler) h

})
}

func MovieCollections(ctx context.Context, api *api.Implementation, next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
api.GetCollection(ctx, r.URL.Query())
})
}
14 changes: 14 additions & 0 deletions internal/app/handlers/movie_collections/handler.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
package handler

import (
"context"
"net/http"

"github.com/go-park-mail-ru/2024_2_GOATS/internal/app/api"
)

func MovieCollections(ctx context.Context, api *api.Implementation, next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
api.GetCollection(ctx, r.URL.Query())
})
}
13 changes: 9 additions & 4 deletions internal/app/router/router.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,15 +5,20 @@ import (
"net/http"

"github.com/go-park-mail-ru/2024_2_GOATS/internal/app/api"
"github.com/go-park-mail-ru/2024_2_GOATS/internal/app/handler"
authHandlers "github.com/go-park-mail-ru/2024_2_GOATS/internal/app/handlers/auth"
movieCollectionHandlers "github.com/go-park-mail-ru/2024_2_GOATS/internal/app/handlers/movie_collections"
"github.com/gorilla/mux"
)

func Setup(ctx context.Context, api *api.Implementation) *mux.Router {
router := mux.NewRouter()
router.Handle("/login", handler.Login(ctx, api, router)).Methods("POST")
router.Handle("/signup", handler.Register(ctx, api, router)).Methods("POST")
router.Handle("/movie_collections", handler.MovieCollections(ctx, api, router)).Methods("GET")

authRouter := router.PathPrefix("/auth").Subrouter()
authRouter.Handle("/login", authHandlers.Login(ctx, api, router)).Methods("POST")
authRouter.Handle("/signup", authHandlers.Register(ctx, api, router)).Methods("POST")

movieCollectionsRouter := router.PathPrefix("/movie_collections").Subrouter()
movieCollectionsRouter.Handle("", movieCollectionHandlers.MovieCollections(ctx, api, router)).Methods("GET")

// TODO: Add middleware using for sessions
http.Handle("/", router)
Expand Down
2 changes: 1 addition & 1 deletion internal/config/config.yml
Original file line number Diff line number Diff line change
Expand Up @@ -9,4 +9,4 @@ postgres:
port: 5432
user: test
password: test
name: netflix
name: cassette-world

0 comments on commit f5d08ad

Please sign in to comment.