forked from cucumber/godog
-
Notifications
You must be signed in to change notification settings - Fork 0
/
api.go
60 lines (47 loc) · 1.21 KB
/
api.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
// Example - demonstrates REST API server implementation tests.
package main
import (
"encoding/json"
"fmt"
"net/http"
"github.com/cucumber/godog"
)
func getVersion(w http.ResponseWriter, r *http.Request) {
if r.Method != "GET" {
fail(w, "Method not allowed", http.StatusMethodNotAllowed)
return
}
data := struct {
Version string `json:"version"`
}{Version: godog.Version}
ok(w, data)
}
func main() {
http.HandleFunc("/version", getVersion)
http.ListenAndServe(":8080", nil)
}
// fail writes a json response with error msg and status header
func fail(w http.ResponseWriter, msg string, status int) {
w.Header().Set("Content-Type", "application/json")
data := struct {
Error string `json:"error"`
}{Error: msg}
resp, _ := json.Marshal(data)
w.WriteHeader(status)
fmt.Fprintf(w, string(resp))
}
// ok writes data to response with 200 status
func ok(w http.ResponseWriter, data interface{}) {
w.Header().Set("Content-Type", "application/json")
if s, ok := data.(string); ok {
fmt.Fprintf(w, s)
return
}
resp, err := json.Marshal(data)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
fail(w, "oops something evil has happened", 500)
return
}
fmt.Fprintf(w, string(resp))
}