-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtisy.go
50 lines (43 loc) · 1.11 KB
/
tisy.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
package main
import (
"fmt"
"github.com/dchest/uniuri"
"io/ioutil"
"net/http"
)
const URLS_FOLDER = "data"
type Url struct {
Uri string
ShortLink string
}
func (u *Url) save() error {
return ioutil.WriteFile(
URLS_FOLDER+"/"+u.ShortLink, []byte(u.Uri), 0600)
}
func handler(w http.ResponseWriter, r *http.Request) {
id := r.URL.Path
if id != "/" {
body, _ := ioutil.ReadFile(URLS_FOLDER + "/" + id[1:len(id)-1])
str := string(body)
http.Redirect(w, r, str, 301)
} else {
fmt.Fprintf(w, "<h1>Create shortlink</h1>"+
"<form action=\"/create/\" method=\"POST\">"+
"<input type=\"text\" name=\"url\"/><br>"+
"<input type=\"submit\" value=\"Save\">"+
"</form>")
}
}
func saveHandler(w http.ResponseWriter, r *http.Request) {
rawUrl := r.FormValue("url")
id := uniuri.NewLen(5)
url := &Url{Uri: rawUrl, ShortLink: id}
url.save()
fmt.Fprintf(w, "<h1>Generated shortlink</h1>"+
"<p>Shortlink: <a href='/%s/'>%s<a/>, Url: %s", url.ShortLink, url.ShortLink, url.Uri)
}
func main() {
http.HandleFunc("/", handler)
http.HandleFunc("/create/", saveHandler)
http.ListenAndServe(":8080", nil)
}