<?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 Asefeh Sadid on Medium]]></title>
        <description><![CDATA[Stories by Asefeh Sadid on Medium]]></description>
        <link>https://medium.com/@aasefeh?source=rss-b07a44374f7e------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*j8Bo9FQMIdTUA7Eb</url>
            <title>Stories by Asefeh Sadid on Medium</title>
            <link>https://medium.com/@aasefeh?source=rss-b07a44374f7e------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 08:49:08 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@aasefeh/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[“Developing a Google OAuth-Powered App with Go”]]></title>
            <link>https://medium.com/@aasefeh/developing-a-google-oauth-powered-app-with-go-a9719d12520e?source=rss-b07a44374f7e------2</link>
            <guid isPermaLink="false">https://medium.com/p/a9719d12520e</guid>
            <dc:creator><![CDATA[Asefeh Sadid]]></dc:creator>
            <pubDate>Sun, 05 Jan 2025 20:35:25 GMT</pubDate>
            <atom:updated>2025-01-05T20:35:25.301Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8l0EdEn7Q8eurnu4ZFUWsw.jpeg" /></figure><p>In this tutorial, I’ll walk you through how I built an application that integrates with Google APIs using OAuth in Go. This app allows users to authenticate via Google, fetch recent emails from Gmail, and list files from Google Drive.</p><p>You’ll also find code snippets, a sample output, and a link to the GitHub repository at the end.</p><h3>Why OAuth and Google APIs?</h3><p>OAuth2 is the industry-standard protocol for authorization. By using OAuth, we can allow users to grant our app permission to access their data securely. Combined with Google APIs, this enables functionality like fetching emails and managing files without compromising user credentials.</p><h3>Setting Up Your Google Cloud Project</h3><p>To get started, you need to set up a Google Cloud Project:</p><ol><li><strong>Create a project</strong> in the Google Cloud Console.</li><li>Navigate to <strong>API &amp; Services &gt; Library</strong> and enable the Gmail API, Google Drive API, or any other APIs you want to use.</li><li>Go to <strong>API &amp; Services &gt; Credentials</strong> and create an <strong>OAuth Client ID</strong>.</li></ol><ul><li>Select <strong>Web Application</strong> as the application type.</li><li>Add your app’s callback URL (e.g., <a href="http://localhost:8888/api/v1/admin/callback).">http://localhost:8888/api/v1/admin/callback).</a></li></ul><p>4. Once created, you’ll receive a <strong>Client ID</strong> and <strong>Client Secret</strong>. Save these as you’ll use them in your Go application.</p><h3>Project Overview</h3><h4>Core Functionalities</h4><ol><li>Authenticate users via Google OAuth.</li><li>Fetch the user’s recent emails.</li><li>List files from the user’s Google Drive.</li></ol><h3>Customized API Endpoints</h3><p>This app uses the /api/v1 prefix for all OAuth-related endpoints, but you can adjust it to match your app’s structure. For example, the following handlers are used for authentication and data retrieval:</p><ul><li>/api/v1/admin: Initiates the Google OAuth flow.</li><li>/api/v1/admin/callback: Handles the OAuth callback.</li><li>/api/v1/emails: Fetches emails from Gmail.</li><li>/api/v1/drive: Lists files from Google Drive.</li></ul><p>Feel free to replace /api/v1/admin with any path that suits your app’s design.</p><h3>Installing OAuth and Google API Libraries</h3><p>To integrate with Google APIs in Go, you’ll need the following libraries:</p><pre>$ go get golang.org/x/oauth2  <br>$ go get golang.org/x/oauth2/google  <br>$ go get google.golang.org/api/gmail/v1  <br>$ go get google.golang.org/api/drive/v3<br></pre><p>These libraries provide the tools to handle OAuth flows and interact with Gmail and Drive APIs.</p><h3>Authentication Flow</h3><h4>Configuring OAuth</h4><p>We start by defining the OAuth2 configuration in a dedicated package, oauth:</p><pre>package oauth  <br><br>import (  <br> &quot;golang.org/x/oauth2&quot;  <br> &quot;golang.org/x/oauth2/google&quot;  <br>)  <br><br>var OauthConfig *oauth2.Config  <br><br>func InitOAuth() {  <br> OauthConfig = &amp;oauth2.Config{  <br>  ClientID:     &quot;&lt;Your Client ID&gt;&quot;,  <br>  ClientSecret: &quot;&lt;Your Client Secret&gt;&quot;,  <br>  Scopes: []string{  <br>   &quot;https://www.googleapis.com/auth/userinfo.email&quot;,  <br>   &quot;https://www.googleapis.com/auth/userinfo.profile&quot;,  <br>   &quot;https://www.googleapis.com/auth/gmail.readonly&quot;,  <br>   &quot;https://www.googleapis.com/auth/drive.readonly&quot;,  <br>  },  <br>  RedirectURL: &quot;http://localhost:8888/api/v1/admin/callback&quot;,  <br>  Endpoint:    google.Endpoint,  <br> }  <br>}</pre><p><strong>Note:</strong> The URL /api/v1/admin/callback is an example endpoint for handling OAuth callbacks. You can adjust this to match your application&#39;s URL structure. For example, /api/v1/user/callback or /oauth/callback might make more sense depending on your use case.</p><h4>Redirecting to Google OAuth</h4><p>To initiate the authentication flow, the app uses the AuthHandler.</p><pre>func AuthHandler(c *gin.Context) {  <br>    if oauth.OauthConfig == nil {  <br>        c.JSON(http.StatusInternalServerError, gin.H{&quot;error&quot;: &quot;OAuth config is not initialized&quot;})  <br>        return  <br>    }  <br>    url := oauth.OauthConfig.AuthCodeURL(&quot;state&quot;, oauth2.AccessTypeOffline, oauth2.ApprovalForce)  <br>    c.Redirect(http.StatusTemporaryRedirect, url)  <br>}</pre><p>Visiting /api/v1/admin in your browser will redirect users to Google for authentication.</p><p><strong>Customizing </strong><strong>/api/v1/admin:</strong> This endpoint is customizable. If you&#39;re using a different structure, replace /api/v1/admin with your preferred path, such as /auth/login.</p><h4>Handling the Callback</h4><p>Once the user grants permission, the AuthCallbackHandler exchanges the authorization code for a token:</p><pre>func AuthCallbackHandler(c *gin.Context) {  <br>    code := c.Query(&quot;code&quot;)  <br>    if code == &quot;&quot; {  <br>        c.Redirect(http.StatusTemporaryRedirect, &quot;/api/v1/error?message=No code in the query string&quot;)  <br>        return  <br>    }  <br><br>    token, err := oauth.OauthConfig.Exchange(c, code)  <br>    if err != nil {  <br>        c.Redirect(http.StatusTemporaryRedirect, &quot;/api/v1/error?message=Failed to exchange token&quot;)  <br>        return  <br>    }  <br><br>    userTokens[&quot;user&quot;] = token  <br>    c.String(http.StatusOK, &quot;User authenticated successfully!&quot;)  <br>}</pre><h4>Gmail API Integration</h4><p>After authentication, the app retrieves the user’s recent emails, including the sender, recipient, subject, and date:</p><pre>func FetchEmailsHandler(c *gin.Context) {  <br>    // Retrieve the token (for demonstration, using a hardcoded user key)  <br>    token, exists := userTokens[&quot;user&quot;]  <br>    if !exists {  <br>        c.JSON(http.StatusUnauthorized, gin.H{&quot;error&quot;: &quot;User not authenticated&quot;})  <br>        return  <br>    }  <br><br>    client := oauth.OauthConfig.Client(c, token)  <br>    service, err := gmail.NewService(c, option.WithHTTPClient(client))  <br>    if err != nil {  <br>        c.JSON(http.StatusInternalServerError, gin.H{&quot;error&quot;: &quot;Failed to create Gmail service&quot;})  <br>        return  <br>    }  <br><br>    // Fetch the first 10 messages  <br>    msgs, err := service.Users.Messages.List(&quot;me&quot;).MaxResults(10).Do()  <br>    if err != nil {  <br>        c.JSON(http.StatusInternalServerError, gin.H{&quot;error&quot;: &quot;Failed to fetch messages&quot;})  <br>        return  <br>    }  <br><br>    essentialKeys := []string{&quot;From&quot;, &quot;To&quot;, &quot;Subject&quot;, &quot;Date&quot;}  <br><br>    emailDetails := []map[string]interface{}{}  <br>    for _, msg := range msgs.Messages {  <br><br>        fullMessage, err := service.Users.Messages.Get(&quot;me&quot;, msg.Id).Do()  <br>        if err != nil {  <br>            continue<br>        }  <br><br>        filteredHeaders := map[string]string{}  <br>        for _, header := range fullMessage.Payload.Headers {  <br>            for _, key := range essentialKeys {  <br>                if header.Name == key {  <br>                    filteredHeaders[key] = header.Value  <br>                }  <br>            }  <br>        }  <br><br>        emailDetails = append(emailDetails, map[string]interface{}{  <br>            &quot;ID&quot;:      msg.Id,  <br>            &quot;Headers&quot;: filteredHeaders,  <br>        })  <br>    }  <br><br>    c.JSON(http.StatusOK, gin.H{&quot;emails&quot;: emailDetails})  <br>}</pre><p><strong>Endpoint:</strong> /api/v1/admin/emails</p><h4>Explanation</h4><ol><li><strong>Token Retrieval:</strong><br>The function retrieves the OAuth token from userTokens to authorize the API call.</li><li><strong>Fetching Messages:</strong><br>The Gmail API’s Users.Messages.List fetches up to 10 recent messages.</li><li><strong>Extracting Headers:</strong><br>For each message, the Users.Messages.Get method retrieves detailed information, including headers. These headers are filtered to include only the essential keys: &quot;From&quot;, &quot;To&quot;, &quot;Subject&quot;, and &quot;Date&quot;.</li><li><strong>JSON Response:</strong><br>The extracted data is structured into a JSON format and returned to the client.</li></ol><h4>Sample API Response</h4><p>When you call this endpoint, the response might look like this:</p><pre>{  <br>    &quot;emails&quot;: [  <br>        {  <br>            &quot;ID&quot;: &quot;17c23d9f&quot;,  <br>            &quot;Headers&quot;: {  <br>                &quot;From&quot;: &quot;example@gmail.com&quot;,  <br>                &quot;To&quot;: &quot;user@gmail.com&quot;,  <br>                &quot;Subject&quot;: &quot;Welcome to Google!&quot;,  <br>                &quot;Date&quot;: &quot;Thu, 1 Jan 2025 12:00:00 +0000&quot;  <br>            }  <br>        },  <br>        {  <br>            &quot;ID&quot;: &quot;17c23eaf&quot;,  <br>            &quot;Headers&quot;: {  <br>                &quot;From&quot;: &quot;report@gmail.com&quot;,  <br>                &quot;To&quot;: &quot;user@gmail.com&quot;,  <br>                &quot;Subject&quot;: &quot;Monthly Report&quot;,  <br>                &quot;Date&quot;: &quot;Fri, 2 Jan 2025 15:00:00 +0000&quot;  <br>            }  <br>        }  <br>    ]  <br>}</pre><h3>Fetching Files from Google Drive</h3><p>Here’s the function to fetch files from Google Drive:</p><pre>func FetchDriveFilesHandler(c *gin.Context) {  <br>    // Retrieve the token (for demonstration, using a hardcoded user key)  <br>    token, exists := userTokens[&quot;user&quot;]  <br>    if !exists {  <br>        c.JSON(http.StatusUnauthorized, gin.H{&quot;error&quot;: &quot;User not authenticated&quot;})  <br>        return  <br>    }  <br><br>    client := oauth.OauthConfig.Client(c, token)  <br>    driveService, err := drive.NewService(c, option.WithHTTPClient(client))  <br>    if err != nil {  <br>        c.JSON(http.StatusInternalServerError, gin.H{&quot;error&quot;: &quot;Failed to create Drive service&quot;})  <br>        return  <br>    }  <br><br>    // Fetch the first 10 files  <br>    fileList, err := driveService.Files.List().Fields(&quot;files(id, name)&quot;).PageSize(10).Do()  <br>    if err != nil {  <br>        c.JSON(http.StatusInternalServerError, gin.H{&quot;error&quot;: &quot;Failed to fetch files&quot;})  <br>        return  <br>    }  <br><br>    files := []map[string]string{}  <br>    for _, file := range fileList.Files {  <br>        files = append(files, map[string]string{  <br>            &quot;ID&quot;:   file.Id,  <br>            &quot;Name&quot;: file.Name,  <br>        })  <br>    }  <br><br>    c.JSON(http.StatusOK, gin.H{&quot;files&quot;: files})  <br>}</pre><p><strong>Endpoint:</strong> /api/v1/admin/drive</p><h4>Explanation</h4><ol><li><strong>Token Retrieval:</strong><br>The handler authenticates the user using their OAuth token.</li><li><strong>Google Drive API Service:</strong><br>The drive.NewService initializes the API client.</li><li><strong>Fetching Files:</strong><br>The Files.List method retrieves the first 10 files and their metadata (ID and name).</li><li><strong>Formatting Response:</strong><br>The data is formatted into a JSON response containing file details.</li></ol><h4>Sample Response</h4><pre>{  <br>    &quot;files&quot;: [  <br>        {  <br>            &quot;ID&quot;: &quot;1a2b3c4d&quot;,  <br>            &quot;Name&quot;: &quot;Report.pdf&quot;  <br>        },  <br>        {  <br>            &quot;ID&quot;: &quot;5e6f7g8h&quot;,  <br>            &quot;Name&quot;: &quot;Presentation.pptx&quot;  <br>        }  <br>    ]  <br>}</pre><h3>Conclusion</h3><p>By integrating Google OAuth with Gmail and Drive APIs, we’ve built a Go application that fetches emails and lists Google Drive files efficiently. These handlers can be extended further for other operations like file uploads, message searches, and more.</p><p>Check out the <a href="https://github.com/Asefeh-J/OAuth_Go">GitHub Repository</a> for the complete project.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a9719d12520e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Setting Up a Redis Cluster in a Go Application Using Docker Compose]]></title>
            <link>https://medium.com/@aasefeh/setting-up-a-redis-cluster-in-a-go-application-using-docker-compose-0e8044dfb6d1?source=rss-b07a44374f7e------2</link>
            <guid isPermaLink="false">https://medium.com/p/0e8044dfb6d1</guid>
            <dc:creator><![CDATA[Asefeh Sadid]]></dc:creator>
            <pubDate>Sun, 15 Dec 2024 19:54:44 GMT</pubDate>
            <atom:updated>2024-12-15T19:54:44.546Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ac40KuW-MuKF6YgJIeqbww.png" /></figure><p>When building scalable applications, leveraging a Redis cluster can provide high availability and enhanced performance. In this article, we’ll walk through the steps of setting up a Redis cluster using Docker Compose and integrating it into a Go application. By the end, you’ll have a working Redis cluster and a Go app connected to it.</p><h4>1. Setting Up a Redis Cluster Using Docker Compose</h4><p>To begin, let’s define our Docker Compose configuration. This file will set up a Redis cluster with three nodes. Below is the docker-compose.yml file:</p><pre><br>version: &#39;3.8&#39;<br>services:<br>redis1:<br>    image: redis:latest<br>    command: &gt;<br>      redis-server --cluster-enabled yes --cluster-config-file /data/nodes.conf<br>      --cluster-node-timeout 5000 --appendonly yes --port 6379<br>      --bind 0.0.0.0 --protected-mode no<br>    ports:<br>      - &quot;7001:6379&quot;<br>      - &quot;17001:16379&quot;<br>    networks:<br>      redis-cluster-net:<br>        ipv4_address: 192.168.240.100      <br>    restart: always<br>redis2:<br>    image: redis:latest<br>    command: &gt;<br>      redis-server --cluster-enabled yes --cluster-config-file /data/nodes.conf<br>      --cluster-node-timeout 5000 --appendonly yes --port 6379<br>      --bind 0.0.0.0 --protected-mode no<br>    ports:<br>      - &quot;7002:6379&quot;<br>      - &quot;17002:16379&quot;<br>    networks:<br>      redis-cluster-net:<br>        ipv4_address: 192.168.240.101<br>    restart: always<br>redis3:<br>    image: redis:latest<br>    command: &gt;<br>      redis-server --cluster-enabled yes --cluster-config-file /data/nodes.conf<br>      --cluster-node-timeout 5000 --appendonly yes --port 6379<br>      --bind 0.0.0.0 --protected-mode no<br>    ports:<br>      - &quot;7003:6379&quot;<br>      - &quot;17003:16379&quot;<br>    restart: always<br>    networks:<br>      redis-cluster-net:<br>        ipv4_address: 192.168.240.102<br>redis-cluster-setup:<br>    image: redis:latest<br>    depends_on:<br>      - redis1<br>      - redis2<br>      - redis3<br>    entrypoint: &gt;<br>      sh -c &quot;<br>      sleep 30 &amp;&amp;<br>      echo yes | redis-cli --cluster create<br>      192.168.240.100:6379 192.168.240.101:6379 192.168.240.102:6379<br>      --cluster-replicas 0<br>      &quot;<br>    networks:<br>      redis-cluster-net:<br>        ipv4_address: 192.168.240.103    <br>networks:<br>  redis-cluster-net:<br>    driver: bridge<br>    driver_opts:<br>      com.docker.network.bridge.host_binding_ipv4: &quot;0.0.0.0&quot;<br>    ipam:<br>      config:<br>        - subnet: 192.168.240.0/20  <br>          gateway: 192.168.240.1</pre><p><strong>Explanation:</strong></p><ul><li>Each Redis service (redis1, redis2, redis3) is configured to enable clustering with --cluster-enabled yes.</li><li>The redis-cluster-setup service initializes the cluster using redis-cli after the nodes are up.</li><li>Custom IP addresses and a shared network (redis-cluster-net) ensure that the nodes can communicate.</li></ul><p><strong>Start the cluster:</strong> Run the following command to launch the cluster:</p><pre>$ docker-compose up -d</pre><p>Once the cluster is running, you can check the status using:</p><pre>$ redis-cli -h 192.168.240.100 -p 6379 cluster nodes</pre><h4>2. Connecting a Go Application to the Redis Cluster</h4><p>Now that the Redis cluster is set up, let’s connect it to a Go application. Here is the Go code for initializing a Redis client:</p><pre>package cache<br><br>import (<br><br> //...<br><br> &quot;github.com/redis/go-redis/v9&quot;<br>)<br><br>var Client *redis.ClusterClient<br><br>// StartRedis initializes the Redis client and performs a test.<br>func StartRedis() {<br> Client = redis.NewClusterClient(&amp;redis.ClusterOptions{<br>  Addrs: []string{<br>   &quot;localhost:7001&quot;,<br>   &quot;localhost:7002&quot;,<br>   &quot;localhost:7003&quot;,<br>  },<br>  DialTimeout:  30 * time.Second,<br>  ReadTimeout:  30 * time.Second,<br>  WriteTimeout: 30 * time.Second,<br><br>  RouteByLatency: true, // Optimize routing by latency.<br> })<br><br><br> ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)<br> defer cancel()<br><br> _, err := Client.Ping(ctx).Result()<br> if err != nil {<br>  logger.Inst().Error(fmt.Sprintf(&quot;Failed to connect to Redis: %v&quot;, err))<br>  os.Exit(-1)<br> }<br> logger.Inst().Info(&quot;Redis connection successful.&quot;)<br>}</pre><p><strong>Key Points:</strong></p><ol><li><strong>Redis Library</strong>: The go-redis/v9 library simplifies working with Redis clusters in Go. Use the following command to install the go-redis/v9 library:</li></ol><pre>$ go get github.com/redis/go-redis/v9</pre><ol><li><strong>Cluster Options</strong>:</li></ol><ul><li>Addrs: List of Redis cluster node addresses.</li><li>RouteByLatency: Routes commands to the node with the least latency.</li></ul><p><strong>3. Connection Testing</strong>:</p><ul><li>The Ping command ensures that the connection is active.</li><li>Errors are logged using a custom logger.</li></ul><p>Add this code to your application and call StartRedis() during app initialization to connect to the cluster.</p><h4>3. Testing the Integration</h4><p>With both the cluster and the Go application running, you can verify the connection:</p><ol><li>Start the application and check logs for the message: Redis connection successful.</li><li>Perform basic Redis operations to validate functionality:</li></ol><pre>ctx := context.Background()<br>err := Client.Set(ctx, &quot;key&quot;, &quot;value&quot;, 0).Err()<br>if err != nil {<br>    fmt.Println(&quot;Failed to set key:&quot;, err)<br>    return<br>}<br>val, err := Client.Get(ctx, &quot;key&quot;).Result()<br>if err != nil {<br>    fmt.Println(&quot;Failed to get key:&quot;, err)<br>    return<br>}<br>fmt.Println(&quot;Value:&quot;, val)</pre><h4>4. Troubleshooting Tips</h4><ol><li><strong>Connection Issues</strong>:</li></ol><ul><li>Ensure Docker containers are running with docker ps.</li><li>Use redis-cli to verify cluster status.</li></ul><p><strong>2. Networking</strong>:</p><ul><li>Make sure Redis nodes are on the same network.</li><li>Check docker-compose logs for errors.</li></ul><p><strong>3. Timeouts</strong>:</p><ul><li>Increase DialTimeout if connection latency is high.</li></ul><h4>Conclusion</h4><p>Setting up a Redis cluster in a Go application using Docker Compose is a powerful way to scale your application and improve performance. By following this guide, you can set up a robust Redis cluster and connect it to your Go app seamlessly.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0e8044dfb6d1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Debugging PgBouncer Integration with Golang: A Journey Through Errors and Solutions]]></title>
            <link>https://medium.com/@aasefeh/debugging-pgbouncer-integration-with-golang-a-journey-through-errors-and-solutions-93d132fd51b7?source=rss-b07a44374f7e------2</link>
            <guid isPermaLink="false">https://medium.com/p/93d132fd51b7</guid>
            <dc:creator><![CDATA[Asefeh Sadid]]></dc:creator>
            <pubDate>Wed, 04 Dec 2024 11:06:06 GMT</pubDate>
            <atom:updated>2024-12-04T11:06:06.547Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0al-NXsd6pwJSomB5zYAzg.jpeg" /></figure><p>Integrating <strong>PgBouncer</strong> into a Golang project might seem straightforward, but as I learned, it can quickly turn into a labyrinth of errors. Here’s my journey of troubleshooting PgBouncer integration, starting with GORM and ending with a fully functional configuration.</p><h3>Step 1: Setting Up PgBouncer in Transaction Mode</h3><p>My project — a <strong>ticket management system</strong> — used:</p><ul><li><strong>PostgreSQL</strong> for the database.</li><li><strong>GORM</strong> as the ORM for most database interactions.</li></ul><h3>Full Setup on GitHub</h3><p>You can find the complete setup, including the Docker Compose file and PgBouncer configuration on my GitHub repository:</p><p><a href="https://github.com/Asefeh-J/Pgbouncer-Connector">https://github.com/Asefeh-J/Pgbouncer-Connector</a></p><p>I introduced <strong>PgBouncer</strong> to manage database connections and reduce overhead. The initial setup used <strong>transaction pooling mode</strong> (PgBouncer’s default). After modifying the connection string to route traffic through PgBouncer on port 6432, I ran the application and encountered this error:</p><pre>ERROR: prepared statement &quot;stmtcache_1220d15a56dbf823eaa452fbafa17442ab0568bc81a31fa3&quot; already exists (SQLSTATE 42P05)</pre><h3>Step 2: Disabling Statement Caching in GORM</h3><p>The error pointed to a problem with <strong>prepared statements</strong>. I modified the GORM initialization to explicitly disable prepared statements by setting PrepareStmt to false:</p><pre>db, err = gorm.Open(postgres.Open(connStr), &amp;gorm.Config{PrepareStmt: false})<br>if err != nil {<br>    log.Fatalf(&quot;Failed to connect to the database: %v&quot;, err)<br>}</pre><p>However, I still encountered prepared statement-related issues, even when using raw SQL queries. I discovered that <strong>GORM might internally use prepared statements</strong> even for raw queries.</p><h3>Step 3: Switching to the sql Package</h3><p>To simplify things and avoid GORM-related prepared statement handling, I transitioned to using the Go standard library’s sql package for database operations. This gave me full control over queries and connection behavior.</p><p>However, upon switching, I encountered a new error:</p><pre>Database ping failed: pq: unsupported startup parameter: extra_float_digits</pre><h3>Step 4: The “extra_float_digits” Parameter Issue</h3><p>This error suggested that PostgreSQL wasn’t recognizing the extra_float_digits parameter sent during the connection initialization. I updated my <strong>Docker Compose</strong> file to set extra_float_digits=3 in the PostgreSQL container:</p><pre>services:<br>  postgres:<br>    image: postgres:latest<br>    environment:<br>      - POSTGRES_USER=testuser<br>      - POSTGRES_PASSWORD=testpass<br>      - POSTGRES_DB=testdb<br>      - PGOPTIONS=-c extra_float_digits=3<br>    ports:<br>      - &quot;5432:5432&quot;<br>    volumes:<br>      - postgres_data:/var/lib/postgresql/data</pre><p>Unfortunately, the same error persisted. I realized that this parameter was being rejected by <strong>PgBouncer</strong>, not PostgreSQL.</p><h3>Step 5: Resolving Connection Refusal and Configuration Errors</h3><p>As I continued debugging, I faced another error:</p><pre>PgBouncer connection verification failed: unable to ping the database: dial tcp [::1]:6432: connect: connection refused</pre><p>To debug, I took the following steps:</p><p><strong>1. Verified the Connection String</strong>:<br> I ensured my application’s connection string pointed correctly to localhost:6432.</p><p>2. <strong>Reviewed PgBouncer Logs</strong>:<br> The logs showed PgBouncer was running and listening on both 127.0.0.1:6432 and the Unix socket /tmp/.s.PGSQL.6432. However, the repeated &quot;stats&quot; lines suggested no queries were being processed.</p><p><strong>3. Checked PostgreSQL Logs</strong>:<br> The logs indicated that PostgreSQL started successfully and was ready to accept connections. However, I noticed:</p><pre>FATAL: database &quot;testuser&quot; does not exist</pre><p>This error highlighted a database connection configuration issue.</p><p><strong>4. Validated User Credentials and Configuration</strong>:<br>I verified that the testuser credentials existed in PgBouncer’s userlist.txt file. I also updated the PgBouncer configuration to ensure it was listening for connections from all addresses:</p><pre>listen_addr = 0.0.0.0</pre><p>These changes resolved the connection refusal issue, but the extra_float_digits error persisted.</p><h3>Step 6: Addressing the “extra_float_digits” Parameter in PgBouncer</h3><p>Through further investigation, I found that the extra_float_digits parameter is sent by PostgreSQL clients (including the pq driver) as part of the connection initialization. PgBouncer, however, does not support this parameter by default.</p><p>To fix this:</p><ol><li>I first tried adding binary_parameters=yes to the connection string:</li></ol><pre>db, err := sql.Open(&quot;postgres&quot;, &quot;host=localhost port=6432 user=testuser password=testpass dbname=testdb binary_parameters=yes&quot;)</pre><p>This attempt did not resolve the issue.</p><p>2. I then updated pgbouncer.ini to explicitly ignore the unsupported parameter:</p><pre>[databases]<br>testdb = host=postgres port=5432 dbname=testdb user=testuser<br><br>[pgbouncer]<br>listen_addr = 0.0.0.0<br>listen_port = 6432<br>auth_type = md5<br>auth_file = /etc/pgbouncer/userlist.txt<br>ignore_startup_parameters = extra_float_digits</pre><p>This change finally resolved the issue, and my application successfully connected to the database through PgBouncer.</p><h3>Key Takeaways</h3><ol><li><strong>Disabling Prepared Statements in GORM</strong>:<br>You can disable prepared statements in GORM by setting PrepareStmt: false in the GORM configuration.</li><li><strong>GORM and PgBouncer</strong>: Using GORM with PgBouncer in transaction pooling mode is problematic due to prepared statement handling. Switching to raw SQL queries or the sql package offers better control.</li><li><strong>Configuration Details Matter</strong>: Ensure all credentials and connection settings are correctly aligned between PostgreSQL, PgBouncer, and your application.</li><li><strong>Handling Unsupported Parameters</strong>: PgBouncer’s strict behavior with startup parameters requires careful configuration to avoid compatibility issues.</li></ol><p>Integrating PgBouncer into my project was a challenging but rewarding experience. If you’re tackling a similar problem, I hope this guide helps you navigate through it more smoothly!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=93d132fd51b7" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>