feat: add create short url

This commit is contained in:
Bastien Riviere 2024-01-29 21:21:23 +01:00
parent c7be765c23
commit 31fde6cad6
Signed by: babariviere
GPG key ID: 4E5F0839249F162E
8 changed files with 149 additions and 20 deletions

View file

@ -7,19 +7,21 @@ import (
"github.com/babariviere/short/internal/db"
"github.com/babariviere/short/internal/oas"
"github.com/babariviere/short/internal/url"
"github.com/jackc/pgx/v5"
)
var _ oas.Handler = (*handler)(nil)
type handler struct {
oas.UnimplementedHandler
queries *db.Queries
serverUrl string
queries *db.Queries
}
func NewHandler(queries *db.Queries) *handler {
func NewHandler(serverUrl string, queries *db.Queries) *handler {
return &handler{
queries: queries,
serverUrl: serverUrl,
queries: queries,
}
}
@ -36,3 +38,28 @@ func (h *handler) RedirectLongURL(ctx context.Context, params oas.RedirectLongUR
Location: oas.NewOptString(res.LongUrl),
}, nil
}
func (h *handler) CreateShortURL(ctx context.Context, req *oas.CreateShortURLReq) (oas.CreateShortURLRes, error) {
hash, err := url.GenerateHash(req.URL)
if err != nil {
return nil, fmt.Errorf("failed to generate hash for url %s: %w", req.URL, err)
}
res, err := h.queries.InsertURL(ctx, db.InsertURLParams{
Hash: hash,
LongUrl: req.URL,
})
if err != nil {
// No row == conflict since we do a "ON CONFLICT DO NOTHING"
if errors.Is(err, pgx.ErrNoRows) {
return &oas.CreateShortURLBadRequest{
Message: oas.NewOptString("URL already exist."),
}, nil
}
return nil, fmt.Errorf("failed to insert url: %w", err)
}
return &oas.CreateShortURLCreated{
Shorten: h.serverUrl + "/" + res.Hash,
}, nil
}

View file

@ -20,3 +20,22 @@ func (q *Queries) GetURLByHash(ctx context.Context, hash string) (Url, error) {
err := row.Scan(&i.ID, &i.Hash, &i.LongUrl)
return i, err
}
const insertURL = `-- name: InsertURL :one
INSERT INTO urls (hash, long_url)
VALUES ($1, $2)
ON CONFLICT (hash) DO NOTHING
RETURNING id, hash, long_url
`
type InsertURLParams struct {
Hash string
LongUrl string
}
func (q *Queries) InsertURL(ctx context.Context, arg InsertURLParams) (Url, error) {
row := q.db.QueryRow(ctx, insertURL, arg.Hash, arg.LongUrl)
var i Url
err := row.Scan(&i.ID, &i.Hash, &i.LongUrl)
return i, err
}

View file

