-
Notifications
You must be signed in to change notification settings - Fork 7
/
search.go
84 lines (74 loc) · 1.82 KB
/
search.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
package infermedica
import (
"encoding/json"
"fmt"
"net/http"
"net/url"
"strings"
"time"
"strconv"
"github.com/pkg/errors"
)
type SearchRes struct {
ID string `json:"id"`
Label string `json:"label"`
}
type LabTestsSearchRes struct {
ID string `json:"id"`
Label string `json:"label"`
Results []LabResult `json:"results"`
}
type SearchType string
const (
SearchTypeSymptom SearchType = "symptom"
SearchTypeRiskFactor SearchType = "risk_factor"
SearchTypeLabTest SearchType = "lab_test"
)
func (s SearchType) Ptr() *SearchType { return &s }
func (s SearchType) String() string { return string(s) }
func (s *SearchType) IsValid() bool {
_, err := SearchTypeFromString(s.String())
if err != nil {
return false
}
return true
}
func SearchTypeFromString(x string) (SearchType, error) {
switch strings.ToLower(x) {
case "symptom":
return SearchTypeSymptom, nil
case "risk_factor":
return SearchTypeRiskFactor, nil
case "lab_test":
return SearchTypeLabTest, nil
default:
return "", fmt.Errorf("Unexpected value for search type: %q", x)
}
}
func (a *App) Search(phrase string, sex Sex, maxResults int, st SearchType) (*[]SearchRes, error) {
if !sex.IsValid() {
return nil, errors.New("Unexpected value for Sex")
}
if !st.IsValid() {
return nil, errors.New("Unexpected value for search type")
}
url := "search?phrase=" + url.QueryEscape(phrase) + "&sex=" + sex.String() + "&max_results=" + strconv.Itoa(maxResults) + "&type=" + st.String()
req, err := a.prepareRequest("GET", url, nil)
if err != nil {
return nil, err
}
client := &http.Client{
Timeout: time.Second * 5,
}
res, err := client.Do(req)
if err != nil {
return nil, err
}
defer res.Body.Close()
r := []SearchRes{}
err = json.NewDecoder(res.Body).Decode(&r)
if err != nil {
return nil, err
}
return &r, nil
}