github.com/hscells/guru@v0.0.0-20200207042420-2dabeb950d69/umlsconcepts.go (about) 1 package guru 2 3 import ( 4 "bytes" 5 "encoding/json" 6 "fmt" 7 "io/ioutil" 8 "net/http" 9 "regexp" 10 ) 11 12 type UMLSClient struct { 13 client http.Client 14 ticketGrantingTicket string 15 } 16 17 func NewUMLSClient(username, password string) (UMLSClient, error) { 18 var ( 19 client http.Client 20 umls UMLSClient 21 ) 22 23 fmt.Println("getting umls ticket") 24 resp, err := client.Post("https://utslogin.nlm.nih.gov/cas/v1/tickets", "application/x-www-form-urlencoded", bytes.NewBufferString(fmt.Sprintf("username=%s&password=%s", username, password))) 25 if err != nil { 26 return umls, err 27 } 28 b, err := ioutil.ReadAll(resp.Body) 29 if err != nil { 30 return umls, err 31 } 32 re := regexp.MustCompile(`action=".*(?P<Ticket>TGT-.*-cas)"`) 33 ticketGrantingTicket := re.FindStringSubmatch(string(b))[1] 34 35 return UMLSClient{ 36 client: client, 37 ticketGrantingTicket: ticketGrantingTicket, 38 }, nil 39 } 40 41 func (c UMLSClient) Preferred(cui string) (string, error) { 42 // Request service ticket. 43 resp, err := c.client.Post(fmt.Sprintf("https://utslogin.nlm.nih.gov/cas/v1/tickets/%s", c.ticketGrantingTicket), "application/x-www-form-urlencoded", bytes.NewBufferString(fmt.Sprintf("service=%s", "http://umlsks.nlm.nih.gov"))) 44 if err != nil { 45 return "", err 46 } 47 b, err := ioutil.ReadAll(resp.Body) 48 if err != nil { 49 panic(err) 50 return "", err 51 } 52 53 ticket := string(b) 54 resp, err = c.client.Get(fmt.Sprintf("https://uts-ws.nlm.nih.gov/rest/content/current/CUI/%s/atoms/preferred?ticket=%s", cui, ticket)) 55 if err != nil { 56 panic(err) 57 return "", err 58 } 59 60 if resp.StatusCode != 200 { 61 return "", nil 62 } 63 64 b, err = ioutil.ReadAll(resp.Body) 65 if err != nil { 66 fmt.Println(err) 67 return "", err 68 } 69 70 var r map[string]interface{} 71 err = json.Unmarshal(b, &r) 72 if err != nil { 73 fmt.Println(err) 74 return "", err 75 } 76 77 s := r["result"].(map[string]interface{})["name"].(string) 78 return s, nil 79 }