-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdb.go
87 lines (75 loc) · 1.52 KB
/
db.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
package main
import (
"database/sql"
"math/rand"
"net/http"
"time"
)
import _ "modernc.org/sqlite"
var db *sql.DB
func CreateDB() {
var err error
db, err = sql.Open("sqlite", "./URLS.db")
if err != nil {
panic(err)
}
}
func CreateTables() {
_, err := db.Exec("CREATE TABLE IF NOT EXISTS urls (id INTEGER PRIMARY KEY, url TEXT, short TEXT)")
if err != nil {
panic(err)
}
}
func init() {
rand.Seed(time.Now().UnixNano())
}
var letters = []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")
func GenerateLetters(n int) string {
b := make([]rune, n)
for i := range b {
b[i] = letters[rand.Intn(len(letters))]
}
return string(b)
}
func GenerateShort(url string) string {
short := GenerateLetters(5)
_, err := db.Exec("INSERT INTO urls (url, short) VALUES (?, ?)", url, short)
if err != nil {
panic(err)
}
http.HandleFunc("/"+short, HandleCode)
return short
}
func GetURL(short string) string {
var url string
err := db.QueryRow("SELECT url FROM urls WHERE short=?", short).Scan(&url)
if err != nil {
panic(err)
}
return url
}
func GetShort(url string) string {
var short string
err := db.QueryRow("SELECT short FROM urls WHERE url=?", url).Scan(&short)
if err != nil {
return ""
}
return short
}
func Startup() {
rows, err := db.Query("SELECT * FROM urls")
if err != nil {
return
}
defer rows.Close()
for rows.Next() {
var id int
var url string
var short string
err = rows.Scan(&id, &url, &short)
if err != nil {
panic(err)
}
http.HandleFunc("/"+short, HandleCode)
}
}