### Handle API Pagination in Go Source: https://context7.com/huandu/facebook/llms.txt This Go example demonstrates how to navigate through paginated Facebook API responses using the github.com/huandu/facebook/v2 library. It shows how to retrieve the first page of results, create a paging structure, and then iterate through subsequent pages until all data is fetched. The code also includes an example of checking API usage information. ```go package main import ( "fmt" "log" fb "github.com/huandu/facebook/v2" ) func main() { session := &fb.Session{} session.SetAccessToken("EAABsbCS1iHgBO7ZC6z...") // Get first page of feed res, err := session.Get("/me/feed", fb.Params{ "limit": "25", }) if err != nil { log.Fatal(err) } // Create paging structure paging, err := res.Paging(session) if err != nil { log.Fatal("Failed to create paging:", err) } var allPosts []fb.Result // Append first page allPosts = append(allPosts, paging.Data()...) fmt.Printf("First page: %d posts\n", len(paging.Data())) // Iterate through all pages pageCount := 1 for paging.HasNext() { noMore, err := paging.Next() if err != nil { log.Fatal("Error getting next page:", err) } if noMore { break } pageCount++ allPosts = append(allPosts, paging.Data()...) fmt.Printf("Page %d: %d posts\n", pageCount, len(paging.Data())) // Check rate limiting if usage := paging.UsageInfo(); usage != nil { fmt.Printf("API Call Count: %d%%\n", usage.App.CallCount) } } fmt.Printf("Total posts retrieved: %d\n", len(allPosts)) // Output: // First page: 25 posts // Page 2: 25 posts // API Call Count: 15% // Total posts retrieved: 50 } ``` -------------------------------- ### Quick Start: Fetch User First Name with Golang Facebook SDK Source: https://github.com/huandu/facebook/blob/master/README.md Demonstrates how to quickly fetch a user's first name from the Facebook Graph API using the Go SDK. It shows how to make a GET request and access the 'first_name' field from the response. The example highlights the use of `fb.Params` for query parameters and `fb.Result` for handling the API response. ```go package main import ( "fmt" fb "github.com/huandu/facebook/v2" ) func main() { res, _ := fb.Get("/538744468", fb.Params{ "fields": "first_name", "access_token": "a-valid-access-token", }) fmt.Println("Here is my Facebook first name:", res["first_name"]) } ``` -------------------------------- ### Integrate Facebook SDK with Golang OAuth2 Package Source: https://github.com/huandu/facebook/blob/master/README.md This example details how to use the `golang.org/x/oauth2` package for Facebook OAuth2 authentication and token management with the Facebook SDK. It involves creating an OAuth2 configuration, exchanging a code for a token, creating an HTTP client, and then assigning this client to the Facebook SDK's `Session#HttpClient`. ```go import ( "golang.org/x/oauth2" oauth2fb "golang.org/x/oauth2/facebook" fb "github.com/huandu/facebook/v2" ) // Get Facebook access token. conf := &oauth2.Config{ ClientID: "AppId", ClientSecret: "AppSecret", RedirectURL: "CallbackURL", Scopes: []string{"email"}, Endpoint: oauth2fb.Endpoint, } token, err := conf.Exchange(oauth2.NoContext, "code") // Create a client to manage access token life cycle. client := conf.Client(oauth2.NoContext, token) // Use OAuth2 client with session. session := &fb.Session{ Version: "v2.4", HttpClient: client, } // Use session. res, _ := session.Get("/me", nil) ``` -------------------------------- ### Integrate Facebook SDK with Google App Engine URLFetch Source: https://github.com/huandu/facebook/blob/master/README.md This example shows how to configure the Facebook SDK to work with Google App Engine's standard HTTP client, `appengine/urlfetch`. It requires explicitly setting the `HttpClient` in the `Session` object to `urlfetch.Client(context)`. This is necessary because the default `net/http` client is not permitted in the App Engine environment. ```go import ( "appengine" "appengine/urlfetch" ) // suppose it's the AppEngine context initialized somewhere. var context appengine.Context // default Session object uses http.DefaultClient which is not allowed to use // in appengine. one has to create a Session and assign it a special client. seesion := globalApp.Session("a-access-token") session.HttpClient = urlfetch.Client(context) // now, the session uses AppEngine HTTP client now. res, err := session.Get("/me", nil) ``` -------------------------------- ### Enable appsecret_proof for Secure Graph API Calls Source: https://github.com/huandu/facebook/blob/master/README.md This example shows how to enable `appsecret_proof` for enhanced Graph API call security. You can enable this globally for all sessions created by an app using `globalApp.EnableAppsecretProof = true` or on a per-session basis using `session.EnableAppsecretProof(bool)`. This feature verifies Graph API calls. ```go globalApp := fb.New("your-app-id", "your-app-secret") // enable "appsecret_proof" for all sessions created by this app. globalApp.EnableAppsecretProof = true // all calls in this session are secured. session := globalApp.Session("a-valid-access-token") session.Get("/me", nil) // it's also possible to enable/disable this feature per session. session.EnableAppsecretProof(false) ``` -------------------------------- ### Simple GET Request to Facebook Graph API (Go) Source: https://context7.com/huandu/facebook/llms.txt Performs a simple GET request to the Facebook Graph API without explicit session management. It requires a user access token and returns a map of the response data. Error handling for Facebook-specific errors is included. ```go package main import ( "fmt" "log" fb "github.com/huandu/facebook/v2" ) func main() { res, err := fb.Get("/538744468", fb.Params{ "fields": "first_name,last_name,email", "access_token": "EAABsbCS1iHgBO7ZC6z...", }) if err != nil { if e, ok := err.(*fb.Error); ok { log.Printf("Facebook error: [message:%v] [type:%v] [code:%v] [subcode:%v]", e.Message, e.Type, e.Code, e.ErrorSubcode) return } log.Fatal(err) } fmt.Println("First name:", res["first_name"]) // Output: First name: John } ``` -------------------------------- ### Execute Batch API Requests in Go Source: https://context7.com/huandu/facebook/llms.txt This Go code snippet shows how to send multiple Facebook API requests concurrently in a single batch request. It utilizes the fb.BatchApi function from the github.com/huandu/facebook/v2 package, allowing for efficient execution of GET and POST operations. The results are processed individually to extract data and status information. ```go package main import ( "fmt" "log" fb "github.com/huandu/facebook/v2" ) func main() { accessToken := "EAABsbCS1iHgBO7ZC6z..." // Define batch requests params1 := fb.Params{ "method": fb.GET, "relative_url": "me?fields=id,name", } params2 := fb.Params{ "method": fb.GET, "relative_url": "me/friends?limit=5", } params3 := fb.Params{ "method": fb.POST, "relative_url": "me/feed", "body": "message=Hello from batch API!", } // Execute batch request results, err := fb.BatchApi(accessToken, params1, params2, params3) if err != nil { log.Fatal("Batch API error:", err) } // Process first batch result batchResult1, err := results[0].Batch() if err != nil { log.Fatal("Failed to parse batch result 1:", err) } var userData struct { ID string `facebook:"id"` Name string `facebook:"name"` } batchResult1.Result.Decode(&userData) fmt.Printf("User: %s (ID: %s)\n", userData.Name, userData.ID) fmt.Printf("Status Code: %d\n", batchResult1.StatusCode) fmt.Printf("Content-Type: %s\n", batchResult1.Header.Get("Content-Type")) // Output: // User: John Doe (ID: 538744468) // Status Code: 200 // Content-Type: application/json } ``` -------------------------------- ### Initialize and Use App and Session Objects in Go Source: https://github.com/huandu/facebook/blob/master/README.md Demonstrates how to create a global `App` instance with credentials, set a redirect URI, and obtain a `Session` from a signed request or an access token. It also shows how to validate the session and make an API call. ```go package main import ( "github.com/huandu/facebook" ) func main() { // Create a global App var to hold app id and secret. var globalApp = fb.New("your-app-id", "your-app-secret") // Facebook asks for a valid redirect URI when parsing the signed request. // It's a newly enforced policy starting as of late 2013. globalApp.RedirectUri = "http://your.site/canvas/url/" // Here comes a client with a Facebook signed request string in the query string. // This will return a new session from a signed request. signedRequest := "YOUR_SIGNED_REQUEST_STRING" ssession, _ := globalApp.SessionFromSignedRequest(signedRequest) // If there is another way to get decoded access token, // this will return a session created directly from the token. token := "YOUR_ACCESS_TOKEN" session = globalApp.Session(token) // This validates the access token by ensuring that the current user ID is properly returned. err is nil if the token is valid. err := session.Validate() if err != nil { // Handle validation error } // Use the new session to send an API request with the access token. res, _ := session.Get("/me/feed", nil) // You can also override the API base URL for unit-testing purposes // testSrv := httptest.NewServer(someMux) // session.BaseURL = testSrv.URL + "/" // Enable RFC3339 timestamp formatting for JSON decoding fb.RFC3339Timestamps = true session.RFC3339Timestamps = true } ``` -------------------------------- ### Initialize Facebook App and Session (Go) Source: https://context7.com/huandu/facebook/llms.txt Demonstrates how to initialize a Facebook app instance with an app ID and secret, configure redirect URIs, and enable security features. It then creates an authenticated session using an access token and validates it before making an API call. ```go package main import ( "fmt" "log" fb "github.com/huandu/facebook/v2" ) func main() { // Create global app instance globalApp := fb.New("your-app-id", "your-app-secret") globalApp.RedirectUri = "http://your.site/oauth/callback" globalApp.EnableAppsecretProof = true // Create session with access token session := globalApp.Session("EAABsbCS1iHgBO7ZC6z...") // Validate the access token err := session.Validate() if err != nil { log.Fatal("Invalid access token:", err) } // Make API call with session res, err := session.Get("/me", fb.Params{ "fields": "id,name,email", }) if err != nil { log.Fatal(err) } var user struct { ID string `facebook:"id"` Name string `facebook:"name"` Email string `facebook:"email"` } res.Decode(&user) fmt.Printf("User: %s (%s)\n", user.Name, user.ID) // Output: User: John Doe (538744468) } ``` -------------------------------- ### Handle Pagination Source: https://context7.com/huandu/facebook/llms.txt Provides methods to navigate through paginated API responses, fetching all data across multiple pages. ```APIDOC ## GET /me/feed ### Description Retrieve a list of posts from the user's feed, supporting pagination to fetch all available data. ### Method GET ### Endpoint /me/feed ### Parameters #### Query Parameters - **limit** (integer) - Optional - The maximum number of posts to return per page. - **access_token** (string) - Required - The access token for authentication. ### Request Example ``` GET /me/feed?limit=25&access_token=EAABsbCS1iHgBO7ZC6z... ``` ### Response #### Success Response (200) - **data** (array) - An array of posts. - **paging** (object) - An object containing pagination information, including next and previous page cursors. #### Response Example ```json { "data": [ { "id": "...", "message": "..." }, { "id": "...", "message": "..." } ], "paging": { "cursors": { "before": "...", "after": "..." }, "next": "https://graph.facebook.com/..." } } ``` ``` -------------------------------- ### Send Batch Requests with Facebook SDK for Go Source: https://github.com/huandu/facebook/blob/master/README.md This snippet demonstrates how to send multiple Facebook Graph API requests in a single batch. It shows how to define parameters for each request, execute the batch, and process the individual results and headers. Dependencies include the Facebook SDK for Go. ```go params1 := Params{ "method": fb.GET, "relative_url": "me", } params2 := Params{ "method": fb.GET, "relative_url": uint64(100002828925788), } results, err := fb.BatchApi(your_access_token, params1, params2) if err != nil { // check error... return } // batchResult1 and batchResult2 are response for params1 and params2. batchResult1, _ := results[0].Batch() batchResult2, _ := results[1].Batch() // Use parsed result. var id string res := batchResult1.Result res.DecodeField("id", &id) // Use response header. contentType := batchResult1.Header.Get("Content-Type") ``` -------------------------------- ### Upload Files to Facebook API in Go Source: https://context7.com/huandu/facebook/llms.txt This Go code demonstrates how to upload files to the Facebook API using the github.com/huandu/facebook/v2 library. It covers uploading from a file path, uploading from an io.Reader (like a bytes.Buffer), and uploading with a custom content type, all using multipart form data. ```go package main import ( "bytes" "fmt" "log" fb "github.com/huandu/facebook/v2" ) func main() { session := &fb.Session{} session.SetAccessToken("EAABsbCS1iHgBO7ZC6z...") // Upload from file path res1, err := session.Post("/me/photos", fb.Params{ "message": "Check out this photo!", "source": fb.File("/path/to/photo.jpg"), }) if err != nil { log.Fatal("File upload error:", err) } fmt.Println("Photo ID:", res1["id"]) // Upload from io.Reader (e.g., bytes.Buffer) imageData := bytes.NewReader([]byte{/* image bytes */}) res2, err := session.Post("/me/photos", fb.Params{ "message": "Uploaded from memory", "source": fb.Data("photo.png", imageData), }) if err != nil { log.Fatal("Data upload error:", err) } fmt.Println("Photo ID:", res2["id"]) // Upload with custom content type res3, err := session.Post("/me/videos", fb.Params{ "title": "My Video", "description": "Video description", "source": fb.DataWithContentType("video.mp4", imageData, "video/mp4"), }) if err != nil { log.Fatal("Video upload error:", err) } fmt.Println("Video ID:", res3["id"]) // Output: // Photo ID: 123456789 // Photo ID: 987654321 // Video ID: 555666777 } ``` -------------------------------- ### Handle Paging in Graph API Responses with Go Source: https://github.com/huandu/facebook/blob/master/README.md Explains how to traverse paginated results from the Facebook Graph API using the `Result.Paging()` method. It demonstrates fetching data page by page until all results are retrieved. ```go package main import ( "github.com/huandu/facebook" ) type Result struct { // Define fields for your result data } func main() { // Assume 'session' is an authenticated facebook.Session object var session *facebook.Session res, _ := session.Get("/me/home", nil) // create a paging structure. paging, _ := res.Paging(session) var allResults []facebook.Result // Use facebook.Result or your specific struct type // append first page of results to slice of Result allResults = append(allResults, paging.Data()...) for { // get next page. noMore, err := paging.Next() if err != nil { panic(err) } if noMore { // No more results available break } // append current page of results to slice of Result allResults = append(allResults, paging.Data()...) } } ``` -------------------------------- ### Monitor API Usage Info with Facebook SDK for Go Source: https://github.com/huandu/facebook/blob/master/README.md This code shows how to retrieve API usage information, including rate limits, from API responses. The `Result#UsageInfo()` method returns a `UsageInfo` struct containing app-level, page-level, ad account, and business use case rate limit details. This is useful for managing API call frequency. ```go res, _ := fb.Get("/me", fb.Params{"access_token": "xxx"}) usageInfo := res.UsageInfo() fmt.Println("App level rate limit information:", usageInfo.App) fmt.Println("Page level rate limit information:", usageInfo.Page) fmt.Println("Ad account rate limiting information:", usageInfo.AdAccount) fmt.Println("Business use case usage information:", usageInfo.BusinessUseCase) ``` -------------------------------- ### Batch API Requests Source: https://context7.com/huandu/facebook/llms.txt Allows executing multiple API calls within a single batch request for efficiency. ```APIDOC ## POST /batch ### Description Execute multiple API calls in a single batch request. ### Method POST ### Endpoint /batch ### Parameters #### Query Parameters - **access_token** (string) - Required - The access token for authentication. #### Request Body - **batch** (array) - Required - An array of batch requests, each with a method, relative_url, and optional body. ### Request Example ```json [ { "method": "GET", "relative_url": "me?fields=id,name" }, { "method": "GET", "relative_url": "me/friends?limit=5" }, { "method": "POST", "relative_url": "me/feed", "body": "message=Hello from batch API!" } ] ``` ### Response #### Success Response (200) - **results** (array) - An array of results, corresponding to each request in the batch. #### Response Example ```json [ { "code": 200, "body": { "id": "538744468", "name": "John Doe" } }, { "code": 200, "body": { "data": [...], "paging": {...} } }, { "code": 200, "body": { "id": "123456789" } } ] ``` ``` -------------------------------- ### Go: Control API call timeout and cancelation with Context Source: https://github.com/huandu/facebook/blob/master/README.md This Go code snippet shows how to create a context with a timeout and use it to make an API call through a `Session`. The `context.WithTimeout` function is used to set a time limit, and the `defer cancel()` ensures the context resources are released. The `session.WithContext(ctx)` method is used to apply the context to the API call. Note that the session returned by `WithContext` is a shadow copy and should only be used once. ```go // Create a new context. ctx, cancel := context.WithTimeout(session.Context(), 100 * time.Millisecond) deffer cancel() // Call an API with ctx. // The return value of `session.WithContext` is a shadow copy of original session and // should not be stored. It can be used only once. result, err := session.WithContext(ctx).Get("/me", nil) ``` -------------------------------- ### Search Facebook Pages and Decode Results in Golang Source: https://github.com/huandu/facebook/blob/master/README.md Demonstrates how to search for Facebook pages using the Graph API and decode the results into a slice of maps with the Go SDK. It shows how to construct the search query with parameters like 'q' and 'access_token', and then use `res.DecodeField` to extract the 'data' array into a `[]fb.Result` slice. ```go res, _ := fb.Get("/pages/search", fb.Params{ "access_token": "a-valid-access-token", "q": "nightlife,singapore", }) var items []fb.Result err := res.DecodeField("data", &items) if err != nil { fmt.Printf("An error has happened %v", err) return } for _, item := range items { fmt.Println(item["id"]) } ``` -------------------------------- ### Upload Files Source: https://context7.com/huandu/facebook/llms.txt Enables uploading files such as images and videos to Facebook using multipart form data. ```APIDOC ## POST /me/photos ### Description Upload photos or videos to the user's timeline. ### Method POST ### Endpoint /me/photos ### Parameters #### Request Body - **message** (string) - Optional - A caption for the photo or video. - **source** (file|bytes) - Required - The photo or video file to upload. Can be a file path, bytes, or an io.Reader. - **access_token** (string) - Required - The access token for authentication. ### Request Example (File Path) ```go session.Post("/me/photos", fb.Params{ "message": "Check out this photo!", "source": fb.File("/path/to/photo.jpg"), }) ``` ### Request Example (Bytes/Reader) ```go imageData := bytes.NewReader([]byte{/* image bytes */}) session.Post("/me/photos", fb.Params{ "message": "Uploaded from memory", "source": fb.Data("photo.png", imageData), }) ``` ### Response #### Success Response (200) - **id** (string) - The ID of the uploaded photo or video. #### Response Example ```json { "id": "123456789" } ``` ``` ```APIDOC ## POST /me/videos ### Description Upload videos to the user's timeline. ### Method POST ### Endpoint /me/videos ### Parameters #### Request Body - **title** (string) - Optional - The title of the video. - **description** (string) - Optional - The description of the video. - **source** (file|bytes) - Required - The video file to upload. Can be a file path, bytes, or an io.Reader. - **access_token** (string) - Required - The access token for authentication. ### Request Example (Custom Content Type) ```go imageData := bytes.NewReader([]byte{/* video bytes */}) session.Post("/me/videos", fb.Params{ "title": "My Video", "description": "Video description", "source": fb.DataWithContentType("video.mp4", imageData, "video/mp4"), }) ``` ### Response #### Success Response (200) - **id** (string) - The ID of the uploaded video. #### Response Example ```json { "id": "555666777" } ``` ``` -------------------------------- ### Convert Go Structs to Facebook API Params in Go Source: https://context7.com/huandu/facebook/llms.txt Converts Go structs into a map of parameters suitable for Facebook API calls, including handling optional fields. This function simplifies the process of constructing API requests by automatically mapping struct fields to their corresponding snake_case API parameters. It requires a Go struct with `facebook` tags and the `github.com/huandu/facebook/v2` package. ```go package main import ( "fmt" "log" fb "github.com/huandu/facebook/v2" ) type AdCreativeData struct { Message string `facebook:"message"` Link string `facebook:"link"` Name string `facebook:"name"` Description string `facebook:"description,omitempty"` CallToAction string `facebook:"call_to_action,omitempty"` PageID string `facebook:"page_id"` } func main() { session := &fb.Session{} session.SetAccessToken("EAABsbCS1iHgBO7ZC6z...") // Create struct with data creative := AdCreativeData{ Message: "Check out our new product!", Link: "https://example.com/product", Name: "Amazing Product", Description: "The best product ever", CallToAction: "SHOP_NOW", PageID: "123456789", } // Convert struct to Params params := fb.MakeParams(creative) // Add additional params params["access_token"] = session.AccessToken() // Make API call res, err := session.Post("/act_123456789/adcreatives", params) if err != nil { log.Fatal(err) } fmt.Println("Ad Creative ID:", res["id"]) // Also works with maps paramsMap := fb.MakeParams(map[string]interface{}{ "message": "Another post", "link": "https://example.com", }) fmt.Printf("Generated params: %v\n", paramsMap) // Output: // Ad Creative ID: 987654321 // Generated params: map[link:https://example.com message:Another post] } ``` -------------------------------- ### Debug Facebook API Requests with Facebook SDK for Go Source: https://github.com/huandu/facebook/blob/master/README.md This snippet demonstrates how to enable and use the debugging features provided by the Facebook SDK. Debugging can be controlled globally via `fb.Debug` or per session using `Session#SetDebug`. When enabled, `Result#DebugInfo` can retrieve detailed debug information, including headers and API version. ```go fb.Debug = fb.DEBUG_ALL res, _ := fb.Get("/me", fb.Params{"access_token": "xxx"}) debugInfo := res.DebugInfo() fmt.Println("http headers:", debugInfo.Header) fmt.Println("facebook api version:", debugInfo.FacebookApiVersion) ``` -------------------------------- ### Specify Graph API Version with Facebook SDK for Go Source: https://github.com/huandu/facebook/blob/master/README.md This code illustrates how to control the Graph API version used by the Facebook SDK. You can set a global default version by modifying `fb.Version` or specify a version on a per-session basis by setting `session.Version`. Refer to Facebook's Platform Versioning documentation for details. ```go // This package uses the default version which is controlled by the Facebook app setting. // change following global variable to specify a global default version. fb.Version = "v3.0" // starting with Graph API v2.0; it's not allowed to get useful information without an access token. fb.Api("huan.du", GET, nil) // it's possible to specify version per session. session := &fb.Session{} session.Version = "v3.0" // overwrite global default. ``` -------------------------------- ### Decode Graph API JSON Response into Go Structs Source: https://github.com/huandu/facebook/blob/master/README.md Illustrates how the Facebook SDK for Go can automatically map snake_case JSON keys from API responses to camelCase Go struct fields. It shows custom mapping using `facebook` or `json` tags and handling required fields. ```go package main import ( "github.com/huandu/facebook" ) // Define a Facebook feed object with custom field mapping. type FacebookFeed struct { Id string `facebook:",required"` // this field must exist in response. Story string FeedFrom *FacebookFeedFrom `facebook:"from"` // use customized field name "from". CreatedTime string `facebook:"created_time,required"` // both customized field name and "required" flag. Omitted string `facebook:"-"` // this field is omitted when decoding. } type FacebookFeedFrom struct { Name string `json:"name"` // the "json" key also works as expected. Id string `facebook:"id" json:"shadowed"` // if both "facebook" and "json" key are set, the "facebook" key is used. } func main() { // Assume 'session' is an authenticated facebook.Session object var session *facebook.Session // create a feed object direct from Graph API result. var feed FacebookFeed res, _ := session.Get("/me/feed", nil) // Decode the 'data.0' field from the response into the 'feed' struct. err := res.DecodeField("data.0", &feed) if err != nil { panic(err) } // Example of decoding a simple struct with snake_case keys type Data struct { FooBar string `json:"foo_bar"` // Explicit mapping } var data Data // Assume 'simpleRes' is a facebook.Result with JSON like {"foo_bar": "player"} // err = simpleRes.Decode(&data) } ``` -------------------------------- ### Read User Feed and Handle Facebook API Errors in Golang Source: https://github.com/huandu/facebook/blob/master/README.md Shows how to retrieve a user's feed from the Facebook Graph API using the Go SDK and robustly handle potential API errors. It demonstrates checking for `facebook.Error` and `facebook.UnmarshalError` types to provide specific error messages, including details like message, type, code, subcode, and trace ID. ```go res, err := fb.Get("/me/feed", fb.Params{ "access_token": "a-valid-access-token", }) if err != nil { // err can be a Facebook API error. // if so, the Error struct contains error details. if e, ok := err.(*Error); ok { fmt.Printf("facebook error. [message:%v] [type:%v] [code:%v] [subcode:%v] [trace:%v]", e.Message, e.Type, e.Code, e.ErrorSubcode, e.TraceID) return } // err can be an unmarshal error when Facebook API returns a message which is not JSON. if e, ok := err.(*UnmarshalError); ok { fmt.Printf("facebook error. [message:%v] [err:%v] [payload:%v]", e.Message, e.Err, string(e.Payload)) return } return } // read my last feed story. fmt.Println("My latest feed story is:", res.Get("data.0.story")) ``` -------------------------------- ### Enable Debug Mode for Facebook API Calls in Go Source: https://context7.com/huandu/facebook/llms.txt Enables debug mode for Facebook API calls to retrieve detailed information about the request and response. Debugging can be enabled globally for all sessions or on a per-session basis. This feature is useful for troubleshooting and understanding API interactions. The `DebugInfo()` method on the response object provides access to API version, trace IDs, protocol information, headers, and any debug messages returned by Facebook. ```go package main import ( "fmt" "log" fb "github.com/huandu/facebook/v2" ) func main() { // Enable global debug mode fb.Debug = fb.DEBUG_ALL session := &fb.Session{} session.SetAccessToken("EAABsbCS1iHgBO7ZC6z...") // Or enable per-session debug session.SetDebug(fb.DEBUG_INFO) res, err := session.Get("/me", fb.Params{ "fields": "id,name", }) if err != nil { log.Fatal(err) } // Get debug information debugInfo := res.DebugInfo() if debugInfo != nil { fmt.Println("API Version:", debugInfo.FacebookApiVersion) fmt.Println("Debug Trace ID:", debugInfo.FacebookDebug) fmt.Println("Facebook Rev:", debugInfo.FacebookRev) fmt.Println("Protocol:", debugInfo.Proto) fmt.Println("Headers:", debugInfo.Header) if len(debugInfo.Messages) > 0 { for _, msg := range debugInfo.Messages { fmt.Printf("Debug Message [%s]: %s\n", msg.Type, msg.Message) if msg.Link != "" { fmt.Printf(" Link: %s\n", msg.Link) } } } } // Output: // API Version: v19.0 // Debug Trace ID: AbCdEf123456 // Facebook Rev: 1234567 // Protocol: HTTP/2.0 // Headers: map[Content-Type:[application/json] ...] } ``` -------------------------------- ### Monitor Facebook API Rate Limits in Go Source: https://context7.com/huandu/facebook/llms.txt Tracks API usage and rate limiting information for your Facebook application and specific resources like pages. It retrieves call counts, estimated time to regain access, and usage percentages, helping to manage API quotas effectively. This function requires a valid Facebook session and API access. ```go package main import ( "fmt" "log" fb "github.com/huandu/facebook/v2" ) func main() { session := &fb.Session{} session.SetAccessToken("EAABsbCS1iHgBO7ZC6z...") res, err := session.Get("/me/insights", fb.Params{ "metric": "page_impressions", "period": "day", }) if err != nil { log.Fatal(err) } // Get usage information usageInfo := res.UsageInfo() if usageInfo != nil { // App-level rate limiting if usageInfo.App.CallCount > 0 { fmt.Printf("App Usage:\n") fmt.Printf(" Call Count: %d%%\n", usageInfo.App.CallCount) fmt.Printf(" Total Time: %d%%\n", usageInfo.App.TotalTime) fmt.Printf(" CPU Time: %d%%\n", usageInfo.App.TotalCPUTime) if usageInfo.App.EstimatedTimeToRegainAccess > 0 { fmt.Printf(" Time to regain: %d minutes\n", usageInfo.App.EstimatedTimeToRegainAccess) } } // Page-level rate limiting if usageInfo.Page.CallCount > 0 { fmt.Printf("Page Usage:\n") fmt.Printf(" Call Count: %d%%\n", usageInfo.Page.CallCount) } // Ad account rate limiting if usageInfo.AdAccount.AccIDUtilPCT > 0 { fmt.Printf("Ad Account Usage:\n") fmt.Printf(" Usage: %.2f%%\n", usageInfo.AdAccount.AccIDUtilPCT) fmt.Printf(" Access Tier: %s\n", usageInfo.AdAccount.AdsAPIAccessTier) } } // Output: // App Usage: // Call Count: 15% // Total Time: 12% // CPU Time: 8% // Page Usage: // Call Count: 5% } ``` -------------------------------- ### Decode Facebook API Results to Go Structs (Go) Source: https://context7.com/huandu/facebook/llms.txt Illustrates how to decode Facebook Graph API responses directly into Go structs, leveraging the SDK's automatic field mapping based on `facebook` tags. It supports custom unmarshalling and handles specific date formats like RFC3339. ```go package main import ( "fmt" "log" "time" fb "github.com/huandu/facebook/v2" ) type FacebookPost struct { ID string `facebook:"id,required"` Message string `facebook:"message"` CreatedTime time.Time `facebook:"created_time,required"` From struct { Name string `facebook:"name"` ID string `facebook:"id"` } `facebook:"from"` Likes struct { Data []struct { Name string `facebook:"name"` ID string `facebook:"id"` } `facebook:"data"` } `facebook:"likes"` } func main() { fb.RFC3339Timestamps = true // Enable RFC3339 timestamp format session := &fb.Session{} session.SetAccessToken("EAABsbCS1iHgBO7ZC6z...") res, err := session.Get("/me/posts", fb.Params{ "fields": "id,message,created_time,from,likes", "limit": "1", }) if err != nil { log.Fatal(err) } var post FacebookPost err = res.DecodeField("data.0", &post) if err != nil { log.Fatal(err) } fmt.Printf("Post ID: %s\n", post.ID) fmt.Printf("Message: %s\n", post.Message) fmt.Printf("Posted by: %s at %s\n", post.From.Name, post.CreatedTime) // Output: // Post ID: 123456789_987654321 // Message: Hello world! // Posted by: John Doe at 2025-01-15 10:30:00 } ``` -------------------------------- ### Decode Facebook Graph API Response with Golang SDK Source: https://github.com/huandu/facebook/blob/master/README.md Illustrates how to decode API responses from the Facebook Graph API using the Go SDK. It shows decoding specific fields into Go types like strings and structs, and handling types that implement `json.Unmarshaler`, such as `time.Time`. This functionality is crucial for safely parsing complex JSON responses. ```go // Decode "first_name" to a Go string. var first_name string res.DecodeField("first_name", &first_name) fmt.Println("Here's an alternative way to get first_name:", first_name) // It's also possible to decode the whole result into a predefined struct. type User struct { FirstName string } var user User res.Decode(&user) fmt.Println("print first_name in struct:", user.FirstName) // Example with time.Time // res := Result{ // "create_time": "2006-01-02T15:16:17Z", // } // var tm time.Time // res.DecodeField("create_time", &tm) ``` -------------------------------- ### Exchange Short-Lived Facebook Access Token for Long-Lived in Go Source: https://context7.com/huandu/facebook/llms.txt Exchanges a short-lived Facebook access token for a long-lived one, which is valid for approximately 60 days. This process requires the app ID and app secret. The function takes the short-lived token as input and returns the long-lived token, its expiration duration in seconds, and any error encountered. The long-lived token can then be used to create a session for further API interactions. ```go package main import ( "fmt" "log" "time" fb "github.com/huandu/facebook/v2" ) func main() { globalApp := fb.New("your-app-id", "your-app-secret") // Short-lived access token (typically valid for 1-2 hours) shortToken := "EAABsbCS1iHgBO7ZC6z..." // Exchange for long-lived token (valid for ~60 days) longToken, expires, err := globalApp.ExchangeToken(shortToken) if err != nil { log.Fatal("Token exchange failed:", err) } fmt.Printf("Long-lived token: %s\n", longToken) fmt.Printf("Expires in: %d seconds (~%d days)\n", expires, expires/86400) expiryTime := time.Now().Add(time.Duration(expires) * time.Second) fmt.Printf("Valid until: %s\n", expiryTime.Format(time.RFC3339)) // Use the long-lived token session := globalApp.Session(longToken) res, err := session.Get("/me", fb.Params{"fields": "name"}) if err != nil { log.Fatal(err) } fmt.Println("User name:", res["name"]) // Output: // Long-lived token: EAABsbCS1iHgBAr3UZC... // Expires in: 5184000 seconds (~60 days) // Valid until: 2025-03-15T10:30:00Z // User name: John Doe } ``` -------------------------------- ### Parse Facebook Signed Request in Go Source: https://context7.com/huandu/facebook/llms.txt Parses and validates Facebook signed requests, commonly used in canvas apps. It requires the app ID, app secret, and redirect URI. The function takes a signed request string as input and returns a session object or an error. This session can then be used to make authenticated API calls. ```go package main import ( "fmt" "log" fb "github.com/huandu/facebook/v2" ) func main() { globalApp := fb.New("your-app-id", "your-app-secret") globalApp.RedirectUri = "http://your.site/canvas/" // Signed request from Facebook (typically from query parameter) signedRequest := "vlXgu64BQGFSQrY0ZcJBZASMvYvTHu9GQ0YM9rjPSso.eyJhbGdvcml0aG0iOiJITUFDLVNIQTI1NiIsImNvZGUiOiJBUUF..." // Parse signed request session, err := globalApp.SessionFromSignedRequest(signedRequest) if err != nil { log.Fatal("Failed to parse signed request:", err) } // Use the session to make API calls res, err := session.Get("/me", fb.Params{ "fields": "id,name,email", }) if err != nil { log.Fatal(err) } var user struct { ID string `facebook:"id"` Name string `facebook:"name"` Email string `facebook:"email"` } res.Decode(&user) fmt.Printf("Authenticated user: %s (%s)\n", user.Name, user.ID) // Output: Authenticated user: John Doe (538744468) } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.