-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathhttp_server.go
73 lines (57 loc) · 1.89 KB
/
http_server.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
package main
import (
"log"
"net/http"
"os"
"path/filepath"
"github.com/blevesearch/bleve"
bleveHttp "github.com/blevesearch/bleve/http"
"github.com/gorilla/mux"
)
type corsWrapper struct {
r *mux.Router
}
var indexDir = filepath.Join(homeDir, ".goin")
func muxVariableLookup(req *http.Request, name string) string {
return mux.Vars(req)[name]
}
func indexNameLookup(req *http.Request) string {
return muxVariableLookup(req, "indexName")
}
func startServer() {
router := mux.NewRouter()
router.StrictSlash(true)
listIndexesHandler := bleveHttp.NewListIndexesHandler()
router.Handle("/api", listIndexesHandler).Methods("GET")
docCountHandler := bleveHttp.NewDocCountHandler("")
docCountHandler.IndexNameLookup = indexNameLookup
router.Handle("/api/{indexName}/_count", docCountHandler).Methods("GET")
searchHandler := bleveHttp.NewSearchHandler("")
searchHandler.IndexNameLookup = indexNameLookup
router.Handle("/api/{indexName}/_search", searchHandler).Methods("POST")
http.Handle("/", &corsWrapper{router})
log.Printf("opening indexes")
indexPath := indexDir + string(os.PathSeparator) + "index.bleve"
i, err := bleve.OpenUsing(indexPath, map[string]interface{}{
"read_only": true,
})
if err != nil {
log.Printf("error opening index %s: %v", indexPath, err)
} else {
bleveHttp.RegisterIndexName("index.bleve", i)
}
}
func (s *corsWrapper) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
if origin := req.Header.Get("Origin"); origin != "" {
rw.Header().Set("Access-Control-Allow-Origin", origin)
rw.Header().Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE")
rw.Header().Set("Access-Control-Allow-Headers",
"Accept, Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization")
}
// Stop here if its Preflighted OPTIONS request
if req.Method == "OPTIONS" {
return
}
// Continue to process request
s.r.ServeHTTP(rw, req)
}