-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
145 lines (120 loc) · 3.15 KB
/
main.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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
package main
import (
"database/sql"
"encoding/json"
"fmt"
_ "github.com/go-sql-driver/mysql"
"github.com/teris-io/shortid"
"html/template"
"log"
"net/http"
"os"
)
var (
db *sql.DB
)
type ShortenedURLResponse struct {
Original string `json:"original_url"`
Shortened string `json:"code"`
}
func main() {
fmt.Println("URL Shortener with Go")
sid, err := shortid.New(1, shortid.DefaultABC, 2342)
checkErr(err)
shortid.SetDefault(sid)
db = openDb()
defer db.Close()
http.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir("static"))))
http.HandleFunc("/", rootHandler) // set router
http.HandleFunc("/login", login) // set router
http.HandleFunc("/register", register) // set router
http.HandleFunc("/new", shortener)
port := os.Getenv("PORT")
log.Fatal(
http.ListenAndServe(":"+port, nil), // set listening port
)
}
func openDb() *sql.DB {
//dbinfo := "root:edwinharly@tcp(127.0.0.1:3306)/url_shortener"
dbuser := os.Getenv("DBUSER")
dbpass := os.Getenv("DBPASS")
dbhost := os.Getenv("DBHOST")
schema := os.Getenv("SCHEMA")
dbinfo := dbuser + ":" + dbpass + "@tcp(" + dbhost + ":3306)/" + schema
db, err := sql.Open("mysql", dbinfo)
checkErr(err)
return db
}
func rootHandler(w http.ResponseWriter, r *http.Request) {
shortURL := r.URL.Path[len("/"):]
if shortURL == "" {
t, _ := template.ParseFiles("pages/index.html")
t.Execute(w, nil)
} else {
dest := queryShortenedURL(shortURL)
if dest != "" {
http.Redirect(w, r, dest, http.StatusSeeOther)
}
}
}
func queryShortenedURL(code string) string {
var (
dest string
)
rows, err := db.Query("select original_url from shortened where shortened_url = ?", code)
checkErr(err)
defer rows.Close()
for rows.Next() {
err := rows.Scan(&dest)
checkErr(err)
}
err = rows.Err()
checkErr(err)
return dest
}
func login(w http.ResponseWriter, r *http.Request) {
fmt.Println("method: ", r.Method)
if r.Method == "GET" {
t, _ := template.ParseFiles("login.gtpl")
t.Execute(w, nil)
} else {
fmt.Println("username:", r.FormValue("username"))
fmt.Println("password:", r.FormValue("password"))
}
}
func register(w http.ResponseWriter, r *http.Request) {
fmt.Println("method: ", r.Method)
if r.Method == "GET" {
t, _ := template.ParseFiles("register.gtpl")
t.Execute(w, nil)
} else {
fmt.Println("username:", r.FormValue("username"))
fmt.Println("password:", r.FormValue("password"))
}
}
func shortener(w http.ResponseWriter, r *http.Request) {
fmt.Println("method: ", r.Method)
if r.Method == "POST" {
originalURL := r.FormValue("url")
short, err := shortid.Generate()
userID := 0
stmt, err := db.Prepare("INSERT INTO shortened(original_url, shortened_url, user_id) VALUES(?, ?, ?)")
checkErr(err)
defer stmt.Close()
_, err = stmt.Exec(originalURL, short, userID)
checkErr(err)
successResponse := &ShortenedURLResponse{
Original: originalURL,
Shortened: short}
successResponseJSON, _ := json.Marshal(successResponse)
w.Write(successResponseJSON)
} else {
w.WriteHeader(http.StatusMethodNotAllowed)
w.Write([]byte("405 - Method Not Allowed"))
}
}
func checkErr(err error) {
if err != nil {
log.Fatal(err)
}
}