impl http api server for serving index.html, api calls

master
Bel LaPointe 2022-02-08 12:40:34 -07:00
parent db7e7fadbf
commit 09b3e4a002
2 changed files with 51 additions and 11 deletions

View File

@ -9,6 +9,8 @@ import (
"net/http" "net/http"
"os" "os"
"path" "path"
"path/filepath"
"regexp"
"strings" "strings"
"time" "time"
@ -241,5 +243,45 @@ func (server *Server) apiV0FilesIDDelHandler(w http.ResponseWriter, r *http.Requ
} }
func (server *Server) apiV0SearchHandler(w http.ResponseWriter, r *http.Request) error { func (server *Server) apiV0SearchHandler(w http.ResponseWriter, r *http.Request) error {
return errors.New("not impl" + r.URL.Path) query := r.URL.Query().Get("q")
queries := strings.Split(query, " ")
if len(queries) == 0 {
w.Write([]byte(`[]`))
return nil
}
patterns := []*regexp.Regexp{}
unsafepattern := regexp.MustCompile(`[^a-zA-Z0-9]`)
for _, query := range queries {
if len(query) > 0 {
query = unsafepattern.ReplaceAllString(query, ".")
patterns = append(patterns, regexp.MustCompile(query))
}
}
if len(patterns) == 0 {
w.Write([]byte(`[]`))
return nil
}
results := []string{}
if err := filepath.Walk(path.Dir(server.diskFilePath("id")), func(p string, info os.FileInfo, err error) error {
if err != nil {
return err
}
if info.IsDir() {
return nil
}
b, err := ioutil.ReadFile(p)
if err != nil {
return err
}
for _, pattern := range patterns {
if !pattern.Match(b) {
return nil
}
}
results = append(results, path.Base(p))
return err
}); err != nil {
return err
}
return json.NewEncoder(w).Encode(results)
} }

View File

@ -1,7 +1,6 @@
package main package main
import ( import (
"bytes"
"net/http" "net/http"
"net/http/httptest" "net/http/httptest"
"path" "path"
@ -37,8 +36,9 @@ func TestServerRoutes(t *testing.T) {
want: "mom", want: "mom",
}, },
"v0: search: get": { "v0: search: get": {
path: "/api/v0/search", path: "/api/v0/search?q=getf%20bod",
method: http.MethodGet, method: http.MethodGet,
want: `["getfid"]`,
}, },
"v0: tree: get": { "v0: tree: get": {
path: "/api/v0/tree", path: "/api/v0/tree",
@ -88,15 +88,13 @@ func TestServerRoutes(t *testing.T) {
if w.Code == http.StatusNotFound { if w.Code == http.StatusNotFound {
t.Fatal(w) t.Fatal(w)
} }
if !bytes.HasPrefix(w.Body.Bytes(), []byte("not impl")) { if w.Code != http.StatusOK {
if w.Code != http.StatusOK { t.Fatal(w)
t.Fatal(w)
}
if len(c.want) > 0 && !strings.Contains(string(w.Body.Bytes()), c.want) {
t.Fatal(w)
}
t.Logf("%s %s (%+v) => %s", c.method, c.path, w.Header(), w.Body.Bytes())
} }
if len(c.want) > 0 && !strings.Contains(string(w.Body.Bytes()), c.want) {
t.Fatal(w)
}
t.Logf("%s %s (%+v) => %s", c.method, c.path, w.Header(), w.Body.Bytes())
}) })
} }
} }