-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmain.go
68 lines (53 loc) · 1.37 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
/**
* @author Jongmin Kim (@golanger)
*/
package main
import (
"flag"
"http"
"template"
"json"
)
var (
listenAddr = flag.String("port", "80", "http listen port")
hostName = flag.String("host", "you.rl", "http host name")
//hostName = flag.String("host", "localhost", "http host name")
)
type Title struct {
Logo string
}
var store Store
func Redirect(w http.ResponseWriter, r *http.Request) {
key := r.URL.Path[1:]
if key == "favicon.ico" {
http.NotFound(w, r)
} else if key == "" {
logo := &Title{Logo: "You.RL"}
tpl, _ := template.ParseFile("index.html", nil)
tpl.Execute(w, logo)
} else if key == "index.js" {
http.ServeFile(w, r, "index.js")
} else {
var url string
store.Get(&key, &url)
http.Redirect(w, r, url, http.StatusFound)
}
}
func Shorten(w http.ResponseWriter, r *http.Request) {
var key string
for key = genKey(); store.Check(&key) == false; { }
long_url := r.FormValue("url")
store.Put(&key, &long_url)
v := make(map[string]string)
v["url"] = "http://" + *hostName + "/" + key
enc := json.NewEncoder(w)
enc.Encode(&v)
}
func main() {
flag.Parse()
store = new(URLStore)
http.HandleFunc("/", Redirect)
http.HandleFunc("/shorten", Shorten)
http.ListenAndServe(":" + *listenAddr, nil)
}
/* EOF */