-
Notifications
You must be signed in to change notification settings - Fork 8
/
handle_proxy.go
95 lines (82 loc) · 2.3 KB
/
handle_proxy.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
package sparql
import (
"errors"
"fmt"
"io/ioutil"
"net/http"
"strings"
"github.com/delving/hub3/ikuzo/domain"
"github.com/delving/hub3/ikuzo/render"
)
func (s *Service) sparqlProxy(w http.ResponseWriter, r *http.Request) {
orgID := domain.GetOrganizationID(r)
repo, err := s.GetRepo(orgID)
if err != nil {
if errors.Is(err, domain.ErrServiceNotEnabled) {
render.Error(w, r, fmt.Errorf("sparql: %w", err), &render.ErrorConfig{
StatusCode: http.StatusNotAcceptable,
})
return
}
render.Error(w, r, fmt.Errorf("sparql: %w", err), &render.ErrorConfig{
StatusCode: http.StatusInternalServerError,
})
return
}
var query string
switch r.Method {
case http.MethodGet:
query = r.URL.Query().Get("query")
case http.MethodPost:
query = r.FormValue("query")
}
if query == "" {
render.Error(w, r, fmt.Errorf("sparql query cannot be empty"), &render.ErrorConfig{
StatusCode: http.StatusBadRequest,
})
return
}
if !strings.Contains(strings.ToLower(query), "limit ") {
query = fmt.Sprintf("%s LIMIT %d", query, s.queryLimit)
}
resp, statusCode, contentType, err := s.runSparqlQuery(repo, query)
if err != nil {
render.Error(w, r, fmt.Errorf("error with sparql query"), &render.ErrorConfig{
StatusCode: http.StatusBadRequest,
Message: string(resp),
})
return
}
w.Header().Set("Content-Type", contentType)
_, err = w.Write(resp)
if err != nil {
render.Error(w, r, err, &render.ErrorConfig{
StatusCode: http.StatusInternalServerError,
Message: string(resp),
})
return
}
render.Status(r, statusCode)
return
}
// runSparqlQuery sends a SPARQL query to the SPARQL-endpoint specified in the configuration
func (s *Service) runSparqlQuery(repo *Repo, query string) (body []byte, statusCode int, contentType string, err error) {
resp, err := repo.queryRaw(query, http.MethodGet, "")
if err != nil {
s.log.Error().Err(err).Msg("Error in sparql query")
if strings.Contains(err.Error(), "connection refused") {
body = []byte("triple store unavailable")
}
statusCode = http.StatusBadRequest
return
}
defer resp.Body.Close()
body, err = ioutil.ReadAll(resp.Body)
if err != nil {
s.log.Error().Err(err).Msg("Unable to read the response body with error: %s")
return
}
statusCode = resp.StatusCode
contentType = resp.Header.Get("Content-Type")
return
}