Skip to content

Commit

Permalink
Encode ampersand correctly for category names
Browse files Browse the repository at this point in the history
  • Loading branch information
davemachado committed Dec 18, 2020
1 parent a5d59ff commit d155272
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 2 deletions.
3 changes: 1 addition & 2 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -68,11 +68,10 @@ func main() {
negroni.Wrap(healthCheckHandler()),
))

n := negroni.New()
n := negroni.New(negroni.HandlerFunc(logger.logFunc), negroni.HandlerFunc(encodeURL))
recovery := negroni.NewRecovery()
recovery.PrintStack = false
n.Use(recovery)
n.Use(negroni.HandlerFunc(logger.logFunc))
n.UseHandler(mux)

log.Println("logging requests in " + filename)
Expand Down
7 changes: 7 additions & 0 deletions util.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,20 @@ import (
"encoding/json"
"fmt"
"net/http"
"net/url"
"os"
"strconv"
"strings"

"github.com/gorilla/schema"
)

func encodeURL(rw http.ResponseWriter, r *http.Request, next http.HandlerFunc) {
encoded := strings.Replace(r.URL.String(), "%20&%20", "%20%26%20", -1)
r.URL, _ = url.Parse(encoded)
next(rw, r)
}

// getList initializes an Entries struct filled from the public-apis project
func getList(jsonFile string) {
file, err := os.OpenFile(jsonFile, os.O_RDONLY, 0644)
Expand Down
22 changes: 22 additions & 0 deletions util_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,33 @@ package main

import (
"net/http"
"net/http/httptest"
"net/url"
"reflect"
"testing"
)

func TestEncodeURL(t *testing.T) {
testCases := []struct {
actual string
expected string
}{
{"/entries?category=Science%20%26%20Math", "/entries?category=Science%20%26%20Math"},
{"/entries?category=Science & Math", "/entries?category=Science & Math"},
{"/entries?category=Science%20Math", "/entries?category=Science%20Math"},
}

for _, tc := range testCases {
req, _ := http.NewRequest("GET", tc.actual, nil)
rr := httptest.NewRecorder()
encodeURL(rr, req,
http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {}))
if req.URL.String() != tc.expected {
t.Errorf("incorrect encoding: expected %q, got %q", tc.expected, tc.actual)
}
}
}

func TestGetCategories(t *testing.T) {
actual := parseCategories([]Entry{
Entry{Category: "A"},
Expand Down

0 comments on commit d155272

Please sign in to comment.