11.6.4. Go 함수 반환 값

HTTP 요청에 의해 트리거된 함수는 응답을 직접 설정할 수 있습니다. Go http.ResponseWriter 를 사용하여 이 작업을 수행하도록 함수를 구성할 수 있습니다.

HTTP 응답의 예

func Handle(ctx context.Context, res http.ResponseWriter, req *http.Request) {
  // Set response
  res.Header().Add("Content-Type", "text/plain")
  res.Header().Add("Content-Length", "3")
  res.WriteHeader(200)
  _, err := fmt.Fprintf(res, "OK\n")
  if err != nil {
	fmt.Fprintf(os.Stderr, "error or response write: %v", err)
  }
}

클라우드 이벤트에 의해 트리거한 함수는 이벤트를 Knative Eventing 시스템으로 푸시하기 위해 아무것도 반환하지 않거나 error 또는 CloudEvent를 반환할 수 있습니다. 이 경우 클라우드 이벤트의 고유 ID, 적절한 SourceType을 설정해야 합니다. 데이터는 정의된 구조 또는 map에서 채워질 수 있습니다.

CloudEvent 응답 예

func Handle(ctx context.Context, event cloudevents.Event) (resp *cloudevents.Event, err error) {
  // ...
  response := cloudevents.NewEvent()
  response.SetID("example-uuid-32943bac6fea")
  response.SetSource("purchase/getter")
  response.SetType("purchase")
  // Set the data from Purchase type
  response.SetData(cloudevents.ApplicationJSON, Purchase{
	CustomerId: custId,
	ProductId:  prodId,
  })
  // OR set the data directly from map
  response.SetData(cloudevents.ApplicationJSON, map[string]string{"customerId": custId, "productId": prodId})
  // Validate the response
  resp = &response
  if err = resp.Validate(); err != nil {
	fmt.Printf("invalid event created. %v", err)
  }
  return
}