在 Golang 中从 Twilio 获取访问令牌

Get Access Token from Twilio in Golang

我的后端使用 Golang,我需要从 Twilio 获取访问令牌,但我找不到任何适用于 Golang 的库。 NodeJS 中的示例代码是:

const AccessToken = require('twilio').jwt.AccessToken;
const VideoGrant = AccessToken.VideoGrant;

// Used when generating any kind of Access Token
const twilioAccountSid = 'ACxxxxxxxxxx';
const twilioApiKey = 'SKxxxxxxxxxx';
const twilioApiSecret = 'xxxxxxxxxxxx';

// Create an access token which we will sign and return to the client,
// containing the grant we just created
const token = new AccessToken(twilioAccountSid, twilioApiKey, twilioApiSecret);
token.identity = 'alice';

// Create a Video grant which enables a client to use Video 
// and limits access to the specified Room (DailyStandup)
const videoGrant = new VideoGrant({
    room: 'DailyStandup'
});

// Add the grant to the token
token.addGrant(videoGrant);

// Serialize the token to a JWT string
console.log(token.toJwt());

我尝试了这个库 -> https://github.com/xaviiic/twilioGo 但没有成功。

使用您链接的库 (https://github.com/xaviiic/twilioGo) code/methods 等非常接近 NodeJS sample-code:

import twilio "github.com/xaviiic/twilioGo"

var (
    accountID = "AC...."
    keyID     = "SK...."
    secret    = "....."
)

token := twilio.NewAccessToken(accountID, keyID, secret)
identity := "alice"
token.SetIdentity(identity)

videoGrant := twilio.NewVideoGrant("DailyStandup")
token.AddGrant(videoGrant)

log.Println(token.ToJWT())

https://play.golang.org/p/6mEpQqisITf

注意:虽然以上内容将构建在 GOPATH 环境中(即使用最新的项目提交),但如果进行 go modules 构建,则需要一些帮助:

# this will initially fail:
go build

# choose latest commit of this dependency - latest v0.9.1 tag appears to be incompatible
go get github.com/SermoDigital/jose@master    

go build