-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgoshima.go
92 lines (69 loc) · 2.3 KB
/
goshima.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
package main
import (
"fmt"
"log"
"os"
"strings"
"goshima/database"
"goshima/mapping"
"github.com/joho/godotenv"
)
const (
SHORT = "short"
LONG = "long"
)
var BASE_URL string = "https://ddh.in/"
func main() {
// Loading .env file
err := godotenv.Load()
if err != nil {
log.Fatal("Error loading .env file")
}
// Generating DSN string for GORM initialization
configString := "host=%s user=%s password=%s dbname=%s port=%s sslmode=%s"
config := fmt.Sprintf(configString, os.Getenv("HOST"), os.Getenv("USER"), os.Getenv("PASSWORD"), os.Getenv("DBNAME"), os.Getenv("PORT"), os.Getenv("SSLMODE"))
// Getting command-line argument
mode, url := getArgs()
// Creating a map containing mapping for a bijective function
bijectiveMap := make(map[int32]string, 62)
mapping.EncodeMap(bijectiveMap, mapping.Charset{Start: 97, Iterations: 25})
mapping.EncodeMap(bijectiveMap, mapping.Charset{Start: 65, Iterations: 25})
mapping.EncodeMap(bijectiveMap, mapping.Charset{Start: 48, Iterations: 9})
// Initializing the database
db, err := database.InitializeGorm(config)
if err != nil {
panic("Failed to connect to database")
}
db.AutoMigrate(&database.UrlStore{})
var urlStore database.UrlStore
switch mode {
case SHORT:
db.Create(&database.UrlStore{OriginalUrl: url})
db.Find(&urlStore, "original_url = ?", url)
shortenedUrl := BASE_URL + mapping.GetShortPath(urlStore.ID, bijectiveMap)
fmt.Printf("Shortened URL: %s\n", shortenedUrl)
case LONG:
shortPath := strings.SplitAfter(url, BASE_URL)[1]
primaryKey := mapping.GetUrlId(shortPath, bijectiveMap)
db.Find(&urlStore, "id = ?", primaryKey)
originalUrl := urlStore.OriginalUrl
fmt.Printf("Original URL: %s\n", originalUrl)
default:
fmt.Println("Invalid choice")
}
}
// Gets the first command line argument
func getArgs() (string, string) {
var url string
var mode string
args := os.Args[1:]
if len(args) > 0 {
mode = args[0]
url = args[1]
fmt.Printf("Entered URL is %s\nMode: %s\n", url, mode)
if url != "" {
return strings.TrimSpace(mode), strings.TrimSpace(url)
}
}
return mode, url
}