Documentation
¶
Overview ¶
This is a Go library fully supports Facebook Graph API with file upload, batch request and FQL. It's simple but powerful.
Library design is highly influenced by facebook official PHP/JS SDK. If you have used PHP/JS SDK, it should look familiar to you.
Here is a list of common scenarios to help you to get started.
Scenario 1: Read a graph `user` object without access token.
res, _ := facebook.Get("/huandu", nil) fmt.Println("my facebook id is", res["id"])
Scenario 2: Read a graph `user` object with a valid access token.
res, _ := facebook.Get("/me/feed", facebook.Params{ "access_token": "a-valid-access-token", }) // read my last feed. fmt.Println("my latest feed story is:", res.Get("data.0.story"))
Scenario 3: Use App and Session struct. It's recommended to use them in a production app.
// create a global App var to hold your app id and secret. var globalApp = facebook.New("your-app-id", "your-app-secret") // facebook asks for a valid redirect uri when parsing signed request. // it's a new enforced policy starting in late 2013. // it can be omitted in a mobile app server. globalApp.RedirectUri = "http://your-site-canvas-url/" // here comes a client with a facebook signed request string in query string. // creates a new session with signed request. session, _ := globalApp.SessionFromSignedRequest(signedRequest) // or, you just get a valid access token in other way. // creates a session directly. seesion := globalApp.Session(token) // use session to send api request with your access token. res, _ := session.Get("/me/feed", nil) // validate access token. err is nil if token is valid. err := session.Validate()
Scenario 4: Read graph api response and decode result into a struct. Struct tag definition is compatible with the definition in `encoding/json`.
// define a facebook feed object. type FacebookFeed struct { Id string `facebook:",required"` // must exist Story string From *FacebookFeedFrom CreatedTime string `facebook:"created_time"` // use customized field name } type FacebookFeedFrom struct { Name, Id string } // create a feed object direct from graph api result. var feed FacebookFeed res, _ := session.Get("/me/feed", nil) res.DecodeField("data.0", &feed) // read latest feed
Scenario 5: Send a batch request.
params1 := Params{ "method": facebook.GET, "relative_url": "huandu", } params2 := Params{ "method": facebook.GET, "relative_url": uint64(100002828925788), } res, err := facebook.BatchApi(your_access_token, params1, params2) // res is a []Result. if err is nil, res[0] and res[1] are response to // params1 and params2 respectively.
For more detailed documents, see doc in every public method. I've try my best to provide enough information. Still not enough? Tell me or help me to improve wording by sending me Pull Request.
This library doesn't implement any deprecated old RESTful API. And it won't.
Index ¶
- Constants
- type App
- func (app *App) AppAccessToken() string
- func (app *App) ExchangeToken(accessToken string) (token string, expires int, err error)
- func (app *App) GetCode(accessToken string) (code string, err error)
- func (app *App) ParseCode(code string) (token string, err error)
- func (app *App) ParseSessionCode(code string, session *Session) (token string, err error)
- func (app *App) ParseSignedRequest(signedRequest string) (res Result, err error)
- func (app *App) Session(accessToken string, context appengine.Context) *Session
- func (app *App) SessionFromRequest(req *http.Request) (session *Session, err error)
- func (app *App) SessionFromSignedRequest(signedRequest string, context appengine.Context) (session *Session, err error)
- type BinaryData
- type BinaryFile
- type Error
- type Method
- type Params
- type Result
- func Api(path string, method Method, params Params) (Result, error)
- func Batch(batchParams Params, params ...Params) ([]Result, error)
- func BatchApi(accessToken string, params ...Params) ([]Result, error)
- func Delete(path string, params Params) (Result, error)
- func Get(path string, params Params) (Result, error)
- func Post(path string, params Params) (Result, error)
- func Put(path string, params Params) (Result, error)
- type Session
- func (session *Session) AccessToken() string
- func (session *Session) Api(path string, method Method, params Params) (Result, error)
- func (session *Session) App() *App
- func (session *Session) Batch(batchParams Params, params ...Params) ([]Result, error)
- func (session *Session) BatchApi(params ...Params) ([]Result, error)
- func (session *Session) Delete(path string, params Params) (Result, error)
- func (session *Session) Get(path string, params Params) (Result, error)
- func (session *Session) Inspect() (result Result, err error)
- func (session *Session) Post(path string, params Params) (Result, error)
- func (session *Session) Put(path string, params Params) (Result, error)
- func (session *Session) SetAccessToken(token string)
- func (session *Session) User() (id string, err error)
- func (session *Session) Validate() (err error)
Constants ¶
const (
ERROR_CODE_UNKNOWN = -1 // unknown facebook graph api error code.
)
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type App ¶
type App struct { // Facebook app id AppId string // Facebook app secret AppSecret string // Facebook app redirect URI in the app's configuration. RedirectUri string }
Holds facebook application information.
func (*App) AppAccessToken ¶
Gets application access token, useful for gathering public information about users and applications.
func (*App) ExchangeToken ¶
Exchange a short lived access token to a long lived access token. Return new access token and its expires time.
func (*App) GetCode ¶
Get code from a long lived access token. Return the code retrieved from facebook.
func (*App) ParseCode ¶
Parses facebook code to a valid access token.
In facebook PHP SDK, there is a CSRF state to avoid attack. That state is not checked in this library. Caller is responsible to store and check state if possible.
Returns a valid access token exchanged from a code.
func (*App) ParseSessionCode ¶
func (*App) ParseSignedRequest ¶
Parses signed request.
func (*App) SessionFromRequest ¶
Creates a session from a regular request. If a request contains a code, it will automatically use this code to exchange a valid access token.
func (*App) SessionFromSignedRequest ¶
func (app *App) SessionFromSignedRequest(signedRequest string, context appengine.Context) (session *Session, err error)
Creates a session from a signed request. If signed request contains a code, it will automatically use this code to exchange a valid access token.
type BinaryData ¶
type BinaryData struct { Filename string // filename used in multipart form writer. Source io.Reader // file data source. }
Binary data.
type BinaryFile ¶
type BinaryFile struct { Filename string // filename used in multipart form writer. Path string // path to file. must be readable. }
Binary file.
type Error ¶
type Error struct { Message string Type string Code int ErrorSubcode int // subcode for authentication related errors. }
Facebook API error.
type Params ¶
type Params map[string]interface{}
Api params.
For general uses, just use Params as a ordinary map.
For advanced uses, use MakeParams to create Params from any struct.
func MakeParams ¶
func MakeParams(data interface{}) (params Params)
Makes a new Params instance by given data. Data must be a struct or a map with string keys. MakeParams will change all struct field name to lower case name with underscore. e.g. "FooBar" will be changed to "foo_bar".
Returns nil if data cannot be used to make a Params instance.
type Result ¶
type Result map[string]interface{}
Facebook api call result.
func Api ¶
Makes a facebook graph api call.
Method can be GET, POST, DELETE or PUT.
Params represents query strings in this call. Keys and values in params will be encoded for URL automatically. So there is no need to encode keys or values in params manually. Params can be nil.
If you want to get
https://graph.facebook.com/huandu?fields=name,username
Api should be called as following
Api("/huandu", GET, Params{"fields": "name,username"})
or in a simplified way
Get("/huandu", Params{"fields": "name,username"})
Api is a wrapper of Session.Api(). It's designed for graph api that doesn't require app id, app secret and access token. It can be called in multiple goroutines.
If app id, app secret or access token is required in graph api, caller should create a new facebook session through App instance instead.
func Batch ¶
Makes a batch facebook graph api call. Batch is designed for more advanced usage including uploading binary files.
An uploading files sample
// equivalent to following curl command (borrowed from facebook docs) // curl \ // -F 'access_token=…' \ // -F 'batch=[{"method":"POST","relative_url":"me/photos","body":"message=My cat photo","attached_files":"file1"},{"method":"POST","relative_url":"me/photos","body":"message=My dog photo","attached_files":"file2"},]' \ // -F 'file1=@cat.gif' \ // -F 'file2=@dog.jpg' \ // https://graph.facebook.com Batch(Params{ "access_token": "the-access-token", "file1": File("cat.gif"), "file2": File("dog.jpg"), }, Params{ "method": "POST", "relative_url": "me/photos", "body": "message=My cat photo", "attached_files": "file1", }, Params{ "method": "POST", "relative_url": "me/photos", "body": "message=My dog photo", "attached_files": "file2", })
See https://developers.facebook.com/docs/reference/api/batch/ to learn more about Batch Requests.
func BatchApi ¶
Makes a batch facebook graph api call.
BatchApi supports most kinds of batch calls defines in facebook batch api document, except uploading binary data. Use Batch to do so.
See https://developers.facebook.com/docs/reference/api/batch/ to learn more about Batch Requests.
func (Result) Decode ¶
Decodes full result to a struct. It only decodes fields defined in the struct.
As all facebook response fields are lower case strings, Decode will convert all camel-case field names to lower case string. e.g. field name "FooBar" will be converted to "foo_bar". The side effect is that if a struct has 2 fields with only capital differences, decoder will map these fields to a same result value.
If a field is missing in the result, Decode keeps it unchanged by default.
Decode can read struct field tag value to change default behavior.
Examples:
type Foo struct { // "id" must exist in response. note the leading comma. Id string `facebook:",required"` // use "name" as field name in response. TheName string `facebook:"name"` }
To change default behavior, set a struct tag `facebook:",required"` to fields should not be missing.
Returns error if v is not a struct or any required v field name absents in res.
func (Result) DecodeField ¶
Decodes a field of result to any type, including struct. Field name format is defined in Result.Get().
More details about decoding struct see Result.Decode().
func (Result) Err ¶
Checks if Result is a Graph API error. Returns nil if Result is not an error.
The returned error can be converted to Error by type assertion.
err := res.Err() if err != nil { if e, ok := err.(*Error); ok { // read more details in e.Message, e.Code and e.Type } }
For more information about Graph API Errors, see https://developers.facebook.com/docs/reference/api/errors/
type Session ¶
type Session struct {
// contains filtered or unexported fields
}
Holds a facebook session with an access token. Session should be created by App.Session or App.SessionFromSignedRequest.
func (*Session) AccessToken ¶
Gets current access token.
func (*Session) Api ¶
Makes a facebook graph api call.
If session access token is set, "access_token" in params will be set to the token value.
Returns facebook graph api call result. If facebook returns error in response, returns error details in res and set err.
func (*Session) Batch ¶
Makes a batch facebook graph api call. Batch is designed for more advanced usage including uploading binary files.
If session access token is set, "access_token" in batchParams will be set to the token value.
See https://developers.facebook.com/docs/reference/api/batch/ for batch call api details.
func (*Session) BatchApi ¶
Makes a batch call. Each params represent a single facebook graph api call.
BatchApi supports most kinds of batch calls defines in facebook batch api document, except uploading binary data. Use Batch to do so.
See https://developers.facebook.com/docs/reference/api/batch/ for batch call api details.
If session access token is set, the token will be used in batch api call.
Returns an array of batch call result on success.
func (*Session) Inspect ¶
Inspect Session access token. Returns JSON array containing data about the inspected token.
func (*Session) SetAccessToken ¶
Sets a new access token.