7

腾讯云之无服务器云函数

 3 years ago
source link: https://studygolang.com/articles/16529?fr=sidebar
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

使用腾讯的 无服务器云函数启动了一个服务,用golang代码生成以太坊的私钥跟地址。

https://service-exvd0ctl-1258120565.ap-beijing.apigateway.myqcloud.com/release/addr

47789-0e2a5e777d322cd6.png
genEthAddr.png

无服务器云函数是什么

腾讯云的无服务器云函数,跟 aws lambda类似,把一段代码放到云函数服务器上,设定好访问路径, 就可以对外访问了。之前若想发布1段20行代码执行的服务,你可能需要买个vps,现在用腾讯的云函数即可,灵活方便,省资源。

如果要做些工具类微信小程序,生成eth、btc地址,查看天气数据,雾霾指数,运行个云函数,小程序去请求即可。只要不保存大量数据, 搭建建服务器的费用可以省了。

云函数上使用golang

云函数服务支持的语言真不少,有 python nodejs java golang, 为什么选择golang了呢? python、nodejs 引入的类库,我不知道如何才能导入到云函数,java语法比较啰嗦,而golang 编译完二进制文件就能直接run了,实在是方便,为什么不用呢?

package main

import (
    "encoding/hex"
    "fmt"

    "github.com/ethereum/go-ethereum/crypto"
    "github.com/tencentyun/scf-go-lib/cloudfunction"
)

func main() {
    cloudfunction.Start(genEthAddr) //使用云函数的固定用法
}

func genEthAddr() (string, error) {
    key, _ := crypto.GenerateKey()

    privateKey := hex.EncodeToString(key.D.Bytes())
    address := crypto.PubkeyToAddress(key.PublicKey).Hex()

    fmt.Printf("privateKey: 0x%s\n", privateKey)
    fmt.Printf("addr: %s\n", address)

    return fmt.Sprintf("私钥: 0x%s 地址: %s", privateKey, address), nil
}

编译并打包

GOOS=linux GOARCH=amd64 go build -o main main.go
zip main.zip main

将打包好的zip文件上传到腾讯的云函数服务器,设定好访问路由,就可以使用了。

过段时间会放上一个小视频,介绍如何使用腾讯的云函数服务。


https://cloud.tencent.com/document/product/583/18032
https://cloud.tencent.com/document/product/583/9702
https://cloud.tencent.com/document/product/583/12513

https://cloud.tencent.com/document/product/583/12284 计费方式
https://cloud.tencent.com/document/product/583/12282 免费额度


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK