Documentation ¶
Overview ¶
This is a Go library fully supports Facebook Graph API (both 1.0 and 2.x) with file upload, batch request, FQL and multi-FQL. It can be used in Google App Engine.
Library design is highly influenced by facebook official PHP/JS SDK. If you have experience with PHP/JS SDK, you may feel quite familiar with it.
Go to project home page to see samples. Link: https://github.com/huandu/facebook
This library doesn't implement any deprecated old RESTful API. And it won't.
Index ¶
- Constants
- Variables
- func Data(filename string, source io.Reader) *binaryData
- func File(filename, path string) *binaryFile
- func FileAlias(filename, path string) *binaryFile
- func SetHttpClient(client HttpClient)
- 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) ParseCodeInfo(code, machineId string) (token string, expires int, newMachineId string, err error)
- func (app *App) ParseSignedRequest(signedRequest string) (res Result, err error)
- func (app *App) Session(accessToken string) *Session
- func (app *App) SessionFromSignedRequest(signedRequest string) (session *Session, err error)
- type BatchResult
- type DebugInfo
- type DebugMessage
- type DebugMode
- type Error
- type HttpClient
- type Method
- type PagingResult
- 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 FQL(query string) ([]Result, error)
- func Get(path string, params Params) (Result, error)
- func MakeResult(jsonBytes []byte) (Result, error)
- func MultiFQL(queries Params) (Result, error)
- func Post(path string, params Params) (Result, error)
- func Put(path string, params Params) (Result, error)
- func Request(request *http.Request) (Result, error)
- func (res Result) Batch() (*BatchResult, error)
- func (res Result) DebugInfo() *DebugInfo
- func (res Result) Decode(v interface{}) (err error)
- func (res Result) DecodeField(field string, v interface{}) error
- func (res Result) Err() error
- func (res Result) Get(field string) interface{}
- func (res Result) GetField(fields ...string) interface{}
- func (res Result) Paging(session *Session) (*PagingResult, 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) AppsecretProof() string
- func (session *Session) Batch(batchParams Params, params ...Params) ([]Result, error)
- func (session *Session) BatchApi(params ...Params) ([]Result, error)
- func (session *Session) Debug() DebugMode
- func (session *Session) Delete(path string, params Params) (Result, error)
- func (session *Session) EnableAppsecretProof(enabled bool) error
- func (session *Session) FQL(query string) ([]Result, error)
- func (session *Session) Get(path string, params Params) (Result, error)
- func (session *Session) Inspect() (result Result, err error)
- func (session *Session) MultiFQL(queries Params) (Result, error)
- func (session *Session) Post(path string, params Params) (Result, error)
- func (session *Session) Put(path string, params Params) (Result, error)
- func (session *Session) Request(request *http.Request) (res Result, err error)
- func (session *Session) SetAccessToken(token string)
- func (session *Session) SetDebug(debug DebugMode) DebugMode
- 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 ¶
var ( // Default facebook api version. // It can be any valid version string (e.g. "v2.3") or empty. // // See https://developers.facebook.com/docs/apps/versions for details. Version string // Set app level debug mode. // After setting DebugMode, all newly created session will use the mode // to communicate with graph API. // // See https://developers.facebook.com/docs/graph-api/using-graph-api/v2.3#debugging Debug DebugMode )
Functions ¶
func FileAlias ¶
func FileAlias(filename, path string) *binaryFile
Creates a binary file holder and specific a different path for reading.
func SetHttpClient ¶ added in v1.5.0
func SetHttpClient(client HttpClient)
SetHttpClient updates the http client of default session.
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 // Enable appsecret proof in every API call to facebook. // Facebook document: https://developers.facebook.com/docs/graph-api/securing-requests EnableAppsecretProof bool }
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 ¶
ParseCode redeems code for a valid access token. It's a shorthand call to ParseCodeInfo(code, "").
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.
func (*App) ParseCodeInfo ¶ added in v1.5.0
func (app *App) ParseCodeInfo(code, machineId string) (token string, expires int, newMachineId string, err error)
ParseCodeInfo redeems code for access token and returns extra information. The machineId is optional.
See https://developers.facebook.com/docs/facebook-login/access-tokens#extending
func (*App) ParseSignedRequest ¶
Parses signed request.
type BatchResult ¶ added in v1.3.0
type BatchResult struct { StatusCode int // HTTP status code. Header http.Header // HTTP response headers. Body string // Raw HTTP response body string. Result Result // Facebook api result parsed from body. }
Represents facebook batch API call result. See https://developers.facebook.com/docs/graph-api/making-multiple-requests/#multiple_methods.
type DebugInfo ¶ added in v1.5.0
type DebugInfo struct { Messages []DebugMessage // debug messages. it can be nil if there is no message. Header http.Header // all HTTP headers for this response. Proto string // HTTP protocol name for this response. // Facebook debug HTTP headers. FacebookApiVersion string // the actual graph API version provided by facebook-api-version HTTP header. FacebookDebug string // the X-FB-Debug HTTP header. FacebookRev string // the x-fb-rev HTTP header. }
DebugInfo is the debug information returned by facebook when debug mode is enabled.
type DebugMessage ¶ added in v1.5.0
DebugMessage is one debug message in "__debug__" of graph API response.
type DebugMode ¶ added in v1.5.0
type DebugMode string
Graph API debug mode. See https://developers.facebook.com/docs/graph-api/using-graph-api/v2.3#graphapidebugmode
type Error ¶
type Error struct { Message string Type string Code int ErrorSubcode int // subcode for authentication related errors. }
Facebook API error.
type HttpClient ¶
type HttpClient interface { Do(req *http.Request) (resp *http.Response, err error) Get(url string) (resp *http.Response, err error) Post(url string, bodyType string, body io.Reader) (resp *http.Response, err error) }
An interface to send http request. This interface is designed to be compatible with type `*http.Client`.
func DefaultHttpClient ¶ added in v1.5.0
func DefaultHttpClient() HttpClient
DefaultHttpClient returns the http client for default session.
type PagingResult ¶
type PagingResult struct {
// contains filtered or unexported fields
}
Represents facebook API call result with paging information.
func (*PagingResult) Decode ¶ added in v1.2.0
func (pr *PagingResult) Decode(v interface{}) (err error)
Decodes the current full result to a struct. See Result#Decode.
func (*PagingResult) HasNext ¶
func (pr *PagingResult) HasNext() bool
Check whether there is next page.
func (*PagingResult) HasPrevious ¶
func (pr *PagingResult) HasPrevious() bool
Check whether there is previous page.
func (*PagingResult) Previous ¶
func (pr *PagingResult) Previous() (noMore bool, err error)
Read previous page.
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 with default session.
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 with default session. 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", })
Facebook document: https://developers.facebook.com/docs/graph-api/making-multiple-requests
func BatchApi ¶
Makes a batch facebook graph api call with default session.
BatchApi supports most kinds of batch calls defines in facebook batch api document, except uploading binary data. Use Batch to do so.
Note: API response is stored in "body" field of a Result.
results, _ := BatchApi(accessToken, Params{...}, Params{...}) // Use first batch api response. var res1 *BatchResult var err error res1, err = results[0].Batch() if err != nil { // this is not a valid batch api response. } // Use BatchResult#Result to get response body content as Result. res := res1.Result
Facebook document: https://developers.facebook.com/docs/graph-api/making-multiple-requests
func FQL ¶
Makes a FQL query with default session. Returns a slice of Result. If there is no query result, the result is nil.
FQL can only make query without "access_token". For query requiring "access_token", create Session and call its FQL method.
Facebook document: https://developers.facebook.com/docs/technical-guides/fql#query
func MakeResult ¶
MakeResult makes a Result from facebook Graph API response.
func MultiFQL ¶
Makes a multi FQL query with default session. Returns a parsed Result. The key is the multi query key, and the value is the query result.
MultiFQL can only make query without "access_token". For query requiring "access_token", create Session and call its MultiFQL method.
See Session.MultiFQL document for samples.
Facebook document: https://developers.facebook.com/docs/technical-guides/fql#multi
func Request ¶
Makes an arbitrary HTTP request with default session. It expects server responses a facebook Graph API response.
request, _ := http.NewRequest("https://graph.facebook.com/538744468", "GET", nil) res, err := Request(request) fmt.Println(res["gender"]) // get "male"
func (Result) Batch ¶ added in v1.3.0
func (res Result) Batch() (*BatchResult, error)
Batch creates a BatchResult for this result and returns error if the Result is not a batch api response.
See BatchApi document for a sample usage.
func (Result) DebugInfo ¶ added in v1.5.0
DebugInfo creates a DebugInfo for this result if this result has "__debug__" key.
func (Result) Decode ¶
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 ¶
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 ¶
Err returns an error if Result is a Graph API 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/
func (Result) Get ¶
Get gets a field from Result.
Field can be a dot separated string. If field name is "a.b.c", it will try to return value of res["a"]["b"]["c"].
To access array items, use index value in field. For instance, field "a.0.c" means to read res["a"][0]["c"].
It doesn't work with Result which has a key contains dot. Use GetField in this case.
Returns nil if field doesn't exist.
func (Result) GetField ¶
GetField gets a field from Result.
Arguments are treated as keys to access value in Result. If arguments are "a","b","c", it will try to return value of res["a"]["b"]["c"].
To access array items, use index value as a string. For instance, args of "a", "0", "c" means to read res["a"][0]["c"].
Returns nil if field doesn't exist.
func (Result) Paging ¶
func (res Result) Paging(session *Session) (*PagingResult, error)
Paging creates a PagingResult for this Result and returns error if the Result cannot be used for paging.
Facebook uses following JSON structure to response paging information. If "data" doesn't present in Result, Paging will return error.
{ "data": [...], "paging": { "previous": "https://graph.facebook.com/...", "next": "https://graph.facebook.com/..." } }
type Session ¶
type Session struct { HttpClient HttpClient Version string // facebook versioning. // 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) AppsecretProof ¶
Check appsecret proof is enabled or not.
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.
Facebook document: https://developers.facebook.com/docs/graph-api/making-multiple-requests
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 upload binary data.
If session access token is set, the token will be used in batch api call.
Returns an array of batch call result on success.
Facebook document: https://developers.facebook.com/docs/graph-api/making-multiple-requests
func (*Session) EnableAppsecretProof ¶
Enable or disable appsecret proof status. Returns error if there is no App associasted with this Session.
func (*Session) FQL ¶
Makes a FQL query. Returns a slice of Result. If there is no query result, the result is nil.
Facebook document: https://developers.facebook.com/docs/technical-guides/fql#query
func (*Session) Inspect ¶
Inspect Session access token. Returns JSON array containing data about the inspected token. See https://developers.facebook.com/docs/facebook-login/manually-build-a-login-flow/v2.2#checktoken
func (*Session) MultiFQL ¶
Makes a multi FQL query. Returns a parsed Result. The key is the multi query key, and the value is the query result.
Here is a multi-query sample.
res, _ := session.MultiFQL(Params{ "query1": "SELECT name FROM user WHERE uid = me()", "query2": "SELECT uid1, uid2 FROM friend WHERE uid1 = me()", }) // Get query results from response. var query1, query2 []Result res.DecodeField("query1", &query1) res.DecodeField("query2", &query2)
Facebook document: https://developers.facebook.com/docs/technical-guides/fql#multi
func (*Session) Request ¶
Makes an arbitrary HTTP request. It expects server responses a facebook Graph API response.
request, _ := http.NewRequest("https://graph.facebook.com/538744468", "GET", nil) res, err := session.Request(request) fmt.Println(res["gender"]) // get "male"
func (*Session) SetAccessToken ¶
Sets a new access token.
func (*Session) SetDebug ¶ added in v1.5.0
SetDebug updates per session debug mode and returns old mode. If per session debug mode is DEBUG_OFF, session will use global Debug mode.