Created
January 18, 2018 20:45
-
-
Save saurcery/331c1519e4f45d31278c86688c4daeed to your computer and use it in GitHub Desktop.
example usage of facebook marketing calls in golang
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
fb "github.com/huandu/facebook" | |
) | |
type AdCampaign struct { | |
EffectiveStatus string | |
BuyingType string | |
} | |
func main() { | |
sess, err := getSession() | |
if err != nil { | |
fmt.Println(err.Error()) | |
} | |
// test a single get request | |
singleGet(sess) | |
batchGet(sess) | |
} | |
func singleGet(sess *fb.Session) { | |
res, err := sess.Get("23842690842140446", fb.Params{ | |
"fields": "effective_status", | |
}) | |
if err != nil { | |
fmt.Println(err.Error()) | |
} | |
var campaign AdCampaign | |
res.Decode(&campaign) | |
fmt.Println("print status in struct:", campaign.EffectiveStatus) | |
} | |
// batchGet is based on https://developers.facebook.com/docs/marketing-api/asyncrequests/v2.11 | |
func batchGet(sess *fb.Session) { | |
fmt.Println("\nmaking batch requests now...") | |
params1 := fb.Params{ | |
"method": fb.GET, | |
"relative_url": "23842690842140446?fields=effective_status", | |
} | |
params2 := fb.Params{ | |
"method": fb.GET, | |
"relative_url": "23842690842140446?fields=buying_type", | |
} | |
results, err := sess.BatchApi(params1, params2) | |
if err != nil { | |
fmt.Println(err.Error()) | |
} | |
// batchResult1 and batchResult2 are response for params1 and params2. | |
batchResult1, _ := results[0].Batch() | |
batchResult2, _ := results[1].Batch() | |
// get the first result | |
res := batchResult1.Result | |
var campaign1 AdCampaign | |
res.Decode(&campaign1) | |
fmt.Println("campaign status:", campaign1.EffectiveStatus) | |
// get the second result | |
res = batchResult2.Result | |
var campaign2 AdCampaign | |
res.Decode(&campaign2) | |
fmt.Println("campaign buying type:", campaign2.BuyingType) | |
fmt.Println("\n============== usage info ============") | |
fmt.Println(res.UsageInfo()) | |
} | |
func getSession() (*fb.Session, error) { | |
// create a global App var to hold app id and secret. | |
var app = fb.New("app-id", "app-secret") | |
session := app.Session("access-token") | |
session.Version = "v2.11" | |
// validate access token. err is nil if token is valid. | |
// err := session.Validate() | |
// if err != nil { | |
// return nil, err | |
// } | |
return session, nil | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment