# HG changeset patch # User Mikael Berthe # Date 1536227024 -7200 # Node ID 80c81e9b77b4baa22af1b184f2be17e7ade37bf8 # Parent ca5639b4768e0ed99346a211935c929da04b913f Support search v2 API diff -r ca5639b4768e -r 80c81e9b77b4 api.go --- a/api.go Thu Sep 06 11:28:42 2018 +0200 +++ b/api.go Thu Sep 06 11:43:44 2018 +0200 @@ -130,7 +130,10 @@ return nil, err } if res.StatusCode < 200 || res.StatusCode >= 300 { - return nil, errors.Errorf("bad server status code (%d): %s", + // Please note that the error string code is used by Search() + // to check the error cause. + const errFormatString = "bad server status code (%d)" + return nil, errors.Errorf(errFormatString+": %s", res.StatusCode, http.StatusText(res.StatusCode)) } diff -r ca5639b4768e -r 80c81e9b77b4 search.go --- a/search.go Thu Sep 06 11:28:42 2018 +0200 +++ b/search.go Thu Sep 06 11:43:44 2018 +0200 @@ -7,21 +7,15 @@ package madon import ( + "strings" + "github.com/sendgrid/rest" ) // Search search for contents (accounts or statuses) and returns a Results -func (mc *Client) Search(query string, resolve bool) (*Results, error) { - if query == "" { - return nil, ErrInvalidParameter - } - - params := make(apiCallParams) - params["q"] = query - if resolve { - params["resolve"] = "true" - } - +func (mc *Client) searchV1(params apiCallParams) (*Results, error) { + // We use a custom structure with shadowed Hashtags field, + // since the v1 version only returns strings. var resultsV1 struct { Results Hashtags []string `json:"hashtags"` @@ -39,3 +33,36 @@ return &results, nil } + +func (mc *Client) searchV2(params apiCallParams) (*Results, error) { + var results Results + if err := mc.apiCall("v2/"+"search", rest.Get, params, nil, nil, &results); err != nil { + return nil, err + } + + return &results, nil +} + +// Search search for contents (accounts or statuses) and returns a Results +func (mc *Client) Search(query string, resolve bool) (*Results, error) { + if query == "" { + return nil, ErrInvalidParameter + } + + // The parameters are the same in both v1 & v2 API versions + params := make(apiCallParams) + params["q"] = query + if resolve { + params["resolve"] = "true" + } + + r, err := mc.searchV2(params) + + // This is not a very beautiful way to check the error cause, I admit. + if err != nil && strings.Contains(err.Error(), "bad server status code (404)") { + // Fall back to v1 API endpoint + r, err = mc.searchV1(params) + } + + return r, err +}