Giter VIP home page Giter VIP logo

facebook's Introduction

大家好 / Hi there 👋

我是一名来自中国的开发者 🎉

  • 我熟悉各种前端和后端技术架构,各种技术栈上都有很多实战经验。
  • 曾作为技术负责人设计开发过多种不同类型的大型复杂互联网业务架构。
  • 我在 Github 上开源的项目大多与 Go 相关,平时喜欢研究 Go runtime 并解决与之相关的疑难杂症。
  • 当前,我是一个创业公司的合伙人,业务主要与视频相关,开发的技术涵盖播放器、流媒体服务、音视频格式等方面。

I'm a software developer from China. 🎉

  • I have lots of work experience in both front end and back end software.
  • I led the development of multiple large scale and complex projects as chief architecture in the past.
  • Most of my open source projects are writen in Go. I'm fond of investigating and hacking Go runtime to solve complicated issues.
  • Right now, I'm a partner of a start-up company. My business involves lots of video technologies, including video player, video streaming server, video format and so forth.

My Stats

facebook's People

Contributors

acochrane avatar alphab avatar appleboy avatar dinedal avatar enm10k avatar gstvg avatar huandu avatar j-p-77 avatar jkozera avatar jpibarra1130 avatar kjk avatar lazyshot avatar maxekman avatar mehdime avatar nrolans avatar oyvindsk avatar panki avatar robbiet480 avatar rogerso avatar sbellity avatar sebnow avatar spazzy757 avatar thomastunde avatar trietphm avatar vania-pooh avatar vishalvishw10 avatar whilei avatar yhbyun avatar zonr avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

facebook's Issues

oauth requests don't unmarshal query string responses correctly

Session.sendOauthRequest supports parsing a response with url.ParseQuery if it looks like urlencoded, but then Result.DecodeField expects the values to already be of the correct type, which won't be the case for anything but strings.

I ran into this with App.ExchangeToken, where the response includes an int "expires". It always ends up with a 0 for the expiration and the error field 'expires' value is string, not a number.

sendOauthRequest URL

in session.go in function sendOauthRequest
Why is there:
urlStr := session.getUrl("graph", "/oauth/client_code", nil)
instead of:
urlStr := session.getUrl("graph", url, nil)

ExchangeToken is on different url, so is not working.

How to read feed?

Hi! Why fb.Get("/me/feed") return only my posts on Facebook? Can I receive news as if I were using a web browser?

Cannot decode into embedded struct

The standard Json library could encode embedded:
https://play.golang.org/p/rA7yHzBYRk

In a case of Facebook' event when one gets it from user it may contain extra fields (rsvp_status) so I've tried to embed one into the other:

type FbEvent struct {
  ID string
  Name string
}

type FbUserEvent struct {
  *FbEvent
  RsvpStatus string
}

I've also tried with non-pointer FbEvent. In both cases the fields from FbEvent are empty.

Make a `BatchResult` struct to hold batch request response

Just like PagingResult, BatchResult should hold all information returned by facebook batch api.

It's difficult to read data in batch request right now. Unlike other graph api response, batch api returns real result (the "body" field) with a JSON stringified string inside a JSON object. One has to parse body to JSON to use it. It's annoying. BatchResult can definitely help us to save time.

Reference: https://developers.facebook.com/docs/graph-api/making-multiple-requests/#multiple_methods

Fields with space in key?

Sometimes the Insights API will return data like this:

{
  "values": [
    {
      "value": {
        "other clicks": 874,
        "photo view": 3,
        "link clicks": 2007
      }
    }
  ],
  "name": "post_consumptions_by_type",
  "period": "lifetime",
  "id": "post_id/insights/post_consumptions_by_type/lifetime"
}

Yet no matter what I do, I can't get those values to marshal into JSON whether I use the Facebook or JSON tags. I can see the values are coming in when I print the raw Result though. Any ideas how to get around or fix this? I'm attempting to Marshal to this struct:

type ConsumptionTypes struct {
	OtherClicks int64 `json:"other clicks"`
	PhotoViews  int64 `json:"photo view"`
	LinkClicks  int64 `json:"link clicks"`
}

