LoginSignup
0
0

More than 1 year has passed since last update.

腾讯云之无服务器云函数运行golang程序

Last updated at Posted at 2021-06-01

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

无服务器云函数是什么

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

小程序

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

云函数上使用 golang

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

Golang code

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/12513

https://cloud.tencent.com/document/product/583/9702 Python 部署程序包
https://cloud.tencent.com/document/product/583/12284 计费方式
https://cloud.tencent.com/document/product/583/12282 免费额度

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0