/
shroty.go
105 lines (81 loc) · 1.85 KB
/
shroty.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
package main
import (
"code.google.com/p/gorilla/mux"
"flag"
"fmt"
"log"
"os"
"path"
"path/filepath"
"net/http"
)
const (
defaultHttpAddr = ":8910"
)
var (
staticDir *string
httpAddr = flag.String("http", "", "http server address, e.g. 192.168.2.1:8910")
)
func shorten(w http.ResponseWriter, r *http.Request) {
url := mux.Vars(r)["url"]
log.Printf("Shorten %v\n", url)
fmt.Fprintf(w, "Shortenize %v", url)
}
func open(w http.ResponseWriter, r *http.Request) {
http.NotFound(w, r)
}
func info(w http.ResponseWriter, r *http.Request) {
http.NotFound(w, r)
}
func static(w http.ResponseWriter, r *http.Request) {
file := mux.Vars(r)["file"]
if len(file) == 0 {
file = "index.html"
}
staticFile := path.Join(*staticDir, file)
fi, e := os.Stat(staticFile)
if e != nil {
log.Printf("File error: %v\n", e)
http.NotFound(w, r)
} else if fi.IsDir() {
log.Printf("File not found: %v\n", staticFile)
http.NotFound(w, r)
} else {
http.ServeFile(w, r, staticFile)
}
}
func usage() {
fmt.Fprintf(os.Stderr, "usage: shroty -http="+defaultHttpAddr+"\n")
flag.PrintDefaults()
os.Exit(2)
}
func main() {
flag.Usage = usage
flag.Parse()
cwd, e := os.Getwd()
if e != nil {
log.Fatalln("Cannot get current directory")
}
cwd, _ = filepath.Abs(cwd)
s := path.Join(cwd, "public")
if _, e := os.Stat(s); e != nil {
log.Fatalln("Cannot find /public directory")
}
staticDir = &s
router := mux.NewRouter()
router.HandleFunc("/s/{url:(.*$)}", shorten)
router.HandleFunc("/go/{id:([a-zA-Z0-9]+$)}", open)
router.HandleFunc("/go/{id:([a-zA-Z0-9]+$)+}", info)
router.HandleFunc("/{file:(.*$)}", static)
server := *httpAddr
if (server == "") {
server = defaultHttpAddr
}
httpServ := &http.Server{
Addr: server,
Handler: router,
}
log.Printf("Listening on %v\n", server)
log.SetOutput(os.Stdout)
httpServ.ListenAndServe()
}