Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add DELETE /url/{id} #13

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
111 changes: 111 additions & 0 deletions api/openapi.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,111 @@
openapi: 3.0.1
info:
title: url-shortener
version: '123'
paths:
/{alias}:
get:
operationId: Redirect
parameters:
- name: alias
in: path
description: Short alias of URL
required: true
schema:
type: string
example: abcd
responses:
'302':
description: redirect
'200':
description: not found
content:
application/json:
schema:
$ref: '#/components/schemas/Response'
/url:
post:
operationId: Save
security:
- basicAuth: []
requestBody:
content:
application/json:
schema:
$ref: '#/components/schemas/SaveRequest'
required: true
responses:
'200':
description: ok
content:
application/json:
schema:
$ref: '#/components/schemas/SaveResponse'
'401':
description: unauthorized
/url/{id}:
delete:
operationId: Delete
security:
- basicAuth: []
parameters:
- name: id
in: path
description: URL ID
required: true
schema:
type: integer
format: int64
example: 10
responses:
'200':
description: ok
content:
application/json:
schema:
$ref: '#/components/schemas/Response'
'401':
description: unauthorized
components:
schemas:
SaveRequest:
required:
- url
type: object
properties:
url:
type: string
format: url
alias:
type: string
SaveResponse:
required:
- status
type: object
properties:
status:
type: string
enum: ["OK", "Error"]
error:
type: string
id:
type: integer
format: int64
alias:
type: string
url:
type: string
format: url
Response:
required:
- status
properties:
status:
type: string
enum: ["OK", "Error"]
error:
type: string
securitySchemes:
basicAuth:
type: http
scheme: basic
10 changes: 5 additions & 5 deletions cmd/url-shortener/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,18 +2,18 @@ package main

import (
"context"
"github.com/go-chi/chi/v5"
"github.com/go-chi/chi/v5/middleware"
"golang.org/x/exp/slog"
"net/http"
"os"
"os/signal"
"syscall"
"time"

"github.com/go-chi/chi/v5"
"github.com/go-chi/chi/v5/middleware"
"golang.org/x/exp/slog"

"url-shortener/internal/config"
"url-shortener/internal/http-server/handlers/redirect"
hDelete "url-shortener/internal/http-server/handlers/url/delete"
"url-shortener/internal/http-server/handlers/url/save"
mwLogger "url-shortener/internal/http-server/middleware/logger"
"url-shortener/internal/lib/logger/handlers/slogpretty"
Expand Down Expand Up @@ -59,7 +59,7 @@ func main() {
}))

r.Post("/", save.New(log, storage))
// TODO: add DELETE /url/{id}
r.Delete("/{id}", hDelete.New(log, storage))
})

router.Get("/{alias}", redirect.New(log, storage))
Expand Down
8 changes: 8 additions & 0 deletions config/local.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
env: "local"
storage_path: "./storage.db"
http_server:
address: "127.0.0.1:8082"
timeout: 4s
idle_timeout: 30s
user: "myuser"
password: "mypass"
59 changes: 59 additions & 0 deletions internal/http-server/handlers/url/delete/delete.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
package delete

import (
"errors"
"github.com/go-chi/chi/v5"
"github.com/go-chi/chi/v5/middleware"
"github.com/go-chi/render"
"golang.org/x/exp/slog"
"net/http"
"strconv"
resp "url-shortener/internal/lib/api/response"
"url-shortener/internal/lib/logger/sl"
"url-shortener/internal/storage"
)

//go:generate go run github.com/vektra/mockery/[email protected] --name=URLDeleter
type URLDeleter interface {
DeleteURL(ID int64) error
}

func New(log *slog.Logger, deleter URLDeleter) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
const op = "handlers.url.delete.New"

log := log.With(
slog.String("op", op),
slog.String("request_id", middleware.GetReqID(r.Context())),
)

id, err := strconv.ParseInt(chi.URLParam(r, "id"), 10, 64)
if err != nil {
log.Error("can't parse url id", sl.Err(err))
render.JSON(w, r, resp.Error("invalid id"))
return
}

