forked from cayleygraph/cayley
-
Notifications
You must be signed in to change notification settings - Fork 0
/
common.go
46 lines (42 loc) · 1.02 KB
/
common.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
package cayleyhttp
import (
"encoding/json"
"fmt"
"net/http"
"github.com/aperturerobotics/cayley/graph"
httpgraph "github.com/aperturerobotics/cayley/graph/http"
)
func jsonResponse(w http.ResponseWriter, code int, err interface{}) {
w.Header().Set("Content-Type", contentTypeJSON)
w.WriteHeader(code)
w.Write([]byte(`{"error": `))
var s string
switch err := err.(type) {
case string:
s = err
case error:
s = err.Error()
default:
s = fmt.Sprint(err)
}
data, _ := json.Marshal(s)
w.Write(data)
w.Write([]byte(`}`))
}
// HandleForRequest returns new graph.Handle for given writer name, options and request
func HandleForRequest(h *graph.Handle, wtyp string, wopt graph.Options, r *http.Request) (*graph.Handle, error) {
g, ok := h.QuadStore.(httpgraph.QuadStore)
if !ok {
return h, nil
}
qs, err := g.ForRequest(r)
if err != nil {
return nil, err
}
qw, err := graph.NewQuadWriter(wtyp, qs, wopt)
if err != nil {
qs.Close()
return nil, err
}
return &graph.Handle{QuadStore: qs, QuadWriter: qw}, nil
}