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
code creates a basic web server which listens on port 8080:
```go
import (
"context"
"log"
```go
import (
"context"
"log"
cloudevents "github.com/cloudevents/sdk-go/v2"
"github.com/google/uuid"
)
cloudevents "github.com/cloudevents/sdk-go/v2"
"github.com/google/uuid"
)
func receive(ctx context.Context, event cloudevents.Event)( * cloudevents.Event, cloudevents.Result) {
// 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) {
// 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 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))
}
```
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
defines the data schema of the CloudEvents.
```go
package main
```go
package main
// HelloWorld defines the Data of CloudEvent with type=dev.knative.samples.helloworld
type HelloWorld struct {
// Msg holds the message from the event
Msg string `json:"msg,omitempty,string"`
}
// HelloWorld defines the Data of CloudEvent with type=dev.knative.samples.helloworld
type HelloWorld struct {
// Msg holds the message from the event
Msg string `json:"msg,omitempty,string"`
}
// HiFromKnative defines the Data of CloudEvent with type=dev.knative.samples.hifromknative
type HiFromKnative struct {
// Msg holds the message from the event
Msg string `json:"msg,omitempty,string"`
}
```
// HiFromKnative defines the Data of CloudEvent with type=dev.knative.samples.hifromknative
type HiFromKnative struct {
// Msg holds the message from the event
Msg string `json:"msg,omitempty,string"`
}
```
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
[Deploying Go servers with Docker](https://blog.golang.org/docker).
```docker
# Use the official Golang image to create a build artifact.
# This is based on Debian and sets the GOPATH to /go.
# https://hub.docker.com/_/golang
FROM golang:1.14 as builder
```dockerfile
# Use the official Golang image to create a build artifact.
# This is based on Debian and sets the GOPATH to /go.
# https://hub.docker.com/_/golang
FROM golang:1.14 as builder
# Copy local code to the container image.
WORKDIR /app
# Copy local code to the container image.
WORKDIR /app
# Retrieve application dependencies using go modules.
# Allows container builds to reuse downloaded dependencies.
COPY go.* ./
RUN go mod download
# Retrieve application dependencies using go modules.
# Allows container builds to reuse downloaded dependencies.
COPY go.* ./
RUN go mod download
# Copy local code to the container image.
COPY . ./
# Copy local code to the container image.
COPY . ./
# Build the binary.
# -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
# Build the binary.
# -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
# 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
FROM alpine:3
RUN apk add --no-cache ca-certificates
# 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
FROM alpine:3
RUN apk add --no-cache ca-certificates
# Copy the binary to the production image from the builder stage.
COPY --from=builder /app/helloworld /helloworld
# Copy the binary to the production image from the builder stage.
COPY --from=builder /app/helloworld /helloworld
# Run the web service on container startup.
CMD ["/helloworld"]
```
# Run the web service on container startup.
CMD ["/helloworld"]
```
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
Hub username.
```yaml
# Namespace for sample application
apiVersion: v1
kind: Namespace
metadata:
name: knative-samples
---
# A default broker
apiVersion: eventing.knative.dev/v1
kind: Broker
metadata:
name: default
namespace: knative-samples
annotations:
# 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.
eventing.knative.dev/broker.class: MTChannelBasedBroker
spec: {}
---
# Helloworld-go app deployment
apiVersion: apps/v1
kind: Deployment
metadata:
name: helloworld-go
namespace: knative-samples
spec:
replicas: 1
selector:
matchLabels: &labels
app: helloworld-go
template:
metadata:
labels: *labels
spec:
containers:
- name: helloworld-go
image: docker.io/{username}/helloworld-go
```yaml
# Namespace for sample application
apiVersion: v1
kind: Namespace
metadata:
name: knative-samples
---
# A default broker
apiVersion: eventing.knative.dev/v1
kind: Broker
metadata:
name: default
namespace: knative-samples
annotations:
# 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.
eventing.knative.dev/broker.class: MTChannelBasedBroker
spec: {}
---
# Helloworld-go app deployment
apiVersion: apps/v1
kind: Deployment
metadata:
name: helloworld-go
namespace: knative-samples
spec:
replicas: 1
selector:
matchLabels: &labels
app: helloworld-go
template:
metadata:
labels: *labels
spec:
containers:
- name: helloworld-go
image: docker.io/{username}/helloworld-go
---
# Service that exposes helloworld-go app.
# This will be the subscriber for the Trigger
kind: Service
apiVersion: v1
metadata:
name: helloworld-go
namespace: knative-samples
spec:
selector:
app: helloworld-go
ports:
- protocol: TCP
port: 80
targetPort: 8080
---
# Knative Eventing Trigger to trigger the helloworld-go service
apiVersion: eventing.knative.dev/v1
kind: Trigger
metadata:
name: helloworld-go
namespace: knative-samples
spec:
broker: default
filter:
attributes:
type: dev.knative.samples.helloworld
source: dev.knative.samples/helloworldsource
subscriber:
ref:
apiVersion: v1
kind: Service
name: helloworld-go
```
---
# Service that exposes helloworld-go app.
# This will be the subscriber for the Trigger
kind: Service
apiVersion: v1
metadata:
name: helloworld-go
namespace: knative-samples
spec:
selector:
app: helloworld-go
ports:
- protocol: TCP
port: 80
targetPort: 8080
---
# Knative Eventing Trigger to trigger the helloworld-go service
apiVersion: eventing.knative.dev/v1
kind: Trigger
metadata:
name: helloworld-go
namespace: knative-samples
spec:
broker: default
filter:
attributes:
type: dev.knative.samples.helloworld
source: dev.knative.samples/helloworldsource
subscriber:
ref:
apiVersion: v1
kind: Service
name: helloworld-go
```
1. Use the go tool to create a
[`go.mod`](https://github.com/golang/go/wiki/Modules#gomod) manifest.
```bash
go mod init github.com/knative/docs/code-samples/serving/hello-world/helloworld-go
```
```bash
go mod init github.com/knative/docs/code-samples/serving/hello-world/helloworld-go
```
## 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
username:
```bash
# Build the container on your local machine
docker build -t {username}/helloworld-go .
```bash
# Build the container on your local machine
docker build -t {username}/helloworld-go .
# Push the container to docker registry
docker push {username}/helloworld-go
```
# Push the container to docker registry
docker push {username}/helloworld-go
```
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
container image value in `sample-app.yaml` matches the container you built in
the previous step. Apply the configuration by running the following command:
```bash
kubectl apply --filename sample-app.yaml
```
```bash
kubectl apply --filename sample-app.yaml
```
1. Verify that the command created the namespace `knative-samples` and a default Broker by running the command:
```bash
kubectl get broker --namespace knative-samples
```
```bash
kubectl get broker --namespace knative-samples
```
**Note:** you can also use injection based on labels with the
Eventing sugar controller.
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).
**Note:** you can also use injection based on labels with the
Eventing sugar controller.
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).
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
kubectl --namespace knative-samples get deployments helloworld-go
```bash
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
helloworld-go application. Make sure that Ready=true
helloworld-go application. Make sure that Ready=true
```bash
kubectl --namespace knative-samples get trigger helloworld-go
```
```bash
kubectl --namespace knative-samples get trigger helloworld-go
```
## Send and verify CloudEvents
@ -282,30 +284,30 @@ with correct CloudEvent headers set.
1. Deploy a curl pod and SSH into it
```bash
kubectl -n knative-samples run curl --image=radial/busyboxplus:curl -it
```
```bash
kubectl -n knative-samples run curl --image=radial/busyboxplus:curl -it
```
1. Get the Broker URL
```bash
kubectl -n knative-samples get broker default
```
```bash
kubectl -n knative-samples get broker default
```
1. Run the following in the SSH terminal. Please replace the URL with the URL of
the default broker.
```bash
curl -v "http://broker-ingress.knative-eventing.svc.cluster.local/knative-samples/default" \
-X POST \
-H "Ce-Id: 536808d3-88be-4077-9d7a-a3f162705f79" \
-H "Ce-Specversion: 1.0" \
-H "Ce-Type: dev.knative.samples.helloworld" \
-H "Ce-Source: dev.knative.samples/helloworldsource" \
-H "Content-Type: application/json" \
-d '{"msg":"Hello World from the curl pod."}'
exit
```
```bash
curl -v "http://broker-ingress.knative-eventing.svc.cluster.local/knative-samples/default" \
-X POST \
-H "Ce-Id: 536808d3-88be-4077-9d7a-a3f162705f79" \
-H "Ce-Specversion: 1.0" \
-H "Ce-Type: dev.knative.samples.helloworld" \
-H "Ce-Source: dev.knative.samples/helloworldsource" \
-H "Content-Type: application/json" \
-d '{"msg":"Hello World from the curl pod."}'
exit
```
### 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
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
# event-display app deployment
apiVersion: apps/v1
kind: Deployment
metadata:
name: event-display
namespace: knative-samples
spec:
replicas: 1
selector:
matchLabels: &labels
app: event-display
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
```yaml
# event-display app deployment
apiVersion: apps/v1
kind: Deployment
metadata:
name: event-display
namespace: knative-samples
spec:
replicas: 1
selector:
matchLabels: &labels
app: event-display
template:
metadata:
name: event-display
namespace: knative-samples
labels: *labels
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
```
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:
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. 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
kubectl -n knative-samples logs -l app=event-display --tail=50