Refactor
Signed-off-by: Oliver Davies <oliver@oliverdavies.uk>
This commit is contained in:
parent
a0cb9d8075
commit
c8d040d8b8
2 changed files with 41 additions and 31 deletions
39
go-api/handlers/handler.go
Normal file
39
go-api/handlers/handler.go
Normal file
|
@ -0,0 +1,39 @@
|
||||||
|
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 != 200) {
|
||||||
|
json.NewEncoder(w).Encode(ErrorResponse{
|
||||||
|
Message: "There has been an error.",
|
||||||
|
StatusCode: 400,
|
||||||
|
})
|
||||||
|
} else {
|
||||||
|
json.NewEncoder(w).Encode(SuccessResponse{
|
||||||
|
Name: "Oliver Davies",
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
|
@ -1,44 +1,15 @@
|
||||||
package main
|
package main
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"encoding/json"
|
|
||||||
"log"
|
"log"
|
||||||
"net/http"
|
"net/http"
|
||||||
|
|
||||||
|
"go-api/handlers"
|
||||||
"go-api/utils"
|
"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 != 200) {
|
|
||||||
json.NewEncoder(w).Encode(ErrorResponse{
|
|
||||||
Message: "There has been an error.",
|
|
||||||
StatusCode: 400,
|
|
||||||
})
|
|
||||||
} else {
|
|
||||||
json.NewEncoder(w).Encode(SuccessResponse{
|
|
||||||
Name: "Oliver Davies",
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
http.HandleFunc("/", handler)
|
http.HandleFunc("/", handlers.Handler)
|
||||||
|
|
||||||
addr := ":" + utils.GetPort()
|
addr := ":" + utils.GetPort()
|
||||||
|
|
||||||
|
|
Loading…
Add table
Add a link
Reference in a new issue