Created
December 29, 2024 02:47
-
-
Save cherryramatisdev/a661d5364641980b270e9ed0fde88e20 to your computer and use it in GitHub Desktop.
some refactor for go app
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package controllers | |
type ControllerWithDB struct { | |
Database *gorm.DB | |
} | |
// Criar um cliente | |
func (co *ControllerWithDB) CreateClient(c *gin.Context) { | |
var client models.Client | |
if err := c.ShouldBindJSON(&client); err != nil { | |
c.JSON(http.StatusBadRequest, gin.H{"error": "Dados inválidos", "details": err.Error()}) | |
return | |
} | |
result := co.Database.Create(&client) | |
if result.Error != nil { | |
c.JSON(http.StatusInternalServerError, gin.H{"error": "Erro ao criar cliente", "details": result.Error.Error()}) | |
return | |
} | |
c.JSON(http.StatusCreated, client) | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package routes | |
import ( | |
"customer-management/controllers" | |
"github.com/gin-gonic/gin" | |
) | |
func ConfigurarRotas(db *gorm.DB, router *gin.Engine) { | |
dbController := controllers.ControllerWithDB { Database: db } | |
clientGroup := router.Group("/clients") | |
{ | |
clientGroup.POST("/", dbController.CreateClient) | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package config | |
import ( | |
"log" | |
"os" | |
"github.com/joho/godotenv" | |
"gorm.io/driver/postgres" | |
"gorm.io/gorm" | |
) | |
// ConnectDatabase é uma função exportada que inicializa a conexão com o banco de dados, neste caso o PostgreSQL | |
func ConnectDatabase() *gorm.DB { | |
// Carregando o .env | |
err := godotenv.Load() | |
if err != nil { | |
log.Fatalf("Erro ao carregar o arquivo .env: %v", err) | |
} | |
// Para Obter variáveis de ambiente | |
host := os.Getenv("DB_HOST") | |
user := os.Getenv("DB_USER") | |
password := os.Getenv("DB_PASSWORD") | |
dbname := os.Getenv("DB_NAME") | |
port := os.Getenv("DB_PORT") | |
// Montar o DSN | |
dsn := "host=" + host + " user=" + user + " password=" + password + " dbname=" + dbname + " port=" + port + " sslmode=disable TimeZone=America/Sao_Paulo" | |
// Conectar ao banco de dados | |
db, err := gorm.Open(postgres.Open(dsn), &gorm.Config{}) | |
if err != nil { | |
log.Fatalf("Erro ao conectar ao banco de dados: %v", err) | |
} | |
log.Println("Conectado ao banco de dados com sucesso!") | |
return db | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"customer-management/config" | |
"customer-management/models" | |
"customer-management/routes" | |
"github.com/gin-gonic/gin" | |
) | |
func main() { | |
// Conectar ao banco | |
db := config.ConnectDatabase() | |
// Migrar o modelo | |
err := db.AutoMigrate(&models.Client{}) | |
if err != nil { | |
panic("Erro ao migrar o modelo Client: " + err.Error()) | |
} | |
// Configurar o servidor | |
router := gin.Default() | |
// Configurar as rotas | |
routes.ConfigurarRotas(db, router) | |
// Iniciar o servidor | |
router.Run(":8080") | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment