-
Notifications
You must be signed in to change notification settings - Fork 3
/
http.go
56 lines (43 loc) · 1.3 KB
/
http.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
package main
import (
"fmt"
"net/http"
"time"
)
type LongenerHandler struct {
writer http.ResponseWriter
request *http.Request
longener Longener
}
type LongenerHandlerFunc func(LongenerHandler)
func createHandler (handler LongenerHandler) {
value := handler.request.FormValue("url")
key := handler.longener.Store(value)
fmt.Fprintf(handler.writer, key)
}
func fetchHandler (handler LongenerHandler) {
key := handler.request.URL.Path[1:]
if key == "" {
http.ServeFile(handler.writer, handler.request, "index.html")
return
}
location := handler.longener.Fetch(key)
if location == "" {
fmt.Fprintf(handler.writer, "not found")
} else {
http.Redirect(handler.writer, handler.request, location, http.StatusFound)
}
}
func generateHandler (longener Longener, handler LongenerHandlerFunc) http.HandlerFunc {
return func (w http.ResponseWriter, r *http.Request) {
handler(LongenerHandler{w, r, longener})
}
}
func LongenerHTTP (filename string, save_interval int, port string) {
kv := KeyValue{}
kv.Init(filename, time.Duration(save_interval) * time.Second)
longener := Longener{&kv}
http.HandleFunc("/create", generateHandler(longener, createHandler));
http.HandleFunc("/", generateHandler(longener, fetchHandler));
http.ListenAndServe(":" + port, nil)
}