Skip to content

Commit

Permalink
Implement map method to check longurl exist or not
Browse files Browse the repository at this point in the history
Signed-off-by: viveksahu26 <vivekkumarsahu650@gmail.com>
  • Loading branch information
viveksahu26 committed Sep 14, 2022
1 parent 547b13b commit 4926d2e
Show file tree
Hide file tree
Showing 4 changed files with 78 additions and 34 deletions.
15 changes: 10 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,10 @@
1) go run main.go

2)
Enter your URL after *http://localhost:8080/short-url?longURL=*
Enter your URL after *http://localhost:8080/enterLongURL?longURL=*
And let's say your URL is *http://google.com/1346461234567890123456789/get/vivekkumarsahu*
Finally you complete URL will look like:
```http://localhost:8080/short-url?longURL=http://google.com/1346461234567890123456789/get/vivekkumarsahu```
```http://localhost:8080/enterLongURL?longURL=http://google.com/1346461234567890123456789/get/vivekkumarsahu```

3) You will get output
```
Expand Down Expand Up @@ -49,11 +49,16 @@

Example:
Now, copy and paste to your browser:

http://localhost:49154/short-url?longURL=http://google.com/1346461234567890123456789/get/viveksahu26

## Step:3
http://localhost:8090/enterLongURL?longURL=http://google.com/1346461234567890123456789/get/viveksahu26

OR

http://localhost:49154/enterLongURL?longURL=http://google.com/1346461234567890123456789/get/viveksahu26



DockerHub: https://hub.docker.com/repository/docker/viveksahu26/my-url-shortner
Docker Image: https://hub.docker.com/repository/docker/viveksahu26/my-url-shortner:v1.0.0

*NOTE*: Do not forget to change port number(49154) and also replace this url(http://google.com/1346461234567890123456789/get/viveksahu26) with your URL.
6 changes: 3 additions & 3 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ func handleShortURL(writer http.ResponseWriter, req *http.Request) {
fmt.Println("originalURL: ", originalURL)

// generate random shortURL
shortURL := src.GenerateShortURL()
shortURL := src.GenerateShortURL(originalURL)
fmt.Println("shortURL: ", shortURL)

// save short and long URL to file
Expand Down Expand Up @@ -46,8 +46,8 @@ func main() {
ReadTimeout: 30 * time.Second,
}

// handleShortUrl function mapped to /short-url
serveMux.HandleFunc("/short-url", handleShortURL)
// handleShortUrl function mapped to /enterLongURL
serveMux.HandleFunc("/enterLongURL", handleShortURL)

// Server Listing on "localhost:8080"
srv.ListenAndServe()
Expand Down
73 changes: 48 additions & 25 deletions src/saveInfile.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package src

import (
"errors"
"fmt"
"io/ioutil"
"log"
"os"
Expand All @@ -11,38 +12,60 @@ import (
// Saving LongURL corresponding to ShortURL
func SaveInFile(shortURL string, longURL string) {
fileName := "url.properties"
prop := shortURL + "=" + longURL
if _, err := os.Stat(fileName); errors.Is(err, os.ErrNotExist) {
os.Create(fileName)
os.WriteFile(fileName, []byte(prop+"\n"), 0o644)
} else {
isFileExist, _ := IsFileExist(fileName)

input, err := ioutil.ReadFile(fileName)
if err != nil {
log.Fatalln(err)
}
combinedURL := shortURL + "=" + longURL

lines := strings.Split(string(input), "\n")
if !isFileExist {
fmt.Printf("New file %s is created.", fileName)
os.Create(fileName)
os.WriteFile(fileName, []byte(combinedURL+"\n"), 0o644)

var flag bool
for i, line := range lines {
if strings.Contains(line, shortURL) {
lines[i] = prop
flag = true
}
}
if flag {
output := strings.Join(lines, "\n")
err = ioutil.WriteFile(fileName, []byte(output), 0o644)
if err != nil {
log.Fatalln(err)
}
} else {
} else {
fmt.Printf("File %s already exist.", fileName)
_, msg, fileContainLongURL := IsLongURLPresentInFile(fileName, longURL)
fmt.Println("\n", msg)

if !fileContainLongURL {
file, err := os.OpenFile(fileName, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0o644)
if err != nil {
panic(err)
}
_, _ = file.WriteString(prop + "\n")
_, _ = file.WriteString(combinedURL + "\n")
}
}
}

func IsFileExist(fileName string) (bool, error) {
if _, err := os.Stat(fileName); errors.Is(err, os.ErrNotExist) {
return false, err
}
return true, nil
}

func IsLongURLPresentInFile(fileName, longURL string) (map[string]string, string, bool) {
fileBytes, err := ioutil.ReadFile(fileName)
if err != nil {
log.Fatalln(err)
}
fileContent := strings.Split(string(fileBytes), "\n")

var fileContainLongURL bool
var message string
ShortAndLongURLValue := make(map[string]string)
for _, line := range fileContent {
totalURL := strings.Split(line, "=")
if len(totalURL) == 2 {
ShortAndLongURLValue[totalURL[1]] = totalURL[0]
}

if strings.Contains(line, longURL) {
message = fmt.Sprintln("Yes, URL is already present in the file")
fileContainLongURL = true
return ShortAndLongURLValue, message, fileContainLongURL
}
message = fmt.Sprintln("URL is not present in the file.")
}
fmt.Println("\n", message)
return ShortAndLongURLValue, message, fileContainLongURL
}
18 changes: 17 additions & 1 deletion src/shortURLGenerator.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,23 @@ type Result struct {
}

// Generate Random URL of 10 characters
func GenerateShortURL() string {
// First check LongURL is present in the file or not
// If present, then get that existing shortURL corresponditing to that LongURL
// Otherwise generate new ShortURL
func GenerateShortURL(longURL string) string {
fileName := "url.properties"
isFilePresent, _ := IsFileExist(fileName)

if isFilePresent {
shortAndLongURLKeyValuePair, _, fileContainLongURL := IsLongURLPresentInFile(fileName, longURL)

if fileContainLongURL {
// then retrieve ShortURL from there.
if shorturl, ok := shortAndLongURLKeyValuePair[longURL]; ok {
return shorturl
}
}
}
allCharacters := []rune("%$#@!*^+0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")
randomChar := make([]rune, 10)
for i := range randomChar {
Expand Down

0 comments on commit 4926d2e

Please sign in to comment.