forked from apex/up-examples
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
77 lines (66 loc) · 1.66 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
74
75
76
77
package main
import (
"fmt"
"io/ioutil"
"net/http"
"os"
"github.com/apex/log"
"github.com/apex/log/handlers/json"
"github.com/apex/log/handlers/text"
"github.com/gorilla/pat"
)
// pets database-ish
var pets = make(map[string]struct{})
// use JSON logging when run by Up (including `up start`).
func init() {
if os.Getenv("UP_STAGE") == "" {
log.SetHandler(text.Default)
} else {
log.SetHandler(json.Default)
}
}
// setup.
func main() {
addr := ":" + os.Getenv("PORT")
app := pat.New()
app.Get("/", get)
app.Post("/", post)
app.Delete("/{name}", del)
if err := http.ListenAndServe(addr, app); err != nil {
log.WithError(err).Fatal("error listening")
}
}
// curl http://localhost:3000/
func get(w http.ResponseWriter, r *http.Request) {
log.Info("list pets")
if len(pets) == 0 {
fmt.Fprintf(w, "no pets")
return
}
for name := range pets {
fmt.Fprintf(w, "- %s\n", name)
}
}
// curl -d Tobi http://localhost:3000/
// curl -d Loki http://localhost:3000/
// curl -d Jane http://localhost:3000/
func post(w http.ResponseWriter, r *http.Request) {
b, err := ioutil.ReadAll(r.Body)
if err != nil {
http.Error(w, http.StatusText(http.StatusBadRequest), http.StatusBadRequest)
return
}
name := string(b)
pets[name] = struct{}{}
log.WithField("name", name).Info("add pet")
fmt.Fprintf(w, "welcome to the family %s!\n", name)
}
// curl -X DELETE http://localhost:3000/Tobi
// curl -X DELETE http://localhost:3000/Loki
// curl -X DELETE http://localhost:3000/Jane
func del(w http.ResponseWriter, r *http.Request) {
name := r.URL.Query().Get(":name")
log.WithField("name", name).Info("remove pet")
delete(pets, name)
fmt.Fprintf(w, "removed %s!\n", name)
}