<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Achintha Perera on Medium]]></title>
        <description><![CDATA[Stories by Achintha Perera on Medium]]></description>
        <link>https://medium.com/@achinthaperera02?source=rss-2366a47becad------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*jfCjnZq-vkuAC6AE</url>
            <title>Stories by Achintha Perera on Medium</title>
            <link>https://medium.com/@achinthaperera02?source=rss-2366a47becad------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 22 Nov 2026 04:57:46 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@achinthaperera02/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[CLEAN ARCHITECTURE IN GO: THE PRACTICAL GUIDE]]></title>
            <link>https://medium.com/@achinthaperera02/clean-architecture-in-go-the-practical-guide-78222fbcdc12?source=rss-2366a47becad------2</link>
            <guid isPermaLink="false">https://medium.com/p/78222fbcdc12</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[clean-architecture]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[golang]]></category>
            <dc:creator><![CDATA[Achintha Perera]]></dc:creator>
            <pubDate>Sun, 29 Mar 2026 13:50:30 GMT</pubDate>
            <atom:updated>2026-03-29T13:50:30.367Z</atom:updated>
            <content:encoded><![CDATA[<p>The previous article outlined the theory behind clean architecture boundaries. This guide expands on those concepts to demonstrate the practical implementation. Developers will see pure Go code and understand data flow across application boundaries. The following sections explain each concept in detail to ensure engineers grasp the mechanics of this design. The guide walks through the exact steps needed to build a resilient system. Developers learn to write code resilient to shifting requirements.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Q3XiFeIEOPJWTPy07_-m7A.png" /><figcaption>A stacked diagram visualizing the Clean Architecture rule: source code dependencies must point inward toward high-level policies.</figcaption></figure><p><strong>THE DOMAIN LAYER THE ABSOLUTE CORE</strong></p><p>The domain layer defines core business rules through plain Go structs. These structs represent the real world concepts an application manages. Engineers define interfaces for external storage to keep the core isolated. Developers avoid importing web frameworks and database drivers. The code relies solely on standard library packages. This isolation ensures business rules never change because a team switched from PostgreSQL to MongoDB. The domain logic remains pure.</p><p>A core entity like an order holds specific state and behavior. The validation logic belongs right next to the data, so engineers do not scatter validation checks across HTTP handlers or database queries. Developers centralize the rules in the domain struct to make the rules easy to test and verify. Any programmer reading the struct immediately understands the constraints of an order. The interface definition acts as a strict contract. The domain dictates the requirements needed to survive. The outside world must conform to this contract. This design inverts the dependency.</p><pre>package domain<br><br>import &quot;context&quot;<br><br>type Order struct {<br>ID     string<br>Amount float64<br>Status string<br>}<br><br>func (o Order) IsValid() bool {<br>return o.Amount &gt; 0<br>}<br><br>type OrderRepository interface {<br>Save(ctx context.Context, order Order) error<br>GetByID(ctx context.Context, id string) (Order, error)<br>}</pre><p>The code above defines an Order struct containing ID, Amount, and Status fields. This struct holds the raw data. The IsValid method attaches directly to the Order struct to verify the amount is greater than zero. This placement guarantees validation happens alongside the data. The OrderRepository interface defines two methods for database operations. The context package allows cancellation signals to pass through the application. The interface requires any database implementation to accept a context and an Order object.</p><p><strong>THE USE CASE LAYER ORCHESTRATING THE FLOW</strong></p><p>The use case layer orchestrates system actions. The system receives input data from the outside world and applies business rules defined in the domain layer. The application then calls the persistence interface to store the results. The use case layer depends entirely on the domain layer. The layer acts as the manager instructing the domain entities on what actions to take.</p><p>This section holds the application specific logic. A user placing an order triggers a specific sequence of events, and the use case handles this exact sequence. The service receives the raw input to instantiate the domain entity. The service then triggers the domain validation. Upon successful validation, the service passes the entity to the repository interface. The use case also handles error routing. If validation fails, the use case returns the error upward. If the database save fails, the use case returns the error upward. The use case avoids formatting the error for an HTTP response because the layer only knows about the domain and the interfaces. Software engineers test this entire flow using a simple mock struct. Teams do not need a running database to prove the application logic works. Developers test the pure sequence of operations in isolation.</p><pre>package usecase<br><br>import (<br>&quot;context&quot;<br>&quot;errors&quot;<br>&quot;myapp/domain&quot;<br>)<br><br>type OrderService struct {<br>repo domain.OrderRepository<br>}<br><br>func NewOrderService(repo domain.OrderRepository) OrderService {<br>return OrderService{repo: repo}<br>}<br><br>func (s OrderService) PlaceOrder(ctx context.Context, amount float64) error {<br>order := domain.Order{<br>ID:     &quot;new-uuid&quot;,<br>Amount: amount,<br>Status: &quot;PENDING&quot;,<br>}<br><br>if !order.IsValid() {<br>    return errors.New(&quot;invalid order amount&quot;)<br>}<br><br>return s.repo.Save(ctx, order)<br>}</pre><p>The OrderService struct holds a reference to the OrderRepository interface. The NewOrderService function acts as a constructor to inject the repository dependency. The PlaceOrder method accepts a context and an amount. The method creates a new Order entity with a pending status. The code calls the IsValid method on the order. If the validation fails, the function returns an error immediately. If the validation succeeds, the function calls the Save method on the injected repository. The service orchestrates these steps without knowing how the data is stored.</p><p><strong>INTERFACE ADAPTERS TRANSLATING DATA</strong></p><p>Applications must communicate with external systems. Interface adapters handle data translation between the core logic and the outside world. Handlers parse incoming HTTP requests, and repositories execute database queries. The HTTP handler sits at the boundary to parse JSON payloads into Go data structures. The handler calls the use case and returns an HTTP response to the client.</p><p>The handler functions as a translator. The internet sends text based JSON data, but a Go application needs strongly typed structs. The handler decodes the payload to extract the raw values. The handler passes these values to the use case. The use case returns a result or an error. The handler then translates the Go error into an appropriate HTTP status code. The handler knows about HTTP rules but knows nothing about business rules.</p><pre>package delivery<br><br>import (<br>&quot;encoding/json&quot;<br>&quot;net/http&quot;<br>&quot;myapp/usecase&quot;<br>)<br><br>type OrderHandler struct {<br>service usecase.OrderService<br>}<br><br>func (h OrderHandler) HandlePlaceOrder(w http.ResponseWriter, r *http.Request) {<br>var payload struct {<br>Amount float64 json:&quot;amount&quot;<br>}<br><br>err := json.NewDecoder(r.Body).Decode(&amp;payload)<br>if err != nil {<br>    http.Error(w, &quot;invalid json&quot;, http.StatusBadRequest)<br>    return<br>}<br><br>err = h.service.PlaceOrder(r.Context(), payload.Amount)<br>if err != nil {<br>    http.Error(w, err.Error(), http.StatusBadRequest)<br>    return<br>}<br><br>w.WriteHeader(http.StatusCreated)<br>}</pre><p>The OrderHandler struct receives the OrderService. The HandlePlaceOrder method takes standard HTTP request and response objects. The code defines a Payload struct to represent the expected JSON data. The json.NewDecoder function reads the request body and maps the data to the Payload struct. If the decoding fails, the handler sends a bad request error. The handler then calls the PlaceOrder method on the service. The handler evaluates the returned error. If an error exists, the client receives a bad request status. A successful operation results in a status created response.</p><p>The SQL repository implements the domain interface. The repository writes data to Postgres by translating the domain object into a SQL query. Databases need flat rows of data. The code extracts the fields from the domain struct to map these fields to SQL columns. The driver executes the query and handles any driver specific errors. The repository knows about SQL syntax and connection pools, but the repository knows nothing about HTTP requests. This separation of concerns allows multiple developers to work on different parts of the feature without conflicts.</p><pre>package postgres<br><br>import (<br>&quot;context&quot;<br>&quot;database/sql&quot;<br>&quot;myapp/domain&quot;<br>)<br><br>type OrderRepo struct {<br>db *sql.DB<br>}<br><br>func (r OrderRepo) Save(ctx context.Context, order domain.Order) error {<br>query := &quot;INSERT INTO orders (id, amount, status) VALUES ($1, $2, $3)&quot;<br>_, err := r.db.ExecContext(ctx, query, order.ID, order.Amount, order.Status)<br>return err<br>}<br><br>func (r OrderRepo) GetByID(ctx context.Context, id string) (domain.Order, error) {<br>return domain.Order{}, nil<br>}</pre><p>The OrderRepo struct holds a pointer to a standard SQL database connection. The Save method implements the domain interface. The function defines a SQL insert query using placeholders. The ExecContext method runs the query against the database using the provided context and order fields. The function returns any SQL errors directly to the caller. The repository successfully translates the Go struct into a database row.</p><p><strong>WIRING AND INFRASTRUCTURE THE COMPOSITION ROOT</strong></p><p>Engineers connect the layers in the main package. Developers apply dependency injection here by opening the database connection and passing the connection to the repository. The application passes the repository to the use case and passes the use case to the handler. This setup dictates the core logic never creates internal dependencies. The system provides the dependencies from the outside.</p><p>The main function acts as the ultimate configuration file. The main function represents the only place in the entire application where all components meet. The system reads environment variables and establishes network connections here. Developers assemble the application piece by piece. The code instantiates the database adapter to inject the adapter into the business logic layer. The code then injects the business logic into the HTTP server. This explicit wiring removes hidden dependencies to show the entire application structure in one place. A developer swaps a Postgres repository for a memory repository by changing one line of code in the main function.</p><pre>package main<br><br>import (<br>&quot;database/sql&quot;<br>&quot;net/http&quot;<br>&quot;myapp/postgres&quot;<br>&quot;myapp/usecase&quot;<br>&quot;myapp/delivery&quot;<br>)<br><br>func main() {<br>db, _ := sql.Open(&quot;postgres&quot;, &quot;postgres://user:pass@localhost/db&quot;)<br><br>repo := postgres.OrderRepo{db: db}<br>service := usecase.NewOrderService(repo)<br>handler := delivery.OrderHandler{service: service}<br><br>http.HandleFunc(&quot;/order&quot;, handler.HandlePlaceOrder)<br>http.ListenAndServe(&quot;:8080&quot;, nil)<br>}</pre><p>The main function starts by opening a Postgres database connection. The code instantiates the OrderRepo using the database connection. The code creates the OrderService by passing the repository. The code creates the OrderHandler by passing the service. This sequence builds the dependency chain from the inside out. The http.HandleFunc registers the handler to a specific URL route. The http.ListenAndServe function starts the web server on port 8080.</p><p><strong>CONCURRENCY AND CACHING PREVENTING OVERLOAD</strong></p><p>High traffic overloads databases. A hundred users requesting the same popular item at the exact same millisecond sends a hundred identical queries to the database. This event causes a cache stampede. Engineers protect the system with the singleflight package. Multiple requests for identical data merge into one single database query.</p><p>The singleflight pattern provides an elegant solution to concurrency spikes. The wrapper intercepts the incoming request to check if an identical request currently runs. If a similar request runs, the new request waits. The base repository executes the single permitted query, so the database does the work once. The wrapper receives the result and distributes the single result to all waiting requests. This pattern drastically reduces database load during traffic spikes. The domain layer and the use case layer remain completely oblivious to this caching mechanism. Developers implement complex performance optimizations entirely within the infrastructure layer.</p><pre>package postgres<br><br>import (<br>&quot;context&quot;<br>&quot;golang.org/x/sync/singleflight&quot;<br>&quot;myapp/domain&quot;<br>)<br><br>type CachedOrderRepo struct {<br>group singleflight.Group<br>base  domain.OrderRepository<br>}<br><br>func (r CachedOrderRepo) GetByID(ctx context.Context, id string) (domain.Order, error) {<br>result, err, _ := r.group.Do(id, func() (interface{}, error) {<br>return r.base.GetByID(ctx, id)<br>})<br><br>if err != nil {<br>    return domain.Order{}, err<br>}<br><br>order := result.(domain.Order)<br>return order, nil<br>}</pre><p>The CachedOrderRepo struct wraps a singleflight Group and a base OrderRepository. The GetByID method defines a loader function to call the database. The group.Do function uses the order ID as a unique key and executes the loader function. The singleflight package ensures only one database call runs for a given ID at any time. The result casts back to a domain.Order struct. The wrapper protects the database from duplicate queries.</p><p><strong>GRACEFUL SHUTDOWN SAFE DEPLOYMENTS</strong></p><p>Production deployments require safe restarts. Engineers stop the server to load new code. Active connections drop if the system shuts down immediately, and users lose data. Applications listen for operating system signals to intercept the termination command. The server finishes active connections before stopping.</p><p>A robust system handles internal termination gracefully. Kubernetes sends a signal when processes need to stop, and the application must catch this signal. The code instructs the HTTP server to stop accepting new connections. The system waits for existing requests to complete pending database transactions. Developers enforce a strict timeout. If the existing requests take too long, the system forces a shutdown. This timeout prevents the application from hanging indefinitely. This coordinated shutdown sequence prevents corrupted state. The application maintains a reliable experience for the user even during continuous deployment cycles.</p><pre>package main<br><br>import (<br>&quot;context&quot;<br>&quot;log&quot;<br>&quot;net/http&quot;<br>&quot;os&quot;<br>&quot;os/signal&quot;<br>&quot;syscall&quot;<br>&quot;time&quot;<br>)<br><br>func runServer(srv *http.Server) {<br>go func() {<br>srv.ListenAndServe()<br>}()<br><br>stop := make(chan os.Signal, 1)<br>signal.Notify(stop, syscall.SIGINT, syscall.SIGTERM)<br>&lt;-stop<br><br>ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)<br>defer cancel()<br><br>srv.Shutdown(ctx)<br>log.Println(&quot;server stopped safely&quot;)<br>}</pre><p>The runServer function starts the HTTP server in a separate goroutine. The code creates a channel to listen for operating system interrupt signals. The signal.Notify function routes system termination signals to the channel. The receive operation blocks execution until a signal arrives. Once a signal arrives, the code creates a context with a five second timeout. The srv.Shutdown method uses this context to close the server gracefully. Existing requests have five seconds to finish before the program exits completely.</p><p>Clean architecture demands strict discipline from software engineering teams. Developers write more boilerplate code initially to establish clear boundaries. This upfront investment prevents technical debt as applications grow. The rigid layers protect core business rules from infrastructure changes. Teams replace databases or web frameworks without rewriting the domain logic.</p><p>Engineers build highly testable systems by isolating dependencies. Mocking interfaces allows rapid validation of complex business flows. The system remains flexible and predictable under heavy loads. This architectural pattern provides a reliable blueprint for long term success.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=78222fbcdc12" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[BUILDING SCALABLE GO SERVICES WITH CLEAN ARCHITECTURE]]></title>
            <link>https://medium.com/@achinthaperera02/building-scalable-go-services-with-clean-architecture-bd887f34b242?source=rss-2366a47becad------2</link>
            <guid isPermaLink="false">https://medium.com/p/bd887f34b242</guid>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[backend-development]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[clean-architecture]]></category>
            <category><![CDATA[system-design-concepts]]></category>
            <dc:creator><![CDATA[Achintha Perera]]></dc:creator>
            <pubDate>Sun, 22 Feb 2026 07:25:08 GMT</pubDate>
            <atom:updated>2026-02-22T07:25:08.807Z</atom:updated>
            <content:encoded><![CDATA[<p>Software engineering requires a balance between rapid delivery and long term maintainability. As Go applications grow into complex microservices, initial simplicity leads to rigid dependencies. This structure makes testing difficult and slows down new feature development. Clean Architecture separates business logic from technical details to maintain order.</p><p><strong>THE CORE PROBLEM: TIGHT COUPLING</strong></p><p>Many developers write logic directly inside HTTP handlers or database scripts. This approach creates tight coupling where business rules depend on the specific choice of a web framework or database driver. Switching from a relational database to a NoSQL solution or changing your transport protocol from HTTP to gRPC requires rewriting the entire application. Clean Architecture solves this by ensuring dependencies flow inward toward the core logic.</p><p><strong>THE LAYERED STRUCTURE</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JRFR0ONjZHdm3tSN5l-m6A.png" /></figure><p>A well structured Go application using Clean Architecture consists of four distinct layers. Each layer has a specific responsibility and remains isolated from the implementation details of others.</p><p><strong>1. DOMAIN LAYER</strong></p><p>This is the innermost circle. This layer contains the core business models and interfaces. In Go, these are simple structs and interface definitions. This layer has no dependencies on external packages, databases, or frameworks.</p><pre>package domain<br><br>import &quot;context&quot;<br><br>type User struct {<br>    ID       string<br>    Email    string<br>    Password string<br>}<br><br>type UserRepository interface {<br>    Store(ctx context.Context, u User) error<br>    GetByEmail(ctx context.Context, email string) (*User, error)<br>}</pre><p><strong>2. USE CASE LAYER</strong></p><p>The Use Case layer coordinates the flow of data. This section implements the specific business rules of the application. A CreateUser use case checks if an email is already taken before calling the repository to save the user. This layer depends only on the Domain layer. You use real libraries like the UUID package for production readiness. You also wrap errors to maintain context.</p><pre>package usecase<br><br>import (<br>    &quot;context&quot;<br>    &quot;errors&quot;<br>    &quot;fmt&quot;<br>    &quot;yourproject/domain&quot;<br>    &quot;github.com/google/uuid&quot;<br>)<br><br>type CreateUserRequest struct {<br>    Email    string<br>    Password string<br>}<br><br>type CreateUserResponse struct {<br>    ID    string<br>    Email string<br>}<br><br>type UserInteractor struct {<br>    repo domain.UserRepository<br>}<br><br>func NewUserInteractor(repo domain.UserRepository) UserInteractor {<br>    return UserInteractor{<br>        repo: repo,<br>    }<br>}<br><br>func (u UserInteractor) Register(ctx context.Context, req CreateUserRequest) (CreateUserResponse, error) {<br>    existing, _ := u.repo.GetByEmail(ctx, req.Email)<br>    if existing != nil {<br>        return CreateUserResponse{}, errors.New(&quot;email already taken&quot;)<br>    }<br><br>    user := domain.User{<br>        ID:       uuid.New().String(),<br>        Email:    req.Email,<br>        Password: req.Password,<br>    }<br><br>    if err := u.repo.Store(ctx, user); err != nil {<br>        return CreateUserResponse{}, fmt.Errorf(&quot;failed to save user: %w&quot;, err)<br>    }<br><br>    return CreateUserResponse{ID: user.ID, Email: user.Email}, nil<br>}</pre><p><strong>3. INTERFACE ADAPTERS</strong></p><p>This layer converts data from the format most convenient for use cases to the format most convenient for external agencies like databases or web interfaces. This tier includes HTTP handlers, gRPC services, and database repository implementations. A repository implementation uses a specific database driver to satisfy the UserRepository interface defined in the Domain layer. You write real SQL queries here.</p><pre>package postgres<br><br>import (<br>    &quot;context&quot;<br>    &quot;database/sql&quot;<br>    &quot;errors&quot;<br>    &quot;yourproject/domain&quot;<br>)<br><br>type UserRepository struct {<br>    DB *sql.DB<br>}<br><br>func (r UserRepository) Store(ctx context.Context, u domain.User) error {<br>    query := &quot;INSERT INTO users (id, email, password) VALUES ($1, $2, $3)&quot;<br>    _, err := r.DB.ExecContext(ctx, query, u.ID, u.Email, u.Password)<br>    return err<br>}<br><br>func (r UserRepository) GetByEmail(ctx context.Context, email string) (*domain.User, error) {<br>    row := r.DB.QueryRowContext(ctx, &quot;SELECT id, email FROM users WHERE email = $1&quot;, email)<br>    var u domain.User<br>    if err := row.Scan(&amp;u.ID, &amp;u.Email); err != nil {<br>        if errors.Is(err, sql.ErrNoRows) {<br>            return nil, nil<br>        }<br>        return nil, err<br>    }<br>    return &amp;u, nil<br>}</pre><p><strong>4. INFRASTRUCTURE</strong></p><p>The outermost layer contains tools like the database engine, the web framework, or the logging library. You treat these as plugins.</p><p><strong>DEPENDENCY INVERSION IN GO</strong></p><p>Higher level modules do not depend on lower level modules. Both depend on abstractions. You achieve this through interfaces. The concrete implementation is injected into the Use Case when the application starts. Dependency injection keeps the system flexible. You swap components without altering the core logic.</p><p><strong>TESTING STRATEGY</strong></p><p>You write unit tests for use cases by injecting mock repositories. You write integration tests for interface adapters to verify database queries and HTTP responses. This separation ensures fast and reliable test suites.</p><p><strong>SCALABILITY</strong></p><p>Clean Architecture promotes horizontal scaling. Your core services remain stateless. You deploy multiple instances of your application behind a load balancer to handle increased traffic.</p><p><strong>HANDLING CONCURRENCY AND CACHING</strong></p><p>High traffic systems face cache stampedes. Multiple goroutines request missing data simultaneously. This overloads your database. The singleflight package solves this problem. You wrap your database call within a singleflight group. The first request executes the query. Subsequent requests wait for the first to finish. All requests share the single result. This pattern protects your database under heavy load.</p><pre>package repository<br><br>import (<br>    &quot;context&quot;<br>    &quot;golang.org/x/sync/singleflight&quot;<br>    &quot;yourproject/domain&quot;<br>)<br><br>type CachedUserRepository struct {<br>    group singleflight.Group<br>    db    domain.UserRepository<br>}<br><br>func (r CachedUserRepository) GetByEmail(ctx context.Context, email string) (*domain.User, error) {<br>    v, err, _ := r.group.Do(email, func() (interface{}, error) {<br>        return r.db.GetByEmail(ctx, email)<br>    })<br>    <br>    if err != nil {<br>        return nil, err<br>    }<br>    <br>    user := v.(*domain.User)<br>    return user, nil<br>}</pre><p><strong>GRACEFUL SHUTDOWN</strong></p><p>Production services must handle termination signals. You ensure active requests complete before the server stops. This prevents data corruption. The main function wires the dependencies together and listens for OS signals. You use a context timeout to enforce a strict shutdown deadline. This highlights resilience under load.</p><pre>package main<br><br>import (<br>    &quot;context&quot;<br>    &quot;database/sql&quot;<br>    &quot;log&quot;<br>    &quot;net/http&quot;<br>    &quot;os&quot;<br>    &quot;os/signal&quot;<br>    &quot;syscall&quot;<br>    &quot;time&quot;<br>    &quot;yourproject/postgres&quot;<br>    &quot;yourproject/usecase&quot;<br>)<br><br>func main() {<br>    db, _ := sql.Open(&quot;postgres&quot;, &quot;postgres://user:pass@localhost/db&quot;)<br>    userRepo := postgres.UserRepository{DB: db}<br>    userService := usecase.NewUserInteractor(userRepo)<br>    <br>    mux := http.NewServeMux()<br>    <br>    srv := &amp;http.Server{<br>        Addr:    &quot;:8080&quot;,<br>        Handler: mux,<br>    }<br><br>    go func() {<br>        if err := srv.ListenAndServe(); err != nil &amp;&amp; err != http.ErrServerClosed {<br>            log.Fatalf(&quot;listen: %v\n&quot;, err)<br>        }<br>    }()<br><br>    quit := make(chan os.Signal, 1)<br>    signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)<br>    &lt;-quit<br>    log.Println(&quot;Shutting down server...&quot;)<br><br>    ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)<br>    defer cancel()<br><br>    if err := srv.Shutdown(ctx); err != nil {<br>        log.Fatalf(&quot;Server forced to shutdown: %v&quot;, err)<br>    }<br><br>    log.Println(&quot;Server exiting&quot;)<br>}</pre><p>By adhering to these boundaries, you create a system resilient to change and easy to understand as your project scales.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bd887f34b242" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>