-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmain.go
More file actions
113 lines (93 loc) · 3.19 KB
/
main.go
File metadata and controls
113 lines (93 loc) · 3.19 KB
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
package main
import (
"encoding/json"
"log"
"net/http"
"os"
"strconv"
"strings"
)
var (
APIPort = os.Getenv("API_PORT")
OSAddress = os.Getenv("OPENSEARCH_HOST")
IndexName = os.Getenv("OPENSEARCH_INDEX")
osClient OSClient // FOR INITIAL DEV ONLY - DO NOT USE GLOBAL IN PRODUCTION (probably)
)
func main() {
log.Println("Initializing OpenSearch client...")
osClient = InitOpenSearch()
log.Println("OpenSearch client initialized successfully")
log.Println("Starting API server...")
mux := http.NewServeMux()
mux.HandleFunc("/heartbeat", heartbeat)
mux.HandleFunc("/", getData)
// Apply CORS middleware
handler := corsMiddleware(mux)
log.Println("Server starting on :" + APIPort)
err := http.ListenAndServe(":"+APIPort, handler)
log.Fatalf("Error starting server: %s", err)
}
func heartbeat(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("ok"))
}
func getData(response http.ResponseWriter, request *http.Request) {
// Parse query parameters
query := request.URL.Query().Get("query")
clientId := request.URL.Query().Get("client_id")
providerId := request.URL.Query().Get("provider_id")
consortiumId := request.URL.Query().Get("consortium_id")
numDistributionResults := GetURLQueryAsUInt(request, "distribution_size", 10)
fieldsPresent := strings.Split(request.URL.Query().Get("present"), ",")
fieldsDistribution := strings.Split(request.URL.Query().Get("distribution"), ",")
// Build aggregation slices and query
presentAggs := make([]OSAggregation, 0)
for _, field := range fieldsPresent {
if field != "" {
presentAggs = append(presentAggs, buildPresentAggregation(field))
}
}
distributionAggs := make([]OSAggregation, 0)
for _, field := range fieldsDistribution {
if field != "" {
distributionAggs = append(distributionAggs, buildDistributionAggregation(field, numDistributionResults))
}
}
search := BuildBaseQuery(clientId, providerId, consortiumId, query)
search = search.
Aggs(presentAggs...).
Aggs(distributionAggs...)
// Execute search and returned parsed openSearchResponse
openSearchResponse := Run(search)
apiResponse, err := ParseSearchResp(openSearchResponse)
if err != nil {
http.Error(response, err.Error(), http.StatusInternalServerError)
return
}
response.Header().Set("Content-Type", "application/json")
response.WriteHeader(http.StatusOK)
json.NewEncoder(response).Encode(apiResponse)
}
func GetURLQueryAsUInt(request *http.Request, param string, defaultValue uint64) uint64 {
valueStr := request.URL.Query().Get(param)
if valueStr == "" {
return defaultValue
}
value, err := strconv.ParseUint(valueStr, 10, 64)
if err != nil {
return defaultValue
}
return value
}
// https://www.stackhawk.com/blog/golang-cors-guide-what-it-is-and-how-to-enable-it/#h-using-middleware-for-better-organization
func corsMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS")
w.Header().Set("Access-Control-Allow-Headers", "Content-Type, Authorization")
if r.Method == "OPTIONS" {
w.WriteHeader(http.StatusOK)
return
}
next.ServeHTTP(w, r)
})
}