goshorly/main.go

102 lines
2 KiB
Go
Raw Normal View History

2021-12-07 14:49:58 +00:00
package main
import (
"log"
"net/http"
"regexp"
"time"
"github.com/go-redis/redis"
"github.com/gofiber/fiber/v2"
"github.com/gofiber/fiber/v2/middleware/limiter"
"github.com/gofiber/template/html"
gonanoid "github.com/matoous/go-nanoid/v2"
)
func main() {
engine := html.NewFileSystem(http.Dir("./views"), ".html")
app := fiber.New(fiber.Config{
Views: engine,
})
client := redis.NewClient(&redis.Options{
2021-12-07 16:24:24 +00:00
Addr: "redis:6379",
Password: "",
2021-12-07 14:49:58 +00:00
DB: 0,
})
_, err := client.Ping().Result()
if err != nil {
log.Fatal(err)
}
app.Get("/", func(c *fiber.Ctx) error {
return c.Render("home", fiber.Map{})
})
type EUrl struct {
2021-12-07 16:24:24 +00:00
URL string `form:"surl"`
2021-12-07 14:49:58 +00:00
}
app.Get("/:id", func(c *fiber.Ctx) error {
val, err := client.Get(c.Params("id")).Result()
if err != nil {
2021-12-07 16:43:43 +00:00
return c.Render("404", fiber.Map{
"BASEURL": c.Protocol() + "://" + c.Hostname(),
2021-12-07 16:40:28 +00:00
})
2021-12-07 14:49:58 +00:00
}
return c.Redirect(val)
})
app.Use(limiter.New(limiter.Config{
Max: 10,
Expiration: 60 * time.Second,
LimitReached: func(c *fiber.Ctx) error {
2021-12-07 16:34:44 +00:00
return c.Render("home", fiber.Map{
"ERR": "You have reached the limit of requests! Please check back later. (1 minute)",
})
2021-12-07 14:49:58 +00:00
},
}))
app.Post("/", func(c *fiber.Ctx) error {
u := new(EUrl)
if err := c.BodyParser(u); err != nil {
2021-12-07 16:34:44 +00:00
return c.Render("home", fiber.Map{
2021-12-07 16:38:40 +00:00
"ERR": "Parsing Error",
2021-12-07 16:34:44 +00:00
})
2021-12-07 14:49:58 +00:00
}
2021-12-07 16:24:24 +00:00
if !regexp.MustCompile(`^(http|https|mailto|ts3server)://`).MatchString(u.URL) {
2021-12-07 16:34:44 +00:00
return c.Render("home", fiber.Map{
2021-12-07 16:37:04 +00:00
"ERR": "Invalid URL, please check and try again.",
2021-12-07 16:34:44 +00:00
})
2021-12-07 14:49:58 +00:00
}
id, err := gonanoid.New(8)
if err != nil {
2021-12-07 16:34:44 +00:00
return c.Render("home", fiber.Map{
"ERR": err.Error(),
})
2021-12-07 14:49:58 +00:00
}
err = client.Set(id, u.URL, 1296000*time.Second).Err()
if err != nil {
2021-12-07 16:34:44 +00:00
return c.Render("home", fiber.Map{
"ERR": err.Error(),
})
2021-12-07 14:49:58 +00:00
}
2021-12-07 16:24:24 +00:00
fURL := c.Protocol() + "://" + c.Hostname() + "/" + id
return c.Render("home", fiber.Map{
"URL": fURL,
})
2021-12-07 14:49:58 +00:00
})
log.Fatal(app.Listen(":3000"))
}