package main import ( "context" "encoding/json" "fmt" "github.com/tencentyun/scf-go-lib/cloudfunction" "golang.org/x/oauth2" "log" "os" ) // ssh-keygen -t rsa生成的私钥文件,可以根据需求替换成自己的私钥 var keyData = [] byte ( "-----BEGIN RSA PRIVATE KEY-----\n***\n-----END RSA PRIVATE KEY-----" ) var endpotin = oauth2.Endpoint{ AuthURL: "https://accounts.google.com/o/oauth2/auth" , TokenURL: "https://accounts.google.com/o/oauth2/token" , } type Event struct { RequestContext struct { ServiceID string `json: "serviceId" ` Path string `json: "path" ` HTTPMethod string `json: "httpMethod" ` RequestID string `json: "requestId" ` Identity struct { SecretID string `json: "secretId" ` } `json: "identity" ` SourceIP string `json: "sourceIp" ` Stage string `json: "stage" ` } `json: "requestContext" ` Body string `json: "body" ` QueryStringParameters struct { RedirectURL string `json: "RedirectURL" ` } `json: "queryStringParameters" ` HeaderParameters struct { Refer string `json: "Refer" ` } `json: "headerParameters" ` StageVariables struct { Stage string `json: "stage" ` } `json: "stageVariables" ` Path string `json: "path" ` QueryString struct { Foo string `json: "foo" ` Bob string `json: "bob" ` } `json: "queryString" ` } func integratedResponse(body map[string] interface {}) (map[string] interface {}, error) { response := make(map[string] interface {}) response[ "isBase64Encoded" ] = false response[ "statusCode" ] = 200 headers := make(map[string]string) headers[ "Content-Type" ] = "application/json" response[ "headers" ] = headers js, err := json.Marshal(body) if err != nil { log.Printf( "integratedResponse exception:%v" , err) } response[ "body" ] = fmt.Sprintf( "%s" , js) return response, nil } const oauthStateString = "random" func getAuthCodeUrl(ctx context.Context, event Event) (map[string] interface {}, error) { result := make(map[string] interface {}) // 读取环境配置变量,可以在函数配置中编辑 log.Println( "env.ClientID:" , os.Getenv( "ClientID" )) log.Println( "env.ClientSecret:" , os.Getenv( "ClientSecret" )) var googleOauthConfig = &oauth2.Config{ ClientID: os.Getenv( "ClientID" ), ClientSecret: os.Getenv( "ClientSecret" ), // 读取request请求参数 RedirectURL: event.QueryStringParameters.RedirectURL, Scopes: []string{ "https://www.googleapis.com/auth/userinfo.profile" , "https://www.googleapis.com/auth/userinfo.email" }, Endpoint: endpotin, } url := googleOauthConfig.AuthCodeURL(oauthStateString) log.Printf( "googleOauthConfig.AuthCodeURL url:%v" , url) result[ "auth_code_url" ] = url return integratedResponse(result) } func main() { // Make the handler available for Remote Procedure Call by Cloud Function cloudfunction.Start(getAuthCodeUrl) } |