github.com/seeker-insurance/kit@v0.0.13/branch/branch.go (about) 1 package branch 2 3 import ( 4 "encoding/json" 5 "fmt" 6 "net/url" 7 8 "github.com/seeker-insurance/kit/config" 9 "github.com/parnurzeal/gorequest" 10 ) 11 12 const branchApiUrl = "https://api.branch.io/v1/url" 13 14 type ( 15 request struct { 16 BranchKey string `json:"branch_key"` 17 Data Data `json:"data"` 18 } 19 20 Data struct { 21 CanonicalUrl string `json:"$canonical_url"` 22 } 23 24 CanonicalUrlData struct { 25 Url string 26 Params map[string]string 27 } 28 Response struct { 29 Url string 30 Error branchError 31 } 32 33 branchError struct { 34 Code int 35 Message string 36 } 37 ) 38 39 func GetUrl(cud CanonicalUrlData) (Response, error) { 40 cURL, err := generateFullUrl(cud) 41 if err != nil { 42 return Response{}, err 43 } 44 45 return send(request{Data: Data{cURL}}) 46 } 47 48 func generateFullUrl(cud CanonicalUrlData) (string, error) { 49 baseURL, err := url.Parse(cud.Url) 50 if err != nil { 51 return "", err 52 } 53 54 params := url.Values{} 55 for k, v := range cud.Params { 56 params.Add(k, v) 57 } 58 59 baseURL.RawQuery = params.Encode() 60 61 return baseURL.String(), nil 62 } 63 64 func send(req request) (resp Response, err error) { 65 req.BranchKey = config.RequiredString("BRANCH_KEY") 66 67 request := gorequest.New() 68 _, body, _ := request.Post(branchApiUrl).Send(req).End() 69 70 if err := json.Unmarshal([]byte(body), &resp); err != nil { 71 return resp, err 72 } 73 74 if resp.Error.Code > 299 { 75 return resp, fmt.Errorf("Branch.io error: %v - %v", resp.Error.Code, resp.Error.Message) 76 } 77 return resp, nil 78 }