This repository has been archived by the owner on Nov 11, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathserver.go
91 lines (63 loc) · 2.05 KB
/
server.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
package main
import(
"html/template"
"net/http"
"os"
"go_shortify_web_app_heroku/models"
"go_shortify_web_app_heroku/controllers"
)
type pageData struct {
Title string
Short_url string
Long_url string
}
var tpl *template.Template
var page_data pageData
var host_name string = "https://app_id.herokuapp.com"
var notify_type int
var notify_msg string
func init() {
tpl = template.Must(template.ParseGlob("views/*.html"))
models.Redis_db_init()
}
func main(){
http.Handle("/public/", http.StripPrefix("/public/", http.FileServer(http.Dir("public"))))
http.HandleFunc("/about",AboutHandler)
http.HandleFunc("/404",ErrorHandler)
http.HandleFunc("/", HomeHandler)
http.ListenAndServe(":"+os.Getenv("PORT"), nil)
}
func ErrorHandler(w http.ResponseWriter, r *http.Request) {
page_data = pageData{Title:"404"}
tpl.ExecuteTemplate(w, "error.html",page_data)
}
func AboutHandler(w http.ResponseWriter, r *http.Request) {
page_data = pageData{Title:"About"}
tpl.ExecuteTemplate(w, "about.html",page_data)
}
func HomeHandler(w http.ResponseWriter, r *http.Request) {
shortCode := r.URL.Path[1:]
// The variables are static. So we need to re/initialize it every time
page_data = pageData{Title:"Shortify",Short_url:"",Long_url:""}
notify_type = 0
if len(shortCode) != 0 { // GET from DB
redirect_url,err := models.Redis_db_get(shortCode)
if err != nil {
redirect_url = host_name + "/404"
}
controllers.RedirectTo(w,r,redirect_url) // redirect to long url
return
}else if r.Method == "POST" { // SAVE to DB
long_url := r.PostFormValue("long_url") //get form data by id
err := controllers.ValidateURL(long_url)// validate url
if err != nil {
notify_type,notify_msg = 4, "Invalid URL."
}else{
short_url := host_name + "/" + models.Redis_db_save(long_url)
page_data = pageData{Title:"Shortify", Short_url:short_url ,Long_url:long_url}
notify_type,notify_msg = 1, "URL shortified."
}
}
tpl.ExecuteTemplate(w, "app.html",page_data)
controllers.ShowNotifications(w,notify_type,notify_msg) // run this after loading the page
}