Skip to content

Commit

Permalink
adding reddis
Browse files Browse the repository at this point in the history
  • Loading branch information
SartajBhuvaji committed Nov 22, 2024
1 parent a363b19 commit b6df6c2
Show file tree
Hide file tree
Showing 7 changed files with 182 additions and 4 deletions.
10 changes: 10 additions & 0 deletions api/redirect.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
package api

import (
"net/http"
)

// handle the short --> long URL redirection
func RedirectHandler(w http.ResponseWriter, r *http.Request) {
http.Error(w, "Not implemented", http.StatusNotImplemented)
}
27 changes: 23 additions & 4 deletions api/handlers.go → api/shorten.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,13 @@ package api
import (
"encoding/json"
"net/http"
"strings"

"github.com/SartajBhuvaji/utils"
)

const base62Chars = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"

type ShortenURLRequest struct {
URL string `json:"url"`
}
Expand All @@ -31,14 +36,28 @@ func ShortenURLHandler(w http.ResponseWriter, r *http.Request) {
return
}

// For simplicity
shortURL := "https://short.ly/" + generateShortCode(req.URL)
enc := EncodeURL(123)
shortURL := "something/" + enc

resp := ShortenURLResponse{ShortURL: shortURL}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(resp)
}

func generateShortCode(url string) string {
return url[:5]
func EncodeURL(no int) string {
if no == 0 {
return string(base62Chars[0])
}

base := len(base62Chars)
var encoded strings.Builder

for no > 0 {
remainder := no % base
encoded.WriteByte(base62Chars[remainder])
no /= base
}

return utils.ReverseString(encoded.String())

}
90 changes: 90 additions & 0 deletions database/redis.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
package database

import (
"context"
"fmt"

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

// RedisClient is a struct that encapsulates the Redis client.
type RedisClient struct {
client *redis.Client
ctx context.Context
}

// NewRedisClient initializes a new Redis client.
func NewRedisClient(addr, password string, db int) *RedisClient {
rdb := redis.NewClient(&redis.Options{
Addr: addr,
Password: password,
DB: db, // Use default DB
})
return &RedisClient{
client: rdb,
ctx: context.Background(),
}
}

// Ping checks the connection to the Redis server.
func (r *RedisClient) Ping() error {
pong, err := r.client.Ping(r.ctx).Result()
if err != nil {
return err
}
fmt.Printf("Connected to Redis: %s\n", pong)
return nil
}

// Set stores a key-value pair in Redis.
func (r *RedisClient) Set(key, value string) error {
err := r.client.Set(r.ctx, key, value, 0).Err()
if err != nil {
return err
}
fmt.Printf("Key '%s' set successfully!\n", key)
return nil
}

// Get retrieves the value of a given key from Redis.
func (r *RedisClient) Get(key string) (string, error) {
val, err := r.client.Get(r.ctx, key).Result()
if err != nil {
return "", err
}
return val, nil
}

// Close closes the Redis client connection.
func (r *RedisClient) Close() {
err := r.client.Close()
if err != nil {
fmt.Printf("Error closing Redis connection: %v\n", err)
} else {
fmt.Println("Redis connection closed.")
}
}

// // Main function
// func main() {

// // Test connection
// if err := redisClient.Ping(); err != nil {
// fmt.Printf("Could not connect to Redis: %v\n", err)
// return
// }

// // Set a key-value pair
// if err := redisClient.Set("mykey", "myvalue"); err != nil {
// fmt.Printf("Error setting key: %v\n", err)
// return
// }

// // Get the value of a key
// value, err := redisClient.Get("mykey")
// if err != nil {
// fmt.Printf("Error getting key: %v\n", err)
// return
// }
// fmt.Printf("Retrieved value: %s\n", value)
// }
7 changes: 7 additions & 0 deletions go.mod
Original file line number Diff line number Diff line change
@@ -1,3 +1,10 @@
module github.com/SartajBhuvaji

go 1.23.2

require (
github.com/cespare/xxhash/v2 v2.1.2 // indirect
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f // indirect
github.com/go-redis/redis/v8 v8.11.5 // indirect
github.com/joho/godotenv v1.5.1 // indirect
)
8 changes: 8 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
github.com/cespare/xxhash/v2 v2.1.2 h1:YRXhKfTDauu4ajMg1TPgFO5jnlC2HCbmLXMcTG5cbYE=
github.com/cespare/xxhash/v2 v2.1.2/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f h1:lO4WD4F/rVNCu3HqELle0jiPLLBs70cWOduZpkS1E78=
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f/go.mod h1:cuUVRXasLTGF7a8hSLbxyZXjz+1KgoB3wDUb6vlszIc=
github.com/go-redis/redis/v8 v8.11.5 h1:AcZZR7igkdvfVmQTPnu9WE37LRrO/YrBH5zWyjDC0oI=
github.com/go-redis/redis/v8 v8.11.5/go.mod h1:gREzHqY1hg6oD9ngVRbLStwAWKhA0FEgq8Jd4h5lpwo=
github.com/joho/godotenv v1.5.1 h1:7eLL/+HRGLY0ldzfGMeQkb7vMd0as4CfYvUVzLqw0N0=
github.com/joho/godotenv v1.5.1/go.mod h1:f4LDr5Voq0i2e/R5DDNOoa2zzDfwtkZa6DnEwAbqwq4=
34 changes: 34 additions & 0 deletions main.go
Original file line number Diff line number Diff line change
@@ -1,15 +1,49 @@
package main

import (
"fmt"
"log"
"net/http"
"os"

"github.com/SartajBhuvaji/api"
"github.com/SartajBhuvaji/database"
"github.com/joho/godotenv"
)

func main() {
// Load the .env file
err := godotenv.Load()
if err != nil {
log.Fatalf("Error loading .env file: %v", err)
}

var redisHost string
var redisPassword string

// // Read from environment variables
redisHost = os.Getenv("REDIS_HOST")
redisPassword = os.Getenv("REDIS_PASSWORD")

// Create a new RedisClient

redisClient := database.NewRedisClient(redisHost, redisPassword, 0)
defer redisClient.Close()

// Test connection
if err := redisClient.Ping(); err != nil {
fmt.Printf("Could not connect to Redis: %v\n", err)
return
} else {
fmt.Println("Connected to Redis")
}

// longURL --> shortURL
http.HandleFunc("/shorten", api.ShortenURLHandler)

// shortURL --> longURL
http.HandleFunc("/redirect", api.RedirectHandler)

log.Println("Server started on :8080")
if err := http.ListenAndServe(":8080", nil); err != nil {
log.Fatalf("Could not start server: %s\n", err)
Expand Down
10 changes: 10 additions & 0 deletions utils/helper.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
package utils

// ReverseString reverses a given string
func ReverseString(s string) string {
runes := []rune(s)
for i, j := 0, len(runes)-1; i < j; i, j = i+1, j-1 {
runes[i], runes[j] = runes[j], runes[i]
}
return string(runes)
}

0 comments on commit b6df6c2

Please sign in to comment.