feat: migrate Flask API to Go with JWT auth

This commit is contained in:
Cipher Vance
2025-11-20 19:00:53 -06:00
parent c6e330c063
commit 3bf3a9b24d
34 changed files with 1774 additions and 689 deletions

43
pkg/database/db.go Normal file
View File

@@ -0,0 +1,43 @@
package database
import (
"fmt"
"log"
"os"
"gorm.io/driver/postgres"
"gorm.io/gorm"
)
var DB *gorm.DB
func Init() {
dsn := fmt.Sprintf(
"host=%s user=%s password=%s dbname=%s port=%s sslmode=disable",
os.Getenv("PG_HOST"),
os.Getenv("PG_USER"),
os.Getenv("PG_PASSWORD"),
os.Getenv("PG_DATABASE"),
os.Getenv("PG_PORT"),
)
var err error
DB, err = gorm.Open(postgres.Open(dsn), &gorm.Config{})
if err != nil {
log.Fatalf("Failed to connect to database: %v", err)
}
log.Println("Database connected successfully")
}
func Migrate(models ...interface{}) error {
return DB.AutoMigrate(models...)
}
func Close() error {
sqlDB, err := DB.DB()
if err != nil {
return err
}
return sqlDB.Close()
}

26
pkg/errors/errors.go Normal file
View File

@@ -0,0 +1,26 @@
package errors
type AppError struct {
Code int
Message string
Details string
}
func (e *AppError) Error() string {
return e.Message
}
func NewAppError(code int, message, details string) *AppError {
return &AppError{
Code: code,
Message: message,
Details: details,
}
}
var (
ErrUnauthorized = NewAppError(401, "Unauthorized", "")
ErrNotFound = NewAppError(404, "Not Found", "")
ErrBadRequest = NewAppError(400, "Bad Request", "")
ErrInternal = NewAppError(500, "Internal Server Error", "")
)

16
pkg/utils/utils.go Normal file
View File

@@ -0,0 +1,16 @@
package utils
import (
"encoding/json"
"net/http"
)
func JSONResponse(w http.ResponseWriter, code int, payload interface{}) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(code)
json.NewEncoder(w).Encode(payload)
}
func JSONError(w http.ResponseWriter, code int, message string) {
JSONResponse(w, code, map[string]string{"error": message})
}