Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

init commit #18

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 32 additions & 1 deletion cmd/gophermart/main.go
Original file line number Diff line number Diff line change
@@ -1,3 +1,34 @@
package main

func main() {}
import (
"context"
"github.com/StarkovPO/go-musthave-diploma-tpl.git/internal/app"
"github.com/StarkovPO/go-musthave-diploma-tpl.git/internal/config"
"github.com/StarkovPO/go-musthave-diploma-tpl.git/internal/service"
"github.com/StarkovPO/go-musthave-diploma-tpl.git/internal/store"
"log"
"time"
)

func main() {

c, err := config.Init()

if err != nil {
log.Fatalf("init configuration: %s", err)
}

db := store.NewPostgres(store.MustPostgresConnection(c))
s := service.NewService(db, c)
application := app.NewApplication(db, c, s)
router := app.SetupAPI(application.Service)

ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()

err = app.Run(ctx, application.Config, router)
if err != nil {
log.Fatalf("run application: %s", err)
}

}
76 changes: 76 additions & 0 deletions internal/app/app.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
package app

import (
"context"
"fmt"
"github.com/StarkovPO/go-musthave-diploma-tpl.git/internal/config"
"github.com/StarkovPO/go-musthave-diploma-tpl.git/internal/handler"
"github.com/StarkovPO/go-musthave-diploma-tpl.git/internal/service"
"github.com/StarkovPO/go-musthave-diploma-tpl.git/internal/store"
"github.com/gorilla/mux"
"log"
"net"
"net/http"
"os"
"os/signal"
"syscall"
"time"
)

type Application struct {
Store store.Store
Config config.Config
Service service.Service
}

func NewApplication(s store.Store, c config.Config, o service.Service) Application {
return Application{
Store: s,
Config: c,
Service: o,
}
}

func SetupAPI(s service.Service) *mux.Router {
router := mux.NewRouter()
router.HandleFunc("/ping", handler.Test(s)).Methods(http.MethodGet)

return router

}

func Run(ctx context.Context, c config.Config, router *mux.Router) error {

cancelChan := make(chan os.Signal, 1)
signal.Notify(cancelChan, syscall.SIGTERM, syscall.SIGINT)

listener, err := net.Listen("tcp", c.RunAddressValue)
if err != nil {
return fmt.Errorf("failed to listen on address %s: %v", c.RunAddressValue, err)
}

server := &http.Server{
Handler: router,
WriteTimeout: 15 * time.Second,
ReadTimeout: 15 * time.Second,
ReadHeaderTimeout: 15 * time.Second,
}

go func() {
if err = server.Serve(listener); err != nil && err != http.ErrServerClosed {
log.Fatalf("Server error: %v", err)
}
}()

log.Printf("Server started and listening on address and port %s", c.RunAddressValue)

sig := <-cancelChan

log.Printf("Caught signal %v", sig)
if err = server.Shutdown(ctx); err != nil {
return fmt.Errorf("failed to shutdown server: %v", err)
}

log.Println("Server shutdown successfully")
return nil
}
58 changes: 58 additions & 0 deletions internal/config/config.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
package config

import (
"fmt"
"github.com/spf13/cobra"
"os"
)

const (
RUN_ADDRESS_KEY = "RUN_ADDRESS"
DATABASE_URI_KEY = "DATABASE_URI"
ACCRUAL_SYSTEM_ADDRESS_KEY = "ACCRUAL_SYSTEM_ADDRESS"
)

type Config struct {
RunAddressValue string
DatabaseURIValue string
AccrualSystemAddressValue string
}

func NewConfig() *Config {
return &Config{}
}

func ReadFlags(c Config) error {
rootCmd := &cobra.Command{
Use: "go-shop",
Short: "[-a address], [-d database], [-r accrual system]",
Run: func(cmd *cobra.Command, args []string) {
fmt.Printf("address: %s, database: %s, accrual system: %s\n", c.RunAddressValue, c.DatabaseURIValue, c.AccrualSystemAddressValue)
},
}
rootCmd.Flags().StringVarP(&c.RunAddressValue, "Port for service", "a", ":8080", "Server address")
rootCmd.Flags().StringVarP(&c.DatabaseURIValue, "URI for Postgres DB", "d", "postgres://admin:admin@localhost/go-shop?sslmode=disable", "Postgres URI")
rootCmd.Flags().StringVarP(&c.AccrualSystemAddressValue, "ACCRUAL SYSTEM ADDRESS", "r", ":8000", "ACCRUAL_SYSTEM_ADDRESS")

err := rootCmd.Execute()
if err != nil {
return err
}

return nil
}

func Init() (Config, error) {

c := NewConfig()
c.RunAddressValue = os.Getenv(RUN_ADDRESS_KEY)
c.DatabaseURIValue = os.Getenv(DATABASE_URI_KEY)
c.AccrualSystemAddressValue = os.Getenv(ACCRUAL_SYSTEM_ADDRESS_KEY)

if c.RunAddressValue == "" || c.DatabaseURIValue == "" || c.AccrualSystemAddressValue == "" {
if err := ReadFlags(*c); err != nil {
return Config{}, err
}
}
return *c, nil
}
14 changes: 14 additions & 0 deletions internal/handler/handler.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
package handler

import (
"net/http"
)

type ServiceInterface interface {
}

func Test(s ServiceInterface) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {

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

import (
"github.com/StarkovPO/go-musthave-diploma-tpl.git/internal/config"
"github.com/StarkovPO/go-musthave-diploma-tpl.git/internal/store"
)

type Service struct {
store store.Store
config config.Config
}

func NewService(s store.Store, c config.Config) Service {
return Service{
store: s,
config: c,
}
}
11 changes: 11 additions & 0 deletions internal/store/postgre_querry.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
package store

const createURLTable = `
CREATE TABLE IF NOT EXISTS urls (
primary_id integer PRIMARY KEY,
id varchar36 UNIQUE,
login varchar255 UNIQUE,
password_hash varchar60,
created_at datetime NOT NULL
)
`
4 changes: 4 additions & 0 deletions internal/store/store.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
package store

type Store interface {
}
56 changes: 56 additions & 0 deletions internal/store/store_postgre.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
package store

import (
"fmt"
"github.com/StarkovPO/go-musthave-diploma-tpl.git/internal/config"
"github.com/jmoiron/sqlx"
_ "github.com/lib/pq"
"time"
)

const (
DBMaxOpenConnection = 25
DBMaxIdleConnection = 25
DBMaxConnectionLifeTime = 10 * time.Minute
)

type Postgres struct {
db *sqlx.DB
}

func NewPostgres(db *sqlx.DB) *Postgres {
return &Postgres{
db: db,
}
}

func MustPostgresConnection(c config.Config) *sqlx.DB {
db, err := sqlx.Open("postgres", c.DatabaseURIValue)
if err != nil {
panic(err)
}

// Test the connection
err = db.Ping()
if err != nil {
defer db.Close()
return nil
}

db.SetMaxOpenConns(DBMaxOpenConnection)
db.SetMaxIdleConns(DBMaxIdleConnection)
db.SetConnMaxLifetime(DBMaxConnectionLifeTime)

if err = MakeDB(*db); err != nil {
panic(err)
}

return db
}

func MakeDB(db sqlx.DB) error {
if _, err := db.Exec(createURLTable); err != nil {
return fmt.Errorf("error while run migrations %v", err)
}
return nil
}