-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathhttpd.go
97 lines (79 loc) · 1.87 KB
/
httpd.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
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"time"
"github.com/gorilla/mux"
)
var (
db = map[string][]byte{}
)
func handler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "שלום Gophers\n")
}
func pingHandler(w http.ResponseWriter, r *http.Request) {
if r.Method != "GET" {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
return
}
msg := r.URL.Query().Get("msg")
if msg == "" {
msg = "PONG"
}
fmt.Fprintf(w, msg)
}
func timeHandler(w http.ResponseWriter, r *http.Request) {
if r.Method != "GET" {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
return
}
now := time.Now()
fmt.Fprintf(w, now.Format(time.RFC3339))
}
func getHandler(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
key := vars["key"]
value, ok := db[key]
if !ok {
http.Error(w, "Key not found", http.StatusNotFound)
return
}
w.Write(value)
}
func setHandler(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
key := vars["key"]
defer r.Body.Close()
value, err := ioutil.ReadAll(r.Body)
if err != nil {
http.Error(w, "Can't read body", http.StatusInternalServerError)
return
}
db[key] = value
fmt.Fprintf(w, "OK\n")
}
func keysHandler(w http.ResponseWriter, r *http.Request) {
keys := []string{}
for key := range db {
keys = append(keys, key)
}
response := map[string]interface{}{
"keys": keys,
}
enc := json.NewEncoder(w)
if err := enc.Encode(response); err != nil {
http.Error(w, "Can't encode keys", http.StatusInternalServerError)
}
}
func main() {
rtr := mux.NewRouter()
rtr.HandleFunc("/", handler)
rtr.HandleFunc("/ping", pingHandler)
rtr.HandleFunc("/time", timeHandler)
rtr.HandleFunc("/db/{key}", getHandler).Methods("GET")
rtr.HandleFunc("/db/{key}", setHandler).Methods("POST")
rtr.HandleFunc("/keys", keysHandler)
http.ListenAndServe(":8080", rtr)
}