80 lines
1.7 KiB
Go
80 lines
1.7 KiB
Go
package view
|
|
|
|
import (
|
|
"encoding/json"
|
|
"fmt"
|
|
"local/dndex/config"
|
|
"local/dndex/storage"
|
|
"local/dndex/storage/entity"
|
|
"log"
|
|
"net/http"
|
|
"path"
|
|
"strings"
|
|
)
|
|
|
|
func Html(g storage.Graph) error {
|
|
port := config.New().Port
|
|
log.Println("listening on", port)
|
|
err := http.ListenAndServe(fmt.Sprintf(":%d", port), foo(g))
|
|
return err
|
|
}
|
|
|
|
func foo(g storage.Graph) http.Handler {
|
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
var err error
|
|
switch path.Base(r.URL.Path) {
|
|
case "who":
|
|
err = who(g, w, r)
|
|
default:
|
|
http.NotFound(w, r)
|
|
return
|
|
}
|
|
if err != nil {
|
|
http.Error(w, err.Error(), http.StatusInternalServerError)
|
|
}
|
|
})
|
|
}
|
|
|
|
func who(g storage.Graph, w http.ResponseWriter, r *http.Request) error {
|
|
namespace := path.Dir(r.URL.Path)
|
|
if len(namespace) < 2 {
|
|
http.NotFound(w, r)
|
|
return nil
|
|
}
|
|
namespace = strings.Replace(namespace[1:], "/", ".", -1)
|
|
ids := r.URL.Query()["id"]
|
|
_, verbose := r.URL.Query()["v"]
|
|
results := make(map[string]entity.One)
|
|
for i := 0; i < len(ids); i++ {
|
|
id := ids[i]
|
|
ones, err := g.List(r.Context(), namespace, id)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if len(ones) != 1 {
|
|
ones = append(ones, entity.One{})
|
|
}
|
|
one := ones[0]
|
|
if verbose {
|
|
ones, err := g.List(r.Context(), namespace, one.Peers()...)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
for _, another := range ones {
|
|
another.Connections = nil
|
|
for j := range one.Connections {
|
|
if one.Connections[j].Name == another.Name {
|
|
one.Connections[j] = entity.One{
|
|
Name: another.Name,
|
|
Relationship: one.Connections[j].Relationship,
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
results[id] = one
|
|
}
|
|
log.Println("results:", results)
|
|
return json.NewEncoder(w).Encode(results)
|
|
}
|