-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
73 lines (55 loc) · 1.57 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
package main
import (
"flag"
"fmt"
"io/ioutil"
"net"
"net/http"
"os"
"gopkg.in/yaml.v2"
)
var urls map[string]string
var configFile = flag.String("urls", "/etc/shorts.yml", "path to the config file with URLs (map of short: long)")
var port = flag.Int("port", 0, "port to bind to. Defaults to 0 (dynamic), so you will have to check the output to see which port was dynamically assigned.")
func readURLs(configFile string) error {
fmt.Printf("Reading URLs from %s\n", configFile)
yamlFile, err := ioutil.ReadFile(configFile)
if err != nil {
return fmt.Errorf("Unable to read config file: #%v", err)
}
if err := yaml.Unmarshal(yamlFile, &urls); err != nil {
return fmt.Errorf("Unable to parse config file %s: #%v", configFile, err)
}
for short, long := range urls {
fmt.Printf("%s => %s\n", short, long)
}
return nil
}
func main() {
flag.Parse()
err := readURLs(*configFile)
if err != nil {
fmt.Printf("Error: %s\n", err.Error())
os.Exit(1)
}
bindAddress := fmt.Sprintf("localhost:%d", *port)
listener, err := net.Listen("tcp", bindAddress)
if err != nil {
fmt.Printf("Unable to start listening on %s #%v\n", bindAddress, err)
os.Exit(1)
}
fmt.Printf("Listening at %s\n", listener.Addr())
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
short := r.URL.Path[1:]
long := urls[short]
if long == "" {
http.Error(w, "Not found", http.StatusNotFound)
} else {
http.Redirect(w, r, long, http.StatusSeeOther)
}
})
if err := http.Serve(listener, nil); err != nil {
fmt.Printf("Error: %s\n", err.Error())
os.Exit(1)
}
}