Me:
Is there a way to trigger another server to perform a task whenever content is pushed to main
in this repo?
Copilot:
Yes, you can trigger another server to perform a task whenever content is pushed to the main
branch in this repository by using a webhook. A webhook allows you to send HTTP POST requests to a specified URL when certain events occur in your GitHub repository.
Here’s how you can set up a webhook in your GitHub repository:
- Create a Webhook:
- Go to your repository on GitHub.
- Click on
Settings
. - In the left sidebar, click on
Webhooks
. - Click the
Add webhook
button. - In the
Payload URL
field, enter the URL of the server you want to notify. - Set the
Content type
toapplication/json
. - In the
Which events would you like to trigger this webhook?
section, selectJust the push event
. - Click the
Add webhook
button.
- Handle the Webhook on Your Server:
- On your server, set up an endpoint to receive the webhook payload.
- The payload will contain information about the push event, including the repository, the branch, and the commits.
Here’s an example of how you might handle the webhook in a Python Flask application:
In this example, the Flask application listens for POST requests at the /webhook
endpoint. When a push event to the main
branch is detected, it performs the specified task.
- Secure the Webhook:
- To ensure that the webhook requests are coming from GitHub, you can set up a secret token.
- In the webhook settings on GitHub, add a secret token.
- In your server code, verify the token in the request headers.
Here’s an example of how to verify the secret token in the Flask application:
In this example, the verify_signature
function checks the signature of the incoming request to ensure it matches the secret token. If the signature is invalid, the request is aborted with a 403 status code.