62 lines
1.6 KiB
Go
62 lines
1.6 KiB
Go
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))
|
|
}
|