lab/go-api/main.go

59 lines
1.1 KiB
Go
Raw Normal View History

package main
import (
"encoding/json"
"fmt"
"net/http"
"strconv"
)
type ErrorResponse struct {
Message string `json:"message"`
StatusCode int `json:"statusCode"`
}
type SuccessResponse struct {
Name string `json:"name"`
}
func handler(w http.ResponseWriter, r *http.Request) {
fmt.Println("Running handler...")
code := getResponseCode(r)
w.WriteHeader(code)
w.Header().Set("Content-Type", "application/json")
if (code != 200) {
json.NewEncoder(w).Encode(ErrorResponse{
Message: "There has been an error.",
StatusCode: code,
})
} else {
json.NewEncoder(w).Encode(SuccessResponse{
Name: "Oliver Davies",
})
}
}
func getResponseCode(r *http.Request) int {
// If the `force-fail` header is set, get and return its value.
if failCode := r.Header.Get("force-fail"); failCode != "" {
fmt.Println("`force-fail` header set...")
if code, err := strconv.Atoi(failCode); err == nil {
fmt.Printf("Setting the response code to %d...", code)
return code
}
}
return http.StatusOK
}
func main() {
http.HandleFunc("/", handler)
http.ListenAndServe(":8080", nil)
}