facebook

package module
v0.0.0-...-b998dba Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Aug 8, 2014 License: MIT Imports: 19 Imported by: 0

README

A Facebook Graph API Library In Go

Build Status

This is a Go library fully supports Facebook Graph API with file upload, batch request and FQL. It's simple but powerful.

Quick Tutorial

Here is a sample to read my Facebook username by uid.

    package main

    import (
        "fmt"
        fb "github.com/huandu/facebook"
    )

    func main() {
        res, _ := fb.Get("/538744468", fb.Params{
            "fields": "username",
        })
        fmt.Println("here is my facebook username:", res["username"])
    }

Type of res["username"] is interface{}. This library provides several helpful methods to decode fields to any Go type or even a custom Go struct.

    // Decode "username" to a go string.
    var username string
    res.DecodeField("username", &username)
    fmt.Println("alternative way to get username:", username)

    // It's also possible to decode the whole result into a predefined struct.
    type User struct {
        Username string
    }
    var user User
    res.Decode(&user)
    fmt.Println("print username in struct:", user.Username)

Full Document

Read http://godoc.org/github.com/huandu/facebook or use go doc.

Get It

Use go get github.com/huandu/facebook to get and install it.

Out of Scope

  1. No OAuth integration. This library only provides APIs to parse/verify access token and OAuth code.
  2. No old RESTful API support. Such APIs are deprecated for years. Forget about them.

License

This library is licensed under MIT license. See LICENSE for details.

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

View Source
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 New

func New(appId, appSecret string) *App

Creates a new App and sets app id and secret.

func (*App) AppAccessToken

func (app *App) AppAccessToken() string

Gets application access token, useful for gathering public information about users and applications.

func (*App) ExchangeToken

func (app *App) ExchangeToken(accessToken string) (token string, expires int, err error)

Exchange a short lived access token to a long lived access token. Return new access token and its expires time.

func (*App) GetCode

func (app *App) GetCode(accessToken string) (code string, err error)

Get code from a long lived access token. Return the code retrieved from facebook.

func (*App) ParseCode

func (app *App) ParseCode(code string) (token string, err error)

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 *App) ParseSessionCode(code string, session *Session) (token string, err error)

func (*App) ParseSignedRequest

func (app *App) ParseSignedRequest(signedRequest string) (res Result, err error)

Parses signed request.

func (*App) Session

func (app *App) Session(accessToken string, context appengine.Context) *Session

Creates a session based on current App setting.

func (*App) SessionFromRequest

func (app *App) SessionFromRequest(req *http.Request) (session *Session, err error)

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.

func Data

func Data(filename string, source io.Reader) *BinaryData

Creates a new binary data holder.

type BinaryFile

type BinaryFile struct {
	Filename string // filename used in multipart form writer.
	Path     string // path to file. must be readable.
}

Binary file.

func File

func File(filename, path string) *BinaryFile

Creates a binary file holder.

type Error

type Error struct {
	Message      string
	Type         string
	Code         int
	ErrorSubcode int // subcode for authentication related errors.
}

Facebook API error.

func (*Error) Error

func (e *Error) Error() string

Returns error string.

type Method

type Method string

Api HTTP method. Can be GET, POST or DELETE.

const (
	GET    Method = "GET"
	POST   Method = "POST"
	DELETE Method = "DELETE"
	PUT    Method = "PUT"
)

Facebook graph api methods.

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.

func (Params) Encode

func (params Params) Encode(writer io.Writer) (mime string, err error)

Encodes params to query string. If map value is not a string, Encode uses json.Marshal() to convert value to string.

Encode will panic if Params contains values that cannot be marshalled to json string.

type Result

type Result map[string]interface{}

Facebook api call result.

func Api

func Api(path string, method Method, params Params) (Result, error)

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

func Batch(batchParams Params, params ...Params) ([]Result, error)

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

func BatchApi(accessToken string, params ...Params) ([]Result, error)

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 Delete

func Delete(path string, params Params) (Result, error)

Delete is a short hand of Api(path, DELETE, params).

func Get

func Get(path string, params Params) (Result, error)

Get is a short hand of Api(path, GET, params).

func Post

func Post(path string, params Params) (Result, error)

Post is a short hand of Api(path, POST, params).

func Put

func Put(path string, params Params) (Result, error)

Put is a short hand of Api(path, PUT, params).

func (Result) Decode

func (res Result) Decode(v interface{}) (err error)

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

func (res Result) DecodeField(field string, v interface{}) error

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

func (res Result) Err() error

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/

func (Result) Get

func (res Result) Get(field string) interface{}

Gets a field.

Field can be a dot separated string. It means, if field name is "a.b.c", gets field value 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"].

Returns nil if field doesn't exist.

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

func (session *Session) AccessToken() string

Gets current access token.

func (*Session) Api

func (session *Session) Api(path string, method Method, params Params) (Result, error)

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) App

func (session *Session) App() *App

Gets associated App.

func (*Session) Batch

func (session *Session) Batch(batchParams Params, params ...Params) ([]Result, error)

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

func (session *Session) BatchApi(params ...Params) ([]Result, error)

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) Delete

func (session *Session) Delete(path string, params Params) (Result, error)

Delete is a short hand of Api(path, DELETE, params).

func (*Session) Get

func (session *Session) Get(path string, params Params) (Result, error)

Get is a short hand of Api(path, GET, params).

func (*Session) Inspect

func (session *Session) Inspect() (result Result, err error)

Inspect Session access token. Returns JSON array containing data about the inspected token.

func (*Session) Post

func (session *Session) Post(path string, params Params) (Result, error)

Post is a short hand of Api(path, POST, params).

func (*Session) Put

func (session *Session) Put(path string, params Params) (Result, error)

Put is a short hand of Api(path, PUT, params).

func (*Session) SetAccessToken

func (session *Session) SetAccessToken(token string)

Sets a new access token.

func (*Session) User

func (session *Session) User() (id string, err error)

Gets current user id from access token.

Returns error if access token is not set or invalid.

It's a standard way to validate a facebook access token.

func (*Session) Validate

func (session *Session) Validate() (err error)

Validates Session access token. Returns nil if access token is valid.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL