105 lines
2.3 KiB
Go
105 lines
2.3 KiB
Go
package view
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"fmt"
|
|
"local/dndex/config"
|
|
"local/dndex/storage"
|
|
"local/dndex/storage/entity"
|
|
"local/gziphttp"
|
|
"log"
|
|
"net/http"
|
|
"path"
|
|
"strings"
|
|
)
|
|
|
|
func JSON(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) {
|
|
w.Header().Set("Access-Control-Allow-Origin", "*")
|
|
if gziphttp.Can(r) {
|
|
w = gziphttp.New(w)
|
|
}
|
|
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"]
|
|
_, one := r.URL.Query()["one"]
|
|
results := make(map[string]entity.One)
|
|
for i := 0; i < len(ids); i++ {
|
|
id := ids[i]
|
|
one, err := whoOne(r.Context(), g, namespace, id, verbose)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
results[id] = one
|
|
}
|
|
var marshalme interface{}
|
|
if one {
|
|
for k := range results {
|
|
marshalme = results[k]
|
|
break
|
|
}
|
|
} else {
|
|
marshalme = results
|
|
}
|
|
log.Printf("id=%+v, one=%v, verbose=%v, results:%+v", ids, one, verbose, marshalme)
|
|
enc := json.NewEncoder(w)
|
|
enc.SetIndent("", " ")
|
|
return enc.Encode(marshalme)
|
|
}
|
|
|
|
func whoOne(ctx context.Context, g storage.Graph, namespace, id string, verbose bool) (entity.One, error) {
|
|
ones, err := g.List(ctx, namespace, id)
|
|
if err != nil {
|
|
return entity.One{}, err
|
|
}
|
|
if len(ones) != 1 {
|
|
ones = append(ones, entity.One{})
|
|
}
|
|
one := ones[0]
|
|
if verbose {
|
|
ones, err := g.List(ctx, namespace, one.Peers()...)
|
|
if err != nil {
|
|
return entity.One{}, err
|
|
}
|
|
for _, another := range ones {
|
|
another.Connections = nil
|
|
another.Text = ""
|
|
for j := range one.Connections {
|
|
if one.Connections[j].Name == another.Name {
|
|
another.Relationship = one.Connections[j].Relationship
|
|
one.Connections[j] = another
|
|
}
|
|
}
|
|
}
|
|
}
|
|
return one, nil
|
|
}
|