@ -85,10 +85,8 @@ func (s *CreateShortURLCreated) Encode(e *jx.Encoder) {
// encodeFields encodes fields.
func (s *CreateShortURLCreated) encodeFields(e *jx.Encoder) {
{
if s.Shorten.Set {
e.FieldStart("shorten")
s.Shorten.Encode(e)
}
e.FieldStart("shorten")
e.Str(s.Shorten)
}
}
@ -101,13 +99,16 @@ func (s *CreateShortURLCreated) Decode(d *jx.Decoder) error {
if s == nil {
return errors.New("invalid: unable to decode CreateShortURLCreated to nil")
}
var requiredBitSet [1]uint8
if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error {
switch string(k) {
case "shorten":
requiredBitSet[0] |= 1 << 0
if err := func() error {
s.Shorten.Reset()
if err := s.Shorten.Decode(d); err != nil {
v, err := d.Str()
s.Shorten = string(v)
if err != nil {
return err
}
return nil
@ -121,6 +122,38 @@ func (s *CreateShortURLCreated) Decode(d *jx.Decoder) error {
}); err != nil {
return errors.Wrap(err, "decode CreateShortURLCreated")
}
// Validate required fields.
var failures []validate.FieldError
for i, mask := range [1]uint8{
0b00000001,
} {
if result := (requiredBitSet[i] & mask) ^ mask; result != 0 {
// Mask only required fields and check equality to mask using XOR.
//
// If XOR result is not zero, result is not equal to expected, so some fields are missed.
// Bits of fields which would be set are actually bits of missed fields.
missed := bits.OnesCount8(result)
for bitN := 0; bitN < missed; bitN++ {
bitIdx := bits.TrailingZeros8(result)
fieldIdx := i*8 + bitIdx
var name string
if fieldIdx < len(jsonFieldsNameOfCreateShortURLCreated) {
name = jsonFieldsNameOfCreateShortURLCreated[fieldIdx]
} else {
name = strconv.Itoa(fieldIdx)
}
failures = append(failures, validate.FieldError{
Name: name,
Error: validate.ErrFieldRequired,
})
// Reset bit.
result &^= 1 << bitIdx
}
}
}
if len(failures) > 0 {
return &validate.Error{Fields: failures}
}
return nil
}

View file

@ -20,16 +20,16 @@ func (*CreateShortURLBadRequest) createShortURLRes() {}
type CreateShortURLCreated struct {
// Created shorten URL. Going to this URL should redirect to URL from request body.
Shorten OptString `json:"shorten"`
Shorten string `json:"shorten"`
}
// GetShorten returns the value of Shorten.
func (s *CreateShortURLCreated) GetShorten() OptString {
func (s *CreateShortURLCreated) GetShorten() string {
return s.Shorten
}
// SetShorten sets the value of Shorten.
func (s *CreateShortURLCreated) SetShorten(val OptString) {
func (s *CreateShortURLCreated) SetShorten(val string) {
s.Shorten = val
}

34
internal/url/hash.go Normal file
View file

@ -0,0 +1,34 @@
package url
import (
"hash/fnv"
"strings"
)
// GenerateHash hash the `url` param into a 8 characters base62 using fnv algorithm.
func GenerateHash(url string) (string, error) {
hasher := fnv.New32a()
_, err := hasher.Write([]byte(url))
if err != nil {
return "", err
}
return encodeToBase62(hasher.Sum32()), nil
}
var base62 = [62]rune{
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
}
func encodeToBase62(hash uint32) string {
var sb strings.Builder
sb.Grow(8)
for hash > 0 {
sb.WriteRune(base62[hash%62])
hash /= 62
}
return sb.String()
}

10
main.go
View file

@ -5,6 +5,7 @@ import (
"log"
"net/http"
"os"
"strings"
"github.com/babariviere/short/internal/api"
"github.com/babariviere/short/internal/db"
@ -19,13 +20,20 @@ func main() {
log.Fatalln("DATABASE_URL is not configured.")
}
serverUrl := os.Getenv("SERVER_URL")
if serverUrl == "" {
serverUrl = "http://localhost:8080"
}
serverUrl = strings.TrimSuffix(serverUrl, "/")
psql, err := pgx.Connect(context.Background(), psqlUrl)
if err != nil {
log.Fatalf("cannot connect to database: %v", err)
}
queries := db.New(psql)
handler := api.NewHandler(queries)
handler := api.NewHandler(serverUrl, queries)
srv, err := oas.NewServer(handler)
if err != nil {

View file

@ -4,17 +4,17 @@ info:
version: 0.1.0
description: An URL shortener service.
paths:
"/{hash}":
'/{hash}':
get:
responses:
"307":
'307':
description: Redirect client to long URL.
headers:
Location:
schema:
type: string
description: Long URL
"404":
'404':
description: Not Found
description: Redirect client to long URL.
operationId: redirectLongURL
@ -38,11 +38,11 @@ paths:
url:
type: string
description: URL to shorten
example: "https://example.com"
example: 'https://example.com'
required:
- url
responses:
"201":
'201':
description: Succesfully created shorten URL.
content:
application/json:
@ -52,7 +52,9 @@ paths:
shorten:
type: string
description: Created shorten URL. Going to this URL should redirect to URL from request body.
"400":
required:
- shorten
'400':
description: Bad Request
content:
application/json:

View file

@ -1,3 +1,9 @@
-- name: GetURLByHash :one
SELECT * FROM urls
WHERE hash = $1;
-- name: InsertURL :one
INSERT INTO urls (hash, long_url)
VALUES ($1, $2)
ON CONFLICT (hash) DO NOTHING
RETURNING *;