github.com/agilebits/godog@v0.7.9/examples/api/api.go (about) 1 // Example - demonstrates REST API server implementation tests. 2 package main 3 4 import ( 5 "encoding/json" 6 "fmt" 7 "net/http" 8 9 "github.com/DATA-DOG/godog" 10 ) 11 12 func getVersion(w http.ResponseWriter, r *http.Request) { 13 if r.Method != "GET" { 14 fail(w, "Method not allowed", http.StatusMethodNotAllowed) 15 return 16 } 17 data := struct { 18 Version string `json:"version"` 19 }{Version: godog.Version} 20 21 ok(w, data) 22 } 23 24 func main() { 25 http.HandleFunc("/version", getVersion) 26 http.ListenAndServe(":8080", nil) 27 } 28 29 // fail writes a json response with error msg and status header 30 func fail(w http.ResponseWriter, msg string, status int) { 31 w.Header().Set("Content-Type", "application/json") 32 33 data := struct { 34 Error string `json:"error"` 35 }{Error: msg} 36 37 resp, _ := json.Marshal(data) 38 w.WriteHeader(status) 39 40 fmt.Fprintf(w, string(resp)) 41 } 42 43 // ok writes data to response with 200 status 44 func ok(w http.ResponseWriter, data interface{}) { 45 w.Header().Set("Content-Type", "application/json") 46 47 if s, ok := data.(string); ok { 48 fmt.Fprintf(w, s) 49 return 50 } 51 52 resp, err := json.Marshal(data) 53 if err != nil { 54 w.WriteHeader(http.StatusInternalServerError) 55 fail(w, "oops something evil has happened", 500) 56 return 57 } 58 59 fmt.Fprintf(w, string(resp)) 60 }