type ConsumptionTypeInsights struct {
	Values []struct {
		ConsumptionTypes `facebook:"value"`
	} `facebook:"values"`
	Name   string `facebook:"name"`
	Period string `facebook:"period"`
	ID     string `facebook:"id"`
}

Unexpected error from result.Decode()

This comes from trying to decode real facebook response, but this is a minimal test case:

package main

import (
    "encoding/json"
    "fmt"

    "github.com/huandu/facebook"
)

type Actions2 struct {
    Foo int
}

type Foo struct {
    Actions2 *Actions2
    Comment  int
}

func testDecode(sJson string) {
    var result facebook.Result
    err := json.Unmarshal([]byte(sJson), &result)
    if err != nil {
        fmt.Printf("json.Unmarshal() failed with %q\n", err)
        return
    }
    var v Foo
    err = result.Decode(&v)
    if err != nil {
        fmt.Printf("result.Decode() failed with %q\n", err)
        return
    }
    fmt.Printf("testDocode: ok!\n")
}

func main() {
    // this is ok
    sJson := `{
 "comment": 5
}`
    testDecode(sJson)

    // this fails
    sJson = `{
 "actions2": null,
 "comment": 5
}`
    testDecode(sJson)
}

The code fails with error reflect: call of reflect.Value.Type on zero Value when trying to decode actions2 when "actions2" field exists in json but is set to "null".

It doesn't happen when "actions2" field is completely missing.

CamelCase on ID should be _id

go lint complains about how UserId should be UserID. The current implementation converts UserID to user_i_d, and ID to i_d. Facebook, of course, wants id on its fields.

We work around this now using the back-tick decorator to force the fieldname to the correct underscore'd JSON name. It would be nice to just do it automatically, and make huandu/facebook friendly with golint.

facebook.BatchApi should return the results and facebook.Error as error, right now it returns standard error

Getting issues while I write this code:
rfb "github.com/huandu/facebook"
url := fmt.Sprintf("%s/feed?fields=id,from,message,created_time,updated_time,picture,likes&until=%d","xxxxxxx")
results, err := rfb.BatchApi("xxxxxxxxxx", rfb.Params{
"method": rfb.GET,
"relative_url": url,
})
if err != nil {
log.Println("Error on connecting: ", err)
}
This is the result body I use to get: results[0].Get("body")
Its working fine if the access_token is ok.
But I need the facebook error code while the access_token is wrong or user change his password or something else happen in facebook api.
In the above cases I got only error message like
"cannot format facebook batch response. json: cannot unmarshal object into Go value of type []facebook.Result" error.
It doesnt make sense to me what is actually causing the error and what is the error message, error code, type and subcode as well.
It causing because in session.go -> graphBatch function is always return []Result but when its having error then its only Result{} and throughing error from makeResult function decode(res)
It will very helpful to me if I can be able to get the facebook error(I mean the Error struct).
Please have a look on it.

Allow enabling Appsecret Proof for http client created by golang.org/x/oauth2

Currently, creating a session from a client returned by the standard oauth2 library will work correctly for regular ("insecure") requests.

// Use OAuth2 client with session.
session := &fb.Session{
    Version:    "v2.4",
    HttpClient: client,
}

// Use session.
res, _ := session.Get("/me", nil)

However, the documentation for Session states that calling EnableAppsecretProof(true) "returns error if there is no App associasted with this Session."

I would like to know if it is possible to set the appsecretProof property if one is setting their own HttpClient. If not, can I request that this feature be added? Since the appsecretProof field is unexported and requires a non-nil App, I would be fine with being able to hash my own token/secret. Something like,

hash := hmac.New(sha256.New, []byte(secret))
hash.Write([]byte(token))
proof := hex.EncodeToString(hash.Sum(nil))
// Here, the user sets it manually
session.SetAppsecretProof(proof)

I would be willing to contribute. Thanks! :-)

Video Upload

Is there a right way to upload a video using the session.Post() method?

