forked from cayleygraph/cayley
-
Notifications
You must be signed in to change notification settings - Fork 0
/
http.go
171 lines (147 loc) · 5.08 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
// 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 (
"flag"
"fmt"
"html/template"
"net/http"
"os"
"time"
"github.com/barakmich/glog"
"github.com/julienschmidt/httprouter"
"github.com/google/cayley/config"
"github.com/google/cayley/db"
"github.com/google/cayley/graph"
)
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
}
glog.Fatalln("Cannot find assets at", *assetsPath, ".")
}
if hasAssets(".") {
return "."
}
if hasAssets("..") {
return ".."
}
gopathPath := os.ExpandEnv("$GOPATH/src/github.com/google/cayley")
if hasAssets(gopathPath) {
return gopathPath
}
glog.Fatalln("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
}
}
glog.Infof("Started %s %s for %s", req.Method, req.URL.Path, addr)
code := handler(w, req, params)
glog.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 {
http.Error(w, fmt.Sprintf("{\"error\" : \"%s\"}", err), code)
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) APIv1(r *httprouter.Router) {
r.POST("/api/v1/query/:query_lang", LogRequest(api.ServeV1Query))
r.POST("/api/v1/shape/:query_lang", LogRequest(api.ServeV1Shape))
r.POST("/api/v1/write", LogRequest(api.ServeV1Write))
r.POST("/api/v1/write/file/nquad", LogRequest(api.ServeV1WriteNQuad))
//TODO(barakmich): /write/text/nquad, which reads from request.body instead of HTML5 file form?
r.POST("/api/v1/delete", LogRequest(api.ServeV1Delete))
}
func SetupRoutes(handle *graph.Handle, cfg *config.Config) {
r := httprouter.New()
assets := findAssetsPath()
if glog.V(2) {
glog.V(2).Infoln("Found assets at", 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}
api.APIv1(r)
//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)
glog.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 {
glog.Fatal("ListenAndServe: ", err)
}
}