<?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 Luke Sloane-Bulger on Medium]]></title>
        <description><![CDATA[Stories by Luke Sloane-Bulger on Medium]]></description>
        <link>https://medium.com/@luke.sloanebulger?source=rss-f068ade2f3fe------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*RCPGYVwHzUCM_N6IKg1vcQ.jpeg</url>
            <title>Stories by Luke Sloane-Bulger on Medium</title>
            <link>https://medium.com/@luke.sloanebulger?source=rss-f068ade2f3fe------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 22 Nov 2026 05:33:28 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@luke.sloanebulger/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[How To Implement Cache in Your Golang API]]></title>
            <link>https://blog.stackademic.com/how-to-implement-cache-in-your-golang-api-cea87a260e21?source=rss-f068ade2f3fe------2</link>
            <guid isPermaLink="false">https://medium.com/p/cea87a260e21</guid>
            <category><![CDATA[cache]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[golang-tutorial]]></category>
            <dc:creator><![CDATA[Luke Sloane-Bulger]]></dc:creator>
            <pubDate>Mon, 01 Sep 2025 01:39:04 GMT</pubDate>
            <atom:updated>2025-09-01T01:39:04.122Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LL4h8mSmxNIAoIv3UazhlA.png" /><figcaption>How To Implement Cache in Your Golang API In 3 Minutes</figcaption></figure><p>Cache.</p><p>What’s cache? Why do we need it? How do we implement it?</p><p>Cache is a layer that acts as an intermediary between your API and your database.</p><p>It’s purpose is simple: reduce unnecessary database queries by holding frequently used data in-memory to both protect the database and to increase our API performance.</p><p>With a cache, API latency is reduced, responsiveness and performance is increased, and the database overall is less strained.</p><p>Without cache, every request forces a round trip to your database, which quickly becomes a bottleneck as your system scales.</p><p>Think of cache as a protective shield for your database. It absorbs repeated hits, so the database only handles what it really needs to.</p><p>In this article, we’ll explore what caching is, why we need it, the different types of caching strategies, and finally how we can implement a caching layer in our Golang APIs.</p><h3>What is Cache?</h3><p>Cache is an in-memory store used to hold frequently accessed data.</p><p>In system design, it acts as an intermediary between the API and the database.</p><p>By serving requests from memory rather than disk, the cache drastically reduces latency and improves performance.</p><p>Beyond performance, cache is useful for scaling system.</p><p>Adding a cache layer helps to protect the database from repeated, time-consuming network calls and DB queries.</p><p>Here’s a high-level of how a cache works:</p><ol><li>When a request is made, the system first checks the cache.</li><li>If the data exists, that’s a “cache hit”, the cached data is used and the request is returned.</li><li>If the data doesn’t exist, that’s a “cache miss” the system queries the database, stores the data in the cache and returns it.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/637/1*fXWGUTYjnXPCSmFGfETo-Q.png" /><figcaption>If we have cache, return data. If not, query the DB, Store in Cache, return data.</figcaption></figure><p>This workflow makes future requests faster and reduces database pressure.</p><p>Let’s dive deeper into what cache is…</p><h3>What Does Cache Look Like?</h3><p>Cache can take different forms depending on the use case:</p><ul><li><strong>In-Memory Stores</strong>: Simple key-value stores like Go maps, or external solutions like Redis and Memcached.</li><li><strong>Application-Level Caches</strong>: This is when the cache lives inside your APIs memory space like a Go map with a <a href="https://medium.com/stackademic/what-are-mutexes-in-golang-learn-in-3-minutes-16c196e65e3d">mutex</a>. It’s local to that process and disappears when the process restarts. It’s useful for avoiding repeated calculations, API calls, or database queries in that specific instance.</li><li><strong>Distributed Caches</strong>: Shared caches across services for high-scale systems where multiple replicated APIs need to access a shared cache.</li></ul><p>At a low-level, caches are managed using data structures and eviction policies, which determine which items get removed when the cache reaches its limit. Common strategies include:</p><ul><li><strong>FIFO (First-In First-Out)</strong> — evicts the oldest element (the one added first).</li><li><strong>LRU (Least Recently Used)</strong> — evicts items that haven’t been accessed recently.</li><li><strong>LFU (Least Frequently Used)</strong> — evicts items that are accessed the least often, usually tracked by a counter per entry.</li></ul><h3>Cache Invalidation</h3><p>Caching is powerful, but stale data can be problematic. Invalidation ensures cached data doesn’t become outdated.</p><p>Approaches include:</p><ul><li>TTL (Time To Live) — Each entry expires after a fixed time window. Simple, but may serve stale data until expiry.</li><li>Manual Invalidation — Explicitly clear or update cache entries whenever data changes. Useful, but puts responsibility on the developer to ensure the cache stays consistent.</li></ul><p>Various caching strategies can also help manage cache updates in combination with the common approaches above, including LRU and LFU policies.</p><h3>Different Types of Cache Strategies</h3><p>Beyond expirations, there are caching strategies that define how the cache is updated via read/write operations:</p><ul><li><strong>Write-Through</strong> — Every write updates both the cache and DB synchronously. Offers strong consistency, at a trade-off of latency.</li><li><strong>Write-Back</strong> — Writes to the cache first, then the DB asynchronously. Offers low-latency and high performance at the trade-off of durability.</li><li><strong>Write-Around —</strong> Writes to DB first and then on the next read updates the cache lazily. Provides durability, but at the trade-off of increased cache misses.</li><li><strong>Read-Through</strong> — The API always queries the cache. On a miss, the cache itself fetches from the DB and stores it.</li><li><strong>Cache-Aside (Lazy Loading)</strong> — The API checks the cache first. On a miss, the application loads data from the DB, stores it in the cache, and returns it.</li></ul><p>Each method balances freshness, complexity and performance differently with their own benefits and trade-offs.</p><p>The choices depends on system requirements for consistency, latency and durability.</p><h4>When and Why Do We Need a Cache?</h4><p>Caching is a tool in system design that improves performance and protects the DB by reducing repetitive transactions, such as fetching user details.</p><p>However, adding a caching layer introduces complexity in managing, updating, and invalidating cache entries. For a small API with a low number of daily active users (DAU), the overhead of maintaining a cache may not be worth it.</p><p>A cache becomes necessary once DB usage starts to impact latency or stability. Signs include:</p><ul><li><strong>High DB CPU/IO usage</strong> — Queries consuming more than 70–80% of available resources.</li><li><strong>Rising request latency</strong> — Average API response times exceeding 200–300ms for simple lookups, impacting user experience.</li><li><strong>Throughput strain</strong> — The DB is handling thousands of requests per second, or traffic is growing faster than it can scale vertically.</li><li><strong>Frequent repeated queries</strong> — The same “top products” or “user profile” queries being requested hundreds of times per second.</li></ul><p>At this point, adding a cache helps absorb the load, keep responses fast, and protects the DB from becoming a bottleneck.</p><h3>How To Implement Cache in Golang?</h3><p>There are many ways to implement a Cache layer.</p><p>From third-party packages or building your own native solution that you can control and expand on.</p><p>In this article, we’ll focus on a basic native solution to leverage Golang’s in-built packages using a map.</p><p>This approach is straightforward, easy to integrate, and excellent for learning the fundamentals of caching before moving on to more advanced tools like Redis or implementing priority-based eviction strategies such as LRU or LFU.</p><h4>Define the Cache Structure</h4><p>Let’s say we have a RESTful API called TransactionsHistoryAPI.</p><p>We can create a basic cache package in TransactionsHistoryAPI that we can use to store our data in-memory.</p><p>cache.go</p><pre>type ICache interface {<br> Set(key string, value any) error<br> Get(key string) (any, bool)<br> Del(key string) bool<br> cleanup()<br> StopCleanup()<br>}<br><br>type item struct {<br> value any<br> ttl   int64 // expiry time as unix ns timestamp<br>}<br><br>type Cache struct {<br> cacheMap   map[string]item<br> mx         sync.Mutex<br> quit       chan struct{}<br> defaultTTL time.Duration<br>}<br><br>func NewCache(defaultTTL, cleanupInterval time.Duration) *Cache {<br> c := &amp;Cache{<br>  cacheMap:   make(map[string]item),<br>  quit:       make(chan struct{}),<br>  defaultTTL: defaultTTL,<br> }<br><br> // background cleaner<br> go func() {<br>  ticker := time.NewTicker(cleanupInterval)<br>  for {<br>   select {<br>   case &lt;-ticker.C:<br>    c.cleanup()<br>   case &lt;-c.quit:<br>    ticker.Stop()<br>    return<br>   }<br>  }<br> }()<br><br> return c<br>}<br><br>func (c *Cache) Set(key string, value any) error {<br> c.mx.Lock()<br> defer c.mx.Unlock()<br><br> if key == &quot;&quot; || value == nil {<br>  return fmt.Errorf(&quot;cache key/value is invalid&quot;)<br> }<br><br> var expiry int64<br> if c.defaultTTL &gt; 0 {<br>  expiry = time.Now().Add(c.defaultTTL).UnixNano()<br> }<br><br> c.cacheMap[key] = item{value: value, ttl: expiry}<br> return nil<br>}<br><br>func (c *Cache) Get(key string) (any, bool) {<br> c.mx.Lock()<br> defer c.mx.Unlock()<br><br> it, exists := c.cacheMap[key]<br> if !exists {<br>  return nil, false<br> }<br><br> // Expiry Check<br> if it.ttl &gt; 0 &amp;&amp; time.Now().UnixNano() &gt; it.ttl {<br>  delete(c.cacheMap, key)<br>  return nil, false<br> }<br><br> return it.value, true<br>}<br><br>func (c *Cache) Del(key string) bool {<br> c.mx.Lock()<br> defer c.mx.Unlock()<br><br> _, exists := c.cacheMap[key]<br> if !exists {<br>  return false<br> }<br> delete(c.cacheMap, key)<br> return true<br>}<br><br>func (c *Cache) cleanup() {<br> c.mx.Lock()<br> defer c.mx.Unlock()<br><br> now := time.Now().UnixNano()<br> for k, it := range c.cacheMap {<br>  if it.ttl &gt; 0 &amp;&amp; now &gt; it.ttl {<br>   delete(c.cacheMap, k)<br>  }<br> }<br>}<br><br>func (c *Cache) StopCleanup() {<br> close(c.quit)<br>}</pre><p>First, we create the ICache interface so we can declare the cache in a loosely-coupled manner.</p><p>Then we create the Cache struct:</p><ul><li><strong>cacheMap</strong>— A map[string]item for cached data.</li><li><strong>mx</strong> — A sync.Mutex to protect concurrent access to the map. You can read more about Mutexes here: <a href="https://medium.com/stackademic/what-are-mutexes-in-golang-learn-in-3-minutes-16c196e65e3d">What Are Mutexes in Golang In 3 Minutes</a></li><li><strong>quit</strong> — Unbuffered Channel used by StopCleanup() to stop the Goroutine running the background cleaner in NewCache. You can read more about Channels here: <a href="https://medium.com/stackademic/what-are-channels-in-golang-learn-in-3-minutes-f5d5065e52c2">What are Channels in Golang? Learn in 3 Minutes</a></li><li><strong>ttl</strong> — time-to-live for cache entries in NewCache.</li></ul><p>NewCache initialises the Cache struct and starts the Goroutine that runs indefinitely until stopped via the StopCleanup.</p><p>It’s main purpose is to trigger the &lt;-ticker.C channel in the select statement after a set duration to call cleanup() to invalidate the cache that’s reached it’s TTL.</p><p>The main methods:</p><ul><li>Get(key string) (any, bool)— Checks if the cache key exists. If it does check it’s TTL and if it’s not expired return it for a cache-hit. Otherwise it’s invalid and we get a cache-miss.</li><li>Set(key string, value error) error — Add the cache key/val to our map.</li><li>Del(key string) bool — If it exists, delete the cache key.</li></ul><h4>Choose a Caching Strategy</h4><p>Next, we need to decide on our caching strategy.</p><p>As discussed in “Different Types of Cache Strategies” section above there are many strategies, which have their benefits and trade-offs.</p><p>In this section, we’ll explore Write-Through and Write-Back caching examples.</p><p><strong>Write-Through Example:</strong></p><p>Every write updates both the cache and the DB synchronously.</p><ul><li>User calls the TransactionsHistoryAPI handler to update details.</li><li>The handler updates the cache immediately.</li><li>The same update is then written to the database.</li></ul><p>This ensures strong consistency between the cache and the database.</p><p>However, as a trade-off, it adds latency to writes due to the synchronous operations.</p><p>Let’s demonstrate this with a handler in TransactionsHistoryAPI called UpdateTransactionHandler.</p><pre>// Write-Through: update cache and DB synchronously<br>func (m *TransactionModel) UpdateTransactionHistory(h *data.TransactionHistory) error {<br> if err := m.cache.Set(h.UserID, h); err != nil {<br>  return err<br> }<br> if err := m.db.Update(h); err != nil {<br>  return err<br> }<br> return nil<br>}</pre><p>In the snippet we simply call cache.Set followed by the DB to update our Cache with the UserID and the transaction data.</p><p>But, there’s a drawback here.</p><p>What if our DB transaction fails, this leaves us with inconsistent cache and DB states.</p><p>We can swap these around so we update our DB first then cache, meaning the DB is the source of truth. Though that could mean we have a stale cache if the cache fails to update. So we could do the following invalidate-on-failure solution.</p><pre>// Write-Through: update DB and Cache synchronously<br>func (m *TransactionModel) UpdateTransactionHistory(h *data.TransactionHistory) error {<br>    // 1. Write to DB first<br>    if err := m.db.Update(h); err != nil {<br>        // ensure cache isn&#39;t newer than DB<br>        _ = m.cache.Del(h.UserID)<br>        return err<br>    }<br><br>    // 2. Update cache (best-effort, but delete on failure to avoid staleness)<br>    if err := m.cache.Set(h.UserID, h); err != nil {<br>        _ = m.cache.Del(h.UserID) // drop stale entry<br>        // log.Printf(&quot;cache update failed for user %s: %v&quot;, h.UserID, err)<br>    }<br><br>    return nil<br>}</pre><p>Now, if the DB fails, we delete the cache to prevent stale data. If the cache update fails, the cache entry is also deleted. Subsequent read requests will fetch fresh data from the DB, update the cache, and maintain consistency. At worst, the cache is empty and a DB lookup is required.</p><p><strong>Write-Back Example:</strong></p><p>Writes go to the cache first, then the DB is updated asynchronously.</p><ul><li>User calls the TransactionsHistoryAPI handler to update details.</li><li>The handler updates the cache immediately.</li><li>A background goroutine updates the database after.</li></ul><p>This approach improves performance and reduces write latency.</p><p>However, as a trade-off, it risks losing data if the cache crashes before the database is updated.</p><p>Let’s modify the UpdateTransactionHandler function above to implement Write-Back:</p><pre>func (m *TransactionModel) UpdateTransactionHistory(h *data.TransactionHistory) error {<br> if err := m.cache.Set(h.UserID, h); err != nil {<br>  return err<br> }<br> go func() {<br>  if err := m.db.Update(h); err != nil {<br>   // log/handle error here if needed<br>  }<br> }()<br> return nil<br>}</pre><p>In the snippet, the cache is updated first, and the function returns immediately to achieve low write latency. Our DB is then updated asynchronously in the Goroutine at the trade-off of durability for speed.</p><p>However, we can mitigate the durability trade-off with additional complexity.</p><p>For example, you could push the DB update to a durable message queue, such as Kafka, ensuring that data is not lost in the event of a system crash.</p><pre>func (m *TransactionModel) UpdateTransactionHistory(h *data.TransactionHistory) error {<br> // 1. Write to cache immediately<br> if err := m.cache.Set(h.UserID, h); err != nil {<br>  return err<br> }<br><br> // 2. Push async event to Kafka for DB persistence<br> go func(h *data.TransactionHistory) {<br>  // Serialize transaction history (JSON as an example)<br>  msg, err := json.Marshal(h)<br>  if err != nil {<br>   // log.Printf(&quot;failed to marshal transaction history: %v&quot;, err)<br>   return<br>  }<br><br>  kafkaMsg := &amp;m.kafka.Message{<br>   Topic: &quot;transaction-history-updates&quot;,<br>   Key:   []byte(h.UserID),<br>   Value: msg,<br>  }<br><br>  if err := m.kafkaProducer.WriteMessages(context.Background(), *kafkaMsg); err != nil {<br>   // log.Printf(&quot;failed to push update to Kafka for user %s: %v&quot;, h.UserID, err)<br>  }<br> }(h)<br><br> return nil<br>}</pre><p>In this example, we update the cache immediately as before. However, in the Goroutine, we asynchronously send the transaction to the Kafka Topic transaction-history-updates. A consumer service can then update the DB.</p><p>This approach combines the low-latency benefits of Write-Back caching with the durability guarantees of Kafka.</p><p>The trade-off is added complexity in implementing and maintaining the message queue and consumer service.</p><h3>Summary</h3><p>In summary, we covered what caching is, why we need it, the different types of caching strategies, and how to implement a caching layer in Golang APIs.</p><p>Cache is an in-memory store used to hold frequently accessed data. In system design, it acts as an intermediary between the API and the DB.</p><p>Its primary function is to boost performance by serving frequently used data from memory and to protect the database from repeated, time-consuming requests.</p><p>Caching introduces additional complexity in terms of managing, updating, and invalidating cache entries. It is better suited for APIs that operate at a high scale. Signs that your API may need a cache include: high DB CPU/IO usage, rising request latency, throughput strain on the DB, and frequently repeated queries.</p><p>We demonstrated a basic cache implementation using a sync.Map protected by a sync.Mutex (<a href="https://medium.com/stackademic/what-are-mutexes-in-golang-learn-in-3-minutes-16c196e65e3d">What Are Mutexes in Golang In 3 Minutes</a>) for concurrency protection and a TTL to automatically invalidate cache entries after a set duration. We also explored caching strategies such as Write-Through, which updates the cache and DB synchronously, and Write-Back, which updates the cache immediately and then asynchronously updates the DB.</p><p>This foundation allows you to extend your cache further with eviction policies like Least Recently Used (LRU) or Least Frequently Used (LFU). You can also replace the in-memory store with Redis when scaling horizontally for high-scale systems, enabling a Distributed Cache accessible by multiple API replicas.</p><h3>Links</h3><p>If you have any questions/suggestions you can contact me below:</p><p><a href="https://www.linkedin.com/in/luke-sloane-bulger/">Linkedln</a></p><p>Follow me on Medium: <a href="https://medium.com/u/f068ade2f3fe?source=post_page-----6799782d7cb5--------------------------------">Luke Sloane-Bulger</a></p><figure><a href="https://www.buymeacoffee.com/lukesb"><img alt="" src="https://cdn-images-1.medium.com/max/170/1*WfbwTpxi0c0k2Vwzp3s5yg.png" /></a><figcaption>Found this article useful? Feel free to buy me a coffee by clicking the button above</figcaption></figure><h3>A message from our Founder</h3><p><strong>Hey, </strong><a href="https://linkedin.com/in/sunilsandhu"><strong>Sunil</strong></a><strong> here.</strong> I wanted to take a moment to thank you for reading until the end and for being a part of this community.</p><p>Did you know that our team run these publications as a volunteer effort to over 3.5m monthly readers? <strong>We don’t receive any funding, we do this to support the community. ❤️</strong></p><p>If you want to show some love, please take a moment to <strong>follow me on </strong><a href="https://linkedin.com/in/sunilsandhu"><strong>LinkedIn</strong></a><strong>, </strong><a href="https://tiktok.com/@messyfounder"><strong>TikTok</strong></a>, <a href="https://instagram.com/sunilsandhu"><strong>Instagram</strong></a>. You can also subscribe to our <a href="https://newsletter.plainenglish.io/"><strong>weekly newsletter</strong></a>.</p><p>And before you go, don’t forget to <strong>clap</strong> and <strong>follow</strong> the writer️!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cea87a260e21" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/how-to-implement-cache-in-your-golang-api-cea87a260e21">How To Implement Cache in Your Golang API</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How To Implement Rate Limiting in Your Golang API]]></title>
            <link>https://blog.stackademic.com/how-to-implement-rate-limiting-in-your-golang-api-141e1b391c60?source=rss-f068ade2f3fe------2</link>
            <guid isPermaLink="false">https://medium.com/p/141e1b391c60</guid>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[rate-limiting]]></category>
            <category><![CDATA[tutorial]]></category>
            <dc:creator><![CDATA[Luke Sloane-Bulger]]></dc:creator>
            <pubDate>Mon, 30 Jun 2025 10:00:58 GMT</pubDate>
            <atom:updated>2025-06-30T10:00:58.935Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yB6YySe-q8Xjjuf-7bpDcQ.png" /><figcaption>How To Implement Rate Limiting In 3 Minutes</figcaption></figure><p>Implementing a rate limiter is essential for building efficient and resilient APIs.</p><p>Rate Limiting acts as a protection layer in any API.</p><p>It places a cap on the number of requests a client can make within a specified timeframe.</p><p>This safeguards your system’s resources, assets, and costs.</p><p>In this article, we’ll explore what a rate limiter is, why it is needed and provide a practical solution on how to effectively implement it in Golang.</p><h3>What is a Rate Limiter?</h3><p>A rate limiter is a technique used to protect APIs.</p><p>Rate limiting serves as a gatekeeper by protecting the API from how often a user or client can access an API in a specified time window.</p><p>It limits excessive or abusive usage by enforcing thresholds on request rates.</p><p>This helps ensure the API remains available and responsive for legitimate users, especially under high load.</p><p>By filtering out excessive or suspicious traffic like bots, scripts, or bad actors rate limiting protects backend resources and ensures legitimate users receive fair access.</p><p>Over time, this improves overall performance, availability, scalability, and reduces infrastructure costs by ensuring resources are only used by legitimate users.</p><h3>Why Do We Need a Rate Limiter?</h3><p>A rate limiter is critical for any production API.</p><p>It prevents systems from being overwhelmed by excessive requests and helps protect underlying resources.</p><p>Consider a scenario where a bad actor launches a Denial-of-Service (DoS) attack by flooding your API with thousands of requests.</p><p>This attack can degrade performance or even cause a system outage.</p><p>Rate limiting helps prevent such attacks by capping request rates.</p><p>It also promotes fair usage by ensuring no single user or client can monopolise system resources, allowing equal access for all users.</p><p>Furthermore, rate limiting aids in managing resource utilisation, avoiding resource starvation, and maintaining high availability under load.</p><p>In short, it’s a simple yet powerful mechanism that safeguards against overuse, enhances stability, and supports scalability.</p><h3>Types of Rate Limiters</h3><p>There are several common algorithms used to implement rate limiting, each with its own trade-offs:</p><p>Fixed Window — This is one of the simplest algorithms to implement. It works well for applications with fixed quotas per time window, such as per-minute/hour limits. Trade-offs: prone to burst traffic at window boundaries. For example, if a script knows when the window resets, it could send the maximum number of requests at the end of one window and again at the start of the next, which basically doubles the allowed traffic.</p><p>Sliding Window — Similar to Fixed Window, but instead of a static reset point, it tracks usage within a rolling window based on the timestamp of each request. This approach smooths out burst traffic and avoids sharp spikes, providing more consistent enforcement. Trade-offs: it’s more complex to implement and requires additional memory to track the request history.</p><p>Token Bucket — Requests are allowed as long as tokens are available in the bucket. Tokens are added at a fixed rate over time. This allows for short bursts of traffic while enforcing a steady average rate. Trade-offs: allows uneven traffic if enough tokens have accumulated and requires complexity to implement token refill and tracking.</p><p>Leaky Bucket — Similar to Token Bucket, but with a fixed outflow rate. Excess requests are queued or dropped if the bucket is full. It smooths out bursts by processing requests at a constant pace. Trade-offs: burst traffic is slowed, not blocked, so under sustained overload, the queue may overflow and requests are dropped or delayed.</p><p>For this article, we’ll focus on implementing the Fixed Window approach.</p><h3>How Do We Implement a Rate Limiter?</h3><p>There are many ways to implement a rate limiter.</p><p>From third-party packages or building your own native solution that you can control and expand on.</p><p>In this article, we’ll focus on a native solution to leverage Golang’s in-built packages.</p><p>This approach is simple, flexible, and easy to integrate into your projects.</p><p>Let’s say we have a RESTful API called TransactionAPI.</p><p>We can create a rateLimiter package in TransactionAPI that’s called at the top of the endpoint handlers called rateLimiter().</p><p>rateLimiter.go</p><pre>type RateLimiterStruct struct {<br> requestTracker map[string]int<br> limit          int<br> window         time.Duration<br> mx             sync.Mutex<br>}<br><br>func NewRateLimiter(limit int, window time.Duration) *RateLimiterStruct {<br> return &amp;RateLimiterStruct{<br>  requestTracker: make(map[string]int),<br>  limit:          limit,<br>  window:         window,<br>  mx:             sync.Mutex{},<br> }<br>}<br><br>func (r *RateLimiterStruct) IsRequestAllowed(ipAddress string) bool {<br> r.mx.Lock()<br> defer r.mx.Unlock()<br><br> count, exists := r.requestTracker[ipAddress]<br><br> if !exists {<br>  r.requestTracker[ipAddress] = 1<br>  // Start a timer to reset this IP’s counter<br>  go func() {<br>   time.Sleep(r.window)<br>   r.mx.Lock()<br>   defer r.mx.Unlock()<br>   delete(r.requestTracker, ipAddress)<br>  }()<br>  return true<br> }<br><br> if count &gt;= r.limit {<br>  return false<br> }<br><br> r.requestTracker[ipAddress]++<br> return true<br>}</pre><p>First we declare RateLimiterStruct with four members:</p><ul><li>requestTracker - a map where the key is the identifier for the request like the user’s IP Address and the value being a counter. This will increment each time a request for this IP Address is made.</li><li>limit - the request limit, e.g 1000 requests.</li><li>window - the time duration for the window, e.g 30 minutes.</li><li>mx - sync.Mutex mutually exclusive lock to protect requestTracker map from concurrent requests. You can read more about Mutexes here: <a href="https://medium.com/stackademic/what-are-mutexes-in-golang-learn-in-3-minutes-16c196e65e3d">What Are Mutexes in Golang In 3 Minutes</a></li></ul><p>NewRateLimiter is the constructor function to instantiate the struct values.</p><p>IsRequestAllowed is the function with the responsibility of determining if the request is permitted or not.</p><p>First we lock the function with the sync.Mutex (a defer is declared to unlock the function at the end of the workflow), then check if the User’s IP Address exists in our requestTracker.</p><p>If the IP Address doesn’t exist, then it’s our first time here so we add the IP Address and set the request tracking to 1.</p><p>Then we start a Goroutine with the purpose of sleeping until the Fixed Window is finished, when it is the IP Address will be deleted from the map.</p><p>Following requests for this IP Address will then enter a basic check to find if the request tracker is greater than the rate limiter’s set limit.</p><p>If it is, return false to block the request.</p><p>If it isn’t, allow the request to proceed.</p><p>Example usage of this would be to initialise the rate limiter in the API set up and then call it at the top of each handler like CreateTransactions below:</p><pre>func (t *TransactionsControllerStruct) CreateTransactions(w http.ResponseWriter, r *http.Request) {<br> ...<br><br> // Get the IP Address from the request<br> ipAddr, _, err := net.SplitHostPort(r.RemoteAddr)<br><br> if err != nil {<br>  http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)<br>  return<br> }<br><br> // Call the rate limiter. If the request exceeds the limit in the Fixed Window. Return 429 HTTP Status<br> if !t.rl.IsRequestAllowed(ipAddr) {<br>  http.Error(w, http.StatusText(http.StatusTooManyRequests), http.StatusTooManyRequests)<br>  return<br> }<br>...</pre><p>However, the rate limiter would be better suited inside a Middleware Layer to decouple this responsibility from your handler.</p><p>Middleware is a chain of functions called before your handler.</p><p>The workflow may look like: user calls your endpoint, logging middleware is called, followed by rate limiter middleware, followed by authentication middleware, and finally your handler with the core functionality.</p><p>An example of moving this functionality to a Middleware Layer would look like the below:</p><pre>func RateLimiterMiddleware(rl rateLimiter.IRateLimiter) func(http.HandlerFunc) http.HandlerFunc {<br> return func(next http.HandlerFunc) http.HandlerFunc {<br>  return func(w http.ResponseWriter, r *http.Request) {<br><br>   // Get the IP Address from the request<br>   ipAddr, _, err := net.SplitHostPort(r.RemoteAddr)<br>   if err != nil {<br>    http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)<br>    return<br>   }<br><br>   // Call the rate limiter. If the request exceeds the limit in the Fixed Window. Return 429 HTTP Status<br>   if !rl.IsRequestAllowed(ipAddr) {<br>    http.Error(w, http.StatusText(http.StatusTooManyRequests), http.StatusTooManyRequests)<br>    return<br>   }<br><br>   next.ServeHTTP(w, r) // Go to next step in the chain.<br>  }<br> }<br>}</pre><p>Here we shift this responsibility from the CreateTransactions handler and move it into the Middleware Layer in RateLimiterMiddleware function.</p><p>Like before this gets the user’s IP address, calls the IsRequestAllowed from the rate limiter package to check if the request is allowed or not.</p><p>If it isn’t allowed due to exceeding the Fixed Rate Limiter Window the HTTP 429 Too Many Requests status is returned.</p><p>Otherwise the next function in the chain is called.</p><p>If you want to learn more about implementing a Middleware Layer in your APIs you can read more here: <a href="https://medium.com/stackademic/how-to-implement-middleware-in-your-golang-api-d2da8b14a928">How To Implement Middleware In Your Golang API</a>.</p><h3>Rate Limiters in Distributed Systems</h3><p>What about Distributed Systems though?</p><p>If we have multiple instances of the same API for load balancing concerns our current rate limiter implementation would be problematic as each instance would have its own request tracker.</p><p>In a distributed setup, each API instance can enforce its own rate limiting, but this can lead to inconsistencies when requests are load-balanced across multiple nodes.</p><p>To address this inconsistency you can use a distributed rate limiting approach.</p><p>This could be a shared store that each API instances makes a call to so we can track the number of requests across API replicas.</p><p>Redis can be used for this use case to store and update request counters in real time across instances.</p><p>This enables a consistent view of request counts and prevents circumvention of limits by switching servers.</p><p>In terms of scalability, using a centralised cache decouples rate limiting from application nodes, allowing the system to scale horizontally.</p><h3>Summary</h3><p>In this article, we covered what rate limiting is, why it’s important, the main types of rate limiters, and how to implement a simple Fixed Window rate limiter in Golang using only native packages.</p><p>Rate limiting is a critical protection layer for any production API. It prevents systems from being overwhelmed by excessive requests. This keeps our system performant for our users. Without it, your API could be vulnerable to spikes in traffic or malicious attacks like Denial-of-Service (DoS).</p><p>There are different algorithms for rate limiting — Fixed Window, Sliding Window, Token Bucket, and Leaky Bucket — each with its own strengths and trade-offs. Fixed Window is straightforward and works well for simple use cases with predictable quotas, but can be prone to bursts at window boundaries.</p><p>We also looked at how to move rate limiting logic into a Middleware Layer for better separation of concerns.</p><p>It’s important to note for distributed systems, a single-instance limiter isn’t enough — using a shared store like Redis ensures consistent rate limiting across multiple servers.</p><p>In short, a well-implemented rate limiter improves performance, protects resources, and helps APIs scale reliably under load. By understanding the core concepts and trade-offs, you can choose and adapt an approach that best fits your system’s needs.</p><h3>Links</h3><p>If you have any questions/suggestions you can contact me below:</p><p><a href="https://www.linkedin.com/in/luke-sloane-bulger/">LinkedIn</a></p><p>Follow me on Medium: <a href="https://medium.com/u/f068ade2f3fe?source=post_page-----6799782d7cb5--------------------------------">Luke Sloane-Bulger</a></p><figure><a href="https://www.buymeacoffee.com/lukesb"><img alt="" src="https://cdn-images-1.medium.com/max/170/1*WfbwTpxi0c0k2Vwzp3s5yg.png" /></a><figcaption>Found this article useful? Feel free to buy me a coffee by clicking the button above</figcaption></figure><h3>Thanks for reading. If you enjoyed this article you may like the below:</h3><p><a href="https://medium.com/stackademic/how-to-implement-middleware-in-your-golang-api-d2da8b14a928">How To Implement Middleware In Your Golang API</a></p><p><a href="https://medium.com/stackademic/what-are-mutexes-in-golang-learn-in-3-minutes-16c196e65e3d">What Are Mutexes in Golang In 3 Minutes</a></p><p><a href="https://medium.com/stackademic/how-to-implement-a-semaphore-concurrency-pattern-in-golang-3a51e5e517a8">How To Implement a Semaphore Concurrency Pattern in Golang</a></p><h3>Thank you for being a part of the community</h3><p><em>Before you go:</em></p><ul><li>Be sure to <strong>clap</strong> and <strong>follow</strong> the writer ️👏<strong>️️</strong></li><li>Follow us: <a href="https://x.com/inPlainEngHQ"><strong>X</strong></a> | <a href="https://www.linkedin.com/company/inplainenglish/"><strong>LinkedIn</strong></a> | <a href="https://www.youtube.com/@InPlainEnglish"><strong>YouTube</strong></a> | <a href="https://newsletter.plainenglish.io/"><strong>Newsletter</strong></a> | <a href="https://open.spotify.com/show/7qxylRWKhvZwMz2WuEoua0"><strong>Podcast</strong></a> | <a href="https://twitch.tv/inplainenglish"><strong>Twitch</strong></a></li><li><a href="https://differ.blog/"><strong>Start your own free AI-powered blog on Differ</strong></a> 🚀</li><li><a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Join our content creators community on Discord</strong></a> 🧑🏻‍💻</li><li>For more content, visit <a href="https://plainenglish.io/"><strong>plainenglish.io</strong></a> + <a href="https://stackademic.com/"><strong>stackademic.com</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=141e1b391c60" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/how-to-implement-rate-limiting-in-your-golang-api-141e1b391c60">How To Implement Rate Limiting in Your Golang API</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What Are Mutexes in Golang? Learn in 3 Minutes]]></title>
            <link>https://blog.stackademic.com/what-are-mutexes-in-golang-learn-in-3-minutes-16c196e65e3d?source=rss-f068ade2f3fe------2</link>
            <guid isPermaLink="false">https://medium.com/p/16c196e65e3d</guid>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[golang-tutorial]]></category>
            <category><![CDATA[concurrency]]></category>
            <category><![CDATA[mutex]]></category>
            <dc:creator><![CDATA[Luke Sloane-Bulger]]></dc:creator>
            <pubDate>Tue, 27 May 2025 10:30:33 GMT</pubDate>
            <atom:updated>2025-05-27T10:30:33.392Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SRpRm8hXP1oeEvLFffk2tw.png" /><figcaption>Go Mutex in 3 Minutes</figcaption></figure><p>Protecting shared resources is essential for building concurrent and efficient applications.</p><p>One common way to achieve this is by using a <em>Mutex</em>.</p><p>In this article, we’ll explore what a Mutex is and provide an example of how to implement it effectively in Golang.</p><h3>What is a Mutex?</h3><p>A Mutex (<em>mutual exclusion</em>) prevents multiple threads from accessing the same shared resource simultaneously.</p><p>It provides locking and unlocking functionality to ensure only one thread can access the shared resource at a time.</p><p>Imagine a queue of people in front of a door that leads to a room.</p><p>Only one person is allowed in the room at a time.</p><p>When someone enters, the door locks.</p><p>Once they finish their task and exit, the door unlocks, allowing the next person in. This process repeats for each person in the queue.</p><p>Now, let’s map this analogy:</p><ul><li>The <strong>room</strong> is our function.</li><li>The <strong>people</strong> are Threads.</li><li>The <strong>door lock</strong> is the Mutex — it protects access to the function.</li></ul><p>Let’s consider a scenario where a Go API uses a map as a key-value store.</p><p>This API is accessed concurrently by multiple users.</p><p>A standard map in Go is not safe for concurrent use — multiple writes can lead to race conditions, data loss and corruption from overwrites.</p><p>To prevent this, we use sync.Mutex from Go’s standard library.</p><p>It ensures only one Goroutine can access the map at a time.</p><p>If one Goroutine calls mutex.Lock(), any subsequent call to mutex.Lock() by another Goroutine will block until the first Goroutine calls mutex.Unlock().</p><p>For example, in the below code snippet we have GoRoutineConcurrentMapAccess() function.</p><p>This function has a taskMap and launches two Goroutines.</p><p>Each Goroutines can concurrently access the taskMap so we protect it using sync.Mutex.</p><p>To do this we call mutex.Lock() at the start of the Goroutine.</p><p>When the Goroutine finishes it calls mutex.Unlock in the deferred function (defer is called when the function finishes).</p><pre>func GoRoutineConcurrentMapAccess() {<br> var wg sync.WaitGroup<br> wg.Add(2) // Add two jobs<br> var taskMap = make(map[string]string)<br> var mutex sync.Mutex<br><br> go func() {<br>  log.Default().Println(&quot;Goroutine 1 Starts&quot;)<br>  mutex.Lock()<br>  defer mutex.Unlock()<br>  log.Default().Println(&quot;Goroutine 1 Writes&quot;)<br>  taskMap[&quot;Key1&quot;] = &quot;Val1&quot;<br>  log.Default().Println(&quot;Goroutine 1 Finished&quot;)<br>  wg.Done() // Job Complete<br> }()<br><br> go func() {<br>  log.Default().Println(&quot;Goroutine 2 Starts&quot;)<br>  mutex.Lock()<br>  defer mutex.Unlock()<br>  time.Sleep(5 * time.Second) // Pause for 5 seconds.<br>  log.Default().Println(&quot;Goroutine 2 Writes&quot;)<br>  taskMap[&quot;Key2&quot;] = &quot;Val2&quot;<br>  log.Default().Println(&quot;Goroutine 2 Finished&quot;)<br>  wg.Done() // Job Complete<br> }()<br><br> wg.Wait() // Block until both Goroutines are done.<br><br> //Iterate over the map<br> for key := range taskMap {<br>  log.Default().Println(taskMap[key])<br> }<br>}</pre><p>Executing the above will produce the below output:</p><pre>$ go run .<br>2025/05/24 16:54:42 Goroutine 2 Starts<br>2025/05/24 16:54:42 Goroutine 1 Starts<br>2025/05/24 16:54:47 Goroutine 2 Writes<br>2025/05/24 16:54:47 Goroutine 2 Finished<br>2025/05/24 16:54:47 Goroutine 1 Writes<br>2025/05/24 16:54:47 Goroutine 1 Finished<br>2025/05/24 16:54:47 Val2<br>2025/05/24 16:54:47 Val1</pre><p>You can see in the above example, Goroutine 2 acquires the lock first, blocking Goroutine 1.</p><p>Goroutine 2 has acquired the lock with mutex.Lock() at this point. This means that Goroutine 1 is now blocked.</p><p>Once the five seconds has passed. Goroutine 2 writes to taskMap and calls the mutex.Unlock().</p><p>Now, Goroutine 1 can acquire the lock with mutex.Lock() and writes to the taskMap and finishes.</p><h3>How To Implement a Mutex?</h3><p>Implementing sync.Mutex is straightforward.</p><p>In this section, we’ll demonstrate a simple RESTful API that serves as a basic key-value store, with the values stored in a Go map.</p><p>Each HTTP method (GET, PUT, DELETE) will access the shared map, and we’ll use a sync.Mutex to protect these operations from concurrent access issues.</p><p>Endpoints:</p><p>GET - localhost:8080/v1/kvs?key={key}</p><p>PUT - localhost:8080/v1/kvs?key={key}</p><p>Payload Example:</p><pre>{<br>    &quot;Weight&quot;: 180,<br>    &quot;Reps&quot;: 5<br>}</pre><p>DELETE - localhost:8080/v1/kvs?key={key}</p><p>Now, let’s jump into the code snippet of the Key Value Store API.</p><p>Below we declare KVSStore struct with a Mutex and a map to store the key/values.</p><p>There’s a single RESTful endpoint v1/kvs which calls either Get(), Put(), Del() depending on the HTTP method used.</p><p>Each of these methods immediately applies a lock to prevent other concurrent requests from accessing the method.</p><p>Then once the map has been written too or read from and the function finishes it then unlocks to allow the next request.</p><pre>func main() {<br> KVSAPI()<br>}<br><br>type KVSStore struct {<br> mx    sync.Mutex<br> store map[string][]byte<br>}<br><br>func KVSAPI() {<br> kvs := NewKVSStore()<br> http.HandleFunc(&quot;/v1/kvs&quot;, func(w http.ResponseWriter, r *http.Request) {<br>  switch r.Method {<br>  case http.MethodGet:<br>   kvs.Get(w, r)<br>  case http.MethodPut:<br>   kvs.Put(w, r)<br>  case http.MethodDelete:<br>   kvs.Del(w, r)<br>  default:<br>   http.Error(w, http.StatusText(http.StatusMethodNotAllowed), http.StatusMethodNotAllowed)<br>  }<br> })<br><br> if err := http.ListenAndServe(&quot;:8080&quot;, nil); err != nil {<br>  log.Default().Println(err)<br>  return<br> }<br><br> log.Default().Println(&quot;Listening on localhost:8080&quot;)<br>}<br><br>func NewKVSStore() *KVSStore {<br> return &amp;KVSStore{<br>  mx:    sync.Mutex{},<br>  store: make(map[string][]byte),<br> }<br>}<br><br>func (kvs *KVSStore) Get(w http.ResponseWriter, r *http.Request) {<br> kvs.mx.Lock()<br> defer kvs.mx.Unlock()<br><br> key := r.URL.Query().Get(&quot;key&quot;)<br> val, ok := kvs.store[key]<br> if !ok {<br>  http.Error(w, http.StatusText(http.StatusNotFound), http.StatusNotFound)<br>  return<br> }<br> w.Write(val)<br>}<br><br>func (kvs *KVSStore) Put(w http.ResponseWriter, r *http.Request) {<br> kvs.mx.Lock()<br> defer kvs.mx.Unlock()<br> defer r.Body.Close()<br><br> key := r.URL.Query().Get(&quot;key&quot;)<br> val, err := io.ReadAll(r.Body)<br> if err != nil {<br>  http.Error(w, http.StatusText(http.StatusBadRequest), http.StatusBadRequest)<br>  return<br> }<br> kvs.store[key] = val<br> w.WriteHeader(http.StatusCreated)<br>}<br><br>func (kvs *KVSStore) Del(w http.ResponseWriter, r *http.Request) {<br> kvs.mx.Lock()<br> defer kvs.mx.Unlock()<br><br> key := r.URL.Query().Get(&quot;key&quot;)<br> if _, ok := kvs.store[key]; !ok {<br>  http.Error(w, http.StatusText(http.StatusNotFound), http.StatusNotFound)<br>  return<br> }<br> delete(kvs.store, key)<br> w.WriteHeader(http.StatusOK)<br>}</pre><h3>Mutex vs RWMutex</h3><p>In addition to sync.Mutex, Go provides sync.RWMutex.</p><p>The sync.Mutex is unbiased — it provides mutual exclusion on read and write operations.</p><p>This is effective for low-scale use, but in high-concurrency scenarios, it can cause contention — each access blocks others, even reads.</p><p>sync.RWMutex introduces a read/write bias: it allows multiple concurrent readers but only one writer at a time.</p><p>This is ideal for read-heavy applications, improving performance by reducing blocking during reads.</p><p>Below is the above example amended to use a sync.RWMutex.</p><pre>func main() {<br> KVSAPI()<br>}<br><br>type KVSStore struct {<br> mx    sync.RWMutex<br> store map[string][]byte<br>}<br><br>func KVSAPI() {<br> kvs := NewKVSStore()<br> http.HandleFunc(&quot;/v1/kvs&quot;, func(w http.ResponseWriter, r *http.Request) {<br>  switch r.Method {<br>  case http.MethodGet:<br>   kvs.Get(w, r)<br>  case http.MethodPut:<br>   kvs.Put(w, r)<br>  case http.MethodDelete:<br>   kvs.Del(w, r)<br>  default:<br>   http.Error(w, http.StatusText(http.StatusMethodNotAllowed), http.StatusMethodNotAllowed)<br>  }<br> })<br><br> log.Default().Println(&quot;Listening on localhost:8080&quot;)<br> if err := http.ListenAndServe(&quot;:8080&quot;, nil); err != nil {<br>  log.Default().Println(err)<br> }<br>}<br><br>func NewKVSStore() *KVSStore {<br> return &amp;KVSStore{<br>  mx:    sync.RWMutex{},<br>  store: make(map[string][]byte),<br> }<br>}<br><br>func (kvs *KVSStore) Get(w http.ResponseWriter, r *http.Request) {<br> kvs.mx.RLock()<br> defer kvs.mx.RUnlock()<br><br> key := r.URL.Query().Get(&quot;key&quot;)<br> val, ok := kvs.store[key]<br> if !ok {<br>  http.Error(w, http.StatusText(http.StatusNotFound), http.StatusNotFound)<br>  return<br> }<br> w.Write(val)<br>}<br><br>func (kvs *KVSStore) Put(w http.ResponseWriter, r *http.Request) {<br> kvs.mx.Lock()<br> defer kvs.mx.Unlock()<br> defer r.Body.Close()<br><br> key := r.URL.Query().Get(&quot;key&quot;)<br> val, err := io.ReadAll(r.Body)<br> if err != nil {<br>  http.Error(w, http.StatusText(http.StatusBadRequest), http.StatusBadRequest)<br>  return<br> }<br> kvs.store[key] = val<br> w.WriteHeader(http.StatusCreated)<br>}<br><br>func (kvs *KVSStore) Del(w http.ResponseWriter, r *http.Request) {<br> kvs.mx.Lock()<br> defer kvs.mx.Unlock()<br><br> key := r.URL.Query().Get(&quot;key&quot;)<br> if _, ok := kvs.store[key]; !ok {<br>  http.Error(w, http.StatusText(http.StatusNotFound), http.StatusNotFound)<br>  return<br> }<br> delete(kvs.store, key)<br> w.WriteHeader(http.StatusOK)<br>}</pre><p>Notice how the Get() function now uses RLock. This allows for multiple Goroutines to access the shared resource for read operations.</p><p>This small change significantly boosts scalability in scenarios where reads dominate writes.</p><h3>Summary</h3><p>In summary, in this article, we explored what a Mutex is and how to use it in Golang.</p><p>A Mutex (<em>mutual exclusion</em>) prevents multiple threads from accessing the same shared resource simultaneously.</p><p>It provides locking/unlocking functionality to ensure exclusive access to shared resources in concurrent programs.</p><p>sync.Mutex can be used to protect a map from concurrent access, which can lead to data loss, corruption and race conditions</p><p>Above we demonstrated how to use sync.Mutex to protect a map in a simple RESTful API for a Key Value Store. We also compared sync.Mutex with sync.RWMutex, showing how the latter can improve performance in read-heavy scenarios by allowing multiple concurrent readers while still ensuring exclusive access for writers.</p><p>This understanding helps build safer and more efficient concurrent applications in Go.</p><h3>Links</h3><p>If you have any questions/suggestions you can contact me below:</p><p><a href="https://www.linkedin.com/in/luke-sloane-bulger/">Linkedln</a></p><p>Follow me on Medium: <a href="https://medium.com/u/f068ade2f3fe?source=post_page-----6799782d7cb5--------------------------------">Luke Sloane-Bulger</a></p><figure><a href="https://www.buymeacoffee.com/lukesb"><img alt="" src="https://cdn-images-1.medium.com/max/170/1*WfbwTpxi0c0k2Vwzp3s5yg.png" /></a><figcaption>Found this article useful? Feel free to buy me a coffee by clicking the button above</figcaption></figure><h3>Did you like this article? Be sure to share it on social networks. Thanks!</h3><h3>Thank you for being a part of the community</h3><p><em>Before you go:</em></p><ul><li>Be sure to <strong>clap</strong> and <strong>follow</strong> the writer ️👏<strong>️️</strong></li><li>Follow us: <a href="https://x.com/inPlainEngHQ"><strong>X</strong></a> | <a href="https://www.linkedin.com/company/inplainenglish/"><strong>LinkedIn</strong></a> | <a href="https://www.youtube.com/@InPlainEnglish"><strong>YouTube</strong></a> | <a href="https://newsletter.plainenglish.io/"><strong>Newsletter</strong></a> | <a href="https://open.spotify.com/show/7qxylRWKhvZwMz2WuEoua0"><strong>Podcast</strong></a> | <a href="https://differ.blog/inplainenglish"><strong>Differ</strong></a> | <a href="https://twitch.tv/inplainenglish"><strong>Twitch</strong></a></li><li><a href="https://differ.blog/"><strong>Start your own free AI-powered blog on Differ</strong></a> 🚀</li><li><a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Join our content creators community on Discord</strong></a> 🧑🏻‍💻</li><li>For more content, visit <a href="https://plainenglish.io/"><strong>plainenglish.io</strong></a> + <a href="https://stackademic.com/"><strong>stackademic.com</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=16c196e65e3d" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/what-are-mutexes-in-golang-learn-in-3-minutes-16c196e65e3d">What Are Mutexes in Golang? Learn in 3 Minutes</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How To Implement a Semaphore Concurrency Pattern in Golang?]]></title>
            <link>https://blog.stackademic.com/how-to-implement-a-semaphore-concurrency-pattern-in-golang-3a51e5e517a8?source=rss-f068ade2f3fe------2</link>
            <guid isPermaLink="false">https://medium.com/p/3a51e5e517a8</guid>
            <category><![CDATA[semaphore]]></category>
            <category><![CDATA[guides-and-tutorials]]></category>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[concurrency]]></category>
            <category><![CDATA[golang]]></category>
            <dc:creator><![CDATA[Luke Sloane-Bulger]]></dc:creator>
            <pubDate>Mon, 28 Apr 2025 01:06:53 GMT</pubDate>
            <atom:updated>2025-04-28T01:06:53.214Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yd1T9BR0ZmBCb2Nt7wLF5Q.png" /><figcaption>Semaphore Concurrency Pattern In Golang in 3 Minutes</figcaption></figure><p>In this article, we’ll cover the Semaphore Concurrency Pattern and how to implement it in Golang.</p><p>With concurrent programming, managing access to shared resources is a critical aspect that can impact the performance and reliability of an application.</p><p>One technique to manage this is the Semaphore Concurrency Pattern.</p><h3>What is a Semaphore?</h3><p>A Semaphore is a Concurrency Design Pattern used to control access to shared resources by maintaining a count.</p><p>This allows a set number of operations to proceed concurrently, blocking others until space is available.</p><p>Semaphores help manage resource usage and prevent system overload in concurrent programming.</p><p>There are two types:</p><ul><li>Binary Semaphore — Acts like a Mutex (mutually exclusive lock), allowing one Goroutine to access the resource at a time.</li><li>Counting Semaphore — Allows a specified number of Goroutines to access resources concurrently.</li></ul><h3>Why use a Semaphore?</h3><p>Using a Semaphore helps to prevent system exhaustion by limiting the number of concurrent operations.</p><p>Whilst Goroutines are lightweight, without control, a system could easily overwhelm its CPU, memory, or other resources, leading to degraded performance or crashes.</p><p>Semaphores are useful for managing worker pools, limiting API calls and controlling Database connections.</p><p>They provide a simple, effective mechanism for balancing workloads and ensuring reliability in concurrent programming.</p><h3>How To Implement a Semaphore in Golang?</h3><p>Golang doesn’t have an explicit Semaphore type in its standard library.</p><p>However, the sync package has primitives like Mutex and WaitGroup alongside Buffered Channels that can be used to implement a Semaphore easily.</p><p>To create a Binary or Counting Semaphore in Golang, you can use a Buffered Channel.</p><p>A Buffered Channel offers asynchronous behaviour; it’s only blocking for sends when the buffer is full, whilst receiving only blocks when the buffer is empty.</p><p>This makes it ideal for a Semaphore as it won’t create any more Goroutines if the semaphore Buffered Channel is full.</p><p>The buffer size for the Semaphore should be decided on the maximum number of Goroutines you want running concurrently.</p><ol><li>Define the Semaphore: Create a Buffered Channel with a buffer size of the maximum number of Goroutines that you require. One for a Binary Semaphore, and multiple for a Counting Semaphore.</li></ol><pre>semaphore := make(chan struct{}, maxGoroutines)</pre><p>2. Send to the Semaphore: Before a Goroutine accesses the shared resource it must be registered as currently processing to the Buffered Channel. If the Semaphore already reached the maximum capacity, the Goroutine will block until another Goroutine releases the Semaphore.</p><pre>semaphore &lt;- struct{}{} // Register Goroutine</pre><p>3. Receive from the Semaphore: Once the Goroutine completes its job, it should release the Semaphore to allow other Goroutines to access the resource.</p><pre><br>defer func() { &lt;-semaphore }() // Unregister Goroutine</pre><p>4. Example Usage: below, we limit the number of Goroutines performing logging tasks concurrently. Logging is a shared resource, and writing to it without control could lead to performance issues or a jumbled output. Using a Semaphore ensures only a controlled number of Goroutines access the logging operation at the same time.</p><pre>func SimpleSemaphore() {<br> mockLogMap := map[int]string{}<br><br> // Create 20 mock logs<br> for i := 1; i &lt;= 20; i++ {<br>  mockLogMap[i] = &quot;Log &quot; + strconv.Itoa(i) + &quot; Example&quot;<br> }<br><br> maxGoroutines := 1 // Default size<br><br> // Dynamically scale the semaphore if task list is greater than our number of Goroutines, but only if the Num of CPUs allows it.<br> if len(mockLogMap) &gt; maxGoroutines {<br>  maxGoroutines = int(math.Min(float64(len(mockLogMap)), float64(runtime.NumCPU())))<br>  log.Default().Printf(&quot;Goroutines=%d, NumCPU=%d\n&quot;, maxGoroutines, runtime.NumCPU())<br> }<br><br> semaphore := make(chan struct{}, maxGoroutines)<br><br> var wg sync.WaitGroup<br><br> for key := range mockLogMap {<br>  wg.Add(1) // Increment WaitGroup Counter to prevent Function from exiting.<br><br>  go func(ID int) {<br>   // Defer Funcs execute in LIFO order.<br>   defer func() {<br>    if r := recover(); r != nil {<br>     log.Default().Printf(&quot;Recovered from panic: %v\n&quot;, r)<br>    }<br>   }()<br><br>   defer wg.Done() // Mark WaitGroup as complete<br><br>   semaphore &lt;- struct{}{} // Register Goroutine<br><br>   defer func() { &lt;-semaphore }()<br><br>   // Simulating Task<br>   log.Default().Println(mockLogMap[ID])<br>   time.Sleep(500 * time.Millisecond)<br>  }(key)<br> }<br><br> wg.Wait() // Block exit until jobs are complete<br>}</pre><p>In this example, we create twenty mock logs in our mockLogMap dynamically in the for loop.</p><p>The semaphore Buffered Channel is declared to limit the number of Goroutines to a default buffer of 1.</p><p>We dynamically scale the maxGoroutines by calculating the smaller value between the number of mockLogMap items and available CPUs, limiting max Goroutines accordingly.</p><p>The sync.WaitGroup is used to mark the job as ongoing to prevent our SimpleSemaphore func from exiting.</p><p>The Goroutine just sends to the semaphore Buffered Channel to register it before it accesses the shared resource — in this case logging the map value based on the key.</p><p>Once completed the deferred functions execute in a LIFO (Last-In-First-Out) order. First it receives from the semaphore Buffered Channel to unregister the Goroutine to allow other Goroutines to access the shared resource. Then marks the WaitGroup counter as completed. Finally, it runs the recover() block to catch any panics.</p><h3>Summary</h3><p>In summary, we quickly went over the Semaphore Concurrency Pattern, how it works and how to implement it in Golang.</p><p>A Semaphore is a Concurrency Design Pattern used to control access to shared resources by maintaining a count. This allows a set number of operations to proceed concurrently, blocking others until space is available. Semaphores help manage resource usage and prevent system overload in concurrent programming.</p><p>Using a Semaphore helps to prevent system exhaustion by limiting the number of concurrent operations. Semaphores provide a simple, effective mechanism for balancing workloads and ensuring reliability in concurrent programming.</p><p>The Semaphore can simply be created using a Buffered Channel approach alongside other synchronisation primitives. The buffer size is the maximum number of Goroutines you want to be executing concurrently.</p><p>The Semaphore pattern is a powerful tool for managing concurrent access to resources. Implementing a Semaphore using channels and other synchronization primitives from the sync package is both simple and effective.</p><p>By applying this pattern, you can ensure that your Golang applications are robust, efficient, and safe from concurrency-related issues.</p><h3>Links</h3><p>If you have any questions/suggestions you can contact me below:</p><p><a href="https://www.linkedin.com/in/luke-sloane-bulger/">Linkedln</a></p><p>Follow me on Medium: <a href="https://medium.com/u/f068ade2f3fe?source=post_page-----6799782d7cb5--------------------------------">Luke Sloane-Bulger</a></p><figure><a href="https://www.buymeacoffee.com/lukesb"><img alt="" src="https://cdn-images-1.medium.com/max/170/1*WfbwTpxi0c0k2Vwzp3s5yg.png" /></a><figcaption>Found this article useful? Feel free to buy me a coffee by clicking the button above</figcaption></figure><h3>Did you like this article? Be sure to share it on social networks. Thanks!</h3><h3>Thank you for being a part of the community</h3><p><em>Before you go:</em></p><ul><li>Be sure to <strong>clap</strong> and <strong>follow</strong> the writer ️👏<strong>️️</strong></li><li>Follow us: <a href="https://x.com/inPlainEngHQ"><strong>X</strong></a> | <a href="https://www.linkedin.com/company/inplainenglish/"><strong>LinkedIn</strong></a> | <a href="https://www.youtube.com/@InPlainEnglish"><strong>YouTube</strong></a> | <a href="https://newsletter.plainenglish.io/"><strong>Newsletter</strong></a> | <a href="https://open.spotify.com/show/7qxylRWKhvZwMz2WuEoua0"><strong>Podcast</strong></a> | <a href="https://differ.blog/inplainenglish"><strong>Differ</strong></a> | <a href="https://twitch.tv/inplainenglish"><strong>Twitch</strong></a></li><li><a href="https://cofeed.app/"><strong>Check out CoFeed, the smart way to stay up-to-date with the latest in tech</strong></a> <strong>🧪</strong></li><li><a href="https://differ.blog/"><strong>Start your own free AI-powered blog on Differ</strong></a> 🚀</li><li><a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Join our content creators community on Discord</strong></a> 🧑🏻‍💻</li><li>For more content, visit <a href="https://plainenglish.io/"><strong>plainenglish.io</strong></a> + <a href="https://stackademic.com/"><strong>stackademic.com</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3a51e5e517a8" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/how-to-implement-a-semaphore-concurrency-pattern-in-golang-3a51e5e517a8">How To Implement a Semaphore Concurrency Pattern in Golang?</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SOLID Principles In Golang]]></title>
            <link>https://blog.stackademic.com/solid-principles-in-golang-179f92843289?source=rss-f068ade2f3fe------2</link>
            <guid isPermaLink="false">https://medium.com/p/179f92843289</guid>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[solid-design-principles]]></category>
            <category><![CDATA[tutorial]]></category>
            <dc:creator><![CDATA[Luke Sloane-Bulger]]></dc:creator>
            <pubDate>Mon, 07 Apr 2025 06:03:06 GMT</pubDate>
            <atom:updated>2025-04-11T18:56:56.695Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZOlQarXtOmWXyZHJz2UfQw.png" /><figcaption>SOLID Principles in Golang in 3 Minutes</figcaption></figure><p>What are SOLID design principles?</p><p>How would you go about implementing them in Golang?</p><p>In this article, we’ll walk through each of the SOLID principles and demonstrate how to implement them in Golang.</p><p>Whether you’re working on a small project or a large-scale application, applying these principles will help you write code that is both robust and adaptable.</p><h3>What are SOLID Principles?</h3><p>SOLID is a set of five design principles that can help you create maintainable, flexible, and scalable software.</p><p>These are:</p><ul><li>Single-Responsibility Principle (SRP)</li><li>Open-Closed Principle (OCP)</li><li>Liskov Substitution Principle (LSP)</li><li>Interface Segregation Principle (ISP)</li><li>Dependency Inversion Principle (DIP)</li></ul><p>By following these principles, you can write clean and efficient code that’s easier to understand, extend, and maintain.</p><p>In this article, we’ll walk through each of the SOLID principles and provide concise examples in Golang, showing how you can apply them to improve your codebase.</p><h3>S — Single-Responsibility Principle</h3><p>Single-Responsibility Principle (SRP) states that a function, class, or module should have one responsibility and should only have one reason to change.</p><p>When a function or class handles more than one responsibility, it can become complex, difficult to understand and maintain.</p><p>SRP helps isolate changes, reduce complexity, increases readability and reusability of code.</p><h4>Join Handler Without SRP</h4><p>Let’s dive deeper into the example where we have a JoinHandler function that violates the Single-Responsibility Principle (SRP).</p><p>This function is responsible for three distinct responsibilities:</p><ol><li>Validating the user input.</li><li>Registering the user to the Database.</li><li>Sending a notification to the user via email.</li></ol><pre>func JoinHandler(user User) error {<br> // Validate the user<br> if user.Email == &quot;&quot; || user.Password == &quot;&quot; {<br>  return errors.New(&quot;invalid user input&quot;)<br> }<br><br>// Register the user<br> err := database.SaveUser(user)<br> if err != nil {<br>  return err<br> }<br><br>// Send a welcome notification to the user<br> err = notificationService.SendEmail(user.Email, &quot;Welcome!&quot;, &quot;Thanks for joining!&quot;)<br> if err != nil {<br>  return err<br> }<br><br> return nil<br>}</pre><p>The problem with the above JoinHandler is that it has three responsibilities.</p><p>This violates the SRP as the function is doing too much, handling tasks that should be in separate modules.</p><p>If we need to change validation, we may inadvertently affect how users are registered.</p><p>The increased complexity may invite further complexity in future use cases. Think how complex this code snippet could grow when we add new responsibilities like duplicate account checks, logging, and error handling, etc…</p><h4>Join Handler with SRP</h4><p>Now, let’s move onto a JoinHandler implementation with SRP where we break logic into smaller manageable parts.</p><p><strong>User Validation</strong></p><p>ValidateUser function is only responsible for validating user input.</p><pre>func ValidateUser(user User) error {<br> if user.Email == &quot;&quot; || user.Password == &quot;&quot; {<br>  return errors.New(&quot;invalid user input&quot;)<br> }<br> return nil<br>}</pre><p><strong>User Registration</strong></p><p>RegisterUser function is only responsible for calling the database layer to save the user.</p><pre>func RegisterUser(user User) error {<br> return database.SaveUser(user)<br>}</pre><p><strong>Notification Service</strong></p><p>SendWelcomeEmail function is only responsible for sending the welcome email to the user.</p><pre>func SendWelcomeEmail(email string) error {<br> return notificationService.SendEmail(email, &quot;Welcome!&quot;, &quot;Thanks for joining!&quot;)<br>}</pre><p><strong>JoinHandlerThat Delegates These Responsibilities</strong></p><p>Here’s the JoinHandler function refactored to delegate each responsibility to its own function.</p><p>The JoinHandler is now only responsible for orchestrating the flow by calling the services that handle individual responsibilities:</p><pre>func JoinHandler(user User) error {<br> // Validate the user<br> if err := ValidateUser(user); err != nil {<br>  return err<br> }<br><br> // Register the user<br> if err := RegisterUser(user); err != nil {<br>  return err<br> }<br><br> // Send a welcome notification to the user<br> if err := SendWelcomeEmail(user.Email); err != nil {<br>  return err<br> }<br><br> return nil<br>}</pre><p>By breaking the responsibilities into distinct functions, the JoinHandler is now only responsible for orchestrating the calls to the services.</p><p>It delegates each responsibility, improving both clarity and maintainability.</p><p>This achieves a separation of concerns as all functions are isolated making them easier to modify and to create unit tests.</p><p>This approach makes the JoinHandler function much cleaner, readable, and aligned with the Single-Responsibility Principle (SRP).</p><p>It ensures that the code is easier to maintain and extend as the project grows.</p><h3>O — Open-Closed Principle</h3><p>Open Closed Principle (OCP) is where an application is closed for modification, but open for extensibility.</p><p>This means that you should be able to add new functionality to your application without modifying the existing code.</p><p>This helps in keeping your codebase stable while also making it easy to add new features.</p><p>In practical terms, OCP encourages extending functionality via new code rather than changing the existing code.</p><p>This can be achieved through the use of interfaces, polymorphism, or composition.</p><h4>Payment Processor Without OCP</h4><p>Let’s work with Payment Processor implementation without Open-Closed Principle.</p><pre>type Payment struct {<br>  Method string<br>}<br><br>func ProcessPayment(p Payment, amount float64) {<br> if p.Method == &quot;credit_card&quot; {<br>  fmt.Println(&quot;Processing credit card payment:&quot;, amount)<br> } else if p.Method == &quot;paypal&quot; {<br>  fmt.Println(&quot;Processing PayPal payment:&quot;, amount)<br> } else {<br>  fmt.Println(&quot;Unknown payment method&quot;)<br> }<br>}</pre><p>The above ProcessPayment violates OCP as whenever we need to add a new payment like BitCoin or Klarna, we must modify ProcessPayment, which breaks OCP and requires us to then test every payment method as a result.</p><p>This function is not extensible without modification.</p><h4>Payments Processor With OCP</h4><p>Instead of an if-else chain, we can define a IPaymentProcessor interface, so new payment methods can be added without modifying existing code like so:</p><pre>type IPaymentProcessor interface {<br> Pay(amount float64)<br>}</pre><p>We then implement our payment methods from earlier as their own struct with a Pay(amount float64) function to satisfy our interface contract.</p><pre>type CreditCard struct{}<br><br>func (c CreditCard) Pay(amount float64) {<br> fmt.Println(&quot;Processing credit card payment:&quot;, amount)<br>}<br><br>type PayPal struct{}<br><br>func (p PayPal) Pay(amount float64) {<br> fmt.Println(&quot;Processing PayPal payment:&quot;, amount)<br>}</pre><p>Next we can extend by adding new payment methods with Bitcoin and Klarna.</p><pre>type Bitcoin struct{}<br><br>func (b Bitcoin) Pay(amount float64) {<br> fmt.Println(&quot;Processing Bitcoin payment:&quot;, amount)<br>}<br><br>type Klarna struct{}<br><br>func (k Klarna) Pay(amount float64) {<br> fmt.Println(&quot;Processing Klarna payment:&quot;, amount)<br>}</pre><p>Now, we can use Polymorphism to process our payments by passing our IPaymentProcessor interface as a parameter.</p><pre>func ProcessPayment(p IPaymentProcessor, amount float64) {<br> p.Pay(amount)<br>}</pre><p>Example usage:</p><pre>func main() {<br>    // Create a slice of payments that meet the IPaymentProcessor interface contract<br>    payments := []IPaymentProcessor{<br>        CreditCard{},<br>        PayPal{},<br>        Bitcoin{},<br>        Klarna{},<br>    }<br><br>    // Iterate over each of the payments<br>    for _, p := range payments {<br>        ProcessPayment(p, 100.0)<br>    }<br>}</pre><p>Now, our Payment Processor follows OCP.</p><p>To add any new payment methods, simply create a struct with a Pay(amount float64) function to implement the IPaymentProcessor interface without modifying existing code.</p><p>Our Payment Processor remain unchanged, making the system scalable and maintainable.</p><h3>L — Liskov Substitution Principle</h3><p>Liskov Substitution Principle (LSP) states that objects of a superclass should be replaceable by a subclass without affecting functionality.</p><p>In traditional OOP (Object-Oriented Programming), this means that a subclass should extend the behaviour of the parent class while maintaining compatibility.</p><p>In Golang, the Liskov Substitution Principle, although originally imagined for traditional inheritance in mind can still be applied to Golang’s interfaces and struct embedding.</p><p>Let’s focus on an Inheritance (Is-A) and a Composition (Has-A) example.</p><h4>1. Interfaces as Substitutes for Superclasses: Car Is-A Vehicle</h4><p>In this example, the Car type implements the Vehicle interface.</p><p>The Vehicle interface could define general behaviours common to all vehicles.</p><p>For example, starting the engine or moving.</p><p>While Car would provide a specific implementation.</p><p>The idea is that a Car Is-A Vehicle, so anywhere a Vehicle is expected, a Car can be used.</p><pre>package main<br><br>import (<br> &quot;log&quot;<br>)<br><br>func main() {<br> vauxhall := NewCar(&quot;Vauxhall&quot;)<br> skoda := NewCar(&quot;Skoda&quot;)<br> mg := NewCar(&quot;MG&quot;)<br> audi := NewCar(&quot;Audi&quot;)<br><br> Operate(vauxhall)<br> Operate(skoda)<br> Operate(mg)<br> Operate(audi)<br>}<br><br>type IVehicle interface {<br> Start() string<br> Move() string<br>}<br><br>type car struct {<br> Brand string<br>}<br><br>func NewCar(brand string) *car {<br> return &amp;car{<br>  Brand: brand,<br> }<br>}<br><br>func (c *car) Start() string {<br> return c.Brand + &quot; car starts.&quot;<br>}<br><br>func (c *car) Move() string {<br> return c.Brand + &quot; car moves.&quot;<br>}<br><br>func Operate(v IVehicle) {<br> log.Default().Println(v.Start())<br> log.Default().Println(v.Move())<br>}</pre><h4>2. Embedding for Composition: Car Has-An Engine</h4><p>Golang prefers composition over inheritance.</p><p>When you embed one struct inside another, the embedded struct’s methods become part of the outer struct.</p><p>If a derived struct doesn’t break or change the expected behaviour of the embedded struct’s methods, it follows LSP principles.</p><p>Imagine a Car &quot;Has-An&quot; engine.</p><p>Instead of using inheritance, you use embedding to represent this relationship in Go.</p><p>The Engine struct has its own functionality.</p><p>For example, starting the engine and the Car embeds the Engine struct.</p><p>This allows Car to inherit the behaviour of the Engine without modifying it, and it can still be substituted without breaking functionality.</p><pre><br>type engine struct {<br> Type string<br>}<br><br>func NewEngine() *engine {<br> return &amp;engine{}<br>}<br><br>func (e *engine) Start() string {<br> return e.Type + &quot; engine starts.&quot;<br>}<br><br>type car struct {<br> Brand  string<br> engine // Car has-an Engine<br>}<br><br>func NewCar() *car {<br> return &amp;car{}<br>}<br><br>func (c *car) Move() string {<br> return c.Brand + &quot; car moves.&quot;<br>}<br><br>func Operate(c *car) {<br> log.Default().Println(c.Start()) // Uses Engine&#39;s Start method<br> log.Default().Println(c.Move())  // Uses Car&#39;s Move method<br>}</pre><p>In this example, the Car embeds the Engine, meaning the Car &quot;has-an&quot; engine.</p><p>The Car can use the Engine&#39;s Start() method without overriding it.</p><p>You can substitute any Car with an embedded Engine that has the expected behaviour, and it will still function as intended, adhering to LSP.</p><h3>I — Interface Segregation Principle</h3><p>Interface Segregation Principle (ISP) states that clients shouldn’t be forced to depend on interfaces they don’t use.</p><p>This means that rather than having large interfaces with many methods, we should focus on creating concise, specific interfaces tailored to the needs of different clients.</p><h4>Without Interface Segregation Principle</h4><p>Let’s focus on the below IMultiFunctionPointer interface contract that has printing, scanning and faxing functions.</p><pre>type IMultiFunctionPrinter interface {<br> Print(doc string)<br> Scan(doc string)<br> Fax(doc string)<br>}</pre><p>Now, let’s say we want to a basic printer that simply prints documents.</p><pre>type BasicPrinter struct{}<br><br>func (b BasicPrinter) Print(doc string) {<br> fmt.Println(&quot;Printing:&quot;, doc)<br>}<br><br>func (b BasicPrinter) Scan(doc string) {<br> // ❌ This printer doesn&#39;t support scanning, but we must implement it <br> fmt.Println(&quot;Scan not supported!&quot;)<br>}<br><br>func (b BasicPrinter) Fax(doc string) {<br> // ❌ This printer doesn&#39;t support faxing, but we must implement it<br> fmt.Println(&quot;Fax not supported!&quot;)<br>}</pre><p>Here we violate the Interface Segregation Principle as our interface is forcing the developer to have to implement functions that they don’t need just satisfy the contract.</p><p>This leads to empty or misleading implementations, which is bad design.</p><h4>With Interface Segregation Principle</h4><p>To follow ISP, we should split the IMultiFunctionPrinter interface into smaller, concise and focused interfaces.</p><p>First define smaller interfaces like so:</p><pre>type IPrinter interface {<br> Print(doc string)<br>}<br><br>type IScanner interface {<br> Scan(doc string)<br>}<br><br>type IFaxer interface {<br> Fax(doc string)<br>}</pre><p>Then implement interfaces separately.</p><pre>type BasicPrinter struct{}<br><br>func (b BasicPrinter) Print(doc string) {<br> fmt.Println(&quot;Printing:&quot;, doc)<br>}<br><br>type AdvancedScanner struct{}<br><br>func (s AdvancedScanner) Scan(doc string) {<br> fmt.Println(&quot;Scanning:&quot;, doc)<br>}<br><br>type OfficeFaxer struct{}<br><br>func (f OfficeFaxer) Fax(doc string) {<br> fmt.Println(&quot;Faxing:&quot;, doc)<br>}</pre><p>This flexibility allows us to create smaller interfaces where needed and we can just combine them if needed to fix the problematic code snippet from above.</p><p>We do this by using dependency injection to pass types that satisfy the contract so our printer can have printing, scanning and faxing behaviours.</p><pre>type IMultiFunctionDevice interface {<br> IPrinter<br> IScanner<br> IFaxer<br>}<br><br>type AllInOnePrinter struct{}<br><br>func (a AllInOnePrinter) Print(doc string) {<br> fmt.Println(&quot;Printing:&quot;, doc)<br>}<br><br>func (a AllInOnePrinter) Scan(doc string) {<br> fmt.Println(&quot;Scanning:&quot;, doc)<br>}<br><br>func (a AllInOnePrinter) Fax(doc string) {<br> fmt.Println(&quot;Faxing:&quot;, doc)<br>}</pre><p>Example usage:</p><pre>func main() {<br> var printer IPrinter = BasicPrinter{}<br> printer.Print(&quot;Report.pdf&quot;)<br><br> var scanner IScanner = AdvancedScanner{}<br> scanner.Scan(&quot;Document.pdf&quot;)<br><br> var faxer IFaxer = OfficeFaxer{}<br> faxer.Fax(&quot;Contract.pdf&quot;)<br><br> var allInOne IMultiFunctionDevice = AllInOnePrinter{}<br> allInOne.Print(&quot;Manual.pdf&quot;)<br> allInOne.Scan(&quot;Invoice.pdf&quot;)<br> allInOne.Fax(&quot;Agreement.pdf&quot;)<br>}</pre><p>Now, our application follows ISP.</p><p>Each struct only implements the functions that it requires.</p><p>No forced dependencies on unnecessary functions.</p><p>More flexible composition for multi-functional devices if we need to combine our smaller interfaces into one big interface.</p><h3>D — Dependency Inversion Principle</h3><p>Dependency Inversion Principle (DIP) states that high-level modules shouldn’t depend on low-level modules.</p><p>Both should depend on abstractions.</p><p>This helps with decoupling code, making it more flexible, testable, maintainable, and scalable.</p><h4>Without Dependency Inversion Principle</h4><p>Imagine a notification system.</p><p>In this notification system we have a high-level module UserService that has a dependency on a low-level module EmailService.</p><pre>// Low-level module (EmailService)<br>type EmailService struct{}<br><br>func (e EmailService) SendEmail(message string) {<br>    fmt.Println(&quot;Sending email:&quot;, message)<br>}<br><br>// High-level module (UserService)<br>type UserService struct {<br>    emailService EmailService // ❌ Direct dependency on a concrete implementation<br>}<br><br>func (u UserService) NotifyUser() {<br>    u.emailService.SendEmail(&quot;Welcome to our service!&quot;)<br>}<br><br>func main() {<br>    userService := UserService{emailService: EmailService{}}<br>    userService.NotifyUser()<br>}</pre><p>Here we violate Dependency Inversion Principle as our high-level module UserService is now dependent on a low-level module EmailService.</p><p>What if we need to add SMS Service or Web Push Service?</p><p>We’d have to modify UserService directly, which then also violates the Open-Closed Principle (OCP) discussed above.</p><p>This implementation makes it complex to write unit tests and end-to-end tests as we need test multiple notifications if we modify the above code.</p><h4>With Dependency Inversion Principle</h4><p>To follow DIP, we can introduce an interface INotifier so that the UserService is decoupled.</p><p>First define a INotifier interface.</p><pre>type INotifier interface {<br> Notify(message string)<br>}</pre><p>Then add the low-level modules for notification methods use cases with the Notify(message string) to satisfy the interface contract.</p><pre>// Low-level module: EmailNotifier<br>type EmailNotifier struct{}<br><br>func (e EmailNotifier) Notify(message string) {<br> fmt.Println(&quot;Sending Email:&quot;, message)<br>}<br><br>// Low-level module: SMSNotifier<br>type SMSNotifier struct{}<br><br>func (s SMSNotifier) Notify(message string) {<br> fmt.Println(&quot;Sending SMS:&quot;, message)<br>}<br><br>// Low-level module: SMSNotifier<br>type WebPushNotifier struct{}<br><br>func (s WebPushNotifier) Notify(message string) {<br> fmt.Println(&quot;Sending SMS:&quot;, message)<br>}</pre><p>Then inject the interface in high-level module UserService.</p><p>Now it doesn’t depend on concrete implementation and just a contract.</p><pre>// High-level module (UserService)<br>type UserService struct {<br> notifier INotifier // ✅ Depends on abstraction, not a concrete type<br>}<br><br>func (u UserService) NotifyUser() {<br> u.notifier.Notify(&quot;Welcome to our service!&quot;)<br>}</pre><p>Finally, use dependency injection to inject the notification services required for the UserService.</p><pre>func main() {<br>    emailService := UserService{notifier: EmailNotifier{}}<br>    emailService.NotifyUser()<br><br>    smsService := UserService{notifier: SMSNotifier{}}<br>    smsService.NotifyUser()<br>}</pre><p>Now, our application follows DIP.</p><p>UserService is no longer depend on specific concrete implementations and just has a contract to assign the notification services we want to inject into it.</p><p>The code is loosely-coupled, flexible, testable, maintainable, scalable and extendable.</p><p>It follows the Open-Closed Principle since UserService doesn’t need to be modified when we extend by adding more notifiers.</p><h3>Summary</h3><p>In summary, we quickly explored the SOLID Principles and how to implement them in Golang.</p><p>SOLID is a set of five design principles used to create maintainable, scalable applications.</p><p>SOLID stands for:</p><ul><li>Single-Responsibility Principle (SRP) — Functions should have a single responsibility, and therefore have only one reason to change.</li><li>Open-Closed Principle (OCP) — Applications should be closed for modification, but open for extensibility.</li><li>Liskov Substitution Principle (LSP) — Objects of a superclass should be replaceable by a subclass without affecting functionality.</li><li>Interface Segregation Principle (ISP) — Clients shouldn’t be forced to depend on interfaces they don’t use.</li><li>Dependency Inversion Principle (DIP) — high-level modules shouldn’t depend on low-level modules. Both should depend on abstractions.</li></ul><h3>Links</h3><p>If you have any questions/suggestions you can contact me below:</p><p><a href="https://www.linkedin.com/in/luke-sloane-bulger/">Linkedln</a></p><p>Follow me on Medium: <a href="https://medium.com/u/f068ade2f3fe?source=post_page-----6799782d7cb5--------------------------------">Luke Sloane-Bulger</a></p><figure><a href="https://www.buymeacoffee.com/lukesb"><img alt="" src="https://cdn-images-1.medium.com/max/170/1*WfbwTpxi0c0k2Vwzp3s5yg.png" /></a><figcaption>Found this article useful? Feel free to buy me a coffee by clicking the button above</figcaption></figure><h3>Did you like this article? Be sure to share it on social networks. Thanks!</h3><h3>Thank you for being a part of the community</h3><p><em>Before you go:</em></p><ul><li>Be sure to <strong>clap</strong> and <strong>follow</strong> the writer ️👏<strong>️️</strong></li><li>Follow us: <a href="https://x.com/inPlainEngHQ"><strong>X</strong></a> | <a href="https://www.linkedin.com/company/inplainenglish/"><strong>LinkedIn</strong></a> | <a href="https://www.youtube.com/@InPlainEnglish"><strong>YouTube</strong></a> | <a href="https://newsletter.plainenglish.io/"><strong>Newsletter</strong></a> | <a href="https://open.spotify.com/show/7qxylRWKhvZwMz2WuEoua0"><strong>Podcast</strong></a> | <a href="https://differ.blog/inplainenglish"><strong>Differ</strong></a> | <a href="https://twitch.tv/inplainenglish"><strong>Twitch</strong></a></li><li><a href="https://cofeed.app/"><strong>Check out CoFeed, the smart way to stay up-to-date with the latest in tech</strong></a> <strong>🧪</strong></li><li><a href="https://differ.blog/"><strong>Start your own free AI-powered blog on Differ</strong></a> 🚀</li><li><a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Join our content creators community on Discord</strong></a> 🧑🏻‍💻</li><li>For more content, visit <a href="https://plainenglish.io/"><strong>plainenglish.io</strong></a> + <a href="https://stackademic.com/"><strong>stackademic.com</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=179f92843289" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/solid-principles-in-golang-179f92843289">SOLID Principles In Golang</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How To Implement JWT Authentication In Your Golang API]]></title>
            <link>https://blog.stackademic.com/how-to-implement-jwt-authentication-in-your-golang-api-2e4f26c60d60?source=rss-f068ade2f3fe------2</link>
            <guid isPermaLink="false">https://medium.com/p/2e4f26c60d60</guid>
            <category><![CDATA[authentication]]></category>
            <category><![CDATA[authorization]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[jwt-authentication]]></category>
            <dc:creator><![CDATA[Luke Sloane-Bulger]]></dc:creator>
            <pubDate>Thu, 27 Feb 2025 16:17:06 GMT</pubDate>
            <atom:updated>2025-02-27T16:17:06.805Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QTWbqxTTbRG2Ngm0fR-aVg.png" /><figcaption>Authentication With JSON Web Tokens In 3 Minutes</figcaption></figure><p>Implementing a strong authentication mechanism on your API is essential for identifying users, protecting data and securing resources.</p><p>In this article, we’ll focus on authenticating and authorising users using JSON Web Tokens (JWT).</p><p>Understanding how to authenticate users and enforce authorisation levels is crucial for any API.</p><p>You need to be able to isolate user sessions to protect your resources.</p><p>JWTs provide a simple, stateless approach to achieving this securely and efficiently.</p><h3>What is JWT?</h3><p>A JSON Web Token (JWT) is a widely used open standard for securely exchanging information between a client and server.</p><p>JWTs contain encoded JSON objects, known as <em>claims</em>, that hold key information, such as, user details, permission, and other relevant information.</p><p>Each JWT is cryptographically signed to ensure the contents cannot be altered by the client or bad actors.</p><p>These claims represent various types of data, such as username, authorisation levels, and expiration times.</p><p>Below is an example of a JWT:</p><pre>eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6InRlc3QzMzNAZXhhbXBsZS5jb20iLCJleHAiOjE3MzczMDY3OTN9.5-pP_mSsdVUhVy6i7fSwLYZzi4ZDIKxGxEyyERlIQRQ</pre><p>Decoded the payload would look like:</p><pre>{<br>  &quot;username&quot;: &quot;test333@example.com&quot;,<br>  &quot;exp&quot;: 1737306793<br>}</pre><p>Here, the payload contains the user’s email (username) and an expiration timestamp (exp).</p><p>The server uses this information to authenticate and authorise the user.</p><p>To inspect and decode JWTs, you can use the <a href="https://jwt.io/">JWT Decoder</a> like in the below screenshot.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*T_75w4XlyLxqYFKlr4yjYw.png" /><figcaption>JSON Web Token Example</figcaption></figure><h3>Benefits of JWT</h3><p>JWTs offer a series of advantages in systems that require user authentication and authorisation:</p><ol><li>Stateless Authentication — JWTs store all required user information within the token itself, eliminating the need for session storage on the server. This reduces server load and improves scalability as it removes the complexity of maintaining user state across multiple servers.</li><li>Scalability — Since JWTs do not require maintaining session state, they are ideal for Distributed Systems and Microservices architectures where multiple servers handle authentication.</li><li>Security — JWTs can optionally be both signed and encrypted to ensure integrity and confidentiality. Signing prevents tampering, while encryption protects sensitive data from exposure. In the screenshot above, you can see an example of signing JWTs under the “JWT Signature Verification” section. Since JWTs are only encoded by default, anyone can decode the payload. Encrypting JWTs is therefore a good practice to protect any sensitive data in the JWT payload.</li><li>Performance Optimisation — Because JWTs are self-contained, authentication checks can be performed without additional database lookups improving response times.</li><li>Cross-Platform Support — JWTs are widely supported across different programming languages/frameworks, making them a flexible choice for authentication in Web, Mobile and API-based applications.</li></ol><h3>User Authentication With Short-Lived JWTs and Long-Lived JWTs</h3><p>JWTs are a powerful method of exchanging information.</p><p>However, when it comes to authentication and authorisation, we need the ability to invalidate them to unauthenticate and unauthorise users when necessary.</p><p>As mentioned in the previous section, JWTs include an expiry (exp) timestamp in their payload.</p><p>This determines when the token should be invalidated and is useful for automatically logging out users after a set period.</p><p>We can issue a single JWT with a fixed expiration time. When a user logs in, they receive a JWT that remains valid for a specified period. Once it expires, they must log in again to obtain a new JWT to continue interacting with the application.</p><p>But, what if we need to unauthorise and unauthenticate a user at any time, rather than waiting for the token to expire? Imagine a JWT expiry time of, say, 1 hour or more; we’d have to wait for the user’s JWT to expire before they’re unable to interact with the service. This could pose a security risk, as it would allow unauthorized access during that window, potentially exposing sensitive data or operations before the token naturally expires.</p><p>This is where a two-token system approach is ideal:</p><ul><li>Short-Lived JWT (Access Token) — Used for authorising API requests, typically expires within 5 minutes to maintain statelessness.</li><li>Long-Lived JWT (Refresh Token) — Stored in the database and has a significantly longer expiry like 24 hours or more. This introduces statefulness but grants greater control over user sessions.</li></ul><h4>How The Two-Token System Works</h4><p>Short-Lived JWT is used for authorising protected API requests and reduces the need for repeating database calls to validate the user’s session.</p><p>Long-Lived JWT is used to re-issue a Short-Lived JWT if it is valid without requiring the user to do a fresh login to seamlessly authenticate users.</p><p>When the Short-Lived JWT expires, then the workflow for handling this process is as follows:</p><ol><li>The frontends HTTP request to the API has failed with a 401 Unauthorized response from the API.</li><li>The frontend has a condition for this to respond by calling a /refresh endpoint on the API, which essentially makes a DB call to get the user’s Long-Lived JWT (Refresh Token).</li><li>If the Long-Lived JWT is valid, a new Short-Lived JWT is issued and the /refresh endpoint sends this down in the response header. The frontend is now re-authenticated and can re-call the original API endpoint to continue the original operation.</li><li>If the Long-Lived JWT is invalid the API response status is 401 Unauthorized and the frontend simply calls a /logout endpoint to destroy the user’s session and then redirects the user to the /login page.</li></ol><h4>Revoking Access with Long-Lived JWTs</h4><p>Storing the Long-Lived JWT in the database allows the system to revoke a user’s session at any time.</p><p>If an administrator or security policy requires terminating a session, the stored Long-Lived JWT can be deleted from the database.</p><p>This ensures that once the Short-Lived JWT expires, the user will no longer be able to refresh their session and must log in again.</p><h3>How To Implement a JWT In Your Golang API</h3><p>There are many ways to implement a JWT solution for authenticating and authorising users.</p><p>From third-party packages or building your own native solution that you can control and expand on.</p><p>In this article, we’ll focus on using the 3rd party <a href="https://github.com/golang-jwt/jwt">github.com/golang-jwt/jwt/v5 v5.2.1</a> package. This approach is well-documented and easy to integrate into your project.</p><p>To illustrate this, I’ll guide you through an implementation from a recent web app’s JWT user authentication using a Short-Lived and Long-Lived JWT approach using the <a href="https://github.com/golang-jwt/jwt">github.com/golang-jwt/jwt/v5 v5.2.1</a> package for token validation while also storing the Long-Lived JWT in the Database layer.</p><h4>Example of JWT Implementation</h4><p>jwtTokens.go</p><pre>import (<br>...<br> &quot;github.com/golang-jwt/jwt/v5&quot;<br>)<br><br>type JSONWebToken struct {<br> jwtKey []byte<br> db     db.IDB<br>}<br><br>type IJSONWebToken interface {<br> GetJWTKey() []byte<br> GenerateJSONWebTokens(username string) (string, string, error)<br> generateShortLivedJSONWebToken(username string) (string, error)<br> generateLongLivedJSONWebToken(username string) (string, error)<br> generateJSONWebToken(username string, expirationTime time.Time) (string, error)<br> HandleLongLivedJSONWebToken(username string) (string, error)<br>}<br><br>func NewJSONWebToken(jwtSecret string, db db.IDB) *JSONWebToken {<br> return &amp;JSONWebToken{<br>  jwtKey: []byte(jwtSecret),<br>  db:     db,<br> }<br>}<br><br>// Claims represents the JWT claims<br>type Claims struct {<br> Username string `json:&quot;username&quot;`<br> jwt.RegisteredClaims<br>}<br><br>func (sa *JSONWebToken) GetJWTKey() []byte {<br> return sa.jwtKey<br>}<br><br>// Generates the Access/Refresh JWT Tokens<br>func (sa *JSONWebToken) GenerateJSONWebTokens(username string) (string, string, error) {<br> accessToken, err := sa.generateShortLivedJSONWebToken(username) // username will be passed as query param<br><br> if err != nil {<br>  return &quot;&quot;, &quot;&quot;, err<br> }<br><br> refreshToken, err := sa.generateLongLivedJSONWebToken(username)<br><br> if err != nil {<br>  return &quot;&quot;, &quot;&quot;, err<br> }<br><br> return accessToken, refreshToken, err<br>}<br><br>// Generates a new short-lived access token<br>func (sa *JSONWebToken) generateShortLivedJSONWebToken(username string) (string, error) {<br> shortLivedJWT := time.Now().Add(5 * time.Minute)<br> return sa.generateJSONWebToken(username, shortLivedJWT)<br>}<br><br>// Generates a new long-lived refresh token<br>func (sa *JSONWebToken) generateLongLivedJSONWebToken(username string) (string, error) {<br> longLivedJWT := time.Now().Add(24 * time.Hour) // Long-lived refresh token<br> tokenString, err := sa.generateJSONWebToken(username, longLivedJWT)<br><br> return tokenString, err<br>}<br><br>// Generate a JSON Web Token with username and expiry claims<br>func (sa *JSONWebToken) generateJSONWebToken(username string, expirationTime time.Time) (string, error) {<br> expires := expirationTime<br><br> claims := &amp;Claims{<br>  Username: username,<br>  RegisteredClaims: jwt.RegisteredClaims{<br>   ExpiresAt: jwt.NewNumericDate(expires),<br>  },<br> }<br><br> token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)<br><br> return token.SignedString(sa.jwtKey)<br>}<br><br>// Retrieve the refresh token and validate it<br>func (sa *JSONWebToken) HandleLongLivedJSONWebToken(username string) (string, error) {<br> refreshToken, err := sa.db.RetrieveUserSession(username, &quot;&quot;)<br><br> if err != nil {<br>  return &quot;&quot;, err<br> }<br><br> // Check if Refresh Token is valid<br> token, err := jwt.Parse(string(refreshToken), func(token *jwt.Token) (interface{}, error) {<br>  return sa.jwtKey, nil<br> })<br><br> if err != nil || !token.Valid {<br>  return &quot;&quot;, err<br> }<br><br> // Generate a new access token and refresh token<br> newJWTAccessToken, _, err := sa.GenerateJSONWebTokens(username)<br><br> if err != nil {<br>  return &quot;&quot;, err<br> }<br><br> return newJWTAccessToken, nil<br>}</pre><p>Above is the JWT functionality responsible for validating and generating JWTs.</p><p>The main public functions here are:</p><ul><li>GenerateJSONWebTokens — Generates the Short-Lived JWT and Long-Lived JWT. This is called via the loginendpoint.</li><li>HandleLongLivedJSONWebToken — Preforms a READ DB Call to get the Long-Lived JWT to act as the Refresh Token, validates it and if it’s valid generates a new Short-Lived JWT to serve as the new Access Token. This is called via the /refresh endpoint.</li></ul><p>The rest of the members in jwtTokens.go are as follows:</p><h4>JSONWebToken struct</h4><ul><li>JWT Secret Key passed from main.go environment variable.</li><li>IDB — Interface representing the contract for Database methods.</li></ul><h4>IJSONWebToken Interface</h4><ul><li>A dynamic interface that defines the methods associated with JWT functionality. This interface is used throughout the application in a loosely-coupled manner, which also helps facilitate unit testing.</li></ul><h4>NewJSONWebToken(jwtSecret string, db db.IDB) *JWTTokens</h4><ul><li>This is a constructor function that initializes the JSONWebToken struct with a JWT secret key (jwtKey) and a database interface (db).</li><li>It allows dependency injection, making the implementation flexible and testable.</li></ul><h4>Claims Struct</h4><ul><li>Represents the payload of the JWT, containing:</li><li>Username: Stores the username associated with the token.</li><li>RegisteredClaims: Includes standard JWT claims. For example exp for expiration.</li></ul><h4>GetJWTKey() []byte</h4><ul><li>This function returns the stored JWT secret key.</li><li>It is used internally to sign and verify JWT tokens.</li></ul><h4>GenerateJSONWebTokens(username string) (string, string, error)</h4><ul><li>Generates both an Access Token (Short-Lived JWT) and a Refresh Token (Long-Lived JWT) for the given user.</li><li>Calls generateShortLivedJSONWebToken(username) and generateLongLivedJSONWebToken(username) to create these tokens.</li><li>Returns both tokens as strings, or an error if any occurs.</li></ul><h4>generateShortLivedJSONWebToken(username string) (string, error)</h4><ul><li>Creates a Short-Lived JWT that expires in 5 minutes.</li><li>Calls generateJSONWebToken(username, expirationTime) to generate the token.</li><li>Used for authenticating API requests without querying the database frequently.</li></ul><h4>generateLongLivedJSONWebToken(username string) (string, error)</h4><ul><li>Creates a Long-Lived JWT (Refresh Token) with an expiration time of 24 hours.</li><li>Calls generateJSONWebToken(username, expirationTime) to generate the token.</li><li>This Long-Lived JWT is stored in the database and used to refresh the Short-Lived JWT when it expires.</li></ul><h4>generateJSONWebToken(username string, expirationTime time.Time) (string, error)</h4><ul><li>The core function responsible for creating JWTs.</li><li>Takes a username and expiration time as parameters.</li><li>Uses jwt.NewWithClaims to create a JWT with claims, including the username and expiration timestamp.</li><li>Signs the JWT using HMAC SHA256 (jwt.SigningMethodHS256).</li></ul><h4>HandleLongLivedJSONWebToken(username string) (string, error)</h4><ul><li>Used to refresh an expired Access Token using the Refresh Token.</li><li>Retrieves the stored Refresh Token from the database using RetrieveUserSession(username, &quot;&quot;).</li><li>Parses the Refresh Token and checks if it is valid.</li><li>If valid, generates a new Access Token using GenerateJSONWebTokens(username).</li><li>If invalid or expired, returns an error, forcing the user to reauthenticate.</li></ul><p>In terms of implementing JWT in your API, it’s best to apply this on the endpoints you want to protect using a Middleware layer.</p><p>This way, when a protected endpoint is called, the Middleware layer handles all JWT authentication and authorisation logic before the request reaches the endpoint’s handler.</p><p>Using Middleware prevents the duplication of authentication logic across multiple endpoints, keeping your handlers concise and maintainable.</p><p>You can learn more about implementing Middleware in this article: “<a href="https://medium.com/stackademic/how-to-implement-middleware-in-your-golang-api-d2da8b14a928">How To Implement Middleware in Your Golang API</a>”.</p><p>This JWT implementation provides a secure, scalable, and flexible method for handling authentication and session management in a Golang API.</p><p>While the Short-Lived JWT remains stateless, the Long-Lived JWT is stored in the database, introducing a controlled level of state that allows for effective session revocation when required.</p><p>An example of a JWT Authentication Middleware:</p><pre><br>import (<br>...<br> &quot;github.com/golang-jwt/jwt/v5&quot;<br>)<br><br>type contextKey string<br><br>const ClaimsKey = contextKey(&quot;claims&quot;)<br><br><br>func AuthMiddleware(jwtTokens IJSONWebToken, logger logger.ILogger) func(http.HandlerFunc) http.HandlerFunc {<br> functionName := helper.GetFunctionName()<br> return func(next http.HandlerFunc) http.HandlerFunc {<br>  return func(w http.ResponseWriter, r *http.Request) {<br>   logger.InfoLog(functionName, &quot;&quot;)<br><br>   authHeader := r.Header.Get(&quot;Authorization&quot;)<br><br>   // Attempt to get the Access Token from the Authorization Header<br>   if authHeader == &quot;&quot; || !strings.HasPrefix(authHeader, &quot;Bearer &quot;) {<br>    logger.ErrorLog(functionName, &quot;No Auth Header present&quot;)<br>    http.Error(w, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized)<br>    return<br>   }<br><br>   tokenStr := strings.TrimPrefix(authHeader, &quot;Bearer &quot;)<br>   claims := &amp;Claims{}<br>   token, err := jwt.ParseWithClaims(tokenStr, claims, func(token *jwt.Token) (interface{}, error) {<br>    return jwtTokens.GetJWTKey(), nil<br>   })<br><br>   if err != nil || !token.Valid {<br>    logger.ErrorLog(functionName, &quot;JWT Token error&quot;)<br>    http.Error(w, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized)<br>    return<br>   }<br><br>   // Check Access Token Expiry Time:<br>   // If the time remaining is greater than a minute, re-issue the same Access Token<br>   // If there&#39;s less than a minute left get the Refresh Token to attempt to re-issue a new Access Token<br>   expirationTime := claims.ExpiresAt.Time<br><br>   timeRemaining := time.Until(expirationTime)<br><br>   if timeRemaining &gt; time.Minute {<br>    w.Header().Set(&quot;Authorization&quot;, fmt.Sprintf(&quot;Bearer %s&quot;, tokenStr))<br>    ctx := context.WithValue(r.Context(), ClaimsKey, claims)<br>    next.ServeHTTP(w, r.WithContext(ctx))<br>    return<br>   }<br><br>   // Attempt to get a new Access Token<br>   newAccessToken, err := jwtTokens.HandleLongLivedJSONWebToken(claims.Username)<br><br>   if err != nil {<br>    http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)<br>    return<br>   }<br><br>   w.Header().Set(&quot;Authorization&quot;, fmt.Sprintf(&quot;Bearer %s&quot;, newAccessToken))<br>   ctx := context.WithValue(r.Context(), ClaimsKey, claims)<br>   next.ServeHTTP(w, r.WithContext(ctx))<br>  }<br> }<br>}</pre><p>Here the function first checks if the JWT exists in the “Authorization” request header. If it doesn’t return a 401 Unauthorized.</p><p>Next parse the JWT supplied by the Request Header with our JWT Secret Key. If an error occurs or it is no longer valid again return return a 401 Unauthorized.</p><p>Check the Short-Lived JWTs expiry time. If the Short-Lived JWT expiry time is greater than a minute re-use it. Otherwise, if it’s less than a minute left perform a DB READ operation to get the Long-Lived JWT to re-issue a new Short-Lived JWT.</p><p>Finally, set the Authorization response header with the JWT. Then call the next Middleware function in the chain.</p><h3>Summary</h3><p>In summary, in this article, we explored JSON Web Tokens and an implementation example using the <a href="https://github.com/golang-jwt/jwt">github.com/golang-jwt/jwt/v5 v5.2.1</a> package.</p><p>JWTs are a widely used open standard for securely exchanging information between a client and server. They contain encoded JSON objects, known as <em>claims</em>, that hold key information, such as, user details, permissions, and other relevant information. Each JWT is cryptographically signed to ensure the contents cannot be altered by the client or bad actors. These claims represent various types of data, such as username, authorisation levels, and expiration times.</p><p>JWTs are commonly used for authenticating and authorising users until they reach their expiration time, at which point the user must log in again to reauthenticate. The advantages of JWTs include stateless authentication, scalability, security, performance optimisation, and cross-platform support, making them a powerful method for securely exchanging information.</p><p>However, when it comes to authentication and authorisation, it’s crucial to have the ability to invalidate tokens to unauthorise users when necessary. To achieve this, a two-token solution can be implemented. In this approach, a Short-Lived JWT (a stateless access token) is combined with a Long-Lived JWT (a stateful refresh token). When the Short-Lived JWT expires, a READ database call can retrieve the Long-Lived JWT, and if it is still valid, a new Short-Lived JWT can be issued. While the Long-Lived JWT introduces a small amount of state to the database, it provides greater control over user sessions, allowing for session revocation when needed.</p><p>Finally, there are many ways to implement a JWT mechanism for managing user authentication and authorisation on your API, from a third party solution to your own native solution.</p><p>In the above section, we focused on using the <a href="https://github.com/golang-jwt/jwt">github.com/golang-jwt/jwt/v5 v5.2.1</a> 3rd Party package. This approach is straightforward, flexible, and integrates seamlessly with your projects. For an in-depth guide, refer to “How To Implement a JWT In Your Golang API” section above, where we went through a practical example.</p><h3>Links</h3><p>If you have any questions/suggestions you can contact me below:</p><p><a href="https://www.linkedin.com/in/luke-sloane-bulger/">Linkedln</a></p><p>Follow me on Medium: <a href="https://medium.com/u/f068ade2f3fe?source=post_page-----6799782d7cb5--------------------------------">Luke Sloane-Bulger</a></p><figure><a href="https://www.buymeacoffee.com/lukesb"><img alt="" src="https://cdn-images-1.medium.com/max/170/1*WfbwTpxi0c0k2Vwzp3s5yg.png" /></a><figcaption>Found this article useful? Feel free to buy me a coffee by clicking the button above</figcaption></figure><h3>Did you like this article? Be sure to share it on social networks. Thanks!</h3><h3>Thank you for being a part of the community</h3><p><em>Before you go:</em></p><ul><li>Be sure to <strong>clap</strong> and <strong>follow</strong> the writer ️👏<strong>️️</strong></li><li>Follow us: <a href="https://x.com/inPlainEngHQ"><strong>X</strong></a> | <a href="https://www.linkedin.com/company/inplainenglish/"><strong>LinkedIn</strong></a> | <a href="https://www.youtube.com/channel/UCtipWUghju290NWcn8jhyAw"><strong>YouTube</strong></a> | <a href="https://newsletter.plainenglish.io/"><strong>Newsletter</strong></a> | <a href="https://open.spotify.com/show/7qxylRWKhvZwMz2WuEoua0"><strong>Podcast</strong></a></li><li><a href="https://cofeed.app/"><strong>Check out CoFeed, the smart way to stay up-to-date with the latest in tech</strong></a> <strong>🧪</strong></li><li><a href="https://differ.blog/"><strong>Start your own free AI-powered blog on Differ</strong></a> 🚀</li><li><a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Join our content creators community on Discord</strong></a> 🧑🏻‍💻</li><li>For more content, visit <a href="https://plainenglish.io/"><strong>plainenglish.io</strong></a> + <a href="https://stackademic.com/"><strong>stackademic.com</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2e4f26c60d60" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/how-to-implement-jwt-authentication-in-your-golang-api-2e4f26c60d60">How To Implement JWT Authentication In Your Golang API</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How To Implement Middleware In Your Golang API]]></title>
            <link>https://blog.stackademic.com/how-to-implement-middleware-in-your-golang-api-d2da8b14a928?source=rss-f068ade2f3fe------2</link>
            <guid isPermaLink="false">https://medium.com/p/d2da8b14a928</guid>
            <category><![CDATA[golang-tutorial]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[middleware]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Luke Sloane-Bulger]]></dc:creator>
            <pubDate>Mon, 27 Jan 2025 05:48:39 GMT</pubDate>
            <atom:updated>2025-01-27T05:48:39.520Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bRvr-F7lUwfk9MSGDoc03Q.png" /><figcaption>How To Implement Middleware In 3 Minutes</figcaption></figure><p>Building a strong Middleware layer is key for creating concise, maintainable, and efficient Web APIs.</p><p>Middleware serves as the backbone for handling concerns like logging, validation, authentication, and more, all while promoting a clean separation of concerns in your codebase.</p><p>In this article, we’ll explore what Middleware is and provide a practical solution on how to effectively implement it in Golang.</p><p>Whether you’re looking to improve API security, track usage metrics or enhance performance, Middleware can help you achieve these goals with minimal complexity.</p><h3>What is Middleware?</h3><p>Middleware in Golang is a basically a wrapper function that wraps around http.Handler or http.HandleFunc.</p><p>It serves as a processing layer for HTTP requests and responses, either before or after they reach your actual handlers logic.</p><p>Imagine Middleware as a chain.</p><p>Where each chain-link represents a function that can modify the incoming request, perform operations like logging or authentication or short-circuit the request-response lifecycle by rejecting invalid requests early.</p><p>Here are some common use cases for Middleware:</p><ul><li>Validation — Checking HTTP Methods, request headers, bodies or parameters for correctness.</li><li>Authentication — Ensuring only authorised users can access certain endpoints by validating tokens like JWTs (JSON Web Token), or CSRF (Cross-Site Request Forgery) Tokens.</li><li>Logging — Capturing analytics or debugging information about each request.</li><li>Response Headers: Adding or modifying headers like Content-Type, CORS, or security headers.</li><li>Rate-Limiting: Controlling the number of requests a client can make within a specific time-frame.</li></ul><p>In brief, Middleware in Golang is a reusable, centralised piece of logic that enhances and separates the behaviours of your HTTP handlers.</p><h3>Benefits of Middleware</h3><p>There’s many benefits to Middleware.</p><p>Middleware offers numerous advantages in building scalable, maintainable, and efficient web APIs. Let’s focus on five key benefits:</p><ol><li>Reduces Code Duplication — Middleware helps eliminate repetitive boilerplate code in your handlers. For example, instead of writing the same checks for concerns such as, HTTP methods validation, authentication, CSRF tokens, setting response headers, logging, error handling, and more in every single handler, you can centralise these actions in reusable Middleware functions. This not only minimises the chances of mistakes and bugs, but also ensures consistent behaviours across your application.</li><li>Centralised Logic — By declaring common functionality in Middleware, you only need to manage and update your logic in a single area of the codebase. For example, if you decide to update your authentication mechanism, you only need to modify the Middleware layer, and it automatically applies throughout your application. This centralisation ensures consistency, and reduces the overhead of maintaining logic across multiple handlers.</li><li>Separation of Concerns — Middleware promotes a clean separation of concerns by isolating responsibilities in your application. Tasks like authentication, logging and validating requests are all separate responsibilities that should be handled in an individual Middleware function that’s independent of your handlers. This keeps your route handlers focused solely on business logic, improving readability and maintainability.</li><li>Improved Scalability — As your application grows, Middleware allows you to easily add, remove, or reorder functionality without disrupting existing routes. Imagine your app has grown and you need to add a Rate Limiter. With Middleware this is simple, you only need to add a new Middleware function specific for Rate Limiting and inject it into the Middleware chain. This modularity ensures your application remains adaptable to changing requirements.</li><li>Easier Testing and Debugging — Middleware provides a structured layer for testing discrete functionality like authentication or validation. You can write Unit Tests for each Middleware function in isolation, ensuring their reliability and correctness. With centralised logging you can easily track and debug requests more effectively without scattering logs throughout your handlers. Additionally, debugging and stepping through your handlers is easier. In a debug session you can toggle off features like the CSRF token or authentication checks to access your handlers without the need of adding tokens in each of your cURL or Postman requests to debug and find bugs at a faster pace.</li></ol><h3>How To Implement Middleware?</h3><p>There are many ways to implement a Middleware layer.</p><p>From third-party packages or building your own native solution that you can control and expand on.</p><p>In this article, we’ll focus on a native solution to leverage Golang’s existing net/http package. This approach is simple, flexible, and easy to integrate into your projects.</p><p>To illustrate this, I’ll guide you through an implementation from a recent web app’s Middleware in one of my projects.</p><p>Below, you’ll find the core logic for setting up Middleware, followed by how it’s applied in routing.</p><h4>Example of Middleware Implementation</h4><p><strong>middleware.go</strong></p><p>Let’s start with a Middleware struct that encapsulates the dependencies declared earlier when starting the Web App like the JWTs (JSON Web Token), CSRF (Cross-Site Request Forgery) Tokens and our logger.</p><pre>package middleware<br><br>import (<br> &quot;dohabits/data&quot;<br> &quot;dohabits/logger&quot;<br> &quot;dohabits/middleware/session&quot;<br> &quot;net/http&quot;<br>)<br><br>type Middleware struct {<br> jwtTokens  session.IJWTTokens<br> csrfTokens session.ICSRFToken<br> logger     logger.ILogger<br>}<br><br>type IMiddleware interface {<br> MiddlewareList(handler http.HandlerFunc, dependencies data.Middleware) http.HandlerFunc<br> protectedMiddlewareList() []func(http.HandlerFunc) http.HandlerFunc<br> chainMiddleware(handler http.HandlerFunc, middlewares []func(http.HandlerFunc) http.HandlerFunc) http.HandlerFunc<br>}<br><br>func NewMiddleware(jwtTokens session.IJWTTokens, csrfTokens session.ICSRFToken, logger logger.ILogger) *Middleware {<br> return &amp;Middleware{<br>  jwtTokens:  jwtTokens,<br>  csrfTokens: csrfTokens,<br>  logger:     logger,<br> }<br>}</pre><p>The Middleware struct holds the required dependencies we’ll call to implement various Middleware layers.</p><p>These dependencies are injected via the constructor to keep the code modular and testable.</p><p><strong>middleware.go — functions</strong></p><p>The MiddlewareList function determines what Middleware layers are required for your handler based on the route’s configuration.</p><p>The handler and dependencies (from the Middleware struct) are passed in as arguments.</p><pre>func (mw *Middleware) MiddlewareList(handler http.HandlerFunc, dependencies data.Middleware) http.HandlerFunc {<br> middlewares := []func(http.HandlerFunc) http.HandlerFunc{<br>  HTTPMethodValidation(dependencies.HTTPMethod, mw.logger),<br>  JSONMiddleware(mw.logger),<br> }<br><br> if dependencies.IsProtected {<br>  middlewares = append(middlewares, mw.protectedMiddlewareList()...)<br> }<br><br> if dependencies.CSRFRequired {<br>  middlewares = append(middlewares, CSRFToken(mw.csrfTokens, mw.logger))<br> }<br><br> middlewares = append(middlewares, ErrorHandlingMiddleware(mw.logger))<br><br> return mw.chainMiddleware(handler, middlewares)<br>}</pre><p>Here’s what happening:</p><ul><li>First we have a slice of Http.HandleFunc that just holds the Middleware our route will need.</li><li>Common Middleware required for all routes are added here like our validation for the HTTP call and JSON Headers in the response.</li><li>Conditional Middleware is next — if our handler requires protection then we’ll add any necessary Middleware like Authentication or CSRF Token check. For example, for authentication the protectedMiddlewareList is called to add Middleware specifically related to authentication.</li><li>Error Handling: ensures graceful error recovery, reporting and handling.</li></ul><pre>func (mw *Middleware) chainMiddleware(handler http.HandlerFunc, middlewares []func(http.HandlerFunc) http.HandlerFunc) http.HandlerFunc {<br> for i := len(middlewares) - 1; i &gt;= 0; i-- {<br>  handler = middlewares[i](handler)<br> }<br> return handler<br>}</pre><p>This ensures that core Middleware like the Validation and Logging are executed first in our Middleware chain, followed by the conditional layers like Authentication or CSRF Protection and finally the Error Handling Middleware.</p><p><strong>middleware example — HTTPMethodValidation.go</strong></p><p>Below is an example of a Middleware function that handles HTTP method validation.</p><p>This function ensures that the incoming HTTP request method matches the expected one (e.g., POST, GET, etc.).</p><p>If the method doesn&#39;t match, the Middleware immediately returns a 405 Method Not Allowed error.</p><p>If it does match, the request proceeds to the next Middleware or handler.</p><p>This Middleware checks the HTTP method, and if valid, invokes the next function in the chain.</p><pre>func HTTPMethodValidation(httpMethod string, logger logger.ILogger) func(http.HandlerFunc) http.HandlerFunc {<br> functionName := helper.GetFunctionName()<br> return func(next http.HandlerFunc) http.HandlerFunc {<br>  return func(w http.ResponseWriter, r *http.Request) {<br>   logger.InfoLog(functionName, &quot;&quot;)<br><br>   if r.Method != httpMethod {<br>    http.Error(w, http.StatusText(http.StatusMethodNotAllowed), http.StatusMethodNotAllowed)<br>    return<br>   }<br><br>   next.ServeHTTP(w, r)<br>  }<br> }<br>}</pre><p><strong>routes.go — example usage</strong></p><pre>http.HandleFunc(<br> fmt.Sprintf(&quot;/%s/createhabit&quot;, endpoint), <br> app.GetMiddleware().MiddlewareList(<br>  app.GetHabitsController().CreateHabitsHandler, <br>  data.Middleware{<br>   IsProtected:  true, <br>   CSRFRequired: true, <br>   HTTPMethod:   http.MethodPost,<br>  },<br> ),<br>)</pre><p>Above is an example of the Middleware being applied to a HTTP handler.</p><p>Let’s run down what this is doing:</p><ul><li>The route is configured with data.Middleware to specify dependencies like authentication (IsProtected), CSRF requirement (CSRFRequired), and the HTTP Method (HTTPMethod).</li><li>MiddlewareList dynamically builds the Middleware Chain based on these requirements.</li><li>The request flows through each Middleware layer in the chain before reaching the final Handler (CreateHabitsHandler).</li></ul><h3>Summary</h3><p>In summary, in this article, we explored Middleware in Golang, including its benefits and how to implement it natively using Golang’s net/http package.</p><p>Middleware in Golang is a basically a wrapper function that wraps around http.Handler or http.HandleFunc. It serves as a processing layer for HTTP requests and responses before they reach your actual handler’s logic.</p><p>Imagine Middleware like a chain where each chain-link is a function. These functions can modify the incoming request, perform tasks like logging or authentication or short-circuit the request-response lifecycle by rejecting invalid requests early.</p><p>Use-cases for Middleware include: validation, authentication, logging, setting response-headers, and rate-limiting.</p><p>The benefits for Middleware are numerous: reduces code duplication, centralises logic, promotes separation of concerns, improves scalability, and makes debugging and testing easier.</p><p>Finally, there are many ways to implement a Middleware layer, from third-party packages to your own native solution.</p><p>In the above section, we focused on leveraging Golang’s existing net/http package. This approach is straightforward, flexible, and integrates seamlessly with your projects. For an in-depth guide, refer to <em>“How To Implement Middleware?” </em>section above, where we walked through a practical example.</p><h3>Links</h3><p>If you have any questions/suggestions you can contact me below:</p><p><a href="https://www.linkedin.com/in/luke-sloane-bulger/">Linkedln</a></p><p>Follow me on Medium: <a href="https://medium.com/u/f068ade2f3fe?source=post_page-----6799782d7cb5--------------------------------">Luke Sloane-Bulger</a></p><figure><a href="https://www.buymeacoffee.com/lukesb"><img alt="" src="https://cdn-images-1.medium.com/max/170/1*WfbwTpxi0c0k2Vwzp3s5yg.png" /></a><figcaption>Found this article useful? Feel free to buy me a coffee by clicking the button above</figcaption></figure><h3>Did you like this article? Be sure to share it on social networks. Thanks!</h3><h3>Thank you for being a part of the community</h3><p><em>Before you go:</em></p><ul><li>Be sure to <strong>clap</strong> and <strong>follow</strong> the writer ️👏<strong>️️</strong></li><li>Follow us: <a href="https://x.com/inPlainEngHQ"><strong>X</strong></a> | <a href="https://www.linkedin.com/company/inplainenglish/"><strong>LinkedIn</strong></a> | <a href="https://www.youtube.com/channel/UCtipWUghju290NWcn8jhyAw"><strong>YouTube</strong></a> | <a href="https://newsletter.plainenglish.io/"><strong>Newsletter</strong></a> | <a href="https://open.spotify.com/show/7qxylRWKhvZwMz2WuEoua0"><strong>Podcast</strong></a></li><li><a href="https://cofeed.app/"><strong>Check out CoFeed, the smart way to stay up-to-date with the latest in tech</strong></a> <strong>🧪</strong></li><li><a href="https://differ.blog/"><strong>Start your own free AI-powered blog on Differ</strong></a> 🚀</li><li><a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Join our content creators community on Discord</strong></a> 🧑🏻‍💻</li><li>For more content, visit <a href="https://plainenglish.io/"><strong>plainenglish.io</strong></a> + <a href="https://stackademic.com/"><strong>stackademic.com</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d2da8b14a928" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/how-to-implement-middleware-in-your-golang-api-d2da8b14a928">How To Implement Middleware In Your Golang API</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What are Goroutines? Learn in 3 Minutes]]></title>
            <link>https://blog.stackademic.com/what-are-goroutines-learn-in-3-minutes-038da2f0e200?source=rss-f068ade2f3fe------2</link>
            <guid isPermaLink="false">https://medium.com/p/038da2f0e200</guid>
            <category><![CDATA[go]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[goroutines]]></category>
            <category><![CDATA[tutorial]]></category>
            <dc:creator><![CDATA[Luke Sloane-Bulger]]></dc:creator>
            <pubDate>Mon, 09 Sep 2024 16:17:35 GMT</pubDate>
            <atom:updated>2024-09-09T16:17:35.210Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JZx2lIV8abHRJjaWBXSUWQ.png" /></figure><pre>go startLearnWhatAreGoroutinesArticle()</pre><p>Goroutines are a powerful feature in Go, allowing you to handle concurrency easily.</p><p>In this article, we’ll quickly go over the following: what Goroutines are, how they work, how they differ from Threads, how Goroutines differ from Async/Await in other languages like JavaScript, and finally the lifecycle of a Goroutine.</p><h3>What’re Goroutines?</h3><p>Goroutines are Golang’s in-built concurrency mechanism.</p><p>They are lightweight functions that execute independently while sharing the same address space.</p><p>Goroutines are declared with the go keyword before a function call.</p><p>When you create a Goroutine, your program communicates with the Go Runtime Scheduler, which handles interaction with the Operating System’s Threads to execute the tasks.</p><p>This scheduler efficiently handles multitasking without the overhead associated with traditional threads (fewer resources, faster context switching, etc).</p><p>The scheduler-based system allows thousands of goroutines to run simultaneously, optimising CPU usage and simplifying concurrency management for developers.</p><h3>How do Goroutines work?</h3><p>When you declare a Goroutine, your program interacts with the Go Runtime Scheduler.</p><p>The Scheduler then maps these Goroutines to the Operating System’s Threads for execution.</p><p>Here’s a simplified illustration:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eq5OHymD52p-fV_9g-Trgw.png" /><figcaption>Go Program -&gt; Go Routines -&gt; Go Runtime Scheduler -&gt; Threads -&gt; Operating System</figcaption></figure><p>Here we have our Go Program.</p><p>In this illustration we’ve declared six Goroutines.</p><p>These Goroutines are maintained within our Go Program and only interact with the Scheduler. They do not directly interact with the Operating System.</p><p>The Scheduler maps our Goroutines to the Threads on the Operating System, where the concurrent tasks are executed.</p><p>For a Goroutine to perform its task, it must be scheduled onto the Operating System’s Threads.</p><p>The Scheduler optimises performance by determining how many Goroutines are mapped to Threads and manages their execution time to ensure fair CPU time and to improve the efficiency of the program.</p><p>To optimise performance, the Scheduler employs techniques like work-stealing and load-balancing. Work-stealing helps prevent idle time by redistributing tasks among Threads. Load Balancing ensures an even distribution of tasks across available Threads to prevent bottlenecks.</p><h3>Threads vs Goroutines</h3><p>So what’s the difference between Threads and Goroutines?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*I-9iINzVb3-8ruX0jj-jJg.png" /><figcaption>Threads vs Goroutines</figcaption></figure><p>Threads have their own execution stack where all its commands and instructions that’re working on that Thread are contained within that stack.</p><p>This is the same case with the Goroutine. Goroutines have their own execution stack as well.</p><p>A Thread has a fixed stack space (around 1MB).</p><p>Goroutines have a variable stack space (starts at 2KB) which can increase dynamically. So they’re 500x smaller than Threads that’re created by the Operating System.</p><p>This is a benefit because this makes Goroutines extremely lightweight in terms of memory footprint.</p><p>You can have 500 Goroutines and still occupy around the same amount as a single Operating System Thread.</p><p>Then the Go Runtime Scheduler will ensure that each of those Goroutines gets a fair amount of CPU time.</p><p>Threads are managed by the Operating System.</p><p>Goroutines are managed by the Go Runtime Scheduler.</p><p>The benefit here goes to the Threads as they directly communicate with the Operating System, whereas Goroutines communicate with the Go Runtime Scheduler, and that Scheduler allocates the Goroutines to the Threads.</p><p>So the Scheduler does have an overhead, which means Go pays a small performance cost for these Goroutines.</p><p>Though this negative is generally outweighed by the ease of use of Goroutines and in terms of scalability.</p><p>Finally, Threads are relatively expensive because in order for your program to create a Thread it has to actually interact with the Operating System.</p><p>Whereas, the Goroutines are inexpensive since they live within the Go Runtime and don’t have to interact with the Operating System at all.</p><p>Ultimately, while Threads offer direct Operating System Management, Goroutines provide more memory-efficient and scalable approach to concurrency, thanks to their smaller stack size and dynamic stack growth.</p><h3>How do Goroutines concurrency differ from Async/Await in other languages?</h3><p>Goroutines provide true concurrency.</p><p>Here multiple tasks can be executed at the same time on multiple Operating System Threads that are managed by the Go Runtime Scheduler.</p><p>This means Goroutines can handle both CPU-bound and I/O-bound tasks concurrently, taking full advantage of available CPU cores.</p><p>This makes Goroutines effective for applications requiring high parallelism, such as, real-time data processing or handling numerous network connections.</p><p>Async/Await in languages like JavaScript are primarily designed for asynchronous I/O-bound tasks, like waiting on network requests or file reading.</p><p>JavaScript operates in a single-threaded environment, using JavaScript’s Event Loop to handle operations. This model allows JavaScript programs to remain responsive whilst I/O tasks are handled in the background whilst these operations are waiting to be completed.</p><p>In this model, CPU-bound tasks aren’t well suited for async/await because they block the single-thread, which leads to performance issues.</p><p>Async/Await excels in environments optimised for asynchronous I/O operations, such as, Node.js. In these environments, the Event Loop and underlying infrastructure are designed to handle many concurrent I/O operations efficiently. This makes async/await a powerful tool for non-blocking I/O tasks. However, for CPU-intensive tasks, which require high computational resources that block the thread, async/await will not be as efficient as Goroutines.</p><p>To summarise, Goroutines provide more flexibility for concurrency by leveraging parallelism. They can handle CPU and I/O-intensive tasks by being able to utilise multiple Threads with help from the Go Runtime Scheduler. Whilst async/await is better suited for non-blocking I/O operations in single-threaded environments, as it will encounter performance issues for CPU-intensive tasks.</p><h3>What’s the Lifecycle of a Goroutine?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*f5XxceyrYT8-cBHf9ikU3g.png" /><figcaption>Go Routine Lifecycle — Create -&gt; Running or Blocking -&gt; Execute Deferred Funcs -&gt; Finish</figcaption></figure><p>The basic lifecycle of a Goroutine begins when it is invoked with the go keyword.</p><p>Once invoked it enters a <em>ready </em>state, where it waits to be picked up by the Go Runtime Scheduler to assign it to an Operating System Thread where it is executed.</p><p>The Goroutine executes until it either completes or gets blocked.</p><p>The Goroutine may be blocked whilst waiting for a channel that’s waiting for a receiving/sending operation, system calls, sleeping, network requests, queueing to be picked up by the Go Runtime Scheduler, or any other operations that require time to complete.</p><p>If there’s any deferred functions that it initiates like closing a database connection it has the responsibility to execute these functions before finishing.</p><p>Once the Goroutine has completed its task, it exits and is collected by the Garbage Collector in the Go Runtime.</p><h3>Summary</h3><p>In summary, we quickly went over what Goroutines are, how they work, how they differ from Threads, how Goroutines differ from Async/Await in other languages like JavaScript, and finally the lifecycle of a Goroutine.</p><p>Goroutines are are Go’s concurrency mechanism, designed for lightweight, efficient multitasking.</p><p>The difference between Goroutines and Threads are that traditional Threads are managed directly by the Operating System. Whereas Goroutines are managed by the Go Runtime Scheduler which allocates them to the Threads for execution. Goroutines are smaller and lightweight, allowing for more concurrent tasks with less resource usage.</p><p>Goroutines differ from async/await in languages like JavaScript as they handle both CPU and I/O intensive tasks concurrently, whereas async/await is better suited for I/O tasks only in single-threaded environments.</p><p>The lifecycle of a Goroutine is that its executed with the go keyword where it enters a “ready” state.</p><p>This is picked up by the Go Runtime Scheduler where it is pointed at a Thread for execution.</p><p>It can constantly enter a “blocking” or “running” state. It may be blocked by Channels awaiting a receive/send operation to be completed, awaiting a network request or queueing to be picked up by the Go Runtime Scheduler, etc…</p><p>Finally, once the task is completed, if it has any deferred functions like closing a database connection, it’ll execute these deferred functions and finally finish. Then it’ll be picked up by the Garbage Collector in the Go Runtime.</p><h3>Links</h3><p>If you have any questions/suggestions you can contact me below:</p><p><a href="https://www.linkedin.com/in/luke-sloane-bulger/">Linkedln</a></p><p><a href="https://twitter.com/CodingWithSB">Twitter</a></p><p>Follow me on Medium: <a href="https://medium.com/u/f068ade2f3fe?source=post_page-----6799782d7cb5--------------------------------">Luke Sloane-Bulger</a></p><figure><a href="https://www.buymeacoffee.com/lukesb"><img alt="" src="https://cdn-images-1.medium.com/max/170/1*WfbwTpxi0c0k2Vwzp3s5yg.png" /></a><figcaption>Found this article useful? Feel free to buy me a coffee by clicking the button above</figcaption></figure><h3>Did you like this article? Be sure to share it on social networks. Thanks!</h3><h3>Stackademic 🎓</h3><p>Thank you for reading until the end. Before you go:</p><ul><li>Please consider <strong>clapping</strong> and <strong>following</strong> the writer! 👏</li><li>Follow us <a href="https://twitter.com/stackademichq"><strong>X</strong></a> | <a href="https://www.linkedin.com/company/stackademic"><strong>LinkedIn</strong></a> | <a href="https://www.youtube.com/c/stackademic"><strong>YouTube</strong></a> | <a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Discord</strong></a></li><li>Visit our other platforms: <a href="https://plainenglish.io/"><strong>In Plain English</strong></a> | <a href="https://cofeed.app/"><strong>CoFeed</strong></a> | <a href="https://differ.blog/"><strong>Differ</strong></a></li><li>More content at <a href="https://stackademic.com/"><strong>Stackademic.com</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=038da2f0e200" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/what-are-goroutines-learn-in-3-minutes-038da2f0e200">What are Goroutines? Learn in 3 Minutes</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What are Channels in Golang? Learn in 3 Minutes]]></title>
            <link>https://blog.stackademic.com/what-are-channels-in-golang-learn-in-3-minutes-f5d5065e52c2?source=rss-f068ade2f3fe------2</link>
            <guid isPermaLink="false">https://medium.com/p/f5d5065e52c2</guid>
            <category><![CDATA[guides-and-tutorials]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[golang-development]]></category>
            <category><![CDATA[golang-channel]]></category>
            <category><![CDATA[golang-tutorial]]></category>
            <dc:creator><![CDATA[Luke Sloane-Bulger]]></dc:creator>
            <pubDate>Tue, 23 Jul 2024 06:16:45 GMT</pubDate>
            <atom:updated>2024-07-23T06:16:45.598Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*etxjCTU0aKbWmgZs162XRA.png" /><figcaption>What are Channels in Golang in 3 Minutes</figcaption></figure><p>In this article, we’ll quickly go over what Channels are, types of Channel, and Channel Control Flow.</p><h3>What’s a Channel?</h3><p>Channels are designed for communication between Goroutines.</p><p>Channels enable data exchange between Goroutines by coordinating them to allow routines to send data to each other and synchronise their execution.</p><p>This is to ensure that data can be safely passed between different executing threads.</p><p>Channels are blocking operations.</p><p>They cause the application to wait until communication can be proceed — somewhat similar to async/await in other languages.</p><p>Primarily there’s two types of Channel:</p><ul><li>Buffered — Asynchronous Behaviour.</li><li>Unbuffered — Synchronous Behaviour.</li></ul><h3>Buffered Channel</h3><p>A Buffered Channel allows concurrent Goroutines to send and receive values with a specified capacity by temporarily storing elements.</p><p>This enables sending without an immediate receiver until the buffer is full.</p><p>Sending a full buffer or receiving from an empty buffer will block until space is available or data is sent.</p><p>This helps coordination between concurrent processes, enhancing parallelism and synchronisation in Go Programs.</p><p>Buffered Channels have a memory allocation cost. The buffer size is statically allocated, not dynamic.</p><p>We create a Buffered Channel like in the example below.</p><p>Here we use the make function to create a string channel with a specified buffer size of 1.</p><pre>func main() {<br>  ch := make(chan string, 1) // Buffer size of 1<br>  ch &lt;- &quot;message&quot;<br>  fmt.Println(&lt;-ch)<br>}</pre><h3>Unbuffered Channels</h3><p>An Unbuffered Channel facilitates synchronous communication between concurrent Goroutines.</p><p>Unbuffered Channels have no capacity and require both the sender and receiver to be ready at the same time.</p><p>The sending and receiving operations block until the other side is ready.</p><p>This enforces synchronise communication between Goroutines.</p><pre>ch := make(chan int)</pre><h3>Directional Channels</h3><p>Channels in Golang can be further categorised based on their usage and data flow.</p><p>By default, unless specified Channels are bidirectional — we can both send and receive messages.</p><p>To restrict a channels flow you can categorise channels on if they are send-only or receive-only. We want to do this to promote readability and so the compiler enforces this to prevent bugs.</p><p>You can do this by simply adding a left-facing arrow &lt;- on the chan:</p><ul><li>chan&lt;- send-only, &lt;-chan receive-only</li></ul><p>In the example below we have sendOnly and receiveOnly functions that are called from main as Goroutines.</p><p>In main we declare a Bidirectional Unbuffered Channel that.</p><p>We create a wait group which will wait for 2 Goroutines to complete before exiting the main function.</p><p>sendOnly populates the channel with “message”.</p><p>receiveOnly will print out the “message” to the terminal once it is available.</p><pre>func main() {<br> ch := make(chan string)<br> var wg sync.WaitGroup<br><br> wg.Add(2)<br><br> go sendOnly(ch, &amp;wg)<br><br> go receiveOnly(ch, &amp;wg)<br><br> wg.Wait()<br>}<br><br>func sendOnly(ch chan&lt;- string, wg *sync.WaitGroup) {<br> defer wg.Done()<br> ch &lt;- &quot;message&quot;<br>}<br><br>func receiveOnly(ch &lt;-chan string, wg *sync.WaitGroup) {<br> defer wg.Done()<br> fmt.Println(&lt;-ch)<br>}</pre><h3>Control Flow With Channels</h3><p>We have two Control Flow constructs for working with Channels:</p><ul><li>Select Statement — Similar to a Switch Statement, but specifically designed to work with Channel operations that can proceed or not.</li><li>For Loop — Like a collection, we can loop through the messages in a Channel.</li></ul><h4>Select Statements with Channels</h4><p>The built-in “select” keyword is used to wait on multiple Channel operations.</p><p>The Select Statement allows Goroutines to wait for multiple communication operations on multiple channels.</p><p>The Select Statement blocks until one of the cases are met.</p><p>If no cases are met we can run into deadlocks unless there is a default case.</p><p>In the below example, we have two Unbuffered Channels and two Goroutines that will populate their respective channel with 1 or 2.</p><p>We have a Select Statement that blocks until one of the Channels is available.</p><p>There are three cases, a case for channel 1 and 2, and a case that serves as a timeout.</p><p>In this case the channel 1 will complete first, so the first case in the Select Statement will output to the terminal.</p><pre>func main() {<br>    ch1 := make(chan int)<br>    ch2 := make(chan int)<br><br><br>    go func() {<br>        time.Sleep(2 * time.Second)<br>        ch1 &lt;- 1<br>    }()<br><br><br>    go func() {<br>        time.Sleep(3 * time.Second)<br>        ch2 &lt;- 2<br>    }()<br><br><br>    select {<br>    case val := &lt;-ch1:<br>        fmt.Println(&quot;Received from ch1:&quot;, val)<br>    case val := &lt;-ch2:<br>        fmt.Println(&quot;Received from ch2:&quot;, val)<br>    case &lt;-time.After(4 * time.Second):<br>        fmt.Println(&quot;Timeout occurred&quot;)<br>    }<br>}</pre><p>What if both cases are met at the same time like in the below example?</p><p>Here we have two Buffered Channel.</p><p>Channel 1 is a channel that expects an integer with a set buffer of 1.</p><p>Channel 2 is a channel that expects a string with a set buffer of 1.</p><p>Both will complete at the same time.</p><p>So which statement will be outputted first?</p><pre>func main() {<br> ch1 := make(chan int, 1)<br> ch2 := make(chan string, 1)<br><br> ch1 &lt;- 9001<br> ch2 &lt;- &quot;Goku&quot;<br><br> select {<br> case msg := &lt;-ch1:<br>  fmt.Println(msg)<br> case msg := &lt;-ch2:<br>  fmt.Println(msg)<br> }<br>}</pre><p>If this were a Switch Statement, the first case that meets the criteria would be acted upon.</p><p>However, that’s not true for Select Statements.</p><p>In this case it’s actually undefined behaviour.</p><p>Reason for this is because Select Statements work with Channels and Channels imply concurrent behaviour.</p><p>We want to avoid deterministic behaviours when working concurrently with Golang because it can deceive us into making certain assumptions about how the program is going to execute, which leads to synchronise-thinking in asynchronous workflows.</p><p>So when we run into the above situation where both cases are valid, the Go Runtime will actually randomise which case is selected.</p><p>So sometimes we’ll get the number 9001 and other times we’ll get the message “Goku” printed out…</p><h4>For Loop with Channels</h4><p>Can use For Loops to iterate over Channel messages.</p><p>In the below example we’re demonstrating the usage of a for loop with an Unbuffered Channel.</p><p>Here we have a worker goroutine that receives integers from the main goroutine, processes them, and sends results back through another channel.</p><p>The for loop in the main function handles sending data to the worker and receiving results.</p><pre>// Worker function that processes numbers and sends the result back<br>func worker(id int, jobs &lt;-chan int, results chan&lt;- int, wg *sync.WaitGroup) {<br> defer wg.Done()<br> for j := range jobs {<br>  fmt.Printf(&quot;Worker %d processing job %d\n&quot;, id, j)<br>  results &lt;- j * 2<br> }<br>}<br><br>func main() {<br> jobs := make(chan int)<br> results := make(chan int)<br> var wg sync.WaitGroup<br><br> wg.Add(1)<br> go worker(1, jobs, results, &amp;wg)<br><br> go func() {<br>  for i := 1; i &lt;= 5; i++ {<br>   jobs &lt;- i<br>  }<br>  close(jobs)<br> }()<br><br> go func() {<br>  for i := 1; i &lt;= 5; i++ {<br>   result := &lt;-results<br>   fmt.Printf(&quot;Result received: %d\n&quot;, result)<br>  }<br>  close(results)<br> }()<br><br> wg.Wait()<br>}</pre><p>The Worker Goroutine receives an id integer, jobs as a receiveOnly channel of integers, results as a sendOnly channel of integers and a WaitGroup to signal when the Goroutine is completed.</p><p>It loops over the jobs channel, processes each job and sends the result back through the results channel.</p><p>In the main function we have two Unbuffered Channels: jobs and results.</p><p>The jobs channel is responsible for sending out jobs to the worker.</p><p>The results channel is responsible for receiving processed results.</p><p>The work Goroutine is started and we wait for this to finish using the WaitGroup.</p><p>We then send five jobs to the worker in a separate Goroutine and close the jobs channel once this complete.</p><p>Receives and prints the results from the results channel in another Gorountine and closes the results channel when done.</p><p>It’s important that the close() function is called to prevent any additional messages coming into the channel. This tells the Go Runtime that we are expecting no more messages so it doesn’t cause a deadlock by trying to iterate over a non-existent message.</p><pre>Worker 1 processing job 1<br>Worker 1 processing job 2<br>Result received: 2<br>Result received: 4<br>Worker 1 processing job 3<br>Worker 1 processing job 4<br>Result received: 6<br>Result received: 8<br>Worker 1 processing job 5</pre><h3>Summary</h3><p>In summary, we quickly went over what Channels are, types of Channel, and Channel Control Flow.</p><p>Channels are designed for communication between between Goroutines.</p><p>They enable data exchange between Goroutines by coordinating them to allow routines to send data to each other and synchronise their execution to ensure data can safely be passed between different executing threads.</p><p>Channels are blocking operations. They cause the application to wait until communication can be proceed — somewhat similar to async/await in other languages.</p><p>Primarily there’s two types of Channel:</p><ul><li>Buffered — Asynchronous Behaviour</li><li>Unbuffered — Synchronous Behaviour</li></ul><p>Channels are bidirectional by default. We can restrict a channels flow by categorising them with a left-facing arrow as send-only or receive-only.</p><ul><li>chan&lt;- send-only, &lt;-chan receive-only</li></ul><p>The Go Compiler will enforce this. We restrict the channel flows to prevent unnecessary bugs and to promote readability.</p><p>As for Channel Control Flow we have two constructs for working with Channels:</p><ul><li>Select Statement — Similar to a Switch Statement, but specifically designed to work with Channel operations that can proceed or not.</li><li>For Loop — Like a collection, we can loop through the messages in a Channel.</li></ul><h3>Links</h3><p>If you have any questions/suggestions you can contact me below:</p><p><a href="https://www.linkedin.com/in/luke-sloane-bulger/">Linkedln</a></p><p><a href="https://twitter.com/CodingWithSB">Twitter</a></p><p>Follow me on Medium: <a href="https://medium.com/u/f068ade2f3fe?source=post_page-----6799782d7cb5--------------------------------">Luke Sloane-Bulger</a></p><figure><a href="https://www.buymeacoffee.com/lukesb"><img alt="" src="https://cdn-images-1.medium.com/max/170/1*WfbwTpxi0c0k2Vwzp3s5yg.png" /></a><figcaption>Found this article useful? Feel free to buy me a coffee by clicking the button above</figcaption></figure><h3>Did you like this article? Be sure to share it on social networks. Thanks!</h3><h3>Stackademic 🎓</h3><p>Thank you for reading until the end. Before you go:</p><ul><li>Please consider <strong>clapping</strong> and <strong>following</strong> the writer! 👏</li><li>Follow us <a href="https://twitter.com/stackademichq"><strong>X</strong></a> | <a href="https://www.linkedin.com/company/stackademic"><strong>LinkedIn</strong></a> | <a href="https://www.youtube.com/c/stackademic"><strong>YouTube</strong></a> | <a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Discord</strong></a></li><li>Visit our other platforms: <a href="https://plainenglish.io/"><strong>In Plain English</strong></a> | <a href="https://cofeed.app/"><strong>CoFeed</strong></a> | <a href="https://differ.blog/"><strong>Differ</strong></a></li><li>More content at <a href="https://stackademic.com/"><strong>Stackademic.com</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f5d5065e52c2" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/what-are-channels-in-golang-learn-in-3-minutes-f5d5065e52c2">What are Channels in Golang? Learn in 3 Minutes</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What is MVC? Learn in 3 Minutes]]></title>
            <link>https://blog.stackademic.com/what-is-mvc-learn-in-3-minutes-905a2abdd3c2?source=rss-f068ade2f3fe------2</link>
            <guid isPermaLink="false">https://medium.com/p/905a2abdd3c2</guid>
            <category><![CDATA[guides-and-tutorials]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[software]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[mvc-architecture]]></category>
            <dc:creator><![CDATA[Luke Sloane-Bulger]]></dc:creator>
            <pubDate>Tue, 05 Mar 2024 04:17:40 GMT</pubDate>
            <atom:updated>2024-03-05T04:17:40.043Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="What is MVC? Learn in 3 Minutes." src="https://cdn-images-1.medium.com/max/1024/1*uP3Eb1NmJduNRC847GAEhw.png" /><figcaption>What is MVC? In 3 Minutes</figcaption></figure><p>In this article, we’ll quickly go over what the MVC (Model-View-Controller) pattern is, why it is used, and examples.</p><h3>What is MVC and Why Use It?</h3><p>MVC is a software design architecture pattern that essentially splits an application into three specific components.</p><p>Each of these components has their own specific purpose.</p><p>We use the the MVC design pattern to help separate projects into smaller interconnected components for a separation of concerns.</p><p>This makes the project easier to manage, maintain and scale with any new additional future features.</p><p>Model — Responsible for handling data and business logic. The Model interacts with the Database, handles all validation, saving, deleting, etc, of the data.</p><p>View — The View is only concerned with handling data presentation and what to do with the data it receives from the Controller.</p><p>Controller — Acts as a Middleman between the Model and View. It should not contain much logic. It should only be used to interact and coordinate the workflows between the Model and View.</p><h3>Web Application Example</h3><figure><img alt="1. /getBooks request to Controller. 2. Model — Interact with database to get books, passes back to the Controller. 3. The Controller sends that books data to the View, which handles data presentation. 4. The Controller returns response to UI." src="https://cdn-images-1.medium.com/max/1024/1*_6WE-fVYohyeA9Q_z7r6VA.png" /></figure><p>To illustrate this let’s use the example of a Books website.</p><p>The user wants to see a list of their saved books.</p><p>When the user opens the page an endpoint is called called /getBooks.</p><p>Behind the scenes, the endpoint calls our handler controller.GetBooksHandler().</p><pre>package controller<br><br>...<br><br>func GetBooksHandler(w http.ResponseWriter, r *http.Request) {<br>    if r.Method == http.MethodGet {<br>        books, err := model.GetAll()<br>    <br>        if helper.IsHTTPStatusError(w, err, http.StatusInternalServerError) {<br>            return<br>        }<br>    <br>        jsonResponse, err := view.RenderJSON(view.Envelope{&quot;books&quot;: books})<br>      <br>        if helper.IsHTTPStatusError(w, err, http.StatusInternalServerError) {<br>            return<br>        }<br>      <br>        writeJSONResponse(w, http.StatusOK, jsonResponse, nil)<br>    }<br>}</pre><p>As we can see in the example, the controller first calls the model.GetAll() function.</p><pre>package model<br><br>...<br><br>func GetAll() ([]*data.Book, error) {<br>    dataBook, err := collection.GetAll()<br>    if err != nil {<br>        return nil, err<br>    }<br>    return dataBook, nil<br>}</pre><p>The model.GetAll() is responsible for doing our DB calls.</p><p>In this case, we’re calling to our database to perform a retrieve CRUD operation.</p><p>Let’s assume we have a successful response, and we pass our books data back to the Controller.</p><p>The next step for the Controller is to call the view.RenderJSON() function.</p><pre>package view<br><br>...<br><br>func RenderJSON(data Envelope) ([]byte, error) {<br>    jsonResponse, err := json.MarshalIndent(data, &quot;&quot;, &quot;\t&quot;)<br>    <br>    if err != nil {<br>        return nil, err<br>    }<br>    <br>    jsonResponse = append(jsonResponse, &#39;\n&#39;)<br>    <br>    return jsonResponse, nil<br>}</pre><p>Here, we’re handling how we want to present our JSON data back in our /getBooks response.</p><p>Basically wrapping the JSON in an envelope and indenting it.</p><p>Then the View returns this back to our Controller.</p><p>Finally, the Controller returns the JSON response to the UI to present the books to our user.</p><h3>Summary</h3><p>Above we covered what MVC is, why we use MVC and ran over a quick example.</p><p>MVC is a software design architectural pattern that splits an application into three specific components.</p><p>Each component has its own purpose.</p><p>Model — Responsible for handling data and business logic.</p><p>View — The view is only concerned with handling data presentation.</p><p>Controller — Acts as a Middleman between the Model and View.</p><p>We use the the MVC design pattern to help separate projects into smaller interconnected components for a separation of concerns.</p><p>This is so the project is easier to manage, maintain and scale with any new additional future features.</p><p>To explain each section let’s use an example in which a user is interacting with a page, which calls to a server for data.</p><figure><img alt="1. Request to Controller. 2. Model — Interact with database to get data, passes back to the Controller. 3. The Controller sends that data to the View, which handles data presentation. 4. The Controller returns response to UI." src="https://cdn-images-1.medium.com/max/1024/1*u0dPe-2I1h3o4o_8aAuEtw.png" /><figcaption>Model View Controller Representation</figcaption></figure><p>The Controller handles the incoming request and responds with the appropriate workflow.</p><p>The Controller starts by calling to the Model.</p><p>The Model handles the data/business logic for that particular request and interacts with the Database to get the relevant data.</p><p>This data is sent back to the Controller.</p><p>Now, the Controller calls to the View with the data it’s received from the Model.</p><p>The View dynamically renders the data and presents it back to the Controller.</p><p>Finally, the Controller sends back the response to the webpage for the UI to render and display to the user.</p><h3>Links</h3><p>If you have any questions/suggestions you can contact me below:</p><p><a href="https://www.linkedin.com/in/luke-sloane-bulger/">Linkedln</a></p><p><a href="https://twitter.com/CodingWithSB">Twitter</a></p><p>Follow me on Medium: <a href="https://medium.com/u/f068ade2f3fe?source=post_page-----6799782d7cb5--------------------------------">Luke Sloane-Bulger</a></p><figure><a href="https://www.buymeacoffee.com/lukesb"><img alt="" src="https://cdn-images-1.medium.com/max/170/1*WfbwTpxi0c0k2Vwzp3s5yg.png" /></a><figcaption>Found this article useful? Feel free to buy me a coffee by clicking the button above</figcaption></figure><h3>Did you like this article? Be sure to share it on social networks. Thanks!</h3><h3>Stackademic 🎓</h3><p>Thank you for reading until the end. Before you go:</p><ul><li>Please consider <strong>clapping</strong> and <strong>following</strong> the writer! 👏</li><li>Follow us <a href="https://twitter.com/stackademichq"><strong>X</strong></a><strong> | </strong><a href="https://www.linkedin.com/company/stackademic"><strong>LinkedIn</strong></a><strong> | </strong><a href="https://www.youtube.com/c/stackademic"><strong>YouTube</strong></a><strong> | </strong><a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Discord</strong></a></li><li>Visit our other platforms: <a href="https://plainenglish.io/"><strong>In Plain English</strong></a><strong> | </strong><a href="https://cofeed.app/"><strong>CoFeed</strong></a><strong> | </strong><a href="https://venturemagazine.net/"><strong>Venture</strong></a><strong> | </strong><a href="https://blog.cubed.run/"><strong>Cubed</strong></a></li><li>More content at <a href="https://stackademic.com/"><strong>Stackademic.com</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=905a2abdd3c2" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/what-is-mvc-learn-in-3-minutes-905a2abdd3c2">What is MVC? Learn in 3 Minutes</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>