github.com/cayleygraph/cayley@v0.7.7/server/http/common.go (about) 1 package cayleyhttp 2 3 import ( 4 "encoding/json" 5 "fmt" 6 "net/http" 7 8 "github.com/cayleygraph/cayley/graph" 9 "github.com/cayleygraph/cayley/graph/http" 10 ) 11 12 func jsonResponse(w http.ResponseWriter, code int, err interface{}) { 13 w.Header().Set("Content-Type", contentTypeJSON) 14 w.WriteHeader(code) 15 w.Write([]byte(`{"error": `)) 16 var s string 17 switch err := err.(type) { 18 case string: 19 s = err 20 case error: 21 s = err.Error() 22 default: 23 s = fmt.Sprint(err) 24 } 25 data, _ := json.Marshal(s) 26 w.Write(data) 27 w.Write([]byte(`}`)) 28 } 29 30 func HandleForRequest(h *graph.Handle, wtyp string, wopt graph.Options, r *http.Request) (*graph.Handle, error) { 31 g, ok := h.QuadStore.(httpgraph.QuadStore) 32 if !ok { 33 return h, nil 34 } 35 qs, err := g.ForRequest(r) 36 if err != nil { 37 return nil, err 38 } 39 qw, err := graph.NewQuadWriter(wtyp, qs, wopt) 40 if err != nil { 41 qs.Close() 42 return nil, err 43 } 44 return &graph.Handle{QuadStore: qs, QuadWriter: qw}, nil 45 }