Skip to content

Commit

Permalink
Fixed lint
Browse files Browse the repository at this point in the history
  • Loading branch information
burkaydurdu committed Mar 4, 2022
1 parent 48fbd50 commit 223d69f
Show file tree
Hide file tree
Showing 9 changed files with 66 additions and 40 deletions.
15 changes: 11 additions & 4 deletions config/config.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
package config

import "fmt"
import (
"fmt"
"time"
)

/*
*
Expand All @@ -19,16 +22,20 @@ type ServerConfig struct {
}

type Config struct {
AppName string
IsDebug bool
Server ServerConfig
AppName string
IsDebug bool
LengthOfCode int
DurationOfWriteToDisk time.Duration
Server ServerConfig
}

func New() (*Config, error) {
config := &Config{}

config.AppName = AppName
config.IsDebug = IsDebug
config.LengthOfCode = 6
config.DurationOfWriteToDisk = time.Second * 2
config.Server = ServerConfig{
Port: Port,
}
Expand Down
11 changes: 9 additions & 2 deletions internal/db/shortlybase.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"encoding/json"
"errors"
"fmt"
"io/fs"
"io/ioutil"
"os"

Expand All @@ -18,7 +19,7 @@ type Shortly struct {
}

type DB struct {
ShortUrl []Shortly `json:"short_url"`
ShortURL []Shortly `json:"short_url"`
}

type ShortlyBase struct {
Expand Down Expand Up @@ -57,13 +58,19 @@ func (s *ShortlyBase) InitialDB() (*DB, error) {

err = json.Unmarshal(file, &DB)

if err != nil {
return nil, err
}

return DB, nil
}

func (s *ShortlyBase) SaveToFile(db *DB) error {
filePermissionCode := 0600

path := fmt.Sprintf("%s.json", s.FileName)

fileData, _ := json.Marshal(db)

return ioutil.WriteFile(path, fileData, 0644)
return ioutil.WriteFile(path, fileData, fs.FileMode(filePermissionCode))
}
2 changes: 1 addition & 1 deletion internal/domain/shortly/dto.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
package shortly

type SaveRequestDTO struct {
OriginalUrl string `json:"original_url"`
OriginalURL string `json:"original_url"`
}

type SaveResponseDTO struct {
Expand Down
24 changes: 18 additions & 6 deletions internal/domain/shortly/handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ import (
"encoding/json"
"net/http"

"github.com/burkaydurdu/shortly/pkg/log"

shortlyError "github.com/burkaydurdu/shortly/pkg/error"
)

Expand All @@ -15,6 +17,7 @@ type HTTPHandler interface {

type shortlyHandler struct {
s Service
l *log.ShortlyLog
}

func (s *shortlyHandler) RedirectURL(w http.ResponseWriter, r *http.Request) {
Expand All @@ -41,7 +44,8 @@ func (s *shortlyHandler) SaveShortURL(w http.ResponseWriter, r *http.Request) {

if err != nil {
w.WriteHeader(http.StatusBadRequest)
w.Write([]byte(shortlyError.ParserError))
httpResponse(w, []byte(shortlyError.ParserError), s.l)

return
}

Expand All @@ -50,20 +54,28 @@ func (s *shortlyHandler) SaveShortURL(w http.ResponseWriter, r *http.Request) {
responseByteBody, _ := json.Marshal(responseBody)

w.Header().Set("Content-Type", "application/json")
w.Write(responseByteBody)
httpResponse(w, responseByteBody, s.l)
}

func (s *shortlyHandler) GetShortList(w http.ResponseWriter, _ *http.Request) {
shortlyUrl := s.s.GetShortList()
shortlyURL := s.s.GetShortList()

responseByteBody, _ := json.Marshal(shortlyUrl)
responseByteBody, _ := json.Marshal(shortlyURL)

w.Header().Set("Content-Type", "application/json")
w.Write(responseByteBody)
httpResponse(w, responseByteBody, s.l)
}

func httpResponse(w http.ResponseWriter, response []byte, l *log.ShortlyLog) {
_, err := w.Write(response)
if err != nil {
l.ZapFatal(shortlyError.ResponseError, err)
}
}

func NewShortlyHandler(s Service) HTTPHandler {
func NewShortlyHandler(s Service, l *log.ShortlyLog) HTTPHandler {
return &shortlyHandler{
s: s,
l: l,
}
}
28 changes: 15 additions & 13 deletions internal/domain/shortly/service.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,32 +15,33 @@ type Service interface {
}

type shortlyService struct {
db *db.DB
db *db.DB
lengthOfCode int
}

func (s *shortlyService) RedirectURL(code string) (string, error) {
for i, sURL := range s.db.ShortUrl {
for i, sURL := range s.db.ShortURL {
if code == sURL.Code {
// Increment visit count
s.db.ShortUrl[i].VisitCount += 1
s.db.ShortURL[i].VisitCount++
return sURL.OriginalURL, nil
}
}

return "", shortlyError.AddressNotFoundErr
return "", shortlyError.ErrAddressNotFound
}

func (s *shortlyService) SaveShortURL(host string, requestBody *SaveRequestDTO) *SaveResponseDTO {
code := generateShortlyCode(s.db.ShortUrl)
code := generateShortlyCode(s.db.ShortURL, s.lengthOfCode)

shortly := db.Shortly{
OriginalURL: requestBody.OriginalUrl,
OriginalURL: requestBody.OriginalURL,
Code: code,
VisitCount: 0,
ShortURL: fmt.Sprintf("http://%s/%s", host, code),
}

s.db.ShortUrl = append(s.db.ShortUrl, shortly)
s.db.ShortURL = append(s.db.ShortURL, shortly)

var responseBody = &SaveResponseDTO{
ShortURL: shortly.ShortURL,
Expand All @@ -50,7 +51,7 @@ func (s *shortlyService) SaveShortURL(host string, requestBody *SaveRequestDTO)
}

func (s *shortlyService) GetShortList() []db.Shortly {
return s.db.ShortUrl
return s.db.ShortURL
}

/*
Expand All @@ -59,20 +60,21 @@ func (s *shortlyService) GetShortList() []db.Shortly {
* If it generates same code, it will run again
* We can generate 54 x 54 x 54 x 54 x 54 x 54 different values
*/
func generateShortlyCode(list []db.Shortly) string {
code := util.RandShortlyCode(6)
func generateShortlyCode(list []db.Shortly, lengthOfCode int) string {
code := util.RandShortlyCode(lengthOfCode)

for _, s := range list {
if code == s.Code {
return generateShortlyCode(list)
return generateShortlyCode(list, lengthOfCode)
}
}

return code
}

func NewShortlyService(db *db.DB) Service {
func NewShortlyService(shortlyDB *db.DB, lengthOfCode int) Service {
return &shortlyService{
db: db,
db: shortlyDB,
lengthOfCode: lengthOfCode,
}
}
2 changes: 1 addition & 1 deletion internal/domain/shortly/service_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,5 +14,5 @@ func TestShortlyService_GenerateShortlyCode(t *testing.T) {
},
}

assert.Len(t, generateShortlyCode(shortlyList), 6)
assert.Len(t, generateShortlyCode(shortlyList, 6), 6)
}
10 changes: 5 additions & 5 deletions internal/server/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -86,14 +86,14 @@ func (s *Server) Start() error {

db, err := shortlyBase.InitialDB()

go s.saveToDisk(shortlyBase, db)
go s.saveToDisk(shortlyBase, db, s.config.DurationOfWriteToDisk)

if err != nil {
s.l.ZapFatal("Couldn't not connect Shortly DB", err)
}

shortlyService := shortly.NewShortlyService(db)
shortlyHandler := shortly.NewShortlyHandler(shortlyService)
shortlyService := shortly.NewShortlyService(db, s.config.LengthOfCode)
shortlyHandler := shortly.NewShortlyHandler(shortlyService, s.l)

s.s.Handler(
regexp.MustCompile("/api/health"),
Expand Down Expand Up @@ -131,9 +131,9 @@ func (s *Server) healthCheck(w http.ResponseWriter, r *http.Request) {
}
}

func (s *Server) saveToDisk(shortlyBase shortlyDB.ShortlyBase, db *shortlyDB.DB) {
func (s *Server) saveToDisk(shortlyBase shortlyDB.ShortlyBase, db *shortlyDB.DB, durationOfWriteToDisk time.Duration) {
for {
time.Sleep(time.Second * 2)
time.Sleep(durationOfWriteToDisk)

err := shortlyBase.SaveToFile(db)
if err != nil {
Expand Down
3 changes: 2 additions & 1 deletion pkg/error/shortly_error.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ const (
ParserError = "couldn't parser body"
PathNotFoundError = "couldn't find this path"
AddressNotFound = "address not found"
ResponseError = "couldn't answer to request"
)

var AddressNotFoundErr = errors.New(AddressNotFound)
var ErrAddressNotFound = errors.New(AddressNotFound)
11 changes: 4 additions & 7 deletions pkg/util/codegen.go
Original file line number Diff line number Diff line change
@@ -1,20 +1,17 @@
package util

import (
"math/rand"
"time"
"crypto/rand"
"math/big"
)

func init() {
rand.Seed(time.Now().UnixNano())
}

var letterRunes = []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")

func RandShortlyCode(n int) string {
b := make([]rune, n)
for i := range b {
b[i] = letterRunes[rand.Intn(len(letterRunes))]
val, _ := rand.Int(rand.Reader, big.NewInt(int64(len(letterRunes))))
b[i] = letterRunes[val.Int64()]
}
return string(b)
}

0 comments on commit 223d69f

Please sign in to comment.