全部文档
当前文档

暂无内容

如果没有找到您期望的内容,请尝试其他搜索词

文档中心

请求处理程序开发方法

最近更新时间:2023-02-07 18:04:27

本文介绍在云函数KCF中使用Golang语言开发请求处理程序的相关概念和方法。

请求处理程序分为事件请求处理程序(Event Handler)和HTTP请求处理程序(HTTP Handler);其中事件请求由各种事件源触发生成,HTTP请求则由HTTP触发器触发生成。

请求处理程序的具体配置示例如下:

事件请求处理程序(Event Handler)

介绍Go事件请求处理程序的结构和特点。

使用示例

在Go语言的代码中,使用go mod引入cloudevents官方的SDK库 :

go get github.com/cloudevents/sdk-go/[email protected]

在开发代码中导入cloudevents包依赖

import cloudevents "github.com/cloudevents/sdk-go/v2"
cloudevents + gin框架 代码示例
package main

import (
	cloudevents "github.com/cloudevents/sdk-go/v2"
	"github.com/gin-gonic/gin"
	"io/ioutil"
	"log"
)

func main() {
	r := gin.Default()
	r.GET("/health", func(c *gin.Context) {
		c.JSON(200, gin.H{
			"message": "health up",
		})
	})
	r.POST("/event-invoke", eventHandlerDirect)
	r.NoRoute(func(c *gin.Context) {
		c.JSON(404, gin.H{
			"message": "not found",
		})
	})
	log.Printf("will listen on :8080\n")
	if err := r.Run(":8080"); err != nil {
		log.Fatalf("unable to start http server, %s", err)
	}
}

func eventHandlerDirect(c *gin.Context) {
	log.Printf("receive cloudevent")
	// Unmarshal JSON To cloudevents
	event := cloudevents.NewEvent()
	bytes, _ := ioutil.ReadAll(c.Request.Body)
	err := event.UnmarshalJSON(bytes)
	//err := c.Bind(&event)
	if err != nil {
		log.Printf("Unmarshal cloutevent error: %s", err.Error())
		c.JSON(400, gin.H{
			"message": err.Error(),
		})
		return
	}
	// decode body data
	data := &Sample{}
	if err := event.DataAs(data); err != nil {
		log.Printf("failed to get playload data: %s", err)
		c.JSON(400, gin.H{
			"message": "bad data",
		})
		return
	}
	log.Printf("get playload data: %s\n", data)
	log.Printf("----------------------------\n")
	c.JSON(200, gin.H{
		"message": "receive cloudevent success",
	})
}

示例解析如下:

  • package main: 在Go语言中,Go应用程序都包含一个名为main的包。
  • func main():运行函数代码的入口点,Go程序必须包含main函数。
  • import:需要引用的依赖包,主要包括以下包:
    • github.com/cloudevents/sdk-go/v2: cloudevents的核心库。
    • github.com/gin-gonic/gin Go Web服务器。
  • 处理事件请求的方法(即Event Handler),参数含义如下:
    • context:云函数Go语言的Context对象。
  • data结构体
type Sample struct {
	Request  Request  `json:"request,omitempty"`
	Response Response `json:"response,omitempty"`
	Ks3      *Ks3     `json:"ks3,omitempty"`
}
type Request struct {
	SourceIPAddress string `json:"sourceIPAddress,omitempty"`
}
type Response struct {
	RequestID string `json:"requestId,omitempty"`
}

type Ks3 struct {
	Bucket Bucket `json:"bucket,omitempty"`
	Object Object `json:"object,omitempty"`
}

type Bucket struct {
	Name    string `json:"name,omitempty"`
	Ownerid string `json:"ownerid,omitempty"`
}
type Object struct {
	Internalurl string `json:"internalurl,omitempty"`
	Etag        string `json:"etag,omitempty"`
	Objectsize  string `json:"objectsize,omitempty"`
	URL         string `json:"url,omitempty"`
	Key         string `json:"key,omitempty"`
}

cloudevents详细介绍:

HTTP请求处理程序(HTTP Handler)

介绍Go Http请求处理程序的结构和特点

使用示例

代码示例

package main

import (
	"github.com/gin-gonic/gin"
	"io/ioutil"
	"log"
)

// go build with vendor
// go build -mod=vendor -o gin cmd/gin_http/main.go

func main() {
	r := gin.Default()
	r.GET("/health", func(c *gin.Context) {
		c.JSON(200, gin.H{
			"message": "health up",
		})
	})
	r.POST("/http-invoke", postHandler)
	r.GET("/http-invoke", getHandler)
	r.DELETE("/http-invoke", deleteHandler)
	r.PUT("/http-invoke", putHandler)
	r.PATCH("/http-invoke", patchHandler)
	r.NoRoute(func(c *gin.Context) {
		c.JSON(404, gin.H{
			"message": "not found",
		})
	})
	log.Printf("will listen on :8080\n")
	if err := r.Run(":8080"); err != nil {
		log.Fatalf("unable to start http server, %s", err)
	}
}

func postHandler(c *gin.Context) {
	log.Printf("receive http post message")
	// do something with api request
	bytes, _ := ioutil.ReadAll(c.Request.Body)
	log.Printf("post body: %s", string(bytes))
	c.JSON(200, gin.H{
		"message": "receive http post message",
	})
}

func getHandler(c *gin.Context) {
	log.Printf("receive http get message")
	// do something with api request
	c.JSON(200, gin.H{
		"message": "receive http get message",
	})
}

func putHandler(c *gin.Context) {
	log.Printf("receive http put message")
	// do something with api request
	c.JSON(200, gin.H{
		"message": "receive http put message",
	})
}

func patchHandler(c *gin.Context) {
	log.Printf("receive http patch message")
	// do something with api request
	c.JSON(200, gin.H{
		"message": "receive http patch message",
	})
}

func deleteHandler(c *gin.Context) {
	log.Printf("receive http delete message")
	// do something with api request
	c.JSON(200, gin.H{
		"message": "receive http delete message",
	})
}

示例解析如下:

  • package main: 在Go语言中,Go应用程序都包含一个名为main的包。
  • func main():运行函数代码的入口点,Go程序必须包含main函数。
  • import:需要引用函数计算依赖的包,主要包括以下包:
    • github.com/gin-gonic/gin Go Web服务器。
  • 处理HTTP请求的方法(即HTTP Handler),参数含义如下:
    • context:函数计算Go语言的Context对象。
文档导读
纯净模式常规模式

纯净模式

点击可全屏预览文档内容
文档反馈