-
Notifications
You must be signed in to change notification settings - Fork 170
/
Copy pathmain.go
48 lines (36 loc) · 1004 Bytes
/
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
package main
import "net/http"
import "fmt"
import "encoding/json"
func OutputJSON(w http.ResponseWriter, o interface{}) {
res, err := json.Marshal(o)
if err != nil {
w.Write([]byte(err.Error()))
return
}
w.Header().Set("Content-Type", "application/json")
w.Write(res)
w.Write([]byte("\n"))
}
func ActionStudent(w http.ResponseWriter, r *http.Request) {
if id := r.URL.Query().Get("id"); id != "" {
OutputJSON(w, SelectStudent(id))
return
}
OutputJSON(w, GetStudents())
}
func main() {
mux := http.DefaultServeMux
mux.HandleFunc("/student", ActionStudent)
var handler http.Handler = mux
handler = MiddlewareAuth(handler)
handler = MiddlewareAllowOnlyGet(handler)
server := new(http.Server)
server.Addr = ":9000"
server.Handler = handler
fmt.Println("server started at localhost:9000")
server.ListenAndServe()
}
// ===== Test
// curl -X GET --user batman:secret http://localhost:9000/student
// curl -X GET --user batman:secret http://localhost:9000/student?id=s001