err = deleter.DeleteURL(id)

if errors.Is(err, storage.ErrURLNotFound) {
log.Info("url id not found", slog.Int64("id", id))

render.JSON(w, r, resp.Error("url id not found"))

return
}

if err != nil {
log.Error("failed to delete url", sl.Err(err))

render.JSON(w, r, resp.Error("failed to delete url"))

return
}

log.Info("url deleted", slog.Int64("id", id))

render.JSON(w, r, resp.OK())
}
}
99 changes: 99 additions & 0 deletions internal/http-server/handlers/url/delete/delete_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
package delete_test

import (
"encoding/json"
"errors"
"github.com/go-chi/chi/v5"
"net/http"
"net/http/httptest"
"testing"
resp2 "url-shortener/internal/lib/api/response"
"url-shortener/internal/lib/logger/handlers/slogdiscard"
"url-shortener/internal/storage"

"github.com/stretchr/testify/mock"
"github.com/stretchr/testify/require"

"url-shortener/internal/http-server/handlers/url/delete"
"url-shortener/internal/http-server/handlers/url/delete/mocks"
)

func TestDeleteHandler(t *testing.T) {
cases := []struct {
name string
uri string
respError string
mockError error
code int
}{
{
name: "Success",
uri: "/url/10",
code: http.StatusOK,
},
{
name: "Invalid ID",
uri: "/url/XXX",
respError: "invalid id",
code: http.StatusOK,
},
{
name: "Omitted ID",
uri: "/url/",
respError: "Don't delete it! We do not check this message because it is generated" +
" by the router. But it must not be empty for the test to work correctly.",
code: http.StatusNotFound,
},
{
name: "ID Not Found",
uri: "/url/10",
respError: "url id not found",
mockError: storage.ErrURLNotFound,
code: http.StatusOK,
},
{
name: "Delete Error",
uri: "/url/10",
respError: "failed to delete url",
mockError: errors.New("unexpected error"),
code: http.StatusOK,
},
}

for _, tc := range cases {
tc := tc

t.Run(tc.name, func(t *testing.T) {
t.Parallel()

urlDeleterMock := mocks.NewURLDeleter(t)

if tc.respError == "" || tc.mockError != nil {
urlDeleterMock.On("DeleteURL", mock.AnythingOfType("int64")).
Return(tc.mockError).
Once()
}

handler := chi.NewRouter()
handler.Delete("/url/{id}", delete.New(slogdiscard.NewDiscardLogger(), urlDeleterMock))

req, err := http.NewRequest(http.MethodDelete, tc.uri, nil)
require.NoError(t, err)

rr := httptest.NewRecorder()
handler.ServeHTTP(rr, req)

require.Equal(t, rr.Code, tc.code)

if rr.Code == http.StatusOK {
body := rr.Body.String()

var resp resp2.Response

require.NoError(t, json.Unmarshal([]byte(body), &resp))

require.Equal(t, tc.respError, resp.Error)
}
})
}
}
39 changes: 39 additions & 0 deletions internal/http-server/handlers/url/delete/mocks/URLDeleter.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

6 changes: 4 additions & 2 deletions internal/http-server/handlers/url/save/save.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ type Request struct {

type Response struct {
resp.Response
ID int64 `json:"id,omitempty"`
Alias string `json:"alias,omitempty"`
}

Expand Down Expand Up @@ -98,13 +99,14 @@ func New(log *slog.Logger, urlSaver URLSaver) http.HandlerFunc {

log.Info("url added", slog.Int64("id", id))

responseOK(w, r, alias)
responseOK(w, r, id, alias)
}
}

func responseOK(w http.ResponseWriter, r *http.Request, alias string) {
func responseOK(w http.ResponseWriter, r *http.Request, id int64, alias string) {
render.JSON(w, r, Response{
Response: resp.OK(),
ID: id,
Alias: alias,
})
}
Loading