-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmain.go
312 lines (262 loc) · 8.82 KB
/
main.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
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
//go:generate statik -src=./universal_spectrum_explorer -include=*.jpg,*.txt,*.html,*.css,*.js,*png
//go:generate goversioninfo -icon=resources/kusterlab.ico
package main
import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"net/url"
"os"
"os/signal"
"strconv"
"syscall"
"time"
_ "github.com/kusterlab/use_embedded/statik" // TODO: Replace with the absolute import path
logrusmiddleware "github.com/bakins/logrus-middleware"
"github.com/rakyll/statik/fs"
"github.com/sirupsen/logrus"
"github.com/spf13/pflag"
)
func handlerPeptideAtlas(w http.ResponseWriter, req *http.Request) {
// we need to buffer the body if we want to read it here and send it
// in the request.
body, err := ioutil.ReadAll(req.Body)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
// you can reassign the body if you need to parse it as multipart
req.Body = ioutil.NopCloser(bytes.NewReader(body))
query := req.URL.Query()
usi, present := query["usi"] //filters=["color", "price", "brand"]
if !present || len(usi) == 0 {
fmt.Println("usi not present")
}
// create a new url from the raw RequestURI sent by the client
// url := fmt.Sprintf("%s://%s%s", proxyScheme, proxyHost, req.RequestURI)
url := "https://db.systemsbiology.net/sbeams/cgi/PeptideAtlas/ShowObservedSpectrum?USI=" + usi[0]
fmt.Println(url)
proxyReq, err := http.NewRequest(req.Method, url, bytes.NewReader(body))
// We may want to filter some headers, otherwise we could just use a shallow copy
// proxyReq.Header = req.Header
proxyReq.Header = make(http.Header)
for h, val := range req.Header {
proxyReq.Header[h] = val
}
client := &http.Client{
Timeout: 15 * time.Second}
resp, err := client.Do(proxyReq)
fmt.Println(resp)
if err != nil {
http.Error(w, err.Error(), http.StatusBadGateway)
return
}
defer resp.Body.Close()
body, err = ioutil.ReadAll(resp.Body)
if err != nil {
http.Error(w, err.Error(), http.StatusBadGateway)
return
}
w.Header().Set("Content-Type", "text/plain; charset=utf-8")
_, err = w.Write(body)
if err != nil {
logrus.Info(err)
}
// legacy code
}
func handlerJPOST(w http.ResponseWriter, req *http.Request) {
// we need to buffer the body if we want to read it here and send it
// in the request.
body, err := ioutil.ReadAll(req.Body)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
query := req.URL.Query()
usi, present := query["usi"] //filters=["color", "price", "brand"]
if !present || len(usi) == 0 {
fmt.Println("usi not present")
}
// you can reassign the body if you need to parse it as multipart
req.Body = ioutil.NopCloser(bytes.NewReader(body))
// create a new url from the raw RequestURI sent by the client
// url := fmt.Sprintf("%s://%s%s", proxyScheme, proxyHost, req.RequestURI)
// url := "https://repository.jpostdb.org/spectrum/get_data.php?usi=mzspec:PXD005175:CRC_iTRAQ_06:scan:11803:VEYTLGEESEAPGQR/3"
url := "https://repository.jpostdb.org/spectrum/get_data.php?usi=" + usi[0]
fmt.Println(url)
proxyReq, err := http.NewRequest(req.Method, url, bytes.NewReader(body))
// We may want to filter some headers, otherwise we could just use a shallow copy
// proxyReq.Header = req.Header
proxyReq.Header = make(http.Header)
for h, val := range req.Header {
proxyReq.Header[h] = val
}
client := &http.Client{}
resp, err := client.Do(proxyReq)
fmt.Println(resp)
if err != nil {
http.Error(w, err.Error(), http.StatusBadGateway)
return
}
defer resp.Body.Close()
body, err = ioutil.ReadAll(resp.Body)
if err != nil {
http.Error(w, err.Error(), http.StatusBadGateway)
return
}
// w.Header().Set("Content-Type", "text/plain; charset=utf-8")
w.Header().Set("Content-Encoding", "gzip")
_, err = w.Write(body)
if err != nil {
logrus.Info(err)
}
// legacy code
}
const abc = `
[{
"origin": "JPOST",
"url": "https://repository.jpostdb.org/proxi/spectra?"
},{
"origin": "MassIVE",
"url": "http://massive.ucsd.edu/ProteoSAFe/proxi/v0.1/spectra?"
},{
"origin": "PeptideAtlas",
"url" : "http://www.peptideatlas.org/api/proxi/v0.1/spectra?"
},{
"origin": "PRIDE",
"url" : "http://www.ebi.ac.uk/pride/proxi/archive/v0.1/spectra?"
},{
"origin": "ProteomeCentral",
"url": "http://proteomecentral.proteomexchange.org/api/proxi/v0.1/spectra?"
}]
`
type Autogenerated []struct {
Origin string `json:"origin"`
URL string `json:"url"`
}
type Endpoint struct {
Origin string `json:"origin"`
URL string `json:"url"`
}
type RequestResponse struct {
Body []byte
StatusCode int
Error error
Origin string
}
func minimalRequest(endpoint Endpoint, usi string) RequestResponse {
params := url.Values{}
params.Add("resultType", "full")
params.Add("usi", usi)
_url := endpoint.URL + params.Encode()
fmt.Println(_url)
proxyReq, err := http.NewRequest("GET", _url, nil)
client := &http.Client{}
resp, err := client.Do(proxyReq)
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
return RequestResponse{Body: body, StatusCode: resp.StatusCode, Error: err, Origin: endpoint.Origin}
}
func worker(endpoint Endpoint, usi string, outputChannel chan<- RequestResponse) {
req := minimalRequest(endpoint, usi)
outputChannel <- req
}
type UsiRespone struct {
Body string `json:"body"`
Origin string `json:"origin"`
}
func availabilityHandler(w http.ResponseWriter, r *http.Request) {
query := r.URL.Query()
usi, present := query["usi"] //filters=["color", "price", "brand"]
if !present || len(usi) == 0 {
fmt.Println("usi not present")
http.Error(w, "usi not present", http.StatusInternalServerError)
return
}
res := Autogenerated{}
err := json.Unmarshal([]byte(abc), &res)
if err != nil {
fmt.Println("internal json parsing issue")
http.Error(w, "internal json parsing issue", http.StatusInternalServerError)
return
}
// usi = "mzspec:PXD000966:CPTAC_CompRef_00_iTRAQ_05_2Feb12_Cougar_11-10-09.mzML:scan:12298:[UNIMOD:214]-LHFFM[UNIMOD:35]PGFAPLTSR/2"
// usi = "mzspec:PXD000966:CPTAC_CompRef_00_iTRAQ_05_2Feb12_Cougar_11-10-09.mzML:scan:12298:[iTRAQ4plex]-LHFFM[Oxidation]PGFAPLTSR/2"
outputChannel := make(chan RequestResponse, len(res))
for _, endpoint := range res {
// inputChannel <- url
go worker(endpoint, usi[0], outputChannel)
}
for i := 0; i < len(res); i++ {
req := <-outputChannel
if req.StatusCode == 200 {
// if req.StatusCode == 200 && req.Origin != "MassIVE" {
fmt.Println(req.Origin)
w.Header().Set("Content-Type", "application/json")
// w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Cache-Control", "no-cache, no-store, must-revalidate") // HTTP 1.1.
w.Header().Set("Pragma", "no-cache") // HTTP 1.0.
w.Header().Set("Expires", "0") // Proxies.
w.Write([]byte(req.Body))
return
}
}
http.Error(w, "no useful answers", http.StatusInternalServerError)
return
}
func main() {
var port *int= pflag.Int("port", 8080, "port used for local deployment")
var verbose *bool = pflag.BoolP("verbose", "v", false, "verbose output")
pflag.Parse()
var port_string string = ":" + strconv.FormatInt(int64(*port), 10)
// viper.BindPFlags(pflag.CommandLine)
logger := logrus.New()
if *verbose {
logger.Level = logrus.InfoLevel
} else {
logger.Level = logrus.PanicLevel
}
// logger.Formatter = &logrus.JSONFormatter{}
l := logrusmiddleware.Middleware{
Name: "use",
Logger: logger,
}
statikFS, err := fs.New()
if err != nil {
logger.Fatal(err)
}
// Serve the contents over HTTP.
// http.Handle("/isv/", http.StripPrefix("/isv/", http.FileServer(statikFS)))
//http.Handle("/public/", http.StripPrefix("/public/", http.FileServer(statikFS)))
// http.Handle("/", l.Handler(http.HandlerFunc(handler), "homepage"))
http.HandleFunc("/peptideAtlas", handlerPeptideAtlas) // Update this line of code
http.HandleFunc("/jPOST", handlerJPOST) // Update this line of code
http.Handle("/use/", l.Handler(http.StripPrefix("/use/", http.FileServer(statikFS)), "use"))
http.HandleFunc("/availability", availabilityHandler)
go http.ListenAndServe(port_string, nil)
fmt.Println(port_string)
url := "http://localhost" + port_string + "/use/UniversalSpectrumExplorer.html"
_ = openURL(url)
sigs := make(chan os.Signal, 1)
done := make(chan bool, 1)
// `signal.Notify` registers the given channel to
// receive notifications of the specified signals.
signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM)
// This goroutine executes a blocking receive for
// signals. When it gets one it'll print it out
// and then notify the program that it can finish.
go func() {
sig := <-sigs
logger.Println()
logger.Println(sig)
done <- true
}()
// The program will wait here until it gets the
// expected signal (as indicated by the goroutine
// above sending a value on `done`) and then exit.
logger.Println("awaiting signal")
<-done
logger.Println("exiting")
}