controller with error handling

This commit is contained in:
GotPPay
2018-04-22 15:16:08 +02:00
parent e3e4f83d7c
commit 606ac26480
2 changed files with 65 additions and 1 deletions

3
.gitignore vendored
View File

@@ -4,6 +4,9 @@
*.so *.so
*.dylib *.dylib
# monitor binary
gomon_spawn
# Test binary, build with `go test -c` # Test binary, build with `go test -c`
*.test *.test

61
backend/server.go Normal file
View File

@@ -0,0 +1,61 @@
package main
import (
"fmt"
"log"
"net/http"
"strconv"
"strings"
)
const validNumberOfURLParams = 5
const sizeParamIndex = 3
const countParamIndex = 4
const validNumberOfSizeParams = 2
const (
invalidURL = "URL is not valid"
invalidNumberOfParamsError = "Number of params not correct, expected /WIDTHxLENGTH/count"
invalidNumberOfSizeParamError = "Size not correct, expected /WIDTHxLENGTH/count"
invalidParamsType = "Params should be numbers"
)
func errorResponse(w http.ResponseWriter, errType string) {
fmt.Fprintf(w, errType)
}
func diecutHandler(w http.ResponseWriter, r *http.Request) {
if params := strings.Split(r.URL.Path, "/"); len(params) == validNumberOfURLParams {
if size := strings.Split(params[sizeParamIndex], "x"); len(size) == validNumberOfSizeParams {
count := params[countParamIndex]
width, wOk := strconv.ParseInt(size[0], 10, 32)
height, hOk := strconv.ParseInt(size[1], 10, 32)
countNumber, cOk := strconv.ParseInt(count, 10, 32)
if wOk != nil || hOk != nil || cOk != nil {
errorResponse(w, invalidParamsType)
} else {
fmt.Fprintf(w, "%dx%d | %d", width, height, countNumber)
}
} else {
errorResponse(w, invalidNumberOfSizeParamError)
}
} else {
errorResponse(w, invalidNumberOfParamsError)
}
}
func defaultHandler(w http.ResponseWriter, r *http.Request) {
errorResponse(w, invalidURL)
}
func main() {
http.HandleFunc("/prices/diecut/", diecutHandler)
http.HandleFunc("/", defaultHandler)
fmt.Println("Server running on localhost:8080")
log.Fatal(http.ListenAndServe(":8080", nil))
}