package api
import (
+ "encoding/json"
"fmt"
"net/http"
http.Redirect(w, r, u.String(), http.StatusPermanentRedirect)
}
+// setNotFoundHandler catches all requests that were redirected to default API,
+// and not found there.
+func notFoundHandler(w http.ResponseWriter, r *http.Request, _ map[string]string) {
+ srvErr := util.NewServerError(NotFoundError(r.URL.Path))
+ data, err := json.Marshal(srvErr)
+ if err != nil {
+ data = []byte(srvErr.Err)
+ } else {
+ w.Header().Set("Content-Type", "application/json")
+ }
+ w.WriteHeader(srvErr.Status)
+ w.Write(data)
+}
+
// setDefaultAPI register handler for API calls that lack API version in path.
func setDefaultAPIRedirect(prefix *httptreemux.Group) {
for _, method := range [...]string{
http.MethodTrace,
} {
prefix.Handle(method, "/*path", redirectToDefault)
+ // Redirect was done, requested API call wasn't found.
+ prefix.Handle(method, "/"+defaultAPI+"/*path", notFoundHandler)
}
}
package api
import (
+ "encoding/json"
"errors"
"flag"
"io/ioutil"
"path/filepath"
"testing"
+ . "git.tizen.org/tools/boruta"
util "git.tizen.org/tools/boruta/http"
"git.tizen.org/tools/boruta/matcher"
"git.tizen.org/tools/boruta/requests"
// Response is checked in redirCheck.
_, err := client.Post(srv.URL+reqPath, "text/plain", nil)
assert.Nil(err)
+
+ // Path to default version of API, which wasn't found.
+ badPath := "/api/" + defaultAPI + "/missing/test"
+ var srvErr util.ServerError
+ resp, err := client.Post(srv.URL+badPath, "text/plain", nil)
+ assert.Nil(err)
+ defer resp.Body.Close()
+ decoder := json.NewDecoder(resp.Body)
+ assert.Equal("application/json", resp.Header.Get("Content-Type"))
+ err = decoder.Decode(&srvErr)
+ assert.Equal(http.StatusNotFound, resp.StatusCode)
+ assert.Equal(NotFoundError(badPath).Error(), srvErr.Err)
}