feat(links): create basic link shortening algo
This commit is contained in:
parent
fc46164556
commit
81e72cedfa
9 changed files with 144 additions and 23 deletions
|
|
@ -2,8 +2,13 @@ package services
|
|||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"encoding/base64"
|
||||
"errors"
|
||||
"maot-shortner/internal/domain"
|
||||
"maot-shortner/internal/repositories"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
type LinkService struct {
|
||||
|
|
@ -19,3 +24,40 @@ func NewLinkService(repo repositories.LinkRepository) *LinkService {
|
|||
func (s *LinkService) GetLinks(ctx context.Context) ([]*domain.Link, error) {
|
||||
return s.repo.GetLinks(ctx)
|
||||
}
|
||||
|
||||
func (s *LinkService) CreateLink(ctx context.Context, longUrl string, redirectCode *string) (*domain.Link, error) {
|
||||
if !strings.Contains(longUrl, "http://") && !strings.Contains(longUrl, "https://") {
|
||||
return nil, errors.New("Invalid URL")
|
||||
}
|
||||
|
||||
var shortUrl string
|
||||
|
||||
if redirectCode != nil {
|
||||
shortUrl = *redirectCode
|
||||
} else {
|
||||
shortUrl = generateShortCode(5)
|
||||
}
|
||||
|
||||
link := &domain.Link{
|
||||
LongURL: longUrl,
|
||||
ShortURL: shortUrl,
|
||||
CreatedAt: time.Now(),
|
||||
}
|
||||
|
||||
return s.repo.CreateLink(ctx, link)
|
||||
}
|
||||
|
||||
func generateShortCode(length int) string {
|
||||
b := make([]byte, length)
|
||||
rand.Read(b)
|
||||
if _, err := rand.Read(b); err != nil {
|
||||
return ""
|
||||
}
|
||||
|
||||
return base64.RawURLEncoding.EncodeToString(b)
|
||||
}
|
||||
|
||||
func (s *LinkService) GetLink(ctx context.Context, shortUrl string) (*domain.Link, error) {
|
||||
|
||||
return s.repo.GetLinkByShortCode(ctx, shortUrl)
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue