Skip to content

refactor code #5

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

Open
wants to merge 1 commit into
base: master
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
41 changes: 23 additions & 18 deletions cmd/httpapi/handlers/handlers.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
package handlers

import (
"context"
"encoding/json"
"errors"
"io"
Expand All @@ -21,22 +20,28 @@ const (
BlankURLErrMessage = "long URL cannot be blank"
)

type loggerInterface interface {
type LoggerInterface interface {
Print(v ...any)
Fatal(v ...any)
}

type handler struct {
type URLShortenerHandler struct {
redisClient db.RedisClientInterface
logger loggerInterface
logger LoggerInterface
}

func NewHandler(redisClient db.RedisClientInterface, logger loggerInterface) handler {
return handler{redisClient: redisClient, logger: logger}
type ShortnerRedirecter interface {
Shorten(w http.ResponseWriter, r *http.Request)
RedirectToLongURL(w http.ResponseWriter, r *http.Request)
}

func (h *handler) Shorten(w http.ResponseWriter, r *http.Request) {
ctx := context.Background()
// NewURLShortenerHandler creates a new URL shortner handler to be used for incoming requests to shorten a url and redirect to a long url from it
func NewURLShortenerHandler(redisClient db.RedisClientInterface, logger LoggerInterface) ShortnerRedirecter {
return &URLShortenerHandler{redisClient: redisClient, logger: logger}
}

func (h *URLShortenerHandler) Shorten(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
if r.Method != http.MethodPost {
w.Header().Set("Allow", "POST")
http.Error(w, "Method Not Allowed", http.StatusMethodNotAllowed)
Expand All @@ -50,10 +55,10 @@ func (h *handler) Shorten(w http.ResponseWriter, r *http.Request) {
}

longURLCopy := *longURL
domain := getDomain(r)
domainName := getDomainName(r)

uuidTruncated := uuid.New().String()[0:8]
shortURL, err := shortenURL(longURLCopy, domain, uuidTruncated, h.logger)
shortURL, err := shortenURL(longURLCopy, domainName, uuidTruncated, h.logger)
if err != nil {
http.Error(w, internalServerError, http.StatusInternalServerError)
return
Expand All @@ -75,14 +80,14 @@ func (h *handler) Shorten(w http.ResponseWriter, r *http.Request) {
w.Write(b)
}

func (h *handler) RedirectToLongURL(w http.ResponseWriter, r *http.Request) {
ctx := context.Background()
func (h *URLShortenerHandler) RedirectToLongURL(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
if r.Method != http.MethodGet {
w.Header().Set("Allow", "GET")
http.Error(w, "Method Not Allowed", http.StatusMethodNotAllowed)
}

domain := getDomain(r)
domain := getDomainName(r)

r.URL.Host = domain
r.URL.Scheme = "https"
Expand All @@ -97,19 +102,19 @@ func (h *handler) RedirectToLongURL(w http.ResponseWriter, r *http.Request) {
}

// shortenURL shortens a long url
func shortenURL(u url.URL, domain string, uuidString string, logger loggerInterface) (string, error) {
func shortenURL(u url.URL, domainName string, uuidString string, logger LoggerInterface) (string, error) {
if len([]rune(uuidString)) > 10 {
logger.Print(IDTooLongErrMessage)
return "", errors.New(IDTooLongErrMessage)
}
u.Host = domain
u.Host = domainName
u.Path = uuidString
rawURL := u.String()
return rawURL, nil
}

// urlFromBody gets the url sent in the body of a request
func urlFromBody(body io.ReadCloser, logger loggerInterface) (*url.URL, error) {
func urlFromBody(body io.ReadCloser, logger LoggerInterface) (*url.URL, error) {
b, err := io.ReadAll(body)
if len(b) == 0 {
logger.Print(BlankURLErrMessage)
Expand Down Expand Up @@ -138,8 +143,8 @@ func urlFromBody(body io.ReadCloser, logger loggerInterface) (*url.URL, error) {
return u, nil
}

// getDomain gets the host of the server without the network address
func getDomain(r *http.Request) string {
// getDomainName gets the host of the server without the network address
func getDomainName(r *http.Request) string {
subStrings := strings.Split(r.Host, ":")
domain := subStrings[0]

Expand Down
2 changes: 1 addition & 1 deletion cmd/httpapi/handlers/handlers_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -167,7 +167,7 @@ func TestGetDomain(t *testing.T) {
}

for _, tc := range testCases {
got := getDomain(tc.in)
got := getDomainName(tc.in)

if got != tc.want {
t.Errorf("%v: GetDomain(%v)==%v, want %v", tc.name, tc.in, got, tc.want)
Expand Down
2 changes: 1 addition & 1 deletion cmd/httpapi/server/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ func main() {
logger := log.New(os.Stdout, "logger: ", log.Lshortfile)

redisClient := db.InitRedisDB(logger)
handler := handlers.NewHandler(redisClient, logger)
handler := handlers.NewURLShortenerHandler(redisClient, logger)

mux := http.NewServeMux()

Expand Down