Skip to content

Commit

Permalink
refractor packages
Browse files Browse the repository at this point in the history
Signed-off-by: Vivek Kumar Sahu <vivekkumarsahu650@gmail.com>
  • Loading branch information
viveksahu26 committed Feb 9, 2024
1 parent 910132e commit 9ed8499
Show file tree
Hide file tree
Showing 8 changed files with 224 additions and 121 deletions.
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package src
package response

type URLResponse struct {
OriginalURL string `json:"originalURL"`
Expand Down
Original file line number Diff line number Diff line change
@@ -1,14 +1,15 @@
package src
package response_test

import (
"testing"

"github.com/viveksahu26/url_shortner/cmd/url_shortner/cli/response"
"gotest.tools/assert"
)

func TestBuildResonse(t *testing.T) {
expected := BuildURLWithResponse("localhost:8080", "duj3P^+d*C", "http://viveksahu.com")
actual := &URLResponse{
expected := response.BuildURLWithResponse("localhost:8080", "duj3P^+d*C", "http://viveksahu.com")
actual := response.URLResponse{
OriginalURL: "http://viveksahu.com",
ShortURL: "http://localhost:8080/duj3P^+d*C",
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package src
package response

import (
"encoding/json"
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package src
package save

import (
"errors"
Expand Down
156 changes: 156 additions & 0 deletions cmd/url_shortner/cli/short/short.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,156 @@
package short

import (
"fmt"
"net/http"

"github.com/viveksahu26/url_shortner/cmd/url_shortner/cli/response"
"github.com/viveksahu26/url_shortner/cmd/url_shortner/cli/save"
)

// http://localhost:8080/long-url?sortURL=xtNFxaBwCG

// This was earlier main.go program.

// import (
// "fmt"
// "net/http"
// "os"

// "github.com/viveksahu26/url_shortner/src"
// )

// // http://localhost:8080/long-url?sortURL=xtNFxaBwCG
func HandleLongURL(writer http.ResponseWriter, req *http.Request) {
// Procedure:
// Finally got Complete url
// Retrieve shortURL from it by Querying it.
// Once retrieve, check check in file whether it contains short url or not.
// If file exist, then read that file:
// 1. loop over it's content.
// 2. Check line by line,
// 3. short URL is present in that line or not.
// 4. If present retun map and true boolean
// 5. Else retuen false and empty value

if req.Method != "GET" {
writer.WriteHeader(http.StatusMethodNotAllowed)
} else {
// get original--> shortURL
originalURL := req.URL.Query().Get("sortURL")
fmt.Println("originalURL: ", originalURL)

longURL := CheckWhetherShortURLisPresentORNot(originalURL)
fmt.Println("longURL: ", longURL)

if longURL == "" {
writer.Write([]byte("<h1>HSorry, No corresponding longURL is present to the shortURL. !!</h1>"))
}
writer.Write([]byte(longURL))
}
}

func HandleShortURL(writer http.ResponseWriter, req *http.Request) {
if req.Method != "GET" {
writer.WriteHeader(http.StatusMethodNotAllowed)
} else {
// get original URL from GET method by quering
originalURL := req.URL.Query().Get("longURL")
fmt.Println("originalURL: ", originalURL)

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

// save short and long URL to file
save.SaveInFile(shortURL, originalURL)

host := req.Host

// build Response
resp := response.BuildURLWithResponse(host, shortURL, originalURL)

err := response.RespondWithJSON(writer, 200, resp)
if err != nil {
writer.Write([]byte("<h1>Failed to respond with JSON</h1>"))
}
}
}

func HealthCheckUp(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/health" {
http.Error(w, "404 not found", http.StatusNotFound)
return
}

if r.Method != "GET" {
http.Error(w, "Method other than GET not Supported...", http.StatusNotFound)
return
}

w.Write([]byte("<h1>Health of Server is UP & Running... !!</h1>"))
}

// // const addr = "localhost:8080"

// func main() {
// fmt.Println("URL Shorten Service Starts ...")

// port := os.Getenv("PORT")
// if port == "" {
// port = "8080"
// }
// fmt.Println("PORT is: ", port)

// // /health endpoint is mapped to healthCheckUp
// http.HandleFunc("/health", healthCheckUp)

// // /short-url endpoint is mapped to handleShortURL
// http.HandleFunc("/short-url", handleShortURL)

// // /long-url endpoint is mapped to handleLongURL
// http.HandleFunc("/long-url", handleLongURL)

// // Server Listening on localhost:8080
// err := http.ListenAndServe(":"+port, nil)
// if err != nil {
// panic(err)
// }
// }

// next part of main.go
// package main

// import (
// "flag"
// "fmt"
// "os"

// "github.com/viveksahu26/url_shortner/src" // Adjust the import path according to your project structure
// )

// func main() {
// // Define command line flags
// shortCmd := flag.NewFlagSet("short", flag.ExitOnError)
// longURL := shortCmd.String("url", "", "URL to shorten")

// // Check the command provided
// if len(os.Args) < 2 {
// fmt.Println("expected 'short' subcommand")
// os.Exit(1)
// }

// switch os.Args[1] {
// case "short":
// shortCmd.Parse(os.Args[2:])
// if *longURL == "" {
// fmt.Println("Please provide a URL to shorten using --url=\"http://example.com\"")
// os.Exit(1)
// }
// shortURL := src.GenerateShortURL(*longURL)
// fmt.Printf("Your short url: %s\n", shortURL)
// default:
// fmt.Println("expected 'short' subcommand")
// os.Exit(1)
// }
// }
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
package src
package short

import (
"fmt"
"math/rand"

"github.com/viveksahu26/url_shortner/cmd/url_shortner/cli/save"
)

type Result struct {
Expand All @@ -16,10 +18,10 @@ type Result struct {
// Otherwise generate new ShortURL
func GenerateShortURL(longURL string) string {
fileName := "url.properties"
isFilePresent, _ := IsFileExist(fileName)
isFilePresent, _ := save.IsFileExist(fileName)

if isFilePresent {
shortAndLongURLKeyValuePair, _, fileContainLongURL := IsLongURLPresentInFile(fileName, longURL)
shortAndLongURLKeyValuePair, _, fileContainLongURL := save.IsLongURLPresentInFile(fileName, longURL)
if fileContainLongURL {
// then retrieve ShortURL from there.
if shorturl, ok := shortAndLongURLKeyValuePair[longURL]; ok {
Expand Down Expand Up @@ -47,10 +49,10 @@ func CheckWhetherShortURLisPresentORNot(shorturl string) string {
fmt.Println("Yes, you are inside CheckWhetherShortURLisPresentORNot")

fileName := "url.properties"
isFilePresent, _ := IsFileExist(fileName)
isFilePresent, _ := save.IsFileExist(fileName)

if isFilePresent {
shortAndLongURLKeyValuePair, _, fileContainShortURL := IsLongURLPresentInFile(fileName, shorturl)
shortAndLongURLKeyValuePair, _, fileContainShortURL := save.IsLongURLPresentInFile(fileName, shorturl)
if fileContainShortURL {
// then retrieve ShortURL from there.
if longurl, ok := shortAndLongURLKeyValuePair[shorturl]; ok {
Expand Down
54 changes: 54 additions & 0 deletions cmd/url_shortner/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
package main

import (
"flag"
"fmt"
"log"
"net/http"
"os"

"github.com/viveksahu26/url_shortner/cmd/url_shortner/cli/short"
)

func main() {
// CLI part
shortCmd := flag.NewFlagSet("short", flag.ExitOnError)
longURL := shortCmd.String("url", "", "URL to shorten (CLI mode)")

// Web server part
serverCmd := flag.NewFlagSet("server", flag.ExitOnError)
port := serverCmd.String("port", "8080", "Port to run the web server on")

if len(os.Args) < 2 {
fmt.Println("expected 'short' or 'server' subcommands")
os.Exit(1)
}

switch os.Args[1] {
case "short":
shortCmd.Parse(os.Args[2:])
if *longURL == "" {
fmt.Println("Please provide a URL to shorten using --url=\"http://example.com\"")
os.Exit(1)
}
shortURL := short.GenerateShortURL(*longURL)
fmt.Printf("Your short url: %s\n", shortURL)
case "server":
serverCmd.Parse(os.Args[2:])
fmt.Printf("Starting server on port %s...\n", *port)
http.HandleFunc("/health", short.HealthCheckUp)
http.HandleFunc("/short-url", short.HandleShortURL)
http.HandleFunc("/long-url", short.HandleLongURL)
// setupRoutes() // Function to set up web routes
log.Fatal(http.ListenAndServe(":"+*port, nil))
default:
fmt.Println("expected 'short' or 'server' subcommands")
os.Exit(1)
}
}

// func setupRoutes() {
// http.HandleFunc("/health", src.HealthCheckUp)
// http.HandleFunc("/short-url", src.HandleShortURL)
// http.HandleFunc("/long-url", src.HandleLongURL)
// }
110 changes: 0 additions & 110 deletions src/shortner.go

This file was deleted.

0 comments on commit 9ed8499

Please sign in to comment.