Skip to content

Instantly share code, notes, and snippets.

@dragonde
Last active August 3, 2024 17:03
Show Gist options
  • Save dragonde/11feecdaa9ce56cd81217f35708cc27e to your computer and use it in GitHub Desktop.
Save dragonde/11feecdaa9ce56cd81217f35708cc27e to your computer and use it in GitHub Desktop.
api-project[object Object]

api project

package main

import (
	"context"
	"fmt"
	"net/http"
	"strconv"

	"github.com/gin-gonic/gin"
	"github.com/go-redis/redis/v8"
)

var (
	// Redis context
	ctx = context.Background()
	// Redis client
	rdb *redis.Client
	// Key for the counter in Redis
	counterKey = "counter"
)

func main() {
	// Initialize Redis client
	rdb = redis.NewClient(&redis.Options{
		Addr: "localhost:6379", // Redis server address
		DB:   0,                // Use default DB
	})

	// Create Gin router
	router := gin.Default()

	// Increase counter endpoint
	router.GET("/api/increase", increaseCounter)
	// Decrease counter endpoint
	router.GET("/api/decrease", decreaseCounter)

	// Start the server
	if err := router.Run(":8080"); err != nil {
		fmt.Printf("Error starting server: %v\n", err)
	}
}

func increaseCounter(c *gin.Context) {
	// Increment the counter in Redis
	val, err := rdb.Incr(ctx, counterKey).Result()
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "Unable to increase counter"})
		return
	}

	// Return the current value of the counter
	c.JSON(http.StatusOK, gin.H{"counter": val})
}

func decreaseCounter(c *gin.Context) {
	// Decrement the counter in Redis
	val, err := rdb.Decr(ctx, counterKey).Result()
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "Unable to decrease counter"})
		return
	}

	// Return the current value of the counter
	c.JSON(http.StatusOK, gin.H{"counter": val})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment