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

Implement map method to check longurl exist or not #2

Merged
merged 1 commit into from
Sep 14, 2022
Merged
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
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)
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

G304: Potential file inclusion via variable


ℹ️ Learn about @sonatype-lift commands

You can reply with the following commands. For example, reply with @sonatype-lift ignoreall to leave out all findings.

Command Usage
@sonatype-lift ignore Leave out the above finding from this PR
@sonatype-lift ignoreall Leave out all the existing findings from this PR
@sonatype-lift exclude <file|issue|path|tool> Exclude specified file|issue|path|tool from Lift findings by updating your config.toml file

Note: When talking to LiftBot, you need to refresh the page to see its response.
Click here to add LiftBot to another repo.


Was this a good recommendation?
[ 🙁 Not relevant ] - [ 😕 Won't fix ] - [ 😑 Not critical, will fix ] - [ 🙂 Critical, will fix ] - [ 😊 Critical, fixing now ]

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