-
Notifications
You must be signed in to change notification settings - Fork 0
/
rest.go
85 lines (68 loc) · 1.78 KB
/
rest.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
package chat_application
import (
"encoding/json"
"fmt"
"io"
"log"
"net/http"
"sync"
"github.com/gorilla/mux"
)
var router *mux.Router
func listUsers(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(map[string]bool{"ok": true})
}
func listRooms(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
roomJsonMap := map[string]map[string]string{}
roomJsonMap["room"] = map[string]string{}
roomMtx.Lock()
for room, _ := range roomMap {
roomJsonMap["room"][room] = ""
}
roomMtx.Unlock()
json.NewEncoder(w).Encode(roomJsonMap)
}
func listEndpoints(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/html; charset=utf-8")
htmlOutput := `
<!DOCTYPE html>
<html>
<head>
<title>Chat server REST API endpoints</title>
</head>
<body>
<h1>Chat server REST API endpoints</h1>
<ul>
`
err := router.Walk(func(route *mux.Route, router *mux.Router, ancestors []*mux.Route) error {
pathTemplate, err := route.GetPathTemplate()
if err == nil {
htmlOutput += fmt.Sprintf("<li><a href=\"%s\">%s</a></li>", pathTemplate, pathTemplate)
}
return err
})
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
htmlOutput += `
</ul>
</body>
</html>
`
io.WriteString(w, htmlOutput)
}
func RestAPIServer(wg *sync.WaitGroup) {
defer wg.Done()
router = mux.NewRouter()
router.HandleFunc("/", listEndpoints)
router.HandleFunc("/api/user", listUsers)
router.HandleFunc("/api/room", listRooms)
srv := &http.Server{
Handler: router,
Addr: fmt.Sprintf("%s:%d", chatConfig.Host, chatConfig.RestAPIPort),
}
fmt.Printf("Starting REST API endpoint on port %d\n", chatConfig.RestAPIPort)
log.Fatal(srv.ListenAndServe())
}