goshorly/main.go

109 lines
2.1 KiB
Go
Raw Normal View History

2021-12-07 14:49:58 +00:00
package main
import (
2021-12-07 18:10:53 +00:00
"embed"
2021-12-07 14:49:58 +00:00
"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"
)
2021-12-07 18:13:06 +00:00
//go:embed views/*
var viewsfs embed.FS
2021-12-07 18:10:53 +00:00
2021-12-07 18:13:06 +00:00
func main() {
2021-12-07 18:10:53 +00:00
engine := html.NewFileSystem(http.FS(viewsfs), ".html")
2021-12-07 14:49:58 +00:00
app := fiber.New(fiber.Config{
2021-12-07 18:10:53 +00:00
CaseSensitive: true,
ServerHeader: "goshorly",
Views: engine,
2021-12-07 14:49:58 +00:00
})
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"))
}