Skip to content

Instantly share code, notes, and snippets.

@tanvirraj
Created April 6, 2023 19:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tanvirraj/8878cf267766b146c494ea592bc4d192 to your computer and use it in GitHub Desktop.
Save tanvirraj/8878cf267766b146c494ea592bc4d192 to your computer and use it in GitHub Desktop.
package main
import (
"fmt"
"math/rand"
"net/http"
"github.com/gin-gonic/gin"
"gorm.io/driver/sqlite"
"gorm.io/gorm"
)
type ShortURL struct {
ID uint `gorm:"primary_key"`
Short string `gorm:"unique"`
Long string `gorm:"unique"`
}
var db *gorm.DB
func main() {
// Connect to the database
var err error
db, err = gorm.Open(sqlite.Open("urlshortener.db"), &gorm.Config{})
if err != nil {
panic("failed to connect database")
}
// Auto-migrate the schema
db.AutoMigrate(&ShortURL{})
// Create a new Gin router
router := gin.Default()
// Register the route for shortening URLs
router.POST("/shorten", shortenURL)
// Register the route for redirecting short URLs
router.GET("/:shortURL", redirectURL)
// Start the server
router.Run(":8080")
}
func shortenURL(c *gin.Context) {
// Get the long URL from the POST request
longURL := c.PostForm("url")
// Generate a random short URL
shortURL := generateShortURL()
// Add the short URL and long URL to the database
db.Create(&ShortURL{Short: shortURL, Long: longURL})
// Return the short URL to the user
c.JSON(http.StatusOK, gin.H{
"short_url": fmt.Sprintf("http://localhost:8080/%s", shortURL),
})
}
func redirectURL(c *gin.Context) {
// Get the short URL from the request
shortURL := c.Param("shortURL")
// Look up the long URL in the database
var s ShortURL
db.Where("short = ?", shortURL).First(&s)
if s.Long == "" {
// Short URL not found, return a 404 error
c.JSON(http.StatusNotFound, gin.H{
"error": "Short URL not found",
})
return
}
// Redirect the user to the long URL
c.Redirect(http.StatusMovedPermanently, s.Long)
}
func generateShortURL() string {
// Generate a random 6-character string
var letters = []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789")
b := make([]rune, 6)
for i := range b {
b[i] = letters[rand.Intn(len(letters))]
}
return string(b)
}
This code adds a ShortURL struct and a db variable to manage the database using GORM. When a user submits a long URL to the /shorten route, the code creates a new ShortURL object and adds it to the database using db.Create(). When a user visits a short URL, the code looks up the corresponding ShortURL object in the database using db.Where().First() and redirects the user to the long URL.
Note that this implementation is still very basic and doesn't include error handling or validation of user input. But it should give you a good starting point for building your own URL shortener with GORM!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment