lab/go-api/handlers/handler.go

39 lines
680 B
Go
Raw Normal View History

package handlers
import (
"encoding/json"
"log"
"net/http"
"go-api/utils"
)
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) {
log.Println("Running handler...")
code := utils.GetResponseCode(r)
w.WriteHeader(code)
w.Header().Set("Content-Type", "application/json")
if code != http.StatusOK {
json.NewEncoder(w).Encode(ErrorResponse{
Message: "There has been an error.",
StatusCode: code,
})
} else {
json.NewEncoder(w).Encode(SuccessResponse{
Name: "Oliver Davies",
})
}
}