404 to static file server

This commit is contained in:
breel
2020-08-28 15:43:25 -06:00
parent ec5223d530
commit cf3a289a54
4 changed files with 70 additions and 0 deletions

View File

@@ -62,6 +62,13 @@ func NewREST(g storage.RateLimitedGraph) (*REST, error) {
}
}
bar := rest.static
bar = rest.defend(bar)
bar = rest.delay(bar)
if err := rest.router.Add(params, bar); err != nil {
return nil, err
}
return rest, nil
}

13
server/static.go Normal file
View File

@@ -0,0 +1,13 @@
package server
import (
"local/dndex/config"
"local/simpleserve/simpleserve"
"net/http"
)
func (rest *REST) static(w http.ResponseWriter, r *http.Request) {
simpleserve.SetContentTypeIfMedia(w, r)
server := http.FileServer(http.Dir(config.New().StaticRoot))
server.ServeHTTP(w, r)
}

46
server/static_test.go Normal file
View File

@@ -0,0 +1,46 @@
package server
import (
"io/ioutil"
"local/dndex/config"
"net/http"
"net/http/httptest"
"os"
"path"
"testing"
)
func TestRESTStatic(t *testing.T) {
os.Args = []string{"a"}
d, err := ioutil.TempDir(os.TempDir(), "static*")
if err != nil {
t.Fatal(err)
}
os.Setenv("STATIC_ROOT", d)
if err := ioutil.WriteFile(path.Join(d, "index.html"), []byte("Hello, world"), os.ModePerm); err != nil {
t.Fatal(err)
}
rest, _, clean := testREST(t)
defer clean()
t.Run("assert nonstatic OK", func(t *testing.T) {
r := httptest.NewRequest(http.MethodGet, path.Join("/", config.New().APIPrefix, "version"), nil)
w := httptest.NewRecorder()
rest.router.ServeHTTP(w, r)
if w.Code != http.StatusOK {
t.Fatal(w.Code)
}
})
t.Run("assert static OK", func(t *testing.T) {
r := httptest.NewRequest(http.MethodGet, "/", nil)
w := httptest.NewRecorder()
rest.router.ServeHTTP(w, r)
if w.Code != http.StatusOK {
t.Fatal(w.Code)
}
if s := string(w.Body.Bytes()); s != "Hello, world" {
t.Fatal(s)
}
})
}