udemy-go-web-2/cmd/api/api.go

112 lines
2.2 KiB
Go
Raw Normal View History

package main
import (
"flag"
"fmt"
"log"
2024-08-04 21:06:13 +00:00
"myapp/internal/driver"
"myapp/internal/models"
"net/http"
"os"
"time"
)
const (
version = "1.0.0"
)
type config struct {
port int
env string
db struct {
dsn string
}
stripe struct {
secret string
key string
}
2024-08-20 20:36:16 +00:00
smtp struct {
host string
port int
username string
password string
}
}
type application struct {
config config
2024-08-04 21:06:13 +00:00
infoLog *log.Logger
errorLog *log.Logger
version string
DB models.DBModel
}
func (app *application) serve() error {
srv := &http.Server{
Addr: fmt.Sprintf(":%d", app.config.port),
Handler: app.routes(),
IdleTimeout: 30 * time.Second,
ReadTimeout: 10 * time.Second,
ReadHeaderTimeout: 5 * time.Second,
WriteTimeout: 5 * time.Second,
}
2024-08-04 21:06:13 +00:00
app.infoLog.Printf(
"Starting Backend server in %s mode on port %d",
app.config.env,
app.config.port,
)
return srv.ListenAndServe()
}
func main() {
var cfg config
flag.IntVar(&cfg.port, "port", 4001, "Server port to listen on")
flag.StringVar(
&cfg.env,
"env",
"development",
"Application environment {development|production|maintenance}",
)
flag.StringVar(
&cfg.db.dsn,
"dsn",
2024-08-04 21:06:13 +00:00
"root:example@tcp(localhost:3306)/widgets?parseTime=true&tls=false",
"Application environment {development|production}",
)
2024-08-20 20:36:16 +00:00
flag.StringVar(&cfg.smtp.host, "smtphost", "0.0.0.0", "smtp host")
flag.IntVar(&cfg.smtp.port, "smtpport", 1025, "smtp host")
flag.StringVar(&cfg.smtp.username, "smtpuser", "user", "smtp user")
flag.StringVar(&cfg.smtp.password, "smtppwd", "password", "smtp password")
flag.Parse()
cfg.stripe.key = os.Getenv("STRIPE_KEY")
cfg.stripe.secret = os.Getenv("STRIPE_SECRET")
infoLog := log.New(os.Stdout, "INFO\t", log.Ldate|log.Ltime)
errorLog := log.New(os.Stdout, "ERROR\t", log.Ldate|log.Ltime|log.Lshortfile)
2024-08-04 21:06:13 +00:00
conn, err := driver.OpenDB(cfg.db.dsn)
if err != nil {
errorLog.Fatal(err)
}
defer conn.Close()
app := &application{
version: version,
config: cfg,
2024-08-04 21:06:13 +00:00
infoLog: infoLog,
errorLog: errorLog,
DB: models.DBModel{DB: conn},
}
2024-08-04 21:06:13 +00:00
app.infoLog.Println("Connected to MariaDB")
err = app.serve()
if err != nil {
log.Fatal(err)
}
}