Fix Code Block Formatting (#5443)

* Fix Code Block Formatting

* should pass now

Signed-off-by: Debasish Biswas <debasishbsws.abc@gmail.com>

* correct numbers

* may fix

---------

Signed-off-by: Debasish Biswas <debasishbsws.abc@gmail.com>
This commit is contained in:
Debasish Biswas 2023-03-06 20:47:33 +05:30 committed by GitHub
parent a583172c01
commit 0c2a422b2b
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
1 changed files with 266 additions and 262 deletions

View File

@ -33,189 +33,191 @@ cd knative-docs/code-samples/eventing/helloworld/helloworld-go
1. Create a new file named `helloworld.go` and paste the following code. This 1. Create a new file named `helloworld.go` and paste the following code. This
code creates a basic web server which listens on port 8080: code creates a basic web server which listens on port 8080:
```go ```go
import ( import (
"context" "context"
"log" "log"
cloudevents "github.com/cloudevents/sdk-go/v2"
"github.com/google/uuid"
)
cloudevents "github.com/cloudevents/sdk-go/v2" func receive(ctx context.Context, event cloudevents.Event)( * cloudevents.Event, cloudevents.Result) {
"github.com/google/uuid" // Here is where your code to process the event will go.
) // In this example we will log the event msg
log.Printf("Event received. \n%s\n", event)
data: = & HelloWorld {}
if err: = event.DataAs(data);
err != nil {
log.Printf("Error while extracting cloudevent Data: %s\n", err.Error())
return nil, cloudevents.NewHTTPResult(400, "failed to convert data: %s", err)
}
log.Printf("Hello World Message from received event %q", data.Msg)
// Respond with another event (optional)
// This is optional and is intended to show how to respond back with another event after processing.
// The response will go back into the knative eventing system just like any other event
newEvent: = cloudevents.NewEvent()
newEvent.SetID(uuid.New().String())
newEvent.SetSource("knative/eventing/samples/hello-world")
newEvent.SetType("dev.knative.samples.hifromknative")
if err: = newEvent.SetData(cloudevents.ApplicationJSON, HiFromKnative {
Msg: "Hi from helloworld-go app!"
});
err != nil {
return nil, cloudevents.NewHTTPResult(500, "failed to set response data: %s", err)
}
log.Printf("Responding with event\n%s\n", newEvent)
return &newEvent, nil
}
func receive(ctx context.Context, event cloudevents.Event) (*cloudevents.Event, cloudevents.Result) { func main() {
// Here is where your code to process the event will go. log.Print("Hello world sample started.")
// In this example we will log the event msg c, err: = cloudevents.NewDefaultClient()
log.Printf("Event received. \n%s\n", event) if err != nil {
data := &HelloWorld{} log.Fatalf("failed to create client, %v", err)
if err := event.DataAs(data); err != nil { }
log.Printf("Error while extracting cloudevent Data: %s\n", err.Error()) log.Fatal(c.StartReceiver(context.Background(), receive))
return nil, cloudevents.NewHTTPResult(400, "failed to convert data: %s", err) }
} ```
log.Printf("Hello World Message from received event %q", data.Msg)
// Respond with another event (optional)
// This is optional and is intended to show how to respond back with another event after processing.
// The response will go back into the knative eventing system just like any other event
newEvent := cloudevents.NewEvent()
newEvent.SetID(uuid.New().String())
newEvent.SetSource("knative/eventing/samples/hello-world")
newEvent.SetType("dev.knative.samples.hifromknative")
if err := newEvent.SetData(cloudevents.ApplicationJSON, HiFromKnative{Msg: "Hi from helloworld-go app!"}); err != nil {
return nil, cloudevents.NewHTTPResult(500, "failed to set response data: %s", err)
}
log.Printf("Responding with event\n%s\n", newEvent)
return &newEvent, nil
}
func main() {
log.Print("Hello world sample started.")
c, err := cloudevents.NewDefaultClient()
if err != nil {
log.Fatalf("failed to create client, %v", err)
}
log.Fatal(c.StartReceiver(context.Background(), receive))
}
```
1. Create a new file named `eventschemas.go` and paste the following code. This 1. Create a new file named `eventschemas.go` and paste the following code. This
defines the data schema of the CloudEvents. defines the data schema of the CloudEvents.
```go ```go
package main package main
// HelloWorld defines the Data of CloudEvent with type=dev.knative.samples.helloworld // HelloWorld defines the Data of CloudEvent with type=dev.knative.samples.helloworld
type HelloWorld struct { type HelloWorld struct {
// Msg holds the message from the event // Msg holds the message from the event
Msg string `json:"msg,omitempty,string"` Msg string `json:"msg,omitempty,string"`
} }
// HiFromKnative defines the Data of CloudEvent with type=dev.knative.samples.hifromknative // HiFromKnative defines the Data of CloudEvent with type=dev.knative.samples.hifromknative
type HiFromKnative struct { type HiFromKnative struct {
// Msg holds the message from the event // Msg holds the message from the event
Msg string `json:"msg,omitempty,string"` Msg string `json:"msg,omitempty,string"`
} }
``` ```
1. In your project directory, create a file named `Dockerfile` and copy the following code 1. In your project directory, create a file named `Dockerfile` and copy the following code
block into it. For detailed instructions on dockerizing a Go app, see block into it. For detailed instructions on dockerizing a Go app, see
[Deploying Go servers with Docker](https://blog.golang.org/docker). [Deploying Go servers with Docker](https://blog.golang.org/docker).
```docker ```dockerfile
# Use the official Golang image to create a build artifact. # Use the official Golang image to create a build artifact.
# This is based on Debian and sets the GOPATH to /go. # This is based on Debian and sets the GOPATH to /go.
# https://hub.docker.com/_/golang # https://hub.docker.com/_/golang
FROM golang:1.14 as builder FROM golang:1.14 as builder
# Copy local code to the container image. # Copy local code to the container image.
WORKDIR /app WORKDIR /app
# Retrieve application dependencies using go modules. # Retrieve application dependencies using go modules.
# Allows container builds to reuse downloaded dependencies. # Allows container builds to reuse downloaded dependencies.
COPY go.* ./ COPY go.* ./
RUN go mod download RUN go mod download
# Copy local code to the container image. # Copy local code to the container image.
COPY . ./ COPY . ./
# Build the binary. # Build the binary.
# -mod=readonly ensures immutable go.mod and go.sum in container builds. # -mod=readonly ensures immutable go.mod and go.sum in container builds.
RUN CGO_ENABLED=0 GOOS=linux go build -mod=readonly -v -o helloworld RUN CGO_ENABLED=0 GOOS=linux go build -mod=readonly -v -o helloworld
# Use a Docker multi-stage build to create a lean production image. # Use a Docker multi-stage build to create a lean production image.
# https://docs.docker.com/develop/develop-images/multistage-build/#use-multi-stage-builds # https://docs.docker.com/develop/develop-images/multistage-build/#use-multi-stage-builds
FROM alpine:3 FROM alpine:3
RUN apk add --no-cache ca-certificates RUN apk add --no-cache ca-certificates
# Copy the binary to the production image from the builder stage. # Copy the binary to the production image from the builder stage.
COPY --from=builder /app/helloworld /helloworld COPY --from=builder /app/helloworld /helloworld
# Run the web service on container startup. # Run the web service on container startup.
CMD ["/helloworld"] CMD ["/helloworld"]
``` ```
1. Create a new file, `sample-app.yaml` and copy the following service 1. Create a new file, `sample-app.yaml` and copy the following service
definition into the file. Make sure to replace `{username}` with your Docker definition into the file. Make sure to replace `{username}` with your Docker
Hub username. Hub username.
```yaml ```yaml
# Namespace for sample application # Namespace for sample application
apiVersion: v1 apiVersion: v1
kind: Namespace kind: Namespace
metadata: metadata:
name: knative-samples name: knative-samples
--- ---
# A default broker # A default broker
apiVersion: eventing.knative.dev/v1 apiVersion: eventing.knative.dev/v1
kind: Broker kind: Broker
metadata: metadata:
name: default name: default
namespace: knative-samples namespace: knative-samples
annotations: annotations:
# Note: you can set the eventing.knative.dev/broker.class annotation to change the class of the broker. # Note: you can set the eventing.knative.dev/broker.class annotation to change the class of the broker.
# The default broker class is MTChannelBasedBroker, but Knative also supports use of the other class. # The default broker class is MTChannelBasedBroker, but Knative also supports use of the other class.
eventing.knative.dev/broker.class: MTChannelBasedBroker eventing.knative.dev/broker.class: MTChannelBasedBroker
spec: {} spec: {}
--- ---
# Helloworld-go app deployment # Helloworld-go app deployment
apiVersion: apps/v1 apiVersion: apps/v1
kind: Deployment kind: Deployment
metadata: metadata:
name: helloworld-go name: helloworld-go
namespace: knative-samples namespace: knative-samples
spec: spec:
replicas: 1 replicas: 1
selector: selector:
matchLabels: &labels matchLabels: &labels
app: helloworld-go app: helloworld-go
template: template:
metadata: metadata:
labels: *labels labels: *labels
spec: spec:
containers: containers:
- name: helloworld-go - name: helloworld-go
image: docker.io/{username}/helloworld-go image: docker.io/{username}/helloworld-go
--- ---
# Service that exposes helloworld-go app. # Service that exposes helloworld-go app.
# This will be the subscriber for the Trigger # This will be the subscriber for the Trigger
kind: Service kind: Service
apiVersion: v1 apiVersion: v1
metadata: metadata:
name: helloworld-go name: helloworld-go
namespace: knative-samples namespace: knative-samples
spec: spec:
selector: selector:
app: helloworld-go app: helloworld-go
ports: ports:
- protocol: TCP - protocol: TCP
port: 80 port: 80
targetPort: 8080 targetPort: 8080
--- ---
# Knative Eventing Trigger to trigger the helloworld-go service # Knative Eventing Trigger to trigger the helloworld-go service
apiVersion: eventing.knative.dev/v1 apiVersion: eventing.knative.dev/v1
kind: Trigger kind: Trigger
metadata: metadata:
name: helloworld-go name: helloworld-go
namespace: knative-samples namespace: knative-samples
spec: spec:
broker: default broker: default
filter: filter:
attributes: attributes:
type: dev.knative.samples.helloworld type: dev.knative.samples.helloworld
source: dev.knative.samples/helloworldsource source: dev.knative.samples/helloworldsource
subscriber: subscriber:
ref: ref:
apiVersion: v1 apiVersion: v1
kind: Service kind: Service
name: helloworld-go name: helloworld-go
``` ```
1. Use the go tool to create a 1. Use the go tool to create a
[`go.mod`](https://github.com/golang/go/wiki/Modules#gomod) manifest. [`go.mod`](https://github.com/golang/go/wiki/Modules#gomod) manifest.
```bash ```bash
go mod init github.com/knative/docs/code-samples/serving/hello-world/helloworld-go go mod init github.com/knative/docs/code-samples/serving/hello-world/helloworld-go
``` ```
## Building and deploying the sample ## Building and deploying the sample
@ -226,49 +228,49 @@ folder) you're ready to build and deploy the sample app.
Docker Hub, run these commands replacing `{username}` with your Docker Hub Docker Hub, run these commands replacing `{username}` with your Docker Hub
username: username:
```bash ```bash
# Build the container on your local machine # Build the container on your local machine
docker build -t {username}/helloworld-go . docker build -t {username}/helloworld-go .
# Push the container to docker registry # Push the container to docker registry
docker push {username}/helloworld-go docker push {username}/helloworld-go
``` ```
1. After the build has completed and the container is pushed to docker hub, you 1. After the build has completed and the container is pushed to docker hub, you
can deploy the sample application into your cluster. Ensure that the can deploy the sample application into your cluster. Ensure that the
container image value in `sample-app.yaml` matches the container you built in container image value in `sample-app.yaml` matches the container you built in
the previous step. Apply the configuration by running the following command: the previous step. Apply the configuration by running the following command:
```bash ```bash
kubectl apply --filename sample-app.yaml kubectl apply --filename sample-app.yaml
``` ```
1. Verify that the command created the namespace `knative-samples` and a default Broker by running the command: 1. Verify that the command created the namespace `knative-samples` and a default Broker by running the command:
```bash ```bash
kubectl get broker --namespace knative-samples kubectl get broker --namespace knative-samples
``` ```
**Note:** you can also use injection based on labels with the **Note:** you can also use injection based on labels with the
Eventing sugar controller. Eventing sugar controller.
For how to install the Eventing sugar controller, see For how to install the Eventing sugar controller, see
[Install optional Eventing extensions](https://knative.dev/docs/install/eventing/install-eventing-with-yaml/#install-optional-eventing-extensions). [Install optional Eventing extensions](https://knative.dev/docs/install/eventing/install-eventing-with-yaml/#install-optional-eventing-extensions).
1. It deployed the helloworld-go app as a K8s Deployment and created a K8s 1. It deployed the helloworld-go app as a K8s Deployment and created a K8s
service names helloworld-go. Verify using the following command. service names helloworld-go. Verify using the following command.
```bash ```bash
kubectl --namespace knative-samples get deployments helloworld-go kubectl --namespace knative-samples get deployments helloworld-go
kubectl --namespace knative-samples get svc helloworld-go kubectl --namespace knative-samples get svc helloworld-go
``` ```
1. It created a Knative Eventing Trigger to route certain events to the 1. It created a Knative Eventing Trigger to route certain events to the
helloworld-go application. Make sure that Ready=true helloworld-go application. Make sure that Ready=true
```bash ```bash
kubectl --namespace knative-samples get trigger helloworld-go kubectl --namespace knative-samples get trigger helloworld-go
``` ```
## Send and verify CloudEvents ## Send and verify CloudEvents
@ -282,30 +284,30 @@ with correct CloudEvent headers set.
1. Deploy a curl pod and SSH into it 1. Deploy a curl pod and SSH into it
```bash ```bash
kubectl -n knative-samples run curl --image=radial/busyboxplus:curl -it kubectl -n knative-samples run curl --image=radial/busyboxplus:curl -it
``` ```
1. Get the Broker URL 1. Get the Broker URL
```bash ```bash
kubectl -n knative-samples get broker default kubectl -n knative-samples get broker default
``` ```
1. Run the following in the SSH terminal. Please replace the URL with the URL of 1. Run the following in the SSH terminal. Please replace the URL with the URL of
the default broker. the default broker.
```bash ```bash
curl -v "http://broker-ingress.knative-eventing.svc.cluster.local/knative-samples/default" \ curl -v "http://broker-ingress.knative-eventing.svc.cluster.local/knative-samples/default" \
-X POST \ -X POST \
-H "Ce-Id: 536808d3-88be-4077-9d7a-a3f162705f79" \ -H "Ce-Id: 536808d3-88be-4077-9d7a-a3f162705f79" \
-H "Ce-Specversion: 1.0" \ -H "Ce-Specversion: 1.0" \
-H "Ce-Type: dev.knative.samples.helloworld" \ -H "Ce-Type: dev.knative.samples.helloworld" \
-H "Ce-Source: dev.knative.samples/helloworldsource" \ -H "Ce-Source: dev.knative.samples/helloworldsource" \
-H "Content-Type: application/json" \ -H "Content-Type: application/json" \
-d '{"msg":"Hello World from the curl pod."}' -d '{"msg":"Hello World from the curl pod."}'
exit exit
``` ```
### Verify that event is received by helloworld-go app ### Verify that event is received by helloworld-go app
@ -361,84 +363,86 @@ Play around with the CloudEvent attributes in the curl command and the trigger s
mesh via the Broker and can be delivered to other services using a Trigger mesh via the Broker and can be delivered to other services using a Trigger
1. Using the following example, create a YAML file for a Pod that receives any 1. Using the following example, create a YAML file for a Pod that receives any
CloudEvent and logs the event to its output: CloudEvent and logs the event to its output:
```yaml ```yaml
# event-display app deployment # event-display app deployment
apiVersion: apps/v1 apiVersion: apps/v1
kind: Deployment kind: Deployment
metadata: metadata:
name: event-display name: event-display
namespace: knative-samples namespace: knative-samples
spec: spec:
replicas: 1 replicas: 1
selector: selector:
matchLabels: &labels matchLabels: &labels
app: event-display app: event-display
template: template:
metadata:
labels: *labels
spec:
containers:
- name: helloworld-go
# Source code: https://github.com/knative/eventing/tree/main/cmd/event_display
image: gcr.io/knative-releases/knative.dev/eventing/cmd/event_display
---
# Service that exposes event-display app.
# This will be the subscriber for the Trigger
kind: Service
apiVersion: v1
metadata:
name: event-display
namespace: knative-samples
spec:
selector:
app: event-display
ports:
- protocol: TCP
port: 80
targetPort: 8080
```
1. Apply the YAML file by running the command:
```bash
kubectl apply -f <filename>.yaml
```
Where `<filename>` is the name of the file you created in the previous step.
1. Using the following example, create a YAML file for a trigger to deliver the event
to the `event-display` Service:
```yaml
apiVersion: eventing.knative.dev/v1
kind: Trigger
metadata: metadata:
name: event-display labels: *labels
namespace: knative-samples
spec: spec:
broker: default containers:
filter: - name: helloworld-go
attributes: # Source code: https://github.com/knative/eventing/tree/main/cmd/event_display
type: dev.knative.samples.hifromknative image: gcr.io/knative-releases/knative.dev/eventing/cmd/event_display
source: knative/eventing/samples/hello-world ---
subscriber: # Service that exposes event-display app.
ref: # This will be the subscriber for the Trigger
apiVersion: v1 kind: Service
kind: Service apiVersion: v1
name: event-display metadata:
``` name: event-display
namespace: knative-samples
spec:
selector:
app: event-display
ports:
- protocol: TCP
port: 80
targetPort: 8080
```
1. Apply the YAML file by running the command: 1. Apply the YAML file by running the command:
```bash ```bash
kubectl apply -f <filename>.yaml kubectl apply -f <filename>.yaml
``` ```
Where `<filename>` is the name of the file you created in the previous step. Where `<filename>` is the name of the file you created in the previous step.
1. [Send a CloudEvent to the Broker](#send-and-verify-cloudevents) 1. Using the following example, create a YAML file for a trigger to deliver the event
to the `event-display` Service:
1. Check the logs of `event-display` service: ```yaml
apiVersion: eventing.knative.dev/v1
kind: Trigger
metadata:
name: event-display
namespace: knative-samples
spec:
broker: default
filter:
attributes:
type: dev.knative.samples.hifromknative
source: knative/eventing/samples/hello-world
subscriber:
ref:
apiVersion: v1
kind: Service
name: event-display
```
1. Apply the YAML file by running the command:
```bash
kubectl apply -f <filename>.yaml
```
Where `<filename>` is the name of the file you created in the previous step.
1. [Send a CloudEvent to the Broker](#send-and-verify-cloudevents)
1. Check the logs of `event-display` service:
```bash ```bash
kubectl -n knative-samples logs -l app=event-display --tail=50 kubectl -n knative-samples logs -l app=event-display --tail=50