Skip to content

Commit 898b7ea

Browse files
authored
bad request handling (#27)
1 parent 1f5d9ae commit 898b7ea

File tree

2 files changed

+47
-25
lines changed

2 files changed

+47
-25
lines changed

server/utils.go

Lines changed: 28 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -25,15 +25,21 @@ func ValidPort(s string) bool {
2525
return port >= 1 && port <= 65535
2626
}
2727

28-
// returns true if the error message implies a bad request error. Else 500.
29-
func errorBadRequest(message string) bool {
30-
indicators := []string{"not found", "404", "invalid path", "invalid index"}
31-
for _, indicator := range indicators {
28+
// returns error code based on error message text, default 500.
29+
func getErrorCode(message string) int {
30+
notFound := []string{"not found", "404"}
31+
badRequest := []string{"invalid path", "invalid index", "incompatible"}
32+
for _, indicator := range notFound {
3233
if strings.Contains(message, indicator) {
33-
return true
34+
return 404
3435
}
3536
}
36-
return false
37+
for _, indicator := range badRequest {
38+
if strings.Contains(message, indicator) {
39+
return 400
40+
}
41+
}
42+
return 500
3743
}
3844

3945
// get HTTP request and format it into Request object used by server
@@ -66,11 +72,8 @@ func parseRequest(r *http.Request) (Request, error) {
6672
func parseResponse(w http.ResponseWriter, response Response) error {
6773
if response.Error != nil {
6874
w.Header().Set("Content-Type", "text/plain")
69-
if errorBadRequest(response.Error.Error()) {
70-
w.WriteHeader(400)
71-
} else {
72-
w.WriteHeader(500)
73-
}
75+
code := getErrorCode(response.Error.Error())
76+
w.WriteHeader(code)
7477
return json.NewEncoder(w).Encode(response.Error.Error())
7578
}
7679
w.Header().Set("Content-Type", "application/json")
@@ -108,16 +111,16 @@ func write(table string, data any) error {
108111
}
109112

110113
// creates new value based on parameter and mode (add error return)
111-
func updateValue(current any, new any, mode string) any {
114+
func updateValue(current any, new any, mode string) (any, error) {
112115
switch mode {
113116
case "append":
114117
// if it's a slice we append, else we create a new slice to append to.
115118
if tempSlice, ok := current.([]any); ok {
116-
return append(tempSlice, new)
119+
return append(tempSlice, new), nil
117120
} else if current == nil {
118-
return []any{new}
121+
return []any{new}, nil
119122
}
120-
return append([]any{current}, new)
123+
return append([]any{current}, new), nil
121124
case "increment":
122125
// if it's an increment, either increase, or replace.
123126
if new == nil {
@@ -126,14 +129,14 @@ func updateValue(current any, new any, mode string) any {
126129
currentInt, currentOk := current.(float64)
127130
newInt, newOk := new.(float64)
128131
if currentOk && newOk {
129-
return currentInt + newInt
132+
return currentInt + newInt, nil
130133
} else if newOk {
131-
return newInt
134+
return newInt, errors.New("incompatible values")
132135
}
133136
slog.Error("incompatible values", "current", current, "new", new)
134-
return current
137+
return current, errors.New("incompatible values")
135138
default:
136-
return new
139+
return new, nil
137140
}
138141
}
139142

@@ -144,8 +147,9 @@ func insert(data any, path []string, value any, mode string) error {
144147
switch d := current.(type) {
145148
case map[string]any:
146149
if index == len(path)-1 { // last step in path
147-
d[step] = updateValue(d[step], value, mode)
148-
return nil
150+
temp, err := updateValue(d[step], value, mode)
151+
d[step] = temp
152+
return err
149153
}
150154
if _, ok := d[step]; !ok {
151155
d[step] = map[string]any{}
@@ -157,8 +161,9 @@ func insert(data any, path []string, value any, mode string) error {
157161
return errors.New("invalid index: " + step)
158162
}
159163
if index == len(path)-1 { // last step in path
160-
d[idx] = updateValue(d[idx], value, mode)
161-
return nil
164+
temp, err := updateValue(d[idx], value, mode)
165+
d[idx] = temp
166+
return err
162167
}
163168
current = d[idx]
164169
default:

test/smoke_test.go

Lines changed: 19 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -80,8 +80,7 @@ func TestDelete(t *testing.T) {
8080
func TestDeleteList(t *testing.T) {
8181
server.ClearCache()
8282
file := testFile()
83-
status := request("PUT", "/api/test", `[1,2,3,["a","b","c"]]`)
84-
log.Println(status)
83+
request("PUT", "/api/test", `[1,2,3,["a","b","c"]]`)
8584
result1 := readJson(file)
8685
request("DELETE", "/api/test/3", ``)
8786
expected1 := []any{1, 2, 3, []string{"a", "b", "c"}}
@@ -115,6 +114,24 @@ func TestBadRequest(t *testing.T) {
115114
}
116115
}
117116

117+
func TestBadIncrement(t *testing.T) {
118+
server.ClearCache()
119+
request("PUT", "/api/test", `{"foo":"test"}`)
120+
status := request("PUT", "/api/test/foo?mode=increment", `2`)
121+
if status != 400 {
122+
t.Errorf("Bad increment request did not get the correct error code.")
123+
}
124+
}
125+
126+
func TestNotFound(t *testing.T) {
127+
server.ClearCache()
128+
request("PUT", "/api/test", `{"foo":"test"}`)
129+
status := request("GET", "/api/test/something", `2`)
130+
if status != 404 {
131+
t.Errorf("Not found dit not get the correct error code.")
132+
}
133+
}
134+
118135
func init() {
119136
go serve()
120137
}

0 commit comments

Comments
 (0)