Here I have provided a step-by-step guide on how to set up the project
Create the project directory
mkdir rmshop-clean-architecture
cd rmshop-clean-architecture
Initialize Go modules
go mod init github.com/yourusername/rmshop-clean-architecture
Set up the main application entry point (cmd/api/main.go
)
package main
import (
"log"
"net/http"
"github.com/yourusername/rmshop-clean-architecture/internal/config"
"github.com/yourusername/rmshop-clean-architecture/internal/server"
)
func main() {
cfg, err := config.Load()
if err != nil {
log.Fatalf("Failed to load config: %v", err)
}
srv, err := server.New(cfg)
if err != nil {
log.Fatalf("Failed to create server: %v", err)
}
log.Printf("Starting server on :%s", cfg.Server.Port)
if err := http.ListenAndServe(":"+cfg.Server.Port, srv); err != nil {
log.Fatalf("Failed to start server: %v", err)
}
}
Create a basic configuration file (internal/config/config.go
)
package config
import "github.com/spf13/viper"
type Config struct {
Server ServerConfig
DB DBConfig
}
type ServerConfig struct {
Port string
}
type DBConfig struct {
Host string
Port string
User string
Password string
DBName string
}
func Load() (*Config, error) {
viper.SetConfigName("config")
viper.SetConfigType("yaml")
viper.AddConfigPath(".")
viper.AddConfigPath("./config")
if err := viper.ReadInConfig(); err != nil {
return nil, err
}
var config Config
if err := viper.Unmarshal(&config); err != nil {
return nil, err
}
return &config, nil
}
Create a config.yaml file in the project root
server:
port: "8080"
db:
host: "localhost"
port: "5432"
user: "postgres"
password: "your_password"
dbname: "rmshop"
Initialize the basic server setup (internal/server/server.go
)
package server
import (
"net/http"
"github.com/yourusername/rmshop-clean-architecture/internal/config"
)
type Server struct {
router http.Handler
}
func New(cfg *config.Config) (*Server, error) {
// Initialize your router, database connection, and other dependencies here
// For now, we'll just return a basic server
return &Server{
router: http.NewServeMux(),
}, nil
}
func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
s.router.ServeHTTP(w, r)
}
Install necessary dependencies
go get github.com/spf13/viper
go get github.com/lib/pq
This setup provides a solid foundation for your e-commerce project, adhering to clean architecture principles. In the next sections, we'll build upon this structure to implement our business logic, database interactions, and API endpoints.
Top comments (0)