Saturday, 25 January 2025

Channels (chan) in Golang Gin

 In Golang, channels (chan) are commonly used for communication between goroutines. When working with the Gin framework, channels can be helpful in handling tasks like:

  • Asynchronous processing: Offloading tasks to another goroutine.
  • Streaming data: Sending chunks of data to the client in real-time.
  • Timeouts: Managing timeouts for requests.
  • Key Points:

    • <- is used for channel communication:
      • jobs <- j: Sends a value into the channel.
      • <-results: Receives a value from the channel.

    Example 1: Asynchronous Processing

    You can use a channel to process data in a separate goroutine while continuing to serve the request.

    package main

    import (
        "fmt"
        "time"

        "github.com/gin-gonic/gin"
    )

    func main() {
        r := gin.Default()

        r.GET("/process", func(c *gin.Context) {
            resultChan := make(chan string)

            // Start a goroutine for asynchronous processing
            go func() {
                time.Sleep(2 * time.Second) // Simulate a long task
                resultChan <- "Task completed!"
            }()

            // Wait for the result from the channel
            result := <-resultChan

            c.JSON(200, gin.H{
                "message": result,
            })
        })

        r.Run(":8080")
    }

    Thank you

    No comments:

    Post a Comment

    Golang Advanced Interview Q&A