apollo-backend/cmd/apollo-api/main.go

73 lines
1.2 KiB
Go
Raw Normal View History

2021-05-10 00:51:15 +00:00
package main
import (
"database/sql"
"fmt"
"log"
"net/http"
"os"
"github.com/joho/godotenv"
_ "github.com/lib/pq"
2021-06-24 02:19:43 +00:00
2021-07-05 23:22:24 +00:00
"github.com/christianselig/apollo-backend/internal/data"
"github.com/christianselig/apollo-backend/internal/reddit"
2021-05-10 00:51:15 +00:00
)
type config struct {
port int
}
type application struct {
2021-06-24 02:19:43 +00:00
cfg config
logger *log.Logger
db *sql.DB
models *data.Models
client *reddit.Client
2021-05-10 00:51:15 +00:00
}
func main() {
2021-07-06 00:20:00 +00:00
logger := log.New(os.Stdout, "", log.Ldate|log.Ltime)
if err := godotenv.Load(); err != nil {
logger.Printf("Couldn't find .env so I will read from existing ENV.")
2021-05-10 00:51:15 +00:00
}
var cfg config
2021-07-06 00:37:47 +00:00
dburl, ok := os.LookupEnv("DATABASE_CONNECTION_POOL_URL")
if !ok {
dburl = os.Getenv("DATABASE_URL")
}
2021-07-06 01:12:09 +00:00
db, err := sql.Open("postgres", fmt.Sprintf("%s?binary_parameters=yes", dburl))
2021-05-10 00:51:15 +00:00
if err != nil {
log.Fatal(err)
}
defer db.Close()
rc := reddit.NewClient(os.Getenv("REDDIT_CLIENT_ID"), os.Getenv("REDDIT_CLIENT_SECRET"))
app := &application{
cfg,
logger,
db,
data.NewModels(db),
rc,
}
2021-07-06 00:23:50 +00:00
port, ok := os.LookupEnv("PORT")
if !ok {
port = "4000"
}
2021-05-10 00:51:15 +00:00
srv := &http.Server{
2021-07-06 00:23:50 +00:00
Addr: fmt.Sprintf(":%s", port),
2021-05-10 00:51:15 +00:00
Handler: app.routes(),
}
logger.Printf("starting server on %s", srv.Addr)
err = srv.ListenAndServe()
logger.Fatal(err)
}