package shortify import ( "errors" "log" "net" "os" "time" "github.com/gofiber/fiber/v2" ) // wow func (s *Shortener) ServeSocket(path string) { // Remove old socket if exists socketPath := path _ = os.Remove(socketPath) // Create a Unix socket listener ln, err := net.Listen("unix", socketPath) if err != nil { log.Fatalf("Failed to listen on unix socket: %v", err) } // Optionally set permissions so other processes can connect _ = os.Chmod(socketPath, 0666) app := fiber.New() app.Post("/s", s.HandlePOSTShortURLDirect()) log.Fatal(app.Listener(ln)) } func (s *Shortener) ServeHTTP(addr string) { app := fiber.New() app.Get("/s/:id", s.HandleGETShortURL()) log.Fatal(app.Listen(addr)) } func (s *Shortener) NewShortURL(longUrl string) string { shortID, err := s.idPool.PopID() if err != nil { return "" } err = s.put(shortID, longUrl) if err != nil { return "" } return shortID } func (s *Shortener) HandleGETShortURL() func(*fiber.Ctx) error { return func(c *fiber.Ctx) error { shortID := c.Params("id") url, err := s.get(shortID) if err != nil { return err } s.LogVisit(VisitLog{ ShortID: shortID, LongURL: url, IP: c.IP(), UserAgent: string(c.Context().UserAgent()), Language: c.GetReqHeaders()["Accept-Language"][0], Referer: string(c.Request().Header.Referer()), Time: time.Now(), }) c.Set("Referrer-Policy", "no-referrer") return c.Redirect(url, fiber.StatusFound) } } func (s *Shortener) HandlePOSTShortURL() func(*fiber.Ctx) error { return func(c *fiber.Ctx) error { longUrl := string(c.Body()) if longUrl == "" { return errors.New("whut") } shortID, err := s.idPool.PopID() if err != nil { return err } err = s.put(shortID, longUrl) if err != nil { return err } return c.SendString(shortID) } } func (s *Shortener) HandlePOSTShortURLDirect() func(*fiber.Ctx) error { return func(c *fiber.Ctx) error { longUrl := string(c.Body()) shortID := c.Query("s") if longUrl == "" || shortID == "" { return errors.New("no comment") } err := s.put(shortID, longUrl) if err != nil { return err } return c.SendString(shortID) } }