Skip to content

Instantly share code, notes, and snippets.

@robherley
Created March 29, 2019 05:47
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 robherley/ce6033be82bd6b6607522972fdb3bf33 to your computer and use it in GitHub Desktop.
Save robherley/ce6033be82bd6b6607522972fdb3bf33 to your computer and use it in GitHub Desktop.
Crappy URL Shortener
package main
import (
"encoding/hex"
"fmt"
"math/rand"
"net/http"
"time"
valid "github.com/asaskevich/govalidator"
"github.com/gin-contrib/static"
"github.com/gin-gonic/gin"
"github.com/gomodule/redigo/redis"
)
func main() {
rand.Seed(time.Now().UTC().UnixNano())
con, err := redis.Dial("tcp", ":6379")
if err != nil {
panic(err)
}
defer con.Close()
gin.SetMode(gin.ReleaseMode)
r := gin.Default()
r.Use(static.Serve("/", static.LocalFile("./static", true)))
api := r.Group("/r")
api.GET("/:route", func(c *gin.Context) {
route := c.Param("route")
v, err := con.Do("GET", route)
if err != nil {
c.JSON(500, gin.H{"error": err, "route": route})
}
fmt.Printf("redis: %s\n", v)
if v == nil {
c.JSON(404, gin.H{"error": "route not found"})
}
c.Redirect(http.StatusTemporaryRedirect, fmt.Sprintf("%s", v))
})
api.POST("/new", func(c *gin.Context) {
nr := c.PostForm("makeShort")
fmt.Println("route to make tiny", nr)
b := valid.IsURL(nr)
if !b {
c.JSON(400, gin.H{"error": "url is not valid"})
}
bs := make([]byte, 4)
rand.Read(bs)
u := hex.EncodeToString(bs)
_, err := con.Do("SET", u, nr)
if err != nil {
c.JSON(500, gin.H{"error": err})
}
c.JSON(200, gin.H{"newRoute": u})
})
r.Run()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment