72 lines
1.4 KiB
Go
72 lines
1.4 KiB
Go
package main
|
|
|
|
import (
|
|
"database/sql"
|
|
"log"
|
|
"os"
|
|
"time"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
_ "github.com/lib/pq"
|
|
"github.com/yourusername/go-sqlc-jwt/db"
|
|
"github.com/yourusername/go-sqlc-jwt/internal/handlers"
|
|
"github.com/yourusername/go-sqlc-jwt/internal/middleware"
|
|
"net/http"
|
|
)
|
|
|
|
type Config struct {
|
|
DB struct {
|
|
DSN string
|
|
}
|
|
JWT struct {
|
|
Secret string
|
|
}
|
|
}
|
|
|
|
func main() {
|
|
cfg := Config{
|
|
DB: struct{ DSN string }{
|
|
DSN: os.Getenv("DB_DSN"),
|
|
},
|
|
JWT: struct{ Secret string }{
|
|
Secret: os.Getenv("JWT_SECRET"),
|
|
},
|
|
}
|
|
|
|
dbConn, err := sql.Open("postgres", cfg.DB.DSN)
|
|
if err != nil {
|
|
log.Fatal("failed to connect to db:", err)
|
|
}
|
|
defer dbConn.Close()
|
|
|
|
// Configure database connection pool
|
|
dbConn.SetMaxOpenConns(25)
|
|
dbConn.SetMaxIdleConns(25)
|
|
dbConn.SetConnMaxLifetime(5 * time.Minute)
|
|
queries := db.New(dbConn)
|
|
|
|
r := gin.Default()
|
|
|
|
authHandler := handlers.NewAuthHandler(queries, cfg.JWT.Secret)
|
|
authGroup := r.Group("/auth")
|
|
{
|
|
authGroup.POST("/register", authHandler.Register)
|
|
authGroup.POST("/login", authHandler.Login)
|
|
}
|
|
|
|
// Protected routes
|
|
protected := r.Group("/api")
|
|
protected.Use(middleware.AuthMiddleware(cfg.JWT.Secret))
|
|
{
|
|
protected.GET("/profile", func(c *gin.Context) {
|
|
userID := c.MustGet("userID").(float64)
|
|
username := c.MustGet("username").(string)
|
|
c.JSON(http.StatusOK, gin.H{
|
|
"id": userID,
|
|
"username": username,
|
|
})
|
|
})
|
|
}
|
|
|
|
log.Fatal(r.Run(":8080"))
|
|
} |