a simple API project with DDD (Domain-Driven Design) principles in Go
- User
a simple API project with DDD (Domain-Driven Design) principles in Go
- Assistant
a simple API project with DDD (Domain-Driven Design) principles in Go
Domain-Driven Design (DDD) is a design approach that emphasizes the importance of domain modeling and understanding the business requirements. By following DDD principles, you aim to build software that reflects the business domain accurately.
Let's create a simple API project in Go using DDD principles. We'll use a bookstore scenario where we can add and retrieve books.
go-bookstore/
│
├── cmd/
│ └── api/
│ └── main.go
├── internal/
│ ├── domain/
│ │ └── book.go
│ ├── infrastructure/
│ │ ├── router.go
│ │ └── repository.go
│ ├── application/
│ │ └── book_service.go
└── go.mod
Create internal/domain/book.go:
package domain
import "errors"
type Book struct {
ID string
Title string
Author string
}
var ErrBookNotFound = errors.New("book not found")
type BookRepository interface {
Save(book *Book) error
GetByID(id string) (*Book, error)
}
Create internal/infrastructure/repository.go:
package infrastructure
import (
"errors"
"go-bookstore/internal/domain"
)
type InMemoryBookRepository struct {
books map[string]*domain.Book
}
func NewInMemoryBookRepository() *InMemoryBookRepository {
return &InMemoryBookRepository{
books: make(map[string]*domain.Book),
}
}
func (r *InMemoryBookRepository) Save(book *domain.Book) error {
r.books[book.ID] = book
return nil
}
func (r *InMemoryBookRepository) GetByID(id string) (*domain.Book, error) {
if book, ok := r.books[id]; ok {
return book, nil
}
return nil, domain.ErrBookNotFound
}
Create internal/infrastructure/router.go:
package infrastructure
import (
"encoding/json"
"go-bookstore/internal/application"
"go-bookstore/internal/domain"
"net/http"
"github.com/gorilla/mux"
)
type Handler struct {
bookService *application.BookService
}
func NewHandler(bookService *application.BookService) *Handler {
return &Handler{bookService}
}
func (h *Handler) AddBook(w http.ResponseWriter, r *http.Request) {
var book domain.Book
if err := json.NewDecoder(r.Body).Decode(&book); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
if err := h.bookService.AddBook(&book); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusCreated)
}
func (h *Handler) GetBook(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
id := vars["id"]
book, err := h.bookService.GetBook(id)
if err != nil {
if errors.Is(err, domain.ErrBookNotFound) {
http.Error(w, err.Error(), http.StatusNotFound)
} else {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
return
}
if err := json.NewEncoder(w).Encode(book); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}
func NewRouter(handler *Handler) *mux.Router {
r := mux.NewRouter()
r.HandleFunc("/books", handler.AddBook).Methods(http.MethodPost)
r.HandleFunc("/books/{id}", handler.GetBook).Methods(http.MethodGet)
return r
}
Create internal/application/book_service.go:
package application
import "go-bookstore/internal/domain"
type BookService struct {
repository domain.BookRepository
}
func NewBookService(repository domain.BookRepository) *BookService {
return &BookService{repository: repository}
}
func (s *BookService) AddBook(book *domain.Book) error {
return s.repository.Save(book)
}
func (s *BookService) GetBook(id string) (*domain.Book, error) {
return s.repository.GetByID(id)
}
Create cmd/api/main.go:
package main
import (
"go-bookstore/internal/application"
"go-bookstore/internal/infrastructure"
"log"
"net/http"
)
func main() {
bookRepository := infrastructure.NewInMemoryBookRepository()
bookService := application.NewBookService(bookRepository)
handler := infrastructure.NewHandler(bookService)
router := infrastructure.NewRouter(handler)
log.Println("Starting server on :8080")
if err := http.ListenAndServe(":8080", router); err != nil {
log.Fatal(err)
}
}
go mod init go-bookstore
go get github.com/gorilla/mux
go run cmd/api/main.go
The server should start on port 8080, exposing two endpoints:
POST /books to add a new book.GET /books/{id} to retrieve a book by its ID.This setup demonstrates DDD principles by separating the domain, application, and infrastructure concerns. The domain layer defines the core business logic and entities, the application layer implements the business use cases, and the infrastructure layer handles interactions with external systems (HTTP requests in this case).
Not yet included in a published release.