impl http api server for serving index.html, api calls
parent
db7e7fadbf
commit
09b3e4a002
|
|
@ -9,6 +9,8 @@ import (
|
|||
"net/http"
|
||||
"os"
|
||||
"path"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"strings"
|
||||
"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 {
|
||||
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)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,7 +1,6 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"path"
|
||||
|
|
@ -37,8 +36,9 @@ func TestServerRoutes(t *testing.T) {
|
|||
want: "mom",
|
||||
},
|
||||
"v0: search: get": {
|
||||
path: "/api/v0/search",
|
||||
path: "/api/v0/search?q=getf%20bod",
|
||||
method: http.MethodGet,
|
||||
want: `["getfid"]`,
|
||||
},
|
||||
"v0: tree: get": {
|
||||
path: "/api/v0/tree",
|
||||
|
|
@ -88,15 +88,13 @@ func TestServerRoutes(t *testing.T) {
|
|||
if w.Code == http.StatusNotFound {
|
||||
t.Fatal(w)
|
||||
}
|
||||
if !bytes.HasPrefix(w.Body.Bytes(), []byte("not impl")) {
|
||||
if w.Code != http.StatusOK {
|
||||
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 w.Code != http.StatusOK {
|
||||
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())
|
||||
})
|
||||
}
|
||||
}
|
||||
|
|
|
|||
Loading…
Reference in New Issue