-
Notifications
You must be signed in to change notification settings - Fork 1
/
shortyhttpd.go
75 lines (69 loc) · 1.82 KB
/
shortyhttpd.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
package main
import (
"fmt"
"net/http"
"os"
)
type ShortyHTTPd struct {
port int // shorty httpd port
address string // shorty httpd address
domain string // shorty httpd domain
sslcert string // SSL/TLS certificate
sslkey string // SSL/TLS private key
ss *ShortyServer // pointer ShortyServer
log *ShortyLog // pointer to logger
}
/* process_request get the HTTP request and redirects if short URL
* exists. If id is unexsitent responds with 404 and if invalid
* responds with a 403.
*/
func (sh *ShortyHTTPd) ServeHTTP(w http.ResponseWriter, req *http.Request) {
/* only accept GET */
if req.Method != "GET" {
w.WriteHeader(http.StatusForbidden)
return
}
/* clean URI */
id := req.RequestURI[1:]
for i, c := range id {
switch c {
case '/':
case '?':
id = id[:i]
goto cont
}
}
cont:
/* load a index.html in case of / or /index.html or plain
* response in case of non-existent file
*/
if len(id) == 0 || id == "index.html" {
_, err = os.Stat("index.html")
if /* err == nil { */ !os.IsNotExist(err) {
w.Header().Set("Content-Type", "text/html")
http.ServeFile(w, req, "index.html")
} else {
w.Header().Set("Content-Type", "text/plain")
w.Write([]byte(fmt.Sprintf("Shorty service running on %s port %d",
sh.ss.address, sh.ss.port)))
}
} else {
if len(id) != sh.ss.idlen {
/* invalid length */
w.WriteHeader(http.StatusForbidden)
w.Header().Set("Content-Type", "text/plain")
w.Write([]byte("Wrong id."))
} else {
found, short := idexists(id)
if !found {
/* id doesn't exist */
w.WriteHeader(http.StatusNotFound)
w.Header().Set("Content-Type", "text/plain")
w.Write([]byte("Not Found."))
return
}
/* we found the short URL */
http.Redirect(w, req, short.src, http.StatusFound)
}
}
}