clean up some code repetition

This commit is contained in:
John Bintz 2022-02-22 09:00:42 -05:00
parent f28a3aa3e6
commit b6da06df98
1 changed files with 22 additions and 36 deletions

View File

@ -78,6 +78,24 @@ func (s *noteResponse) GetFrontendBody() ([]byte, error) {
return res, nil return res, nil
} }
func handleGetResponse(url string, responseTarget interface{}) error {
resp, err := http.Get(url)
if err != nil {
return err
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return err
}
err = json.Unmarshal(body, responseTarget)
return err
}
func performSearch(query string) (searchResponse, error) { func performSearch(query string) (searchResponse, error) {
params := appConfig.BaseParams() params := appConfig.BaseParams()
params.Add("query", query+"*") params.Add("query", query+"*")
@ -87,27 +105,11 @@ func performSearch(query string) (searchResponse, error) {
url := appConfig.BaseURL() + "/search?" + params.Encode() url := appConfig.BaseURL() + "/search?" + params.Encode()
resp, err := http.Get(url) err := handleGetResponse(url, &response)
if err != nil {
return response, err return response, err
} }
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return response, err
}
err = json.Unmarshal(body, &response)
if err != nil {
return response, err
}
return response, nil
}
func retrieveNote(ID string) (noteResponse, error) { func retrieveNote(ID string) (noteResponse, error) {
params := appConfig.BaseParams() params := appConfig.BaseParams()
params.Add("fields", "title,body,id") params.Add("fields", "title,body,id")
@ -116,23 +118,7 @@ func retrieveNote(ID string) (noteResponse, error) {
url := appConfig.BaseURL() + "/notes/" + ID + "?" + params.Encode() url := appConfig.BaseURL() + "/notes/" + ID + "?" + params.Encode()
resp, err := http.Get(url) err := handleGetResponse(url, &response)
if err != nil {
return response, err return response, err
} }
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return response, err
}
err = json.Unmarshal(body, &response)
if err != nil {
return response, err
}
return response, nil
}