Coder Social home page Coder Social logo

scf-go-lib's Introduction

scf-go-lib

用于 SCF GO 环境的库及工具

GO 环境开发说明

package main

import (
	"context"
	"fmt"

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

type DefineEvent struct {
	// test event define
	Key1 string `json:"key1"`
	Key2 string `json:"key2"`
	Key3 string `json:"key3"`
}

func hello(ctx context.Context, event DefineEvent) (string, error) {
	fmt.Println("key1:", event.Key1)
	fmt.Println("key2:", event.Key2)
	fmt.Println("key3:", event.Key3)
	return fmt.Sprintf("Hello %s!", event.Key1), nil
}

func main() {
	// Make the handler available for Remote Procedure Call by Cloud Function
	cloudfunction.Start(hello)
}

  1. 需要使用 package main 包含 main 函数。
  2. 引用 github.com/tencentyun/scf-go-lib/cloudfunction 库。
  3. 入口函数入参可选 0~2 参数,如包含参数,需 context 在前,event 在后,入参组合有 (),(event),(context),(context,event)。
  4. 入口函数返回值可选 0~2 参数,如包含参数,需 返回内容在前,error 错误信息在否,返回值组合有 (),(ret),(error),(ret,error)。
  5. 入参 event ,和返回值 ret,均需要能够兼容 encoding/json 标准库,可以进行 Marshal、Unmarshal。
  6. 在 main 函数中使用包内的 Start 函数启动入口函数

GO Context 使用说明

package main
import (
    "context"
    "fmt"
    "os"
    "github.com/tencentyun/scf-go-lib/cloudfunction"
    "github.com/tencentyun/scf-go-lib/functioncontext"
)

type DefineEvent struct {
    // test event define
    Key1 string `json:"key1"`
    Key2 string `json:"key2"`
}
func hello(ctx context.Context, event DefineEvent) (string, error) {
    lc, _ := functioncontext.FromContext(ctx)
    fmt.Printf("ctx: %#v\n", lc) 
    fmt.Printf("namespace: %s\n", lc.Namespace)
    fmt.Printf("function name: %s\n", lc.FunctionName)
    return fmt.Sprintf("Hello!"), nil 
}
func main() {
    // Make the handler available for Remote Procedure Call by Cloud Function
    cloudfunction.Start(hello)
}

GO 环境编译说明

使用指定 OS 及 ARCH 即可跨平台编译为二进制,随后通过 zip 工具打包二进制,生成可以上传的代码包。

在 Linux 或 MacOS 下可使用如下命令编译及打包

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

在 Windows 下可使用如下命令编译,然后使用打包工具对输出的二进制文件进行打包,二进制文件需要在 zip 包根目录。

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

云函数创建说明

创建云函数时,GO 环境仅支持 zip 包上传。其中入口函数位置填写 二进制文件名 即可,无需按文件名.函数名格式填写。

scf-go-lib's People

Contributors

alfredhuang211 avatar chenhengqi avatar chenxuat avatar dxk1 avatar fanzhe328 avatar linzang avatar serverlessplus avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

scf-go-lib's Issues

CMQEvent不能解析?

用scf.CMQEvent 作为参数的话,反序列化报错了。

type CMQEventEntity struct {
	Type    			string     	`json:"type"`
	TopicOwner 			int64 		`json:"topicOwner"`
	TopicName 			string 		`json:"topicName"`
	SubscriptionName 	string 		`json:"subscriptionName"`
	PublishTime 		string 		`json:"publishTime"`
	MsgID			 	string 		`json:"msgId"`
	RequestID	 		string 		`json:"requestId"`
	MsgBody			 	string 		`json:"msgBody"`
	MsgTag		 		[]string 	`json:"msgTag"`
}

实际是因为里面的MsgTag是用逗号分隔的字符串,不是数组

无法解析query有数组的情况

例如

?foo=bar&foo=qux

?foo[]=bar&foo[]=qux

反序列化出错了

{
errorCode: 1,
errorMessage: "user code exception caught",
stackTrace: "invoke function failed with err: {"Message":"json: cannot unmarshal array into Go struct field APIGatewayProxyRequest.queryString of type string","Type":"UnmarshalTypeError","StackTrace":null,"ShouldExit":false}"
}

使用 APIGateway 事件, 如何返回 string

package main

import (
	"context"

	"github.com/tencentyun/scf-go-lib/events"
	"github.com/tencentyun/scf-go-lib/cloudfunction"
)
func hello(ctx context.Context, event events.APIGatewayRequest) (string, error){
	if event.QueryString["message"] != nil {
		return "hello\nworld", nil
	}

	return "message 参数缺失", nil
}

func main() {
	// Make the handler available for Remote Procedure Call by Cloud Function
	cloudfunction.Start(hello)
}

repsonse:

/release/helloworld
当前返回:  "message 参数缺失"
期望返回:  message 参数缺失
/release/helloworld?message=hello
当前返回: "hello\nworld"
期望返回:hello\nworld

正常返回string/text, 应该是没有"

无法解析Header某个Key有多个值的情况

events.APIGatewayRequestHeadermap[string]string(golang中http.Headermap[string][]string),因此无法处理Header中某个key有多个value的情况。

如做这样的请求:

$ curl https://service-aaaa-11111.gz.apigw.tencentcs.com/release/w --header key:a --header key:b

报错如下

{"errorCode":1,"errorMessage":"user code exception caught","stackTrace":"invoke function failed with err: {\"Message\":\"json: cannot unmarshal array into Go struct field APIGatewayRequest.headers of type string\",\"Type\":\"UnmarshalTypeError\",\"StackTrace\":null,\"ShouldExit\":false}"} 

建议更改为map[string][]string以契合Golang官方库。(如果因为兼容原因不方便改,JSON转换时能不能将值设置为value1, value2?)

时间解析

cos event 定义的类型实际会出错

{"errorCode":1,"errorMessage":"user code exception caught","stackTrace":"invoke function failed with err: {"Message":"parsing time \"1545152859\" as \"\"2006-01-02T15:04:05Z07:00\"\": cannot parse \"1545152859\" as \"\"\"","Type":"ParseError","StackTrace":null,"ShouldExit":false}"}

时间生产是 unix ,定义的是 rfc3339,文档上也是。

那么到底是生产要更新成这样,还是这个定义的有误。

go mod support

go mod will be official dependency management of Go. So will this repo be adapt for go mod?

README中入口函数的返回值描述有误

返回值的组合(ret)测试了不行,执行会报错
{"errorCode":1,"errorMessage":"user code exception caught","stackTrace":"invoke function failed with err: {\"Message\":\"handler returns a single value, but it does not implement error\",\"Type\":\"errorString\",\"StackTrace\":null,\"ShouldExit\":false}"}

参考文档

返回的json 自动加反斜杠 双引号?怎么解决?

jsonStu, _ := json.Marshal(persons) fmt.Printf(string(jsonStu)) return string(jsonStu), nil

函数内部打印的是正常的json
[{"title":
然后 return 以后 返回的数据是
"[{\"title\":

为什么自动加了反斜杠还有引号了?没办法解析json了
怎么原原本本的返回

无法获取事件值

根据此文档 使用tencent-go模版创建一个hello_world的函数, trigger是api-gateway。

生产的index.go 如此链接 https://cloud.tencent.com/document/product/583/18032

package main

import (
    "context"
    "fmt"
    "github.com/tencentyun/scf-go-lib/cloudfunction"
)

type DefineEvent struct {
    // test event define
    Key1 string `json:"key1"`
    Key2 string `json:"key2"`
}

func hello(ctx context.Context, event DefineEvent) (string, error) {
    fmt.Println("key1:", event.Key1)
    fmt.Println("key2:", event.Key2)
    return fmt.Sprintf("Hello %s!", event.Key1), nil
}

func main() {
    // Make the handler available for Remote Procedure Call by Cloud Function
    cloudfunction.Start(hello)
}

测试的时候

* Uses proxy env variable NO_PROXY == 'localhost,127.0.0.1,10.96.0.0/12,192.168.99.0/24,192.168.64.111'
*   Trying 134.175.211.91:443...
* TCP_NODELAY set
* Connected to service-olcgnvgm-1253364530.gz.apigw.tencentcs.com (134.175.211.91) port 443 (#0)
* ALPN, offering http/1.1
* TLS 1.2 connection using TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256
* Server certificate: *.ap-beijing.apigateway.myqcloud.com
* Server certificate: GlobalSign Organization Validation CA - SHA256 - G2
* Server certificate: GlobalSign Root CA
POST /release/hello HTTP/1.1
Host: service-olcgnvgm-1253364530.gz.apigw.tencentcs.com
User-Agent: Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)
Referer:
Content-Type: application/json
Accept: application/json, */*
Content-Length: 16

{
    "key1": "hello",
    "key2": "world"
}

* upload completely sent off: 16 out of 16 bytes
"Hello World"* Mark bundle as not supporting multiuse

查看函数日志

返回数据:

"Hello World"

日志:

START RequestId: 1c56f751bab962962d8d13603e52ef79

Event RequestId: 1c56f751bab962962d8d13603e52ef79

key1: 

key2: 

END RequestId: 1c56f751bab962962d8d13603e52ef79

Report RequestId: 1c56f751bab962962d8d13603e52ef79 Duration:1m

函数自带的测试功能可以获取到key1或key2的值,但是通过向apigateway调用scf的时候无法获取到

那么这是scf-go-lib/cloudfunction的原因还是apigateway的原因

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.