feat: add create short url
This commit is contained in:
parent
c7be765c23
commit
31fde6cad6
8 changed files with 149 additions and 20 deletions
|
@ -7,19 +7,21 @@ import (
|
||||||
|
|
||||||
"github.com/babariviere/short/internal/db"
|
"github.com/babariviere/short/internal/db"
|
||||||
"github.com/babariviere/short/internal/oas"
|
"github.com/babariviere/short/internal/oas"
|
||||||
|
"github.com/babariviere/short/internal/url"
|
||||||
"github.com/jackc/pgx/v5"
|
"github.com/jackc/pgx/v5"
|
||||||
)
|
)
|
||||||
|
|
||||||
var _ oas.Handler = (*handler)(nil)
|
var _ oas.Handler = (*handler)(nil)
|
||||||
|
|
||||||
type handler struct {
|
type handler struct {
|
||||||
oas.UnimplementedHandler
|
serverUrl string
|
||||||
queries *db.Queries
|
queries *db.Queries
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewHandler(queries *db.Queries) *handler {
|
func NewHandler(serverUrl string, queries *db.Queries) *handler {
|
||||||
return &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),
|
Location: oas.NewOptString(res.LongUrl),
|
||||||
}, nil
|
}, 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
|
||||||
|
}
|
||||||
|
|
|
@ -20,3 +20,22 @@ func (q *Queries) GetURLByHash(ctx context.Context, hash string) (Url, error) {
|
||||||
err := row.Scan(&i.ID, &i.Hash, &i.LongUrl)
|
err := row.Scan(&i.ID, &i.Hash, &i.LongUrl)
|
||||||
return i, err
|
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
|
||||||
|
}
|
||||||
|
|
|
@ -85,10 +85,8 @@ func (s *CreateShortURLCreated) Encode(e *jx.Encoder) {
|
||||||
// encodeFields encodes fields.
|
// encodeFields encodes fields.
|
||||||
func (s *CreateShortURLCreated) encodeFields(e *jx.Encoder) {
|
func (s *CreateShortURLCreated) encodeFields(e *jx.Encoder) {
|
||||||
{
|
{
|
||||||
if s.Shorten.Set {
|
e.FieldStart("shorten")
|
||||||
e.FieldStart("shorten")
|
e.Str(s.Shorten)
|
||||||
s.Shorten.Encode(e)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -101,13 +99,16 @@ func (s *CreateShortURLCreated) Decode(d *jx.Decoder) error {
|
||||||
if s == nil {
|
if s == nil {
|
||||||
return errors.New("invalid: unable to decode CreateShortURLCreated to 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 {
|
if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error {
|
||||||
switch string(k) {
|
switch string(k) {
|
||||||
case "shorten":
|
case "shorten":
|
||||||
|
requiredBitSet[0] |= 1 << 0
|
||||||
if err := func() error {
|
if err := func() error {
|
||||||
s.Shorten.Reset()
|
v, err := d.Str()
|
||||||
if err := s.Shorten.Decode(d); err != nil {
|
s.Shorten = string(v)
|
||||||
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
return nil
|
return nil
|
||||||
|
@ -121,6 +122,38 @@ func (s *CreateShortURLCreated) Decode(d *jx.Decoder) error {
|
||||||
}); err != nil {
|
}); err != nil {
|
||||||
return errors.Wrap(err, "decode CreateShortURLCreated")
|
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
|
return nil
|
||||||
}
|
}
|
||||||
|
|
|
@ -20,16 +20,16 @@ func (*CreateShortURLBadRequest) createShortURLRes() {}
|
||||||
|
|
||||||
type CreateShortURLCreated struct {
|
type CreateShortURLCreated struct {
|
||||||
// Created shorten URL. Going to this URL should redirect to URL from request body.
|
// 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.
|
// GetShorten returns the value of Shorten.
|
||||||
func (s *CreateShortURLCreated) GetShorten() OptString {
|
func (s *CreateShortURLCreated) GetShorten() string {
|
||||||
return s.Shorten
|
return s.Shorten
|
||||||
}
|
}
|
||||||
|
|
||||||
// SetShorten sets the value of Shorten.
|
// SetShorten sets the value of Shorten.
|
||||||
func (s *CreateShortURLCreated) SetShorten(val OptString) {
|
func (s *CreateShortURLCreated) SetShorten(val string) {
|
||||||
s.Shorten = val
|
s.Shorten = val
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
34
internal/url/hash.go
Normal file
34
internal/url/hash.go
Normal 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
10
main.go
|
@ -5,6 +5,7 @@ import (
|
||||||
"log"
|
"log"
|
||||||
"net/http"
|
"net/http"
|
||||||
"os"
|
"os"
|
||||||
|
"strings"
|
||||||
|
|
||||||
"github.com/babariviere/short/internal/api"
|
"github.com/babariviere/short/internal/api"
|
||||||
"github.com/babariviere/short/internal/db"
|
"github.com/babariviere/short/internal/db"
|
||||||
|
@ -19,13 +20,20 @@ func main() {
|
||||||
log.Fatalln("DATABASE_URL is not configured.")
|
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)
|
psql, err := pgx.Connect(context.Background(), psqlUrl)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Fatalf("cannot connect to database: %v", err)
|
log.Fatalf("cannot connect to database: %v", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
queries := db.New(psql)
|
queries := db.New(psql)
|
||||||
handler := api.NewHandler(queries)
|
handler := api.NewHandler(serverUrl, queries)
|
||||||
|
|
||||||
srv, err := oas.NewServer(handler)
|
srv, err := oas.NewServer(handler)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
|
14
openapi.yaml
14
openapi.yaml
|
@ -4,17 +4,17 @@ info:
|
||||||
version: 0.1.0
|
version: 0.1.0
|
||||||
description: An URL shortener service.
|
description: An URL shortener service.
|
||||||
paths:
|
paths:
|
||||||
"/{hash}":
|
'/{hash}':
|
||||||
get:
|
get:
|
||||||
responses:
|
responses:
|
||||||
"307":
|
'307':
|
||||||
description: Redirect client to long URL.
|
description: Redirect client to long URL.
|
||||||
headers:
|
headers:
|
||||||
Location:
|
Location:
|
||||||
schema:
|
schema:
|
||||||
type: string
|
type: string
|
||||||
description: Long URL
|
description: Long URL
|
||||||
"404":
|
'404':
|
||||||
description: Not Found
|
description: Not Found
|
||||||
description: Redirect client to long URL.
|
description: Redirect client to long URL.
|
||||||
operationId: redirectLongURL
|
operationId: redirectLongURL
|
||||||
|
@ -38,11 +38,11 @@ paths:
|
||||||
url:
|
url:
|
||||||
type: string
|
type: string
|
||||||
description: URL to shorten
|
description: URL to shorten
|
||||||
example: "https://example.com"
|
example: 'https://example.com'
|
||||||
required:
|
required:
|
||||||
- url
|
- url
|
||||||
responses:
|
responses:
|
||||||
"201":
|
'201':
|
||||||
description: Succesfully created shorten URL.
|
description: Succesfully created shorten URL.
|
||||||
content:
|
content:
|
||||||
application/json:
|
application/json:
|
||||||
|
@ -52,7 +52,9 @@ paths:
|
||||||
shorten:
|
shorten:
|
||||||
type: string
|
type: string
|
||||||
description: Created shorten URL. Going to this URL should redirect to URL from request body.
|
description: Created shorten URL. Going to this URL should redirect to URL from request body.
|
||||||
"400":
|
required:
|
||||||
|
- shorten
|
||||||
|
'400':
|
||||||
description: Bad Request
|
description: Bad Request
|
||||||
content:
|
content:
|
||||||
application/json:
|
application/json:
|
||||||
|
|
|
@ -1,3 +1,9 @@
|
||||||
-- name: GetURLByHash :one
|
-- name: GetURLByHash :one
|
||||||
SELECT * FROM urls
|
SELECT * FROM urls
|
||||||
WHERE hash = $1;
|
WHERE hash = $1;
|
||||||
|
|
||||||
|
-- name: InsertURL :one
|
||||||
|
INSERT INTO urls (hash, long_url)
|
||||||
|
VALUES ($1, $2)
|
||||||
|
ON CONFLICT (hash) DO NOTHING
|
||||||
|
RETURNING *;
|
||||||
|
|
Loading…
Reference in a new issue