forked from cayleygraph/cayley
/
http.go
215 lines (187 loc) · 6.74 KB
/
http.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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
// Copyright 2014 The Cayley Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package http
import (
"encoding/json"
"flag"
"fmt"
"html/template"
"net/http"
"os"
"time"
"github.com/cayleygraph/cayley/clog"
"github.com/julienschmidt/httprouter"
"github.com/cayleygraph/cayley/graph"
"github.com/cayleygraph/cayley/internal/config"
"github.com/cayleygraph/cayley/internal/db"
"github.com/cayleygraph/cayley/internal/gephi"
)
type ResponseHandler func(http.ResponseWriter, *http.Request, httprouter.Params) int
var assetsPath = flag.String("assets", "", "Explicit path to the HTTP assets.")
var assetsDirs = []string{"templates", "static", "docs"}
func hasAssets(path string) bool {
for _, dir := range assetsDirs {
if _, err := os.Stat(fmt.Sprint(path, "/", dir)); os.IsNotExist(err) {
return false
}
}
return true
}
func findAssetsPath() string {
if *assetsPath != "" {
if hasAssets(*assetsPath) {
return *assetsPath
}
clog.Fatalf("Cannot find assets at", *assetsPath, ".")
}
if hasAssets(".") {
return "."
}
if hasAssets("..") {
return ".."
}
gopathPath := os.ExpandEnv("$GOPATH/src/github.com/cayleygraph/cayley")
if hasAssets(gopathPath) {
return gopathPath
}
clog.Fatalf("Cannot find assets in any of the default search paths. Please run in the same directory, in a Go workspace, or set --assets .")
panic("cannot reach")
}
func LogRequest(handler ResponseHandler) httprouter.Handle {
return func(w http.ResponseWriter, req *http.Request, params httprouter.Params) {
start := time.Now()
addr := req.Header.Get("X-Real-IP")
if addr == "" {
addr = req.Header.Get("X-Forwarded-For")
if addr == "" {
addr = req.RemoteAddr
}
}
clog.Infof("Started %s %s for %s", req.Method, req.URL.Path, addr)
code := handler(w, req, params)
clog.Infof("Completed %v %s %s in %v", code, http.StatusText(code), req.URL.Path, time.Since(start))
}
}
func jsonResponse(w http.ResponseWriter, code int, err interface{}) int {
w.Header().Set("Content-Type", contentTypeJSON)
w.Write([]byte(`{"error": `))
data, _ := json.Marshal(fmt.Sprint(err))
w.Write(data)
w.Write([]byte(`}`))
return code
}
type TemplateRequestHandler struct {
templates *template.Template
}
func (h *TemplateRequestHandler) ServeHTTP(w http.ResponseWriter, r *http.Request, params httprouter.Params) {
uiType := params.ByName("ui_type")
if r.URL.Path == "/" {
uiType = "query"
}
err := h.templates.ExecuteTemplate(w, uiType+".html", h)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
}
type API struct {
config *config.Config
handle *graph.Handle
}
func (api *API) GetHandleForRequest(r *http.Request) (*graph.Handle, error) {
if !api.config.RequiresHTTPRequestContext {
return api.handle, nil
}
opts := make(graph.Options)
opts["HTTPRequest"] = r
qs, err := graph.NewQuadStoreForRequest(api.handle.QuadStore, opts)
if err != nil {
return nil, err
}
qw, err := db.OpenQuadWriter(qs, api.config)
if err != nil {
return nil, err
}
return &graph.Handle{QuadStore: qs, QuadWriter: qw}, nil
}
func (api *API) RWOnly(handler httprouter.Handle) httprouter.Handle {
if api.config.ReadOnly {
return func(w http.ResponseWriter, req *http.Request, params httprouter.Params) {
jsonResponse(w, http.StatusForbidden, "Database is read-only.")
}
}
return handler
}
func CORSFunc(w http.ResponseWriter, req *http.Request, params httprouter.Params) {
if origin := req.Header.Get("Origin"); origin != "" {
w.Header().Set("Access-Control-Allow-Origin", origin)
w.Header().Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE")
w.Header().Set("Access-Control-Allow-Headers",
"Accept, Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization")
}
}
func CORS(h httprouter.Handle) httprouter.Handle {
return func(w http.ResponseWriter, req *http.Request, params httprouter.Params) {
CORSFunc(w, req, params)
h(w, req, params)
}
}
func (api *API) APIv1(r *httprouter.Router) {
r.POST("/api/v1/query/:query_lang", CORS(LogRequest(api.ServeV1Query)))
r.POST("/api/v1/shape/:query_lang", CORS(LogRequest(api.ServeV1Shape)))
r.POST("/api/v1/write", CORS(api.RWOnly(LogRequest(api.ServeV1Write))))
r.POST("/api/v1/write/file/nquad", CORS(api.RWOnly(LogRequest(api.ServeV1WriteNQuad))))
r.POST("/api/v1/delete", CORS(api.RWOnly(LogRequest(api.ServeV1Delete))))
}
func (api *API) APIv2(r *httprouter.Router) {
r.POST("/api/v2/write", CORS(api.RWOnly(LogRequest(api.ServeV2Write))))
r.POST("/api/v2/delete", CORS(api.RWOnly(LogRequest(api.ServeV2Delete))))
r.POST("/api/v2/read", CORS(LogRequest(api.ServeV2Read)))
r.GET("/api/v2/read", CORS(LogRequest(api.ServeV2Read)))
r.GET("/api/v2/formats", CORS(LogRequest(api.ServeV2Formats)))
}
func SetupRoutes(handle *graph.Handle, cfg *config.Config) {
r := httprouter.New()
assets := findAssetsPath()
if clog.V(2) {
clog.Infof("Found assets at %v", assets)
}
var templates = template.Must(template.ParseGlob(fmt.Sprint(assets, "/templates/*.tmpl")))
templates.ParseGlob(fmt.Sprint(assets, "/templates/*.html"))
root := &TemplateRequestHandler{templates: templates}
docs := &DocRequestHandler{assets: assets}
api := &API{config: cfg, handle: handle}
r.OPTIONS("/*path", CORSFunc)
api.APIv1(r)
api.APIv2(r)
gs := &gephi.GraphStreamHandler{QS: handle.QuadStore}
const gephiPath = "/gephi/gs"
r.GET(gephiPath, gs.ServeHTTP)
fmt.Printf("Serving Gephi GraphStream at http://localhost:%s%s\n", cfg.ListenPort, gephiPath)
//m.Use(martini.Static("static", martini.StaticOptions{Prefix: "/static", SkipLogging: true}))
//r.Handler("GET", "/static", http.StripPrefix("/static", http.FileServer(http.Dir("static/"))))
r.GET("/docs/:docpage", docs.ServeHTTP)
r.GET("/ui/:ui_type", root.ServeHTTP)
r.GET("/", root.ServeHTTP)
http.Handle("/static/", http.StripPrefix("/static", http.FileServer(http.Dir(fmt.Sprint(assets, "/static/")))))
http.Handle("/", r)
}
func Serve(handle *graph.Handle, cfg *config.Config) {
SetupRoutes(handle, cfg)
clog.Infof("Cayley now listening on %s:%s\n", cfg.ListenHost, cfg.ListenPort)
fmt.Printf("Cayley now listening on %s:%s\n", cfg.ListenHost, cfg.ListenPort)
err := http.ListenAndServe(fmt.Sprintf("%s:%s", cfg.ListenHost, cfg.ListenPort), nil)
if err != nil {
clog.Fatalf("ListenAndServe: %v", err)
}
}