更新时间:2025-07-31 gmt 08:00

使用go开发http函数-j9九游会登录

本章节介绍使用go运行时开发http函数,更多http详情,请参见创建http函数

约束与限制

  • http函数只能绑定apig/apic触发器,根据函数和apig/apic之间的转发协议。

    函数的返回合法的http响应报文中必须包含body(string)、statuscode(int)、headers(map)和isbase64encoded(boolean),http函数会默认对返回结果做base64编码,isbase64encoded默认为true,其它框架同理。相关约束条件请参考base64解码和返回结构体的说明

  • http函数默认开放端口为8000。
  • context类中提供了许多上下文方法供用户使用,其声明和功能请参见表19

使用go开发http函数示例

示例概述:

由于http函数本身不支持go语言直接代码部署,因此本示例将以转换成二进制的方式为例,将go编写的程序部署到functiongraph上。

操作步骤:

具体操作步骤请参见使用go语言程序构建http函数

代码示例

源文件main.go的代码内容如下,可参考使用:

// main.go
package main
import (
	"fmt"
	"net/http"
	"github.com/emicklei/go-restful"
)
func registerserver() {
	fmt.println("running a go http server at localhost:8000/")
	ws := new(restful.webservice)
	ws.path("/")
	ws.route(ws.get("/hello").to(hello))
	c := restful.defaultcontainer
	c.add(ws)
	fmt.println(http.listenandserve(":8000", c))
}
func hello(req *restful.request, resp *restful.response) {
	resp.write([]byte("nice to meet you"))
}
func main() {
	registerserver()
}
# bootstrap
/opt/function/code/go-http-demo

在main.go中,使用8000端口启动了一个http服务器,并注册了path为/hello的api,调用该api将返回"nice to meet you"。

编译打包

  1. 在linux机器下,将上述代码进行编译:go build -o go-http-demo main.go。
  2. 将go-http-demo和bootstrap打包为xxx.zip。

创建http函数

在functiongraph函数工作流中新建一个http函数,然后上传刚才打包的xxx.zip代码。

创建apig触发器

新建一个apig触发器,选择一个合适的分组和发布环境后,直接确认即可(测试阶段可以不用安全认证,即为none)。

图1 复制url

调用测试

创建apig触发器中生成的“调用url” “代码中注册的path” “/hello”复制到浏览器地址栏,可以看到页面返回结果如下:

图2 返回结果

相关文档

网站地图