So far the the "upload_phase":"start" post works, but uploading the first chunk fails with this extended debugging info:
map[error:map[fbtrace_id:C50g/HaHc+g message:Service temporarily unavailable type:OAuthException is_transient:true code:2 error_subcode:1363030 error_user_title:Video Upload Time Out error_user_msg:Your video upload timed out before it could be completed. This is probably because of a slow network connection or because the video you're trying to upload is too large. Please try again.] __debug__:map[__header__:map[X-Fb-Debug:[pIq0UxYHazOQbO0ymsHjew4B+S2s5SBZc5gmABYglX5y3JSiBAoirhbgiUsaEKXH2K2DxqvlgutX9+1iptZpCQ==] Date:[Sat, 29 Jul 2017 18:23:34 GMT] Pragma:[no-cache] X-Fb-Rev:[3190007] Facebook-Api-Version:[v2.9] Expires:[Sat, 01 Jan 2000 00:00:00 GMT] Www-Authenticate:[OAuth "Facebook Platform" "invalid_request" "Service temporarily unavailable"] Access-Control-Allow-Origin:[*] X-Fb-Trace-Id:[C50g/HaHc+g] Cache-Control:[no-store] Content-Type:[text/javascript; charset=UTF-8] Vary:[Accept-Encoding]] __proto__:HTTP/2.0]] fb.UploadVideoError: Service temporarily unavailable

I tested with the curl method defined here and that works fine.

I'm trying to get video file chunk in the Params right for uploading the first chunk.
So far I have tried a pointer to a byte slice

numBytes, readErr := file.ReadAt(chunkByteSlice, int64(startOffsetInt))
...
fb.Params{...,"video_file_chunk":chunkByteSlice}

and wrapping the byte slice in a buffer,

chunkBuffer := bytes.NewBuffer(chunkByteSlice)
...
fb.Params{...,"video_file_chunk":chunkBuffer}

Panic: assignment to entry in nil map

Hi there!

First of all: Thank you for creating this awesome Go package! Until today I've had zero problems using it.

Unfortunately since the lastest release I've been getting panics from some of the requests made to the FB API. The code panics in addUsageInfo when res is nil. Maybe add a check for that case, like in addDebugInfo?

Why does Session.graph() always creates a post request?

When creating a Get request using a session, the following functions are called:
fb.Session.Get()
session.Api()
session.graph()
session.sendPostRequest()

Why session.sendPostRequest() is called no matter what Method is passed? Why is session.sendGetRequest() not called in this case?

How to use SessionFromSignedRequest?

Hi,

First of all, thanks so much for this package.

I am using it to provide a very simple oauth2 flow —I redirect a user to https://www.facebook.com/dialog/oauth?client_id=<client_id>&redirect_uri=http%3A%2F%2Flocalhost%3A8080%2Fauth%2Fin%2F.

In the handler for /auth/in I get the long-lived access_token by calling ParseCode(r.FormValue("code")). This works fine.

My question is, what is SessionFromSignedRequest for? On Facebook's documentation, it seems the only thing it's used for is Games: https://developers.facebook.com/docs/facebook-login/using-login-with-games/

Maybe I'm missing something, but can you explain how and why I should use SessionFromSignedRequest in a regular Facebook oauth2 site?

Thanks!

Should DecodeField return field names?

Hi,

Looking at DecodeField it seems like it should be returning the field names that I set up in my struct (but I'm a real Go noob, so hey, maybe not). But the result I get has no field names.

My code (pulling posts from a page)

res, _ := session.Get(fbtarget, fb.Params{
        "limit": "15",
        "fields": "caption,created_time,description,id,link,message,name,picture,status_type,story,type",
    })

    type FBPagePosts struct {
        Caption string
        CreatedTime string
        Description string
        Id string
        Link string
        Message string
        Name string
        Picture string
        StatusType string
        Story string    
        Type string
    }

    var feed []FBPagePosts 
    res.DecodeField("data", &feed)

    fmt.Println("\n DECODED: \n", feed)

Result sample

{ 2014-12-09T15:30:01+0000  104812021201_10152941348341202 https://www.facebook.com/projectrunway/photos/a.175609916201.148047.104812021201/10152940008066202/?type=1&relevant_count=1 Sometimes your fashion fate is dependent on a roll of the dice. Watch #PRAllStars this Thursday at 9/8c!  https://fbcdn-sphotos-e-a.akamaihd.net/hphotos-ak-xaf1/v/t1.0-9/p130x130/10849866_10152940008066202_8001883468160308746_n.png?oh=93df37956a74d90a9a344ab68dda7760&oe=55081566&__gda__=1429934227_d475a3992beac94bddf0514237755247 added_photos  photo}

I've tried including facebook:"caption" to my struct, but the results come out the same.

Should I not expect to get field names from DecodeField? If not, could you point me in the right direction to do that?

Thanks!

Some Session methods don't work with http client created by golang.org/x/oauth2

How can I use this pkg with golang.org/x/oauth2 properly?

package main

import (
    "golang.org/x/oauth2"
    oauth2fb "golang.org/x/oauth2/facebook"

    "github.com/huandu/facebook"
)

func main() {

    conf := &oauth2.Config{
        ClientID:     "AppId",
        ClientSecret: "AppSecret",
        RedirectURL:  "CallbackURL",
        Scopes:       []string{"user_location"},
        Endpoint:     oauth2fb.Endpoint,
    }

    token, err := conf.Exchange(oauth2.NoContext, "code")

    client := conf.Client(oauth2.NoContext, tok)

    // Now, I want to pass the above client
    // (that already provides the AccessTokens)
    // into the facebook Session.
    // 
    // ... I tried:

    api := &facebook.Session{
        HttpClient: client,
        Version: "2.2",
    }

    err := api.Validate()  // <= returns "access token is not set" error
}

The question is... how do I create new Session with my own HttpClient and without any AccessToken (as my client's Transport already handles that)?

Marketing/Insights API integration

The facebook library is pretty awesome, but it seems to lack a good way to interact wit the marketing/insights API. When fb.Result is return there is a "Data" field that is an []interface{} that contains a map[string]interface{}.

I created a function that I am using in our system to pull the fields out of the map[string]interface{} (below). I would like to create a new function(s) in this library that support this functionality, but being a new developer would love to have your input on its implementation (e.g. decodeInsights (...) and/or decodeInsight(..).

Thanks!

Dan

func parseFacebookResult(result fb.Result, fieldName string) (float64, *Error) {
	//Loop over the facebook result "data" element as an array of interface
	for _, data := range result["data"].([]interface{}) {
		//loop over each element in the array as a map[string]interface and locate the field needed
		//The value of the field is a string so need to string convert to float 64
		for key, value := range data.(map[string]interface{}) {
			if key == fieldName {
				returnValue, err := strconv.ParseFloat(value.(string), 64)
				if err != nil {
					
					return 0, *err
				} else {
					return returnValue, nil
				}
			}
		}
	}
	err := errors.New("fieldName Not Found")
	return 0, *err
}

RFC: Memory leak

Hi,

I'm not quite sure where, but I have a feeling there's a memory leak occurring somewhere (and it may depend on how you use this package).

In one goroutine (so my program could continue to do other things), I was looping a few pages of results from a public post search and then making queries for user info from each one of those posts. While all that was going on something kept opening up goroutines that never returned.

I tried quickly replacing the http.Client with a wrapper that set a timeout in the round trip, but that didn't solve the problem.

Ultimately I just replaced calls to this package's functions and made a very simple GET request using that same client wrapper with a timeout and decoded into some structs I had anyway when using this package. Not a ton of code, but also not as robust as what this package was offering me otherwise. But also no leaks now. Goroutine count goes up a little but then comes back down when looking at pprof.

You may want to try looping a few requests off in a goroutine and using pprof. It may have been something I missed in how I was calling functions from this package (and missed again when replacing with my own code), because I really couldn't find what might have caused this...But somewhere there was a leak.

Looking at pprof output, I suspect it has something to do with the HTTP requests / session stuff. Again, I'm not 100% sure this will always occur depending on the program, but a little profiling might help.

It may also very likely be that things eventually would return / timeout, but because I was looping and making dozens of requests, it just stacked up and I never got to see the goroutine count drop before I ran into a crash.

I wish I had more details for you, sorry.

Cannot get a session to work

I know you dont cover it in the library, but in the README there is a deal about session. I am trying to use this to authenticate so I can post to my page via my server.

This is not working for me

token, err := conf.Exchange(oauth2.NoContext, "code")

What do I need to put in place of code? How do I get this???? I have looked everywhere. Thanks

Also I will note I am attempting to do this as a server to server connection, so no login via web or anything like that as this will be a triggered post to a business fb page

Errors aren't specific enough.

Lack of sub-typing of the error returned by Session.Validate() means that call-sites have to resort to matching the error's string for certain key words like "expired" or "invalidated" or "confirmed" to handle handle/report Facebook-specific errors differently from, say, a network failure.

What do you think about matching the error string in the library and returning sub-typed errors?

Question regarding library speed

Hi there, I was wondering about the reasons there is no Oauth2 support and if there was any speed issue on a long-term rate. For example, if I wanted to get 1million get requests I think that with the current library I would have to submit the access token for each request, am I right?
How bad is this?

Retrieving amount of likes on a page

Hi,

I'm trying to retrieve the number of likes on a page. The request shows up like this:

GET https://graph.facebook.com/v2.0/1453470311647266?access_token=...

{
   "id": "1453470311647266",
   "about": "EMBRACE YOUR WEIRDNESS! I am unprofessionally professional human being. Eyebrow and life enthusist. Instagram \u0040caradelevingne STOP LABELING! START LIVING",
   "can_post": true,
   "category": "Public Figure",
   "checkins": 0,
   "cover": {
      "cover_id": "1453470654980565",
      "offset_x": 0,
      "offset_y": 31,
      "source": "https://scontent.xx.fbcdn.net/hphotos-xap1/t31.0-0/p480x480/11872112_1453470654980565_1341024201989338022_o.jpg",
      "id": "1453470654980565"
   },
   "has_added_app": false,
   "is_community_page": false,
   "is_published": true,
   "likes": 3249743,
   "link": "https://www.facebook.com/CaraDelevingneOfficialPage/",
   "name": "Cara Delevingne",
   "talking_about_count": 23035,
   "username": "CaraDelevingneOfficialPage",
   "website": "http://www.instagram.com/caradelevingne",
   "were_here_count": 0
}

My code is the following:

res, err := fb.Get("/1453470311647266", fb.Params{
  "access_token": token,
})
if err != nil {
  e, ok := err.(*fb.Error)
    if ok == true {
      Logger.Errorf("Facebook error: [message:%v] [type:%v] [code:%v] [subcode:%v]", e.Message, e.Type, e.Code, e.ErrorSubcode)
    }
    return err
  } else {
    likes, ok := res.Get("likes").(string) // reflect.Kind told me it was a string
    if ok == false {
      // THIS IS ALWAYS GOING THERE
      Logger.Errorf("Error while parsing facebook result (likes): %s", "not a string")
      return false
    }
  }
}

The problem I'm having is that the way you're parsing the json result, golang reflect package thinks it's a string, but it's not, because when I'm trying to cast, it's throwing me an error. Do you know what's causing this, or if there's any way for me to get it working ? (I am able to parse the link, name and category value correctly)

ExchangeToken(token) method thowing error and the program terminated immediately!

Hi Huandu,
token, expires, err := fbApi.ExchangeToken(accessCode)
ExchangeToken() is returning error like this: Error: field 'expires_in' doesn't exist in result.
Reason is when you first time sent exchange token request then it works fine. Because first time facebook api return expires(expires can be never expire or 60 days as a timestamp)
Say after getting response and then between 2-3 minutes I send ExchangeToken function again(As I was testing so I found) that time facebook doesn't send expires/expires_in anymore which turning the problem expires_in doesnt exists.
Is that in between your workaround the please fix. Otherwise I'll fix and send you the PR.
I think we should check DecodeField [ --> app.go] if expires_in or expires exists in results... :)

Thanks
Mujibur

always when i ask my feed the result is nil

always when i consult my feed the result is nil

resu, erro := fb.Get("/me/feed", fb.Params{ "access_token": "CAAHH1zm0bMMBAAfZBznFlgdA7KAZCiJawqafa1SRZAr7I4ZAIgvBO4hcvz8T8yF5eA6tvNumQL3tsziCmTwawXq3MFuQXuLSZCnnZBNt0W1jcvxy3Vh5c3GCoz1VqTl4N7oJ2w7XtKVYtC1L6Ad8nAVCZBZAcoC6ZCip6HneBZC0piyw98vsXIcpgZB", })

Loss of precision in app_scoped_user_ids caused by json using float64

When an app_scoped user_id in a post-Facebook graph 2.0 world exceeds 2^53 (9007199254740992), the id values contained in the Result map[string]interface{} begin to lose their bottom-most bits due to mantissa truncation.

The quick solution in result.go is to use

func MakeResult ... {
        dec := json.NewDecoder(bytes.NewReader(jsonBytes))
        dec.UseNumber()
        err = dec.Decode(&res)

        if err != nil {
                err = fmt.Errorf("cannot format facebook response. %v", err)
                return nil, err
        }

rather than using json.Unmarshal(&res)

Session's App Access Token can't be validated but Session.Get works

Hi, I'm trying to create a Session with an App in the code below.

app := fb.New(appID, appSecret)
session := app.Session(app.AppAccessToken())

err := session.Validate()
if err != nil {
	if e, ok := err.(*fb.Error); ok {
		fmt.printf("[Message: %v] [Type: %v] [Code: %v] [Subcode: %v]",
				e.Message, e.Type, e.Code, e.ErrorSubcode)
	}
}

But I get the following error: [Message: An active access token must be used to query information about the current user.] [Type: OAuthException] [Code: 2500] [Subcode: 0]

However, when my application later executes the following code:

params := fb.Params{
	"fields":       "friends",
}

res, err := f.Session.Get(fmt.Sprintf("/%d", id), params)

err is nil and I'm able to use res.Decode() to get the information I wanted even though my access token was said to be invalid by session.Validate().

If the access token was invalid I shouldn't be able to call Get with success. So, I suppose this is an unexpected behaviour.

Encoded Field Parsers

I'm using the library to get information about some urls using this type of request

result, err := o.session.Get("", fb.Params{  
    "ids":    url_string,  
    "fields": "og_object{title, description,image,url}",  
})

The problem I see is that this return a dictionary structure (can check here https://goo.gl/A6m2Pm) where the key is the URL, that way I can't create structure to decode it, because the the key name is not a fixed value, it change on every request.
And I can't use the DecodeField either, because it try to parse the field using dot (1) and the key is an url.

May be I can make a Pull Request, but want to know what you think. I'm making some mistake ? There is other way to get the information? I think the current Result.Get is ok... may be check if the field starts with some url schemes (http, https) don't try to break it by dots. make sense ?

TIA

(1) https://github.com/huandu/facebook/blob/master/result.go#L102

App level session.

How do I just get an app session? I don't have a token, or a signed request. I want it from the app id and app secret.

Do I just pass appId|secret to token?

get picture in post return empty map

I try to read posts from my page. I can get message and object_id from post in first part. But when i use object_id to make graph call for picture url, I get empty map result.
`
session := fbApp.Session(accessToken)
session.HttpClient = urlfetch.Client(c)
res, _ := session.Get("/1469572976421082/posts", fb.Params{
"fields": "created_time,message,object_id",
})
var posts []fb.Result
err = res.DecodeField("data", &posts)

if err != nil {
	log.Infof(c, "An error has happened %v", err)
	return
}

for _, p := range posts {
	if objid, ok := p["object_id"]; ok {
		ires, _ := session.Get("/"+objid.(string)+"/picture", nil)
		log.Infof(c, "ires: %v", ires)  ***<<=====This alway print empty map e.g. map[]***
	}
}`

What i'm doing wrong? any idea?
I copy query string '/object_id/picture' and test in graph api explorer and it work fine

RFC: Decoding an entire response?

Hi,

Thanks for your work on this and the documentation. I'm just having a little trouble decoding a response with

{ 
  data: [{...}, {...}], 
  paging: {...} 
}

I don't know if I should be looping the result or using Get() on a string or what. Every which way I try I seem to run into issues where Decode undefined (type interface {} has no field or method Decode)

So as soon as I jump into the "data" I lose Decode(). I've tried setting up a struct to decode the whole []Result too but didn't have any luck.

All I see in the documentation (and I could have missed something of course) is how to decode a single item. How would I decode an array of items?

Thanks!

Decode ID to int64

Hi, this didnt worked for me. The ID was always 0

type FacebookPassport struct {
	ID    int64
	Name  string
}

var pass FacebookPassport
r.DecodeField("id", &pass.ID)

I had to revert to:

id := r.Get("id").(string)
nid, err := strconv.ParseInt(id, 10, 64)

Thanks

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.