github.com/joao-fontenele/go-url-shortener@v1.3.4/pkg/shortener/link.go (about)

     1  package shortener
     2  
     3  import (
     4  	"context"
     5  	"fmt"
     6  	"net/url"
     7  	"time"
     8  )
     9  
    10  // Link holds the attributes related to shortened link urls
    11  type Link struct {
    12  	Slug      string    `json:"slug"`
    13  	URL       string    `json:"url"`
    14  	CreatedAt time.Time `json:"createdAt"`
    15  }
    16  
    17  // LinkDao represents a contract to access a single datastore
    18  type LinkDao interface {
    19  	List(ctx context.Context, limit int, skip int) ([]Link, error)
    20  	Find(ctx context.Context, slug string) (*Link, error)
    21  	Insert(ctx context.Context, l *Link) (*Link, error)
    22  	Update(ctx context.Context, l *Link) error
    23  	Delete(ctx context.Context, slug string) error
    24  }
    25  
    26  // Validate checks if a link is valid
    27  func (l *Link) Validate() error {
    28  	if l == nil {
    29  		return fmt.Errorf("%w: Link should not be nil", ErrInvalidLink)
    30  	}
    31  
    32  	u, err := url.Parse(l.URL)
    33  
    34  	if err != nil {
    35  		return fmt.Errorf("%w: Parsing Link.URL generated error", ErrInvalidLink)
    36  	}
    37  
    38  	if u.Host == "" || u.Scheme == "" {
    39  		return fmt.Errorf("%w: Link URL is malformed", ErrInvalidLink)
    40  	}
    41  
    42  	return err
    43  }