From f45e21ecfda940abd1d0ea2aa30479462e18357e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ren=C3=A9?= Date: Mon, 25 Nov 2024 15:07:00 +0100 Subject: [PATCH 01/14] docusaurus preparations --- .github/scripts/sync_docs.sh | 52 +++++++++++ .github/scripts/sync_local.sh | 13 +++ .github/workflows/sync-docs.yml | 34 +++++++ README.md | 134 +++++++++++++++------------- aws-sam/README.md | 10 +-- docker-nginx-loadbalancer/README.md | 13 +-- 6 files changed, 181 insertions(+), 75 deletions(-) create mode 100755 .github/scripts/sync_docs.sh create mode 100755 .github/scripts/sync_local.sh create mode 100644 .github/workflows/sync-docs.yml diff --git a/.github/scripts/sync_docs.sh b/.github/scripts/sync_docs.sh new file mode 100755 index 0000000000..dbaf057e35 --- /dev/null +++ b/.github/scripts/sync_docs.sh @@ -0,0 +1,52 @@ +#!/usr/bin/env bash +set -e + +# Some env variables +BRANCH="main" +REPO_URL="github.com/gofiber/docs.git" +AUTHOR_EMAIL="github-actions[bot]@users.noreply.github.com" +AUTHOR_USERNAME="github-actions[bot]" +REPO_DIR="recipes" +COMMIT_URL="https://github.com/gofiber/recipes" + +# Set commit author +git config --global user.email "${AUTHOR_EMAIL}" +git config --global user.name "${AUTHOR_USERNAME}" + +git clone https://${TOKEN}@${REPO_URL} fiber-docs + +latest_commit=$(git rev-parse --short HEAD) + +for f in $(find -E . -type f -iregex '.*\.(md|png|jpe?g|gif|bmp|svg|webp)$' -not -path "./(fiberDocs)/*" -not -path "*/vendor/*" -not -path "*/.github/*" -not -path "*/.*"); do + log_output=$(git log --oneline "${BRANCH}" HEAD~1..HEAD --name-status -- "${f}") + + if [[ $log_output != "" || ! -f "fiber-docs/docs/${REPO_DIR}/$f" ]]; then + mkdir -p fiber-docs/docs/${REPO_DIR}/$(dirname $f) + cp "${f}" fiber-docs/docs/${REPO_DIR}/$f + fi +done + + +# Push changes +cd fiber-docs/ || true +git add . + +git commit -m "Add docs from ${COMMIT_URL}/commit/${latest_commit}" + +MAX_RETRIES=5 +DELAY=5 +retry=0 + +while ((retry < MAX_RETRIES)) +do + git push https://${TOKEN}@${REPO_URL} && break + retry=$((retry + 1)) + git pull --rebase + sleep $DELAY +done + +if ((retry == MAX_RETRIES)) +then + echo "Failed to push after $MAX_RETRIES attempts. Exiting with 1." + exit 1 +fi diff --git a/.github/scripts/sync_local.sh b/.github/scripts/sync_local.sh new file mode 100755 index 0000000000..fbc3256133 --- /dev/null +++ b/.github/scripts/sync_local.sh @@ -0,0 +1,13 @@ +#!/usr/bin/env bash +set -e + +REPO_DIR="recipes" + +# determine root repo directory +ROOT=$(cd "$(dirname "$0")/.." && dirname "$(pwd -P)") + +for f in $(find -E . -type f -iregex '.*\.(md|png|jpe?g|gif|bmp|svg|webp)$' -not -path "./(fiberDocs)/*" -not -path "*/vendor/*" -not -path "*/.github/*" -not -path "*/.*"); do + echo "Copying $f" + mkdir -p $ROOT/../fiberDocs/docs/${REPO_DIR}/$(dirname $f) + cp "${f}" $ROOT/../fiberDocs/docs/${REPO_DIR}/$f +done diff --git a/.github/workflows/sync-docs.yml b/.github/workflows/sync-docs.yml new file mode 100644 index 0000000000..4c683e2a52 --- /dev/null +++ b/.github/workflows/sync-docs.yml @@ -0,0 +1,34 @@ +name: 'Sync docs' + +on: + push: + branches: + - master + - main + paths: + - '**/*.md' + +jobs: + sync-docs: + runs-on: ubuntu-latest + steps: + - name: Checkout + uses: actions/checkout@v4 + with: + ref: ${{ github.event.pull_request.head.sha }} + fetch-depth: 2 + + - name: Setup Node.js environment + uses: actions/setup-node@v4 + with: + node-version: '18' + + - name: Install JQ + run: sudo apt-get install jq + + - name: Sync docs + run: ./.github/scripts/sync_docs.sh + env: + EVENT: ${{ github.event_name }} + TAG_NAME: ${{ github.ref_name }} + TOKEN: ${{ secrets.DOC_SYNC_TOKEN }} diff --git a/README.md b/README.md index 1d5fda0dd6..f39f2ecae3 100644 --- a/README.md +++ b/README.md @@ -1,3 +1,9 @@ +--- +id: welcome +title: 👋 Overview +sidebar_position: 1 +--- + # 🍳 Examples for [Fiber](https://github.com/gofiber/fiber) **Welcome to the official Fiber cookbook**! @@ -6,72 +12,72 @@ Here you can find the most **delicious** recipes to cook delicious meals using o ## 🌽 Table of contents -- [Amazon Web Services (AWS) Elastic Beanstalk](/aws-eb) -- [AWS SAM](/aws-sam) -- [Certificates from Let's Encrypt](/autocert) -- [Clean Architecture](/clean-architecture) -- [Cloud Run](/cloud-run) -- [Colly Scraping using Fiber and PostgreSQL](/fiber-colly-gorm) -- [CSRF-with-Session](/csrf-with-session) -- [CSRF](/csrf) -- [Custom 404 Not Found](/404-handler) -- [Dependency Injection (with Parsley)](/parsley) -- [Docker MariaDB Clean Architecture](/docker-mariadb-clean-arch) -- [Docker Nginx Loadbalancer](/docker-nginx-loadbalancer) -- [Docker Postgres-JWT](/auth-docker-postgres-jwt) -- [DummyJson](/dummyjson/) -- [Enable HTTPS/TLS using PKCS12 store](/https-pkcs12-tls) -- [Enable HTTPS/TLS](/https-tls) -- [Enable Preforking](/prefork) -- [Ent Mysql Example](/ent-mysql) -- [Entgo Sveltekit](/entgo-sveltekit) -- [Firebase Functions](/firebase-functions) -- [GeoIP (with MaxMind databases)](/geoip-maxmind) -- [GeoIP](/geoip) -- [GORM Mysql Example](/gorm-mysql) -- [GORM](/gorm) -- [Graceful shutdown](/graceful-shutdown) -- [GraphQL](/graphql) -- [Hello, World!](/hello-world) -- [Heroku App](/heroku) -- [Hexagonal Architecture](/hexagonal) -- [i18n](/i18n) -- [JWT](/jwt) -- [Kubernetes](/k8s) -- [Listen on Multiple Ports](/multiple-ports) -- [Live Reloading (Air)](/air) -- [Memgraph](/memgraph) -- [MinIO](/minio) -- [MongoDB](/mongodb) -- [MVC Application Bootstrap](/fiber-bootstrap) +- [Amazon Web Services (AWS) Elastic Beanstalk](./aws-eb) +- [AWS SAM](./aws-sam) +- [Certificates from Let's Encrypt](./autocert) +- [Clean Architecture](./clean-architecture) +- [Cloud Run](./cloud-run) +- [Colly Scraping using Fiber and PostgreSQL](./fiber-colly-gorm) +- [CSRF-with-Session](./csrf-with-session) +- [CSRF](./csrf) +- [Custom 404 Not Found](./404-handler) +- [Dependency Injection (with Parsley)](./parsley) +- [Docker MariaDB Clean Architecture](./docker-mariadb-clean-arch) +- [Docker Nginx Loadbalancer](./docker-nginx-loadbalancer) +- [Docker Postgres-JWT](./auth-docker-postgres-jwt) +- [DummyJson](./dummyjson/) +- [Enable HTTPS/TLS using PKCS12 store](./https-pkcs12-tls) +- [Enable HTTPS/TLS](./https-tls) +- [Enable Preforking](./prefork) +- [Ent Mysql Example](./ent-mysql) +- [Entgo Sveltekit](./entgo-sveltekit) +- [Firebase Functions](./firebase-functions) +- [GeoIP (with MaxMind databases)](./geoip-maxmind) +- [GeoIP](./geoip) +- [GORM Mysql Example](./gorm-mysql) +- [GORM](./gorm) +- [Graceful shutdown](./graceful-shutdown) +- [GraphQL](./graphql) +- [Hello, World!](./hello-world) +- [Heroku App](./heroku) +- [Hexagonal Architecture](./hexagonal) +- [i18n](./i18n) +- [JWT](./jwt) +- [Kubernetes](./k8s) +- [Listen on Multiple Ports](./multiple-ports) +- [Live Reloading (Air)](./air) +- [Memgraph](./memgraph) +- [MinIO](./minio) +- [MongoDB](./mongodb) +- [MVC Application Bootstrap](./fiber-bootstrap) - [Netlify Functions](fiber-svelte-netlify) -- [OAuth2 Google](/oauth2-google) -- [PostgreSQL](/postgresql) +- [OAuth2 Google](./oauth2-google) +- [PostgreSQL](./postgresql) - [RabbitMQ](rabbitmq) -- [React Router](/react-router) -- [Recover from panic](/recover) -- [RSS feed](/rss-feed) -- [Serve Static Files](/file-server) -- [Server Timing](/server-timing) -- [Server-Sent Events](/sse) -- [Sessions-SQLite3](/sessions-sqlite3) -- [Single Page Application Example](/spa) -- [Socket.io](/socketio) -- [Sqlboiler](/sqlboiler) -- [Sqlc](/sqlc) -- [Streaming of the Request Body](/stream-request-body) -- [Sveltekit Embed](/sveltekit-embed) -- [Tableflip (Graceful updates)](/tableflip) -- [Template Asset Bundling](/template-asset-bundling) -- [Unit Test Example](/unit-test) -- [Upload Multiple Files](/upload-file/multiple) -- [Upload Single File](/upload-file/single) -- [URL shortener API](/url-shortener-api) -- [User Auth with JWT](/auth-jwt) -- [Validation](/validation) -- [Vercel](/vercel) -- [WebSocket Chat Example](/websocket-chat) -- [WebSockets](/websocket) +- [React Router](./react-router) +- [Recover from panic](./recover) +- [RSS feed](./rss-feed) +- [Serve Static Files](./file-server) +- [Server Timing](./server-timing) +- [Server-Sent Events](./sse) +- [Sessions-SQLite3](./sessions-sqlite3) +- [Single Page Application Example](./spa) +- [Socket.io](./socketio) +- [Sqlboiler](./sqlboiler) +- [Sqlc](./sqlc) +- [Streaming of the Request Body](./stream-request-body) +- [Sveltekit Embed](./sveltekit-embed) +- [Tableflip (Graceful updates)](./tableflip) +- [Template Asset Bundling](./template-asset-bundling) +- [Unit Test Example](./unit-test) +- [Upload Multiple Files](./upload-file/multiple) +- [Upload Single File](./upload-file/single) +- [URL shortener API](./url-shortener-api) +- [User Auth with JWT](./auth-jwt) +- [Validation](./validation) +- [Vercel](./vercel) +- [WebSocket Chat Example](./websocket-chat) +- [WebSockets](./websocket) ## 👩‍🍳 Have a delicious recipe? diff --git a/aws-sam/README.md b/aws-sam/README.md index 331b2ef091..7f4fd36c53 100644 --- a/aws-sam/README.md +++ b/aws-sam/README.md @@ -19,10 +19,10 @@ This is a sample template for sam-app - Below is a brief explanation of what we ## Setup process -### Installing dependencies & building the target +### Installing dependencies & building the target -In this example we use the built-in `sam build` to automatically download all the dependencies and package our build target. -Read more about [SAM Build here](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/sam-cli-command-reference-sam-build.html) +In this example we use the built-in `sam build` to automatically download all the dependencies and package our build target. +Read more about [SAM Build here](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/sam-cli-command-reference-sam-build.html) ```shell sam build --use-container @@ -35,7 +35,7 @@ sam build --use-container ```bash sam local start-api -curl -XPOST "http://localhost:3001/2015-03-31/functions/sam-app/invocations" +curl -XPOST "http://localhost:3001/2015-03-31/functions/sam-app/invocations" {"statusCode":200,"headers":null,"multiValueHeaders":{"Content-Type":["application/json"]},"body":"{\"message\":\"Hello World\"}"}% ``` @@ -138,7 +138,7 @@ choco upgrade golang Here are a few ideas that you can use to get more acquainted as to how this overall process works: -* Create an additional API resource (e.g. /hello/{proxy+}) and return the name requested through this new path +* Create an additional API resource (e.g. `/hello/{proxy+}`) and return the name requested through this new path * Update unit test to capture that * Package & Deploy diff --git a/docker-nginx-loadbalancer/README.md b/docker-nginx-loadbalancer/README.md index a7d83e0bae..5a181e0f1a 100644 --- a/docker-nginx-loadbalancer/README.md +++ b/docker-nginx-loadbalancer/README.md @@ -1,10 +1,11 @@ # Docker+Nginx 🚀 - - - - Fiber - - + + + + + Fiber + + ## Features From fa871a34a67eaf4b11fd6746620b7e99f0e738ec Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ren=C3=A9?= Date: Tue, 26 Nov 2024 10:30:35 +0100 Subject: [PATCH 02/14] docusaurus preparations --- .github/scripts/sync_docs.sh | 3 +++ .github/scripts/sync_local.sh | 3 +++ 404-handler/README.md | 5 +++++ README.md | 2 +- air/README.md | 5 +++++ auth-docker-postgres-jwt/README.md | 5 +++++ auth-jwt/README.md | 5 +++++ autocert/README.md | 5 +++++ aws-eb/README.md | 5 +++++ aws-sam-container/README.md | 15 ++++++++++----- aws-sam/README.md | 7 ++++++- {fiber-bootstrap => bootstrap}/.env.example | 0 {fiber-bootstrap => bootstrap}/.gitignore | 0 {fiber-bootstrap => bootstrap}/README.md | 17 +++++++++++------ .../app/controllers/main_controller.go | 0 .../app/models/user.go | 0 .../bootstrap/bootstrap.go | 0 {fiber-bootstrap => bootstrap}/go.mod | 0 {fiber-bootstrap => bootstrap}/go.sum | 0 {fiber-bootstrap => bootstrap}/main.go | 0 .../pkg/database/database.go | 0 .../pkg/database/setup.go | 0 {fiber-bootstrap => bootstrap}/pkg/env/env.go | 0 .../pkg/router/api_router.go | 0 .../pkg/router/http_router.go | 0 .../pkg/router/router_interface.go | 0 .../pkg/router/setup.go | 0 {fiber-bootstrap => bootstrap}/views/index.html | 0 clean-architecture/README.md | 5 +++++ cloud-run/README.md | 5 +++++ csrf-with-session/README.md | 7 ++++++- csrf/README.md | 5 +++++ docker-mariadb-clean-arch/README.md | 5 +++++ docker-nginx-loadbalancer/README.md | 13 +++++-------- dummyjson/README.md | 9 +++++++-- ent-mysql/README.md | 11 ++++++++--- entgo-sveltekit/README.md | 5 +++++ 37 files changed, 115 insertions(+), 27 deletions(-) rename {fiber-bootstrap => bootstrap}/.env.example (100%) rename {fiber-bootstrap => bootstrap}/.gitignore (100%) rename {fiber-bootstrap => bootstrap}/README.md (67%) rename {fiber-bootstrap => bootstrap}/app/controllers/main_controller.go (100%) rename {fiber-bootstrap => bootstrap}/app/models/user.go (100%) rename {fiber-bootstrap => bootstrap}/bootstrap/bootstrap.go (100%) rename {fiber-bootstrap => bootstrap}/go.mod (100%) rename {fiber-bootstrap => bootstrap}/go.sum (100%) rename {fiber-bootstrap => bootstrap}/main.go (100%) rename {fiber-bootstrap => bootstrap}/pkg/database/database.go (100%) rename {fiber-bootstrap => bootstrap}/pkg/database/setup.go (100%) rename {fiber-bootstrap => bootstrap}/pkg/env/env.go (100%) rename {fiber-bootstrap => bootstrap}/pkg/router/api_router.go (100%) rename {fiber-bootstrap => bootstrap}/pkg/router/http_router.go (100%) rename {fiber-bootstrap => bootstrap}/pkg/router/router_interface.go (100%) rename {fiber-bootstrap => bootstrap}/pkg/router/setup.go (100%) rename {fiber-bootstrap => bootstrap}/views/index.html (100%) diff --git a/.github/scripts/sync_docs.sh b/.github/scripts/sync_docs.sh index dbaf057e35..d01d958995 100755 --- a/.github/scripts/sync_docs.sh +++ b/.github/scripts/sync_docs.sh @@ -17,6 +17,9 @@ git clone https://${TOKEN}@${REPO_URL} fiber-docs latest_commit=$(git rev-parse --short HEAD) +# remove all files in the docs directory +rm -rf $ROOT/../fiberDocs/docs/${REPO_DIR}/* + for f in $(find -E . -type f -iregex '.*\.(md|png|jpe?g|gif|bmp|svg|webp)$' -not -path "./(fiberDocs)/*" -not -path "*/vendor/*" -not -path "*/.github/*" -not -path "*/.*"); do log_output=$(git log --oneline "${BRANCH}" HEAD~1..HEAD --name-status -- "${f}") diff --git a/.github/scripts/sync_local.sh b/.github/scripts/sync_local.sh index fbc3256133..fd3f401497 100755 --- a/.github/scripts/sync_local.sh +++ b/.github/scripts/sync_local.sh @@ -6,6 +6,9 @@ REPO_DIR="recipes" # determine root repo directory ROOT=$(cd "$(dirname "$0")/.." && dirname "$(pwd -P)") +# remove all files in the docs directory +rm -rf $ROOT/../fiberDocs/docs/${REPO_DIR}/* + for f in $(find -E . -type f -iregex '.*\.(md|png|jpe?g|gif|bmp|svg|webp)$' -not -path "./(fiberDocs)/*" -not -path "*/vendor/*" -not -path "*/.github/*" -not -path "*/.*"); do echo "Copying $f" mkdir -p $ROOT/../fiberDocs/docs/${REPO_DIR}/$(dirname $f) diff --git a/404-handler/README.md b/404-handler/README.md index e46e7ec61c..6969b5a1ce 100644 --- a/404-handler/README.md +++ b/404-handler/README.md @@ -1,3 +1,8 @@ +--- +title: 404 Handler +keywords: [404, not found, handler, errorhandler, custom] +--- + # Custom 404 Not Found Handler Example This example demonstrates how to implement a custom 404 Not Found handler using the [Fiber](https://gofiber.io) web framework in Go. The purpose of this example is to show how to handle requests to undefined routes gracefully by returning a 404 status code. diff --git a/README.md b/README.md index f39f2ecae3..9acbfba98a 100644 --- a/README.md +++ b/README.md @@ -49,7 +49,7 @@ Here you can find the most **delicious** recipes to cook delicious meals using o - [Memgraph](./memgraph) - [MinIO](./minio) - [MongoDB](./mongodb) -- [MVC Application Bootstrap](./fiber-bootstrap) +- [MVC Application Bootstrap](./bootstrap) - [Netlify Functions](fiber-svelte-netlify) - [OAuth2 Google](./oauth2-google) - [PostgreSQL](./postgresql) diff --git a/air/README.md b/air/README.md index fc0411d15a..eaf11a69b8 100644 --- a/air/README.md +++ b/air/README.md @@ -1,3 +1,8 @@ +--- +title: Air Live Reloading +keywords: [air, live reloading, development, air tool, hot reload, watch, changes] +--- + # Live Reloading with Air Example This example demonstrates how to set up live reloading for a Go application using the [Air](https://github.com/cosmtrek/air) tool. The purpose of this example is to show how to automatically reload your application during development whenever you make changes to the source code. diff --git a/auth-docker-postgres-jwt/README.md b/auth-docker-postgres-jwt/README.md index 6027a0d796..c105c02642 100644 --- a/auth-docker-postgres-jwt/README.md +++ b/auth-docker-postgres-jwt/README.md @@ -1,3 +1,8 @@ +--- +title: Auth + Docker + Postgres + JWT +keywords: [auth, docker, postgres, jwt] +--- + # Auth Docker Postgres JWT Example This example demonstrates a boilerplate setup for a Go Fiber application that uses Docker, PostgreSQL, and JWT for authentication. diff --git a/auth-jwt/README.md b/auth-jwt/README.md index 4be19a3e94..eff05e3199 100644 --- a/auth-jwt/README.md +++ b/auth-jwt/README.md @@ -1,3 +1,8 @@ +--- +title: Auth + JWT +keywords: [auth, jwt, gorm, fiber] +--- + # Auth JWT Example This example demonstrates a boilerplate setup for a Go Fiber application that uses JWT for authentication. diff --git a/autocert/README.md b/autocert/README.md index b2f2dec5da..2a3eab5613 100644 --- a/autocert/README.md +++ b/autocert/README.md @@ -1,3 +1,8 @@ +--- +title: Autocert +keywords: [autocert, tls, letsencrypt, ssl, https] +--- + # Autocert Example This example demonstrates how to set up a secure Go Fiber application using Let's Encrypt for automatic TLS certificate management with `autocert`. diff --git a/aws-eb/README.md b/aws-eb/README.md index 5fb8e770b8..a890d8886d 100644 --- a/aws-eb/README.md +++ b/aws-eb/README.md @@ -1,3 +1,8 @@ +--- +title: AWS Elastic Beanstalk +keywords: [aws, elastic beanstalk, deploy, amazon, aws-eb] +--- + # AWS Elastic Beanstalk Example This example demonstrates how to deploy a Go Fiber application to AWS Elastic Beanstalk. diff --git a/aws-sam-container/README.md b/aws-sam-container/README.md index 4d71597025..60df9a1a2b 100644 --- a/aws-sam-container/README.md +++ b/aws-sam-container/README.md @@ -1,4 +1,9 @@ -# app +--- +title: "AWS SAM Container" +keywords: [aws, sam, serverless, lambda, container] +--- + +# AWS SAM Container This is a sample template for app - Below is a brief explanation of what we have generated for you: @@ -28,10 +33,10 @@ You may need the following for local testing. ## Setup process -### Installing dependencies & building the target +### Installing dependencies & building the target -In this example we use the built-in `sam build` to build a docker image from a Dockerfile and then copy the source of your application inside the Docker image. -Read more about [SAM Build here](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/sam-cli-command-reference-sam-build.html) +In this example we use the built-in `sam build` to build a docker image from a Dockerfile and then copy the source of your application inside the Docker image. +Read more about [SAM Build here](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/sam-cli-command-reference-sam-build.html) ### Local development @@ -120,4 +125,4 @@ If it's already installed, run the following command to ensure it's the latest v ```shell choco upgrade golang -``` \ No newline at end of file +``` diff --git a/aws-sam/README.md b/aws-sam/README.md index 7f4fd36c53..36b0b6e0a3 100644 --- a/aws-sam/README.md +++ b/aws-sam/README.md @@ -1,4 +1,9 @@ -# sam-app +--- +title: AWS SAM +keywords: [aws, sam, serverless, lambda] +--- + +# AWS SAM This is a sample template for sam-app - Below is a brief explanation of what we have generated for you: diff --git a/fiber-bootstrap/.env.example b/bootstrap/.env.example similarity index 100% rename from fiber-bootstrap/.env.example rename to bootstrap/.env.example diff --git a/fiber-bootstrap/.gitignore b/bootstrap/.gitignore similarity index 100% rename from fiber-bootstrap/.gitignore rename to bootstrap/.gitignore diff --git a/fiber-bootstrap/README.md b/bootstrap/README.md similarity index 67% rename from fiber-bootstrap/README.md rename to bootstrap/README.md index 096ca12005..54dea15481 100644 --- a/fiber-bootstrap/README.md +++ b/bootstrap/README.md @@ -1,4 +1,9 @@ -# Fiber Bootstrap +--- +title: Bootstrap +keywords: [bootstrap, gorm, validator, env] +--- + +# Bootstrap Fiber bootstrap for rapid development using Go-Fiber / Gorm / Validator. # Components @@ -8,12 +13,12 @@ Fiber bootstrap for rapid development using Go-Fiber / Gorm / Validator. * Monitoring * Gorm * PGSQL Driver -* Validator +* Validator * Env File -# Router -API Router `/api` with rate limiter middleware -Http Router `/` with CORS and CSRF middleware +# Router +API Router `/api` with rate limiter middleware +Http Router `/` with CORS and CSRF middleware # Setup @@ -28,4 +33,4 @@ Http Router `/` with CORS and CSRF middleware ``` go run main.go ``` -Your api should be running at `http://localhost:4000/` if the port is in use you may modify it in the `.env` you just created. \ No newline at end of file +Your api should be running at `http://localhost:4000/` if the port is in use you may modify it in the `.env` you just created. diff --git a/fiber-bootstrap/app/controllers/main_controller.go b/bootstrap/app/controllers/main_controller.go similarity index 100% rename from fiber-bootstrap/app/controllers/main_controller.go rename to bootstrap/app/controllers/main_controller.go diff --git a/fiber-bootstrap/app/models/user.go b/bootstrap/app/models/user.go similarity index 100% rename from fiber-bootstrap/app/models/user.go rename to bootstrap/app/models/user.go diff --git a/fiber-bootstrap/bootstrap/bootstrap.go b/bootstrap/bootstrap/bootstrap.go similarity index 100% rename from fiber-bootstrap/bootstrap/bootstrap.go rename to bootstrap/bootstrap/bootstrap.go diff --git a/fiber-bootstrap/go.mod b/bootstrap/go.mod similarity index 100% rename from fiber-bootstrap/go.mod rename to bootstrap/go.mod diff --git a/fiber-bootstrap/go.sum b/bootstrap/go.sum similarity index 100% rename from fiber-bootstrap/go.sum rename to bootstrap/go.sum diff --git a/fiber-bootstrap/main.go b/bootstrap/main.go similarity index 100% rename from fiber-bootstrap/main.go rename to bootstrap/main.go diff --git a/fiber-bootstrap/pkg/database/database.go b/bootstrap/pkg/database/database.go similarity index 100% rename from fiber-bootstrap/pkg/database/database.go rename to bootstrap/pkg/database/database.go diff --git a/fiber-bootstrap/pkg/database/setup.go b/bootstrap/pkg/database/setup.go similarity index 100% rename from fiber-bootstrap/pkg/database/setup.go rename to bootstrap/pkg/database/setup.go diff --git a/fiber-bootstrap/pkg/env/env.go b/bootstrap/pkg/env/env.go similarity index 100% rename from fiber-bootstrap/pkg/env/env.go rename to bootstrap/pkg/env/env.go diff --git a/fiber-bootstrap/pkg/router/api_router.go b/bootstrap/pkg/router/api_router.go similarity index 100% rename from fiber-bootstrap/pkg/router/api_router.go rename to bootstrap/pkg/router/api_router.go diff --git a/fiber-bootstrap/pkg/router/http_router.go b/bootstrap/pkg/router/http_router.go similarity index 100% rename from fiber-bootstrap/pkg/router/http_router.go rename to bootstrap/pkg/router/http_router.go diff --git a/fiber-bootstrap/pkg/router/router_interface.go b/bootstrap/pkg/router/router_interface.go similarity index 100% rename from fiber-bootstrap/pkg/router/router_interface.go rename to bootstrap/pkg/router/router_interface.go diff --git a/fiber-bootstrap/pkg/router/setup.go b/bootstrap/pkg/router/setup.go similarity index 100% rename from fiber-bootstrap/pkg/router/setup.go rename to bootstrap/pkg/router/setup.go diff --git a/fiber-bootstrap/views/index.html b/bootstrap/views/index.html similarity index 100% rename from fiber-bootstrap/views/index.html rename to bootstrap/views/index.html diff --git a/clean-architecture/README.md b/clean-architecture/README.md index 18692b840e..7bd536f76a 100644 --- a/clean-architecture/README.md +++ b/clean-architecture/README.md @@ -1,3 +1,8 @@ +--- +title: Clean Architecture +keywords: [clean, architecture, fiber, mongodb, go] +--- + # Clean Architecture Example This example demonstrates a Go Fiber application following the principles of Clean Architecture. diff --git a/cloud-run/README.md b/cloud-run/README.md index 8461d15e44..36593231e0 100644 --- a/cloud-run/README.md +++ b/cloud-run/README.md @@ -1,3 +1,8 @@ +--- +title: Cloud Run +keywords: [cloud run, deploy, google, docker, gcp] +--- + # Cloud Run Example This example demonstrates how to deploy a Go Fiber application to Google Cloud Run. diff --git a/csrf-with-session/README.md b/csrf-with-session/README.md index 6d79710c84..1a2f1f2d0c 100644 --- a/csrf-with-session/README.md +++ b/csrf-with-session/README.md @@ -1,3 +1,8 @@ +--- +title: CSRF + Session +keywords: [csrf, security, hacking, vulnerability, session] +--- + # CSRF-with-session Example Example GoFiber web app using Cross Site Request Forgery (CSRF) middleware with session. @@ -107,7 +112,7 @@ Sessions are stored in memory for this example, but you can use any session stor ### Note on pre-sessions -GoFiber's CSRF middleware will automatically create a session if one does not exist. That means that we always have pre-sessions when using the CSRF middleware. In this example we set a session variable `loggedIn` +GoFiber's CSRF middleware will automatically create a session if one does not exist. That means that we always have pre-sessions when using the CSRF middleware. In this example we set a session variable `loggedIn` to `true` when the user logs in, in order to distinguish between logged in and logged out users. diff --git a/csrf/README.md b/csrf/README.md index 6f2b38596d..4ffa489cca 100644 --- a/csrf/README.md +++ b/csrf/README.md @@ -1,3 +1,8 @@ +--- +title: CSRF +keywords: [csrf, security, hacking, vulnerability] +--- + # CSRF Examples Example Cross Site Request Forgery (CSRF) vulnerabilities in action. diff --git a/docker-mariadb-clean-arch/README.md b/docker-mariadb-clean-arch/README.md index 4dcec90b2a..1eb04c41b7 100644 --- a/docker-mariadb-clean-arch/README.md +++ b/docker-mariadb-clean-arch/README.md @@ -1,3 +1,8 @@ +--- +title: Docker + MariaDB +keywords: [docker, mariadb, clean architecture, makefile] +--- + # Docker MariaDB Clean Architecture A slightly complex REST application with Fiber to showcase Clean Architecture with MariaDB as a dependency with Docker. diff --git a/docker-nginx-loadbalancer/README.md b/docker-nginx-loadbalancer/README.md index 5a181e0f1a..89604de475 100644 --- a/docker-nginx-loadbalancer/README.md +++ b/docker-nginx-loadbalancer/README.md @@ -1,12 +1,9 @@ -# Docker+Nginx 🚀 - - - - - Fiber - - +--- +title: Docker + Nginx +keywords: [docker, nginx, loadbalancer, reverse proxy] +--- +# Docker + Nginx ## Features diff --git a/dummyjson/README.md b/dummyjson/README.md index 8e5f9ec5c4..37238836ed 100644 --- a/dummyjson/README.md +++ b/dummyjson/README.md @@ -1,4 +1,9 @@ -## Simple Fiber Proxy Server +--- +title: Dummy JSON Proxy +keywords: [dummyjson, proxy, json, server] +--- + +# Simple Fiber Proxy Server This is a basic Go application using the Fiber framework to create a web server. The server listens on port 3000 and has a single route (`GET /`) that fetches data from an external URL (`https://dummyjson.com/products/1`) and forwards it to the client. @@ -17,4 +22,4 @@ This is a basic Go application using the Fiber framework to create a web server. ### Error Handling - Returns a 500 Internal Server Error if any issue occurs during the fetch. -- Returns the same status code as the external service if it's not a 200 OK. \ No newline at end of file +- Returns the same status code as the external service if it's not a 200 OK. diff --git a/ent-mysql/README.md b/ent-mysql/README.md index 706d1a03af..5d406a99ca 100644 --- a/ent-mysql/README.md +++ b/ent-mysql/README.md @@ -1,8 +1,13 @@ -### Example ent ORM for fiber with MySQL +--- +title: Entgo ORM (MySQL) +keywords: [ent, mysql, orm, rest] +--- + +# Example ent ORM for fiber with MySQL A sample program how to connect ent ORM -### How to start (If no ent dir) +## How to start (If no ent dir) Execute command first ```bash go run -mod=mod entgo.io/ent/cmd/ent new Book @@ -22,7 +27,7 @@ Execute command go generate ./ent ``` -#### Endpoints +### Endpoints | Method | URL | Description | |--------|-------------|-----------------| diff --git a/entgo-sveltekit/README.md b/entgo-sveltekit/README.md index 109b354d35..e5b1ee2587 100644 --- a/entgo-sveltekit/README.md +++ b/entgo-sveltekit/README.md @@ -1,3 +1,8 @@ +--- +title: Entgo Sveltekit +keywords: [ent, sveltekit, tailwindcss, sqlite, rest] +--- + # Todo Application ![image](https://github.com/ugurkorkmaz/gofiber-recipes/assets/40540244/08c6ee52-724a-4cf4-8352-9cf6f5b007ef) From d85c8d25b8b30658e38d71d0111ecac00b55eb78 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ren=C3=A9?= Date: Tue, 26 Nov 2024 14:42:22 +0100 Subject: [PATCH 03/14] docusaurus preparations --- .github/CONTRIBUTING.md | 33 ++++ .gitignore | 2 +- Makefile | 32 ++++ README.md | 103 ++++++------ aws-sam-container/README.md | 2 +- {fiber-colly-gorm => colly-gorm}/README.md | 11 +- .../app/Dockerfile | 0 {fiber-colly-gorm => colly-gorm}/app/app.env | 0 .../app/app.env.example | 0 .../app/cmd/api/main.go | 0 {fiber-colly-gorm => colly-gorm}/app/go.mod | 0 {fiber-colly-gorm => colly-gorm}/app/go.sum | 0 .../app/internals/consts/consts.go | 0 .../internals/services/database/database.go | 0 .../app/internals/services/database/models.go | 20 +++ .../services/scrapers/coursera_courses.go | 0 .../internals/services/scrapers/toscrape.go | 0 .../db/create_db.sql | 0 .../docker-compose.yml | 0 .../README.md | 15 +- .../app/Dockerfile | 0 .../app/go.mod | 0 .../app/go.sum | 0 .../app/main.go | 0 .../authz/Dockerfile | 0 .../authz/go.mod | 0 .../authz/go.sum | 0 .../authz/main.go | 2 +- .../docker-compose.yaml | 0 .../envoy/envoy.yaml | 0 fiber-colly-gorm/app/.idea/.gitignore | 8 - .../app/internals/services/database/models.go | 21 --- fiber-grpc/README.md | 19 --- file-server/README.md | 64 ++++++++ firebase-auth/{README.MD => README.md} | 13 +- firebase-functions/README.md | 7 +- gcloud-firebase/README.md | 13 +- gcloud/README.md | 15 +- geoip-maxmind/README.md | 13 +- geoip/README.md | 85 +++++++++- go.mod | 3 + gorm-mysql/README.md | 93 +++++++++-- gorm-postgres/README.md | 100 ++++++++++++ gorm/README.md | 66 ++++++++ graceful-shutdown/README.md | 7 +- graphql/README.md | 82 ++++++++++ {fiber-grpc => grpc}/.gitignore | 0 grpc/README.md | 62 ++++++++ {fiber-grpc => grpc}/client/main.go | 0 {fiber-grpc => grpc}/go.mod | 0 {fiber-grpc => grpc}/go.sum | 0 {fiber-grpc => grpc}/proto/service.pb.go | 0 {fiber-grpc => grpc}/proto/service.proto | 0 {fiber-grpc => grpc}/server/main.go | 0 hello-world/README.md | 65 ++++++++ heroku/README.md | 94 +++++++++++ hexagonal/README.md | 93 ++++++++++- https-pkcs12-tls/README.md | 107 +++++++++++++ https-tls/README.md | 69 ++++++++ i18n/README.md | 5 + jwt/README.md | 57 ++++++- k8s/README.md | 148 ++++++++++++++++++ memgraph/README.md | 15 +- minio/README.md | 5 + mongodb/README.md | 89 +++++++++++ multiple-ports/README.md | 81 ++++++++++ mysql/README.md | 87 ++++++++++ neo4j/README.md | 94 +++++++++++ oauth2-google/README.md | 67 +++++++- {testOauth2 => oauth2}/.env | 0 {testOauth2 => oauth2}/.gitignore | 0 oauth2/README.md | 86 ++++++++++ {testOauth2 => oauth2}/app.go | 6 +- {testOauth2 => oauth2}/config/config.go | 0 {testOauth2 => oauth2}/go.mod | 2 +- {testOauth2 => oauth2}/go.sum | 0 {testOauth2 => oauth2}/handlers/handlers.go | 2 +- oauth2/makefile | 25 +++ {testOauth2 => oauth2}/middleware/auth.go | 2 +- {testOauth2 => oauth2}/models/models.go | 0 {testOauth2 => oauth2}/router/router.go | 4 +- {testOauth2 => oauth2}/www/errpage.html | 0 {testOauth2 => oauth2}/www/index.html | 0 {testOauth2 => oauth2}/www/protected.html | 0 {testOauth2 => oauth2}/www/welcome.html | 0 optional-parameter/README.md | 66 ++++++++ overview.go | 126 +++++++++++++++ parsley/README.md | 7 +- postgresql/README.md | 86 ++++++++++ prefork/README.md | 69 ++++++++ rabbitmq/README.md | 5 + react-router/README.md | 5 + recover/README.md | 67 ++++++++ rss-feed/README.md | 95 +++++++++++ server-timing/README.md | 71 +++++++++ sessions-sqlite3/README.md | 48 +++++- socketio/README.md | 55 +++++-- spa/README.md | 97 ++++++++++++ sqlboiler/README.md | 5 + sqlc/README.md | 7 +- sse/README.md | 65 +++++++- stream-request-body/README.md | 77 +++++++++ .../.gitignore | 0 .../LICENSE | 0 .../README.md | 9 +- .../adapter/adapter.go | 0 .../build.sh | 0 .../cmd/gateway/main.go | 0 .../functions/.keep | 0 .../go.mod | 0 .../go.sum | 0 .../handler/handler.go | 0 .../netlify.toml | 0 .../public/build/bundle.css | 0 .../public/build/bundle.css.map | 0 .../public/build/bundle.js | 0 .../public/build/bundle.js.map | 0 .../public/global.css | 0 .../public/index.html | 0 sveltekit-embed/README.md | 5 + swagger/README.md | 91 ++++++----- tableflip/README.md | 81 ++++++---- template-asset-bundling/README.md | 59 ++++--- template/README.md | 89 +++++++++++ testOauth2/.vscode/launch.json | 15 -- testOauth2/makefile | 25 --- todo-app-with-auth-gorm/README.md | 45 ++++-- unit-test/README.md | 5 + upload-file/README.md | 5 + url-shortener-api/README.md | 54 ++++--- validation/README.md | 5 + vercel/README.md | 5 + websocket-chat/README.md | 5 + websocket/README.md | 5 + 134 files changed, 3210 insertions(+), 338 deletions(-) create mode 100644 .github/CONTRIBUTING.md create mode 100644 Makefile rename {fiber-colly-gorm => colly-gorm}/README.md (79%) rename {fiber-colly-gorm => colly-gorm}/app/Dockerfile (100%) rename {fiber-colly-gorm => colly-gorm}/app/app.env (100%) rename {fiber-colly-gorm => colly-gorm}/app/app.env.example (100%) rename {fiber-colly-gorm => colly-gorm}/app/cmd/api/main.go (100%) rename {fiber-colly-gorm => colly-gorm}/app/go.mod (100%) rename {fiber-colly-gorm => colly-gorm}/app/go.sum (100%) rename {fiber-colly-gorm => colly-gorm}/app/internals/consts/consts.go (100%) rename {fiber-colly-gorm => colly-gorm}/app/internals/services/database/database.go (100%) create mode 100644 colly-gorm/app/internals/services/database/models.go rename {fiber-colly-gorm => colly-gorm}/app/internals/services/scrapers/coursera_courses.go (100%) rename {fiber-colly-gorm => colly-gorm}/app/internals/services/scrapers/toscrape.go (100%) rename {fiber-colly-gorm => colly-gorm}/db/create_db.sql (100%) rename {fiber-colly-gorm => colly-gorm}/docker-compose.yml (100%) rename {fiber-envoy-extauthz => envoy-extauthz}/README.md (87%) rename {fiber-envoy-extauthz => envoy-extauthz}/app/Dockerfile (100%) rename {fiber-envoy-extauthz => envoy-extauthz}/app/go.mod (100%) rename {fiber-envoy-extauthz => envoy-extauthz}/app/go.sum (100%) rename {fiber-envoy-extauthz => envoy-extauthz}/app/main.go (100%) rename {fiber-envoy-extauthz => envoy-extauthz}/authz/Dockerfile (100%) rename {fiber-envoy-extauthz => envoy-extauthz}/authz/go.mod (100%) rename {fiber-envoy-extauthz => envoy-extauthz}/authz/go.sum (100%) rename {fiber-envoy-extauthz => envoy-extauthz}/authz/main.go (100%) rename {fiber-envoy-extauthz => envoy-extauthz}/docker-compose.yaml (100%) rename {fiber-envoy-extauthz => envoy-extauthz}/envoy/envoy.yaml (100%) delete mode 100644 fiber-colly-gorm/app/.idea/.gitignore delete mode 100644 fiber-colly-gorm/app/internals/services/database/models.go delete mode 100644 fiber-grpc/README.md create mode 100644 file-server/README.md rename firebase-auth/{README.MD => README.md} (79%) create mode 100644 go.mod create mode 100644 gorm-postgres/README.md create mode 100644 gorm/README.md create mode 100644 graphql/README.md rename {fiber-grpc => grpc}/.gitignore (100%) create mode 100644 grpc/README.md rename {fiber-grpc => grpc}/client/main.go (100%) rename {fiber-grpc => grpc}/go.mod (100%) rename {fiber-grpc => grpc}/go.sum (100%) rename {fiber-grpc => grpc}/proto/service.pb.go (100%) rename {fiber-grpc => grpc}/proto/service.proto (100%) rename {fiber-grpc => grpc}/server/main.go (100%) create mode 100644 hello-world/README.md create mode 100644 heroku/README.md create mode 100644 https-pkcs12-tls/README.md create mode 100644 https-tls/README.md create mode 100644 k8s/README.md create mode 100644 mongodb/README.md create mode 100644 multiple-ports/README.md create mode 100644 mysql/README.md create mode 100644 neo4j/README.md rename {testOauth2 => oauth2}/.env (100%) rename {testOauth2 => oauth2}/.gitignore (100%) create mode 100644 oauth2/README.md rename {testOauth2 => oauth2}/app.go (97%) rename {testOauth2 => oauth2}/config/config.go (100%) rename {testOauth2 => oauth2}/go.mod (98%) rename {testOauth2 => oauth2}/go.sum (100%) rename {testOauth2 => oauth2}/handlers/handlers.go (97%) create mode 100644 oauth2/makefile rename {testOauth2 => oauth2}/middleware/auth.go (99%) rename {testOauth2 => oauth2}/models/models.go (100%) rename {testOauth2 => oauth2}/router/router.go (96%) rename {testOauth2 => oauth2}/www/errpage.html (100%) rename {testOauth2 => oauth2}/www/index.html (100%) rename {testOauth2 => oauth2}/www/protected.html (100%) rename {testOauth2 => oauth2}/www/welcome.html (100%) create mode 100644 optional-parameter/README.md create mode 100644 overview.go create mode 100644 postgresql/README.md create mode 100644 prefork/README.md create mode 100644 recover/README.md create mode 100644 rss-feed/README.md create mode 100644 server-timing/README.md create mode 100644 spa/README.md create mode 100644 stream-request-body/README.md rename {fiber-svelte-netlify => svelte-netlify}/.gitignore (100%) rename {fiber-svelte-netlify => svelte-netlify}/LICENSE (100%) rename {fiber-svelte-netlify => svelte-netlify}/README.md (90%) rename {fiber-svelte-netlify => svelte-netlify}/adapter/adapter.go (100%) rename {fiber-svelte-netlify => svelte-netlify}/build.sh (100%) rename {fiber-svelte-netlify => svelte-netlify}/cmd/gateway/main.go (100%) rename {fiber-svelte-netlify => svelte-netlify}/functions/.keep (100%) rename {fiber-svelte-netlify => svelte-netlify}/go.mod (100%) rename {fiber-svelte-netlify => svelte-netlify}/go.sum (100%) rename {fiber-svelte-netlify => svelte-netlify}/handler/handler.go (100%) rename {fiber-svelte-netlify => svelte-netlify}/netlify.toml (100%) rename {fiber-svelte-netlify => svelte-netlify}/public/build/bundle.css (100%) rename {fiber-svelte-netlify => svelte-netlify}/public/build/bundle.css.map (100%) rename {fiber-svelte-netlify => svelte-netlify}/public/build/bundle.js (100%) rename {fiber-svelte-netlify => svelte-netlify}/public/build/bundle.js.map (100%) rename {fiber-svelte-netlify => svelte-netlify}/public/global.css (100%) rename {fiber-svelte-netlify => svelte-netlify}/public/index.html (100%) create mode 100644 template/README.md delete mode 100644 testOauth2/.vscode/launch.json delete mode 100644 testOauth2/makefile diff --git a/.github/CONTRIBUTING.md b/.github/CONTRIBUTING.md new file mode 100644 index 0000000000..2156217b93 --- /dev/null +++ b/.github/CONTRIBUTING.md @@ -0,0 +1,33 @@ +# Contributing Guidelines + +Thank you for considering contributing to this project! To ensure a smooth and efficient process, please follow these guidelines. + +## Adding a New Example + +1. **Create a Directory**: Create a new directory for your example in the root of the repository. Please do not use a "fiber" prefix in the directory name. + +2. **Add a `README.md`**: Each example must include a `README.md` file in its directory. This file should contain the following: + + - **Docusaurus Metadata**: Add the following metadata at the top of the `README.md` file: + ```markdown + --- + title: Your Example Title + keywords: [keyword1, keyword2, keyword3] + --- + ``` + + - `title`: A short and descriptive title for your example. + - `keywords`: A list of relevant keywords (excluding "fiber"). + + - **Content**: The `README.md` should provide a detailed explanation of the example, including: + - The idea behind the example. + - The components used in the example. + - Instructions on how to run the example. + - Any other relevant information. + +3. **Update the Overview**: After adding your example, run the following command in the root directory to update the overview table of contents: + ```bash + make generate + ``` + +By following these guidelines, you help maintain the quality and consistency of the project. Thank you for your contributions! diff --git a/.gitignore b/.gitignore index 9e76aa6742..323e0e2ac4 100644 --- a/.gitignore +++ b/.gitignore @@ -25,7 +25,7 @@ Thumbs.db *.out # Dependency directories (remove the comment below to include it) -# vendor/ +vendor/ # Go workspace file go.work diff --git a/Makefile b/Makefile new file mode 100644 index 0000000000..978e2d01f6 --- /dev/null +++ b/Makefile @@ -0,0 +1,32 @@ +## help: 💡 Display available commands +.PHONY: help +help: + @echo '⚡️ GoFiber/Recipes Development:' + @sed -n 's/^##//p' ${MAKEFILE_LIST} | column -t -s ':' | sed -e 's/^/ /' + +## audit: 🚀 Conduct quality checks +.PHONY: audit +audit: + go mod verify + go vet ./... + go run golang.org/x/vuln/cmd/govulncheck@latest ./... + +## format: 🎨 Fix code format issues +.PHONY: format +format: + go run mvdan.cc/gofumpt@latest -w -l . + +## markdown: 🎨 Find markdown format issues (Requires markdownlint-cli) +.PHONY: markdown +markdown: + markdownlint-cli2 "**/*.md" "#vendor" + +## lint: 🚨 Run lint checks +.PHONY: lint +lint: + go run github.com/golangci/golangci-lint/cmd/golangci-lint@v1.61.0 run ./... + +## generate: ⚡️ Generate implementations +.PHONY: generate +generate: + go generate ./... diff --git a/README.md b/README.md index 9acbfba98a..e64176e61f 100644 --- a/README.md +++ b/README.md @@ -12,72 +12,87 @@ Here you can find the most **delicious** recipes to cook delicious meals using o ## 🌽 Table of contents -- [Amazon Web Services (AWS) Elastic Beanstalk](./aws-eb) + +- [404 Handler](./404-handler) +- [Air Live Reloading](./air) +- [Auth + Docker + Postgres + JWT](./auth-docker-postgres-jwt) +- [Auth + JWT](./auth-jwt) +- [Autocert](./autocert) +- [AWS Elastic Beanstalk](./aws-eb) - [AWS SAM](./aws-sam) -- [Certificates from Let's Encrypt](./autocert) +- [AWS SAM Container](./aws-sam-container) +- [Bootstrap](./bootstrap) - [Clean Architecture](./clean-architecture) - [Cloud Run](./cloud-run) -- [Colly Scraping using Fiber and PostgreSQL](./fiber-colly-gorm) -- [CSRF-with-Session](./csrf-with-session) +- [Colly Gorm](./colly-gorm) - [CSRF](./csrf) -- [Custom 404 Not Found](./404-handler) -- [Dependency Injection (with Parsley)](./parsley) -- [Docker MariaDB Clean Architecture](./docker-mariadb-clean-arch) -- [Docker Nginx Loadbalancer](./docker-nginx-loadbalancer) -- [Docker Postgres-JWT](./auth-docker-postgres-jwt) -- [DummyJson](./dummyjson/) -- [Enable HTTPS/TLS using PKCS12 store](./https-pkcs12-tls) -- [Enable HTTPS/TLS](./https-tls) -- [Enable Preforking](./prefork) -- [Ent Mysql Example](./ent-mysql) +- [CSRF + Session](./csrf-with-session) +- [Docker + MariaDB](./docker-mariadb-clean-arch) +- [Docker + Nginx](./docker-nginx-loadbalancer) +- [Dummy JSON Proxy ](./dummyjson) +- [Entgo ORM (MySQL)](./ent-mysql) - [Entgo Sveltekit](./entgo-sveltekit) +- [Envoy External Authorization](./envoy-extauthz) +- [File Server](./file-server) +- [Firebase Authentication](./firebase-auth) - [Firebase Functions](./firebase-functions) -- [GeoIP (with MaxMind databases)](./geoip-maxmind) +- [Firebase GCloud](./gcloud) +- [Google Cloud Firebase](./gcloud-firebase) - [GeoIP](./geoip) -- [GORM Mysql Example](./gorm-mysql) +- [GeoIP + MaxMind](./geoip-maxmind) - [GORM](./gorm) +- [GORM MySQL](./gorm-mysql) +- [GORM + PostgreSQL](./gorm-postgres) - [Graceful shutdown](./graceful-shutdown) - [GraphQL](./graphql) -- [Hello, World!](./hello-world) -- [Heroku App](./heroku) +- [gRPC](./grpc) +- [Hello World](./hello-world) +- [Heroku](./heroku) - [Hexagonal Architecture](./hexagonal) -- [i18n](./i18n) +- [HTTPS with PKCS12 TLS](./https-pkcs12-tls) +- [HTTPS with TLS](./https-tls) +- [I18n](./i18n) - [JWT](./jwt) - [Kubernetes](./k8s) -- [Listen on Multiple Ports](./multiple-ports) -- [Live Reloading (Air)](./air) - [Memgraph](./memgraph) - [MinIO](./minio) -- [MongoDB](./mongodb) -- [MVC Application Bootstrap](./bootstrap) -- [Netlify Functions](fiber-svelte-netlify) -- [OAuth2 Google](./oauth2-google) -- [PostgreSQL](./postgresql) -- [RabbitMQ](rabbitmq) -- [React Router](./react-router) -- [Recover from panic](./recover) -- [RSS feed](./rss-feed) -- [Serve Static Files](./file-server) +- [MongoDB Example](./mongodb) +- [Multiple Ports](./multiple-ports) +- [MySQL](./mysql) +- [Neo4j](./neo4j) +- [OAuth2](./oauth2) +- [Google OAuth2](./oauth2-google) +- [Optional Parameter Example](./optional-parameter) +- [Parsley](./parsley) +- [PostgreSQL Example](./postgresql) +- [Prefork Example](./prefork) +- [RabbitMQ](./rabbitmq) +- [React](./react-router) +- [Recover Middleware Example](./recover) +- [RSS Feed](./rss-feed) - [Server Timing](./server-timing) -- [Server-Sent Events](./sse) -- [Sessions-SQLite3](./sessions-sqlite3) -- [Single Page Application Example](./spa) -- [Socket.io](./socketio) +- [Sessions + SQLite3](./sessions-sqlite3) +- [Socketio](./socketio) +- [Single Page Application (SPA)](./spa) - [Sqlboiler](./sqlboiler) - [Sqlc](./sqlc) -- [Streaming of the Request Body](./stream-request-body) +- [Server-Sent Events](./sse) +- [Stream Request Body](./stream-request-body) +- [Svelte Netlify](./svelte-netlify) - [Sveltekit Embed](./sveltekit-embed) -- [Tableflip (Graceful updates)](./tableflip) +- [Swagger ](./swagger) +- [Tableflip Example](./tableflip) +- [Template](./template) - [Template Asset Bundling](./template-asset-bundling) -- [Unit Test Example](./unit-test) -- [Upload Multiple Files](./upload-file/multiple) -- [Upload Single File](./upload-file/single) -- [URL shortener API](./url-shortener-api) -- [User Auth with JWT](./auth-jwt) +- [Todo App + Auth + GORM](./todo-app-with-auth-gorm) +- [Unit Testing](./unit-test) +- [File Upload](./upload-file) +- [URL Shortener](./url-shortener-api) - [Validation](./validation) - [Vercel](./vercel) -- [WebSocket Chat Example](./websocket-chat) -- [WebSockets](./websocket) +- [WebSocket](./websocket) +- [WebSocket Chat](./websocket-chat) + ## 👩‍🍳 Have a delicious recipe? diff --git a/aws-sam-container/README.md b/aws-sam-container/README.md index 60df9a1a2b..a7c1bb252a 100644 --- a/aws-sam-container/README.md +++ b/aws-sam-container/README.md @@ -1,5 +1,5 @@ --- -title: "AWS SAM Container" +title: AWS SAM Container keywords: [aws, sam, serverless, lambda, container] --- diff --git a/fiber-colly-gorm/README.md b/colly-gorm/README.md similarity index 79% rename from fiber-colly-gorm/README.md rename to colly-gorm/README.md index ff69eee2fb..7826743ea6 100644 --- a/fiber-colly-gorm/README.md +++ b/colly-gorm/README.md @@ -1,8 +1,13 @@ -## Simple Web Scraping Colly App with Fiber +--- +title: Colly Gorm +keywords: [colly, gorm, postgresql] +--- + +# Simple Web Scraping Colly App with Fiber This is a basic Go application using the Fiber framework to create scraping tasks in colly. -### How to Run +## How to Run 1. Clone the repository. 2. Navigate to the project directory. @@ -11,6 +16,6 @@ This is a basic Go application using the Fiber framework to create scraping task 5. Send `GET` request to `http://127.0.0.1:3000/scrape/coursera` to start scraping Coursera courses. And `http://127.0.0.1:3000/scrape/quotes` to scrape `quotes.toscrape.com`. -### What It Does +## What It Does - Scrapes data from websites and stores in PostgreSQL database. diff --git a/fiber-colly-gorm/app/Dockerfile b/colly-gorm/app/Dockerfile similarity index 100% rename from fiber-colly-gorm/app/Dockerfile rename to colly-gorm/app/Dockerfile diff --git a/fiber-colly-gorm/app/app.env b/colly-gorm/app/app.env similarity index 100% rename from fiber-colly-gorm/app/app.env rename to colly-gorm/app/app.env diff --git a/fiber-colly-gorm/app/app.env.example b/colly-gorm/app/app.env.example similarity index 100% rename from fiber-colly-gorm/app/app.env.example rename to colly-gorm/app/app.env.example diff --git a/fiber-colly-gorm/app/cmd/api/main.go b/colly-gorm/app/cmd/api/main.go similarity index 100% rename from fiber-colly-gorm/app/cmd/api/main.go rename to colly-gorm/app/cmd/api/main.go diff --git a/fiber-colly-gorm/app/go.mod b/colly-gorm/app/go.mod similarity index 100% rename from fiber-colly-gorm/app/go.mod rename to colly-gorm/app/go.mod diff --git a/fiber-colly-gorm/app/go.sum b/colly-gorm/app/go.sum similarity index 100% rename from fiber-colly-gorm/app/go.sum rename to colly-gorm/app/go.sum diff --git a/fiber-colly-gorm/app/internals/consts/consts.go b/colly-gorm/app/internals/consts/consts.go similarity index 100% rename from fiber-colly-gorm/app/internals/consts/consts.go rename to colly-gorm/app/internals/consts/consts.go diff --git a/fiber-colly-gorm/app/internals/services/database/database.go b/colly-gorm/app/internals/services/database/database.go similarity index 100% rename from fiber-colly-gorm/app/internals/services/database/database.go rename to colly-gorm/app/internals/services/database/database.go diff --git a/colly-gorm/app/internals/services/database/models.go b/colly-gorm/app/internals/services/database/models.go new file mode 100644 index 0000000000..6805688858 --- /dev/null +++ b/colly-gorm/app/internals/services/database/models.go @@ -0,0 +1,20 @@ +package database + +import "gorm.io/gorm" + +type Quote struct { + ID int `json:"id"` + Author string `json:"author"` + Text string `json:"quote"` + gorm.Model +} + +type Course struct { + ID int `json:"id"` + Title string `json:"title"` + Description string `json:"description"` + Creator string `json:"creator"` + URL string `json:"url"` + Rating string `json:"rating"` + gorm.Model +} diff --git a/fiber-colly-gorm/app/internals/services/scrapers/coursera_courses.go b/colly-gorm/app/internals/services/scrapers/coursera_courses.go similarity index 100% rename from fiber-colly-gorm/app/internals/services/scrapers/coursera_courses.go rename to colly-gorm/app/internals/services/scrapers/coursera_courses.go diff --git a/fiber-colly-gorm/app/internals/services/scrapers/toscrape.go b/colly-gorm/app/internals/services/scrapers/toscrape.go similarity index 100% rename from fiber-colly-gorm/app/internals/services/scrapers/toscrape.go rename to colly-gorm/app/internals/services/scrapers/toscrape.go diff --git a/fiber-colly-gorm/db/create_db.sql b/colly-gorm/db/create_db.sql similarity index 100% rename from fiber-colly-gorm/db/create_db.sql rename to colly-gorm/db/create_db.sql diff --git a/fiber-colly-gorm/docker-compose.yml b/colly-gorm/docker-compose.yml similarity index 100% rename from fiber-colly-gorm/docker-compose.yml rename to colly-gorm/docker-compose.yml diff --git a/fiber-envoy-extauthz/README.md b/envoy-extauthz/README.md similarity index 87% rename from fiber-envoy-extauthz/README.md rename to envoy-extauthz/README.md index d3a72ada15..45f4ec711e 100644 --- a/fiber-envoy-extauthz/README.md +++ b/envoy-extauthz/README.md @@ -1,4 +1,9 @@ -## Fiber as an Envoy External Authorization HTTP Service +--- +title: Envoy External Authorization +keywords: [envoy, external authorization, keyauth] +--- + +# Fiber as an Envoy External Authorization HTTP Service One way of extending the popular [Envoy](https://www.envoyproxy.io) proxy is by developing an [external authorization service](https://www.envoyproxy.io/docs/envoy/latest/api-v3/service/auth/v3/external_auth.proto). @@ -8,18 +13,18 @@ proxy (the configuration could also be used for an L2 / Sidecar proxy). See `aut It also uses `fiber` as a sample upstream service, with the following endpoints. See `app`. -### Endpoints +## Endpoints | Name | Rute | Protected | Method | | --------- | ------------- | --------- | ------ | | Health | /health | No | GET | | Resource | /api/resource | Yes | GET | -### Run +## Run `docker-compose up --build -d` -### Test +## Test | Name | Command | Status | | --------------- | ----------------------------------------------------------------- | ------ | @@ -28,6 +33,6 @@ It also uses `fiber` as a sample upstream service, with the following endpoints. | Invalid API key | `curl localhost:8000/api/resource -i -H "x-api-key: invalid-key"` | 403 | | Valid API key | `curl localhost:8000/api/resource -i -H "x-api-key: valid-key"` | 200 | -### Stop +## Stop `docker-compose down` diff --git a/fiber-envoy-extauthz/app/Dockerfile b/envoy-extauthz/app/Dockerfile similarity index 100% rename from fiber-envoy-extauthz/app/Dockerfile rename to envoy-extauthz/app/Dockerfile diff --git a/fiber-envoy-extauthz/app/go.mod b/envoy-extauthz/app/go.mod similarity index 100% rename from fiber-envoy-extauthz/app/go.mod rename to envoy-extauthz/app/go.mod diff --git a/fiber-envoy-extauthz/app/go.sum b/envoy-extauthz/app/go.sum similarity index 100% rename from fiber-envoy-extauthz/app/go.sum rename to envoy-extauthz/app/go.sum diff --git a/fiber-envoy-extauthz/app/main.go b/envoy-extauthz/app/main.go similarity index 100% rename from fiber-envoy-extauthz/app/main.go rename to envoy-extauthz/app/main.go diff --git a/fiber-envoy-extauthz/authz/Dockerfile b/envoy-extauthz/authz/Dockerfile similarity index 100% rename from fiber-envoy-extauthz/authz/Dockerfile rename to envoy-extauthz/authz/Dockerfile diff --git a/fiber-envoy-extauthz/authz/go.mod b/envoy-extauthz/authz/go.mod similarity index 100% rename from fiber-envoy-extauthz/authz/go.mod rename to envoy-extauthz/authz/go.mod diff --git a/fiber-envoy-extauthz/authz/go.sum b/envoy-extauthz/authz/go.sum similarity index 100% rename from fiber-envoy-extauthz/authz/go.sum rename to envoy-extauthz/authz/go.sum diff --git a/fiber-envoy-extauthz/authz/main.go b/envoy-extauthz/authz/main.go similarity index 100% rename from fiber-envoy-extauthz/authz/main.go rename to envoy-extauthz/authz/main.go index 80f9cf28df..acd5551951 100644 --- a/fiber-envoy-extauthz/authz/main.go +++ b/envoy-extauthz/authz/main.go @@ -5,8 +5,8 @@ import ( "strings" "github.com/gofiber/fiber/v2" - "github.com/gofiber/fiber/v2/middleware/logger" "github.com/gofiber/fiber/v2/middleware/keyauth" + "github.com/gofiber/fiber/v2/middleware/logger" ) const ( diff --git a/fiber-envoy-extauthz/docker-compose.yaml b/envoy-extauthz/docker-compose.yaml similarity index 100% rename from fiber-envoy-extauthz/docker-compose.yaml rename to envoy-extauthz/docker-compose.yaml diff --git a/fiber-envoy-extauthz/envoy/envoy.yaml b/envoy-extauthz/envoy/envoy.yaml similarity index 100% rename from fiber-envoy-extauthz/envoy/envoy.yaml rename to envoy-extauthz/envoy/envoy.yaml diff --git a/fiber-colly-gorm/app/.idea/.gitignore b/fiber-colly-gorm/app/.idea/.gitignore deleted file mode 100644 index 13566b81b0..0000000000 --- a/fiber-colly-gorm/app/.idea/.gitignore +++ /dev/null @@ -1,8 +0,0 @@ -# Default ignored files -/shelf/ -/workspace.xml -# Editor-based HTTP Client requests -/httpRequests/ -# Datasource local storage ignored files -/dataSources/ -/dataSources.local.xml diff --git a/fiber-colly-gorm/app/internals/services/database/models.go b/fiber-colly-gorm/app/internals/services/database/models.go deleted file mode 100644 index f4cfe95890..0000000000 --- a/fiber-colly-gorm/app/internals/services/database/models.go +++ /dev/null @@ -1,21 +0,0 @@ -package database - -import "gorm.io/gorm" - -type Quote struct { - ID int `json:"id"` - Author string `json:"author"` - Text string `json:"quote"` - gorm.Model -} - - -type Course struct { - ID int `json:"id"` - Title string `json:"title"` - Description string `json:"description"` - Creator string `json:"creator"` - URL string `json:"url"` - Rating string `json:"rating"` - gorm.Model -} diff --git a/fiber-grpc/README.md b/fiber-grpc/README.md deleted file mode 100644 index 4c2dd05bc4..0000000000 --- a/fiber-grpc/README.md +++ /dev/null @@ -1,19 +0,0 @@ -### Example for fiber as a client to gRPC server. - -A sample program to showcase fiber as a client to a gRPC server. - -#### Endpoints - -| Method | URL | Return value | -| ------ | ------------- | ------------ | -| GET | "/add/:a/:b" | a + b | -| GET | "/mult/:a/:b" | a \* b | - -#### Output - -```bash --> curl http://localhost:3000/add/33445/443234 -{"result":"476679"} --> curl http://localhost:3000/mult/33445/443234 -{"result":"14823961130"} -``` diff --git a/file-server/README.md b/file-server/README.md new file mode 100644 index 0000000000..e6ca43b6ef --- /dev/null +++ b/file-server/README.md @@ -0,0 +1,64 @@ +--- +title: File Server +keywords: [file server, static files] +--- + +# File Server Example + +This project demonstrates how to set up a simple file server in a Go application using the Fiber framework. + +## Prerequisites + +Ensure you have the following installed: + +- Golang +- [Fiber](https://github.com/gofiber/fiber) package + +## Setup + +1. Clone the repository: + ```sh + git clone https://github.com/gofiber/recipes.git + cd recipes/file-server + ``` + +2. Install dependencies: + ```sh + go get + ``` + +## Running the Application + +1. Start the application: + ```sh + go run main.go + ``` + +2. Access the file server at `http://localhost:3000`. + +## Example + +Here is an example `main.go` file for the Fiber application serving static files: + +```go +package main + +import ( + "log" + "github.com/gofiber/fiber/v2" +) + +func main() { + app := fiber.New() + + // Serve static files from the "public" directory + app.Static("/", "./public") + + log.Fatal(app.Listen(":3000")) +} +``` + +## References + +- [Fiber Documentation](https://docs.gofiber.io) +- [Golang Documentation](https://golang.org/doc/) diff --git a/firebase-auth/README.MD b/firebase-auth/README.md similarity index 79% rename from firebase-auth/README.MD rename to firebase-auth/README.md index d46de01b4e..80ae73c187 100644 --- a/firebase-auth/README.MD +++ b/firebase-auth/README.md @@ -1,8 +1,13 @@ -# Go FIber Firebase Authentication Example +--- +title: Firebase Authentication +keywords: [firebase, authentication, middleware] +--- + +# Go Fiber Firebase Authentication Example This example use [gofiber-firebaseauth middleware ](https://github.com/sacsand/gofiber-firebaseauth) to authenticate the endpoints. Find the documentation for middlewae here for more confgurtion oprions [docs ](https://github.com/sacsand/gofiber-firebaseauth) -### Setting Up +## Setting Up * Clone the repo and set your firebase credentials in your .env file Need Configured Firebase Authentication App and Google Service Account Credential (JSON file contain credential). You can get all these config from Firebase Console. @@ -11,8 +16,8 @@ This example use [gofiber-firebaseauth middleware ](https://github.com/sacsand/ SERVICE_ACCOUNT_JSON = "path to service account credential json" ``` -### Start +## Start ``` go build go run main -``` \ No newline at end of file +``` diff --git a/firebase-functions/README.md b/firebase-functions/README.md index 05a0674b81..ff34be0a5f 100644 --- a/firebase-functions/README.md +++ b/firebase-functions/README.md @@ -1,4 +1,7 @@ - +--- +title: Firebase Functions +keywords: [firebase, functions, deployment, gcloud, cloud] +--- # Deploying GoFiber Application to Firebase Functions Welcome to this step-by-step guide on deploying a GoFiber application to Firebase Functions. If you’re looking to leverage the power of GoFiber, a fast and lightweight web framework for Go, and host your application on Firebase, you’re in the right place. In this tutorial, we’ll walk through the process of setting up your GoFiber app to run seamlessly on Firebase Functions. @@ -412,4 +415,4 @@ gcloud functions deploy MyCloudFunction --runtime go120 --trigger-http Congratulations! You’ve successfully configured and deployed a GoFiber application on Firebase Functions. This powerful combination allows you to build fast and efficient serverless applications. Experiment further with GoFiber features and Firebase integrations to unlock the full potential of your serverless architecture. Happy coding! ## Medium Post -https://medium.com/@kmltrk07/how-to-deploy-gofiber-app-to-firebase-functions-8d4d537a4464 \ No newline at end of file +https://medium.com/@kmltrk07/how-to-deploy-gofiber-app-to-firebase-functions-8d4d537a4464 diff --git a/gcloud-firebase/README.md b/gcloud-firebase/README.md index 9179f4e20f..953ab41029 100644 --- a/gcloud-firebase/README.md +++ b/gcloud-firebase/README.md @@ -1,15 +1,20 @@ +--- +title: Google Cloud Firebase +keywords: [firebase, gcloud, cloud run, cloud function, app engine] +--- + # Deploy Fiber to Google Cloud with Firebase Examples on how to run an application using Fiber on Google Cloud and connecting to Firebase Realtime Database. -#### Running Locally +## Running Locally * Run on the command line: ``` go run cmd/main.go ``` -#### Deploy using Google Cloud Run +## Deploy using Google Cloud Run This step will build a Docker Image, publish to Google Cloud Registry and deploy on Cloud Run Managed enviroment. @@ -29,7 +34,7 @@ gcloud beta run deploy --platform managed --image gcr.io/$GCLOUD_PROJECT/gcloud- --set-env-vars GCP_PROJECT=$GCLOUD_PROJECT ``` -#### Deploy using Google App Engine +## Deploy using Google App Engine This step will deploy the app to Google App Engine Standard Go enviroment. The app configuration and additional configurations can be tweaked on the `app.yaml` file. @@ -38,7 +43,7 @@ This step will deploy the app to Google App Engine Standard Go enviroment. The a gcloud app deploy ``` -#### Deploy using Google Cloud Function +## Deploy using Google Cloud Function This step will deploy a HTTP Cloud Function using Go enviroment. You can use the `deploy.sh` script. Just edit your project id on it. diff --git a/gcloud/README.md b/gcloud/README.md index 545826262b..550a854b66 100644 --- a/gcloud/README.md +++ b/gcloud/README.md @@ -1,15 +1,20 @@ +--- +title: Firebase GCloud +keywords: [firebase, gcloud, cloud run, cloud function, app engine] +--- + # Deploy Fiber to Google Cloud with Firebase Examples on how to run an application using Fiber on Google Cloud. -#### Running Locally +## Running Locally * Run on the command line: ``` go run cmd/main.go ``` -#### Deploy using Google Cloud Run +## Deploy using Google Cloud Run This step will build a Docker Image, publish to Google Cloud Registry and deploy on Cloud Run Managed enviroment. @@ -26,7 +31,7 @@ gcloud builds submit — -tag gcr.io/$GCLOUD_PROJECT/gcloud-fiber . gcloud beta run deploy --platform managed --image gcr.io/$GCLOUD_PROJECT/gcloud-fiber ``` -#### Deploy using Google App Engine +## Deploy using Google App Engine This step will deploy the app to Google App Engine Standard Go enviroment. The app configuration and additional configurations can be tweaked on the `app.yaml` file. @@ -35,7 +40,7 @@ This step will deploy the app to Google App Engine Standard Go enviroment. The a gcloud app deploy ``` -#### Deploy using Google Cloud Function +## Deploy using Google Cloud Function This step will deploy a HTTP Cloud Function using Go enviroment. You can use the `deploy.sh` script. Just edit your project id on it. @@ -44,4 +49,4 @@ For the Cloud Functions env, Google enforces us to deploy a function that is a ` * Run on the command line: ``` gcloud functions deploy MyCloudFunction --runtime go111 --trigger-http -``` \ No newline at end of file +``` diff --git a/geoip-maxmind/README.md b/geoip-maxmind/README.md index 957a6cb000..3d8174f6aa 100644 --- a/geoip-maxmind/README.md +++ b/geoip-maxmind/README.md @@ -1,8 +1,13 @@ +--- +title: GeoIP + MaxMind +keywords: [geoip, maxmind, databases] +--- + # GeoIP (with MaxMind databases) This is an alternative method to resolve IP addresses to real-world location data using MaxMind GeoLite2 City databases. - -### Prerequisites + +## Prerequisites Before you run this, you must first download a database from the MaxMind website - https://dev.maxmind.com/geoip/geoip2/geolite2/. To do this, you may need to register for a free account. The database you need to download is the one with the edition ID `GeoLite2-City`. Place it in this folder and run @@ -11,7 +16,7 @@ The database you need to download is the one with the edition ID `GeoLite2-City` go run geoip-maxmind ``` -### Usage +## Usage Make a request to `http://127.0.0.1:3000/geo/178.62.56.160`, for example. You can omit an IP address to use your current IP address, or replace to use another. If the IP address is invalid, a HTTP 400 is returned. The response fields can be modified from the `ipLookup` struct, found in the `handlers/handlers.go` file. @@ -40,4 +45,4 @@ The response fields can be modified from the `ipLookup` struct, found in the `ha "AccuracyRadius": 50 } } -``` \ No newline at end of file +``` diff --git a/geoip/README.md b/geoip/README.md index 2db46a21e9..feda901105 100644 --- a/geoip/README.md +++ b/geoip/README.md @@ -1 +1,84 @@ -![](https://i.imgur.com/yifgkJ5.png) \ No newline at end of file +--- +title: GeoIP +keywords: [geoip, maxmind, ip] +--- + +# GeoIP Example + +This project demonstrates how to set up a GeoIP lookup service in a Go application using the Fiber framework. + +## Prerequisites + +Ensure you have the following installed: + +- Golang +- [Fiber](https://github.com/gofiber/fiber) package +- [MaxMind GeoIP2](https://github.com/oschwald/geoip2-golang) package +- GeoIP2 database file (e.g., `GeoLite2-City.mmdb`) + +## Setup + +1. Clone the repository: + ```sh + git clone https://github.com/gofiber/recipes.git + cd recipes/geoip + ``` + +2. Install dependencies: + ```sh + go get + ``` + +3. Download the GeoIP2 database file and place it in the project directory. + +## Running the Application + +1. Start the application: + ```sh + go run main.go + ``` + +2. Access the application at `http://localhost:3000`. + +## Example + +Here is an example `main.go` file for the Fiber application with GeoIP lookup: + +```go +package main + +import ( + "log" + "github.com/gofiber/fiber/v2" + "github.com/oschwald/geoip2-golang" + "net" +) + +func main() { + app := fiber.New() + + db, err := geoip2.Open("GeoLite2-City.mmdb") + if err != nil { + log.Fatal(err) + } + defer db.Close() + + app.Get("/geoip/:ip", func(c *fiber.Ctx) error { + ip := c.Params("ip") + parsedIP := net.ParseIP(ip) + record, err := db.City(parsedIP) + if err != nil { + return c.Status(500).SendString(err.Error()) + } + return c.JSON(record) + }) + + log.Fatal(app.Listen(":3000")) +} +``` + +## References + +- [Fiber Documentation](https://docs.gofiber.io) +- [MaxMind GeoIP2 Documentation](https://pkg.go.dev/github.com/oschwald/geoip2-golang) +- [GeoIP2 Database](https://dev.maxmind.com/geoip/geolite2-free-geolocation-data) diff --git a/go.mod b/go.mod new file mode 100644 index 0000000000..2dbf473a35 --- /dev/null +++ b/go.mod @@ -0,0 +1,3 @@ +module recipes + +go 1.23.3 diff --git a/gorm-mysql/README.md b/gorm-mysql/README.md index 5303c74bcc..5d0da4adba 100644 --- a/gorm-mysql/README.md +++ b/gorm-mysql/README.md @@ -1,14 +1,85 @@ -### Example for fiber as a orm to MySQL +--- +title: GORM MySQL +keywords: [gorm, mysql, database, rest, api] +--- -A sample program to orm mysql connect +# GORM MySQL Example -#### Endpoints +This is a sample program demonstrating how to use GORM as an ORM to connect to a MySQL database with the Fiber web framework. -| Method | URL | -| ------ | --------- | -| GET | /hello | -| GET | /allbooks | -| GET | /book/:id | -| POST | /book | -| PUT | /book | -| DELETE | /book | +## Prerequisites + +- Go 1.16 or higher +- MySQL database +- Go modules + +## Setup + +1. Clone the repository: + ```sh + git clone https://github.com/gofiber/recipes.git + cd recipes/gorm-mysql + ``` + +2. Install dependencies: + ```sh + go mod tidy + ``` + +3. Configure the database connection in the `config.json` file: + ```json + { + "DB_Username": "your_db_username", + "DB_Password": "your_db_password", + "DB_Name": "your_db_name", + "DB_Host": "localhost", + "DB_Port": "3306" + } + ``` + +## Running the Application + +1. Run the application: + ```sh + go run main.go + ``` + +2. The server will start on `http://localhost:3000`. + +## Endpoints + +| Method | URL | Description | +| ------ | --------- | -------------------------- | +| GET | /hello | Returns a hello message | +| GET | /allbooks | Retrieves all books | +| GET | /book/:id | Retrieves a book by ID | +| POST | /book | Creates a new book | +| PUT | /book | Updates an existing book | +| DELETE | /book | Deletes a book | + +## Example Requests + +### Get All Books +```sh +curl -X GET http://localhost:3000/allbooks +``` + +### Get Book by ID +```sh +curl -X GET http://localhost:3000/book/1 +``` + +### Create a New Book +```sh +curl -X POST http://localhost:3000/book -d '{"title": "New Book", "author": "Author Name"}' -H "Content-Type: application/json" +``` + +### Update a Book +```sh +curl -X PUT http://localhost:3000/book -d '{"id": 1, "title": "Updated Book", "author": "Updated Author"}' -H "Content-Type: application/json" +``` + +### Delete a Book +```sh +curl -X DELETE http://localhost:3000/book -d '{"id": 1}' -H "Content-Type: application/json" +``` diff --git a/gorm-postgres/README.md b/gorm-postgres/README.md new file mode 100644 index 0000000000..816b79013d --- /dev/null +++ b/gorm-postgres/README.md @@ -0,0 +1,100 @@ +--- +title: GORM + PostgreSQL +keywords: [gorm, postgres, database] +--- + +# GORM with PostgreSQL Example + +This project demonstrates how to set up a Go application using the Fiber framework with GORM and PostgreSQL. + +## Prerequisites + +Ensure you have the following installed: + +- Golang +- [Fiber](https://github.com/gofiber/fiber) package +- [GORM](https://gorm.io/) package +- PostgreSQL + +## Setup + +1. Clone the repository: + ```sh + git clone https://github.com/gofiber/recipes.git + cd recipes/gorm-postgres + ``` + +2. Install dependencies: + ```sh + go get + ``` + +3. Set up PostgreSQL and create a database: + ```sh + createdb mydb + ``` + +4. Update the database connection string in the code if necessary. + +## Running the Application + +1. Start the application: + ```sh + go run main.go + ``` + +2. Access the application at `http://localhost:3000`. + +## Example + +Here is an example `main.go` file for the Fiber application with GORM and PostgreSQL: + +```go +package main + +import ( + "log" + "github.com/gofiber/fiber/v2" + "gorm.io/driver/postgres" + "gorm.io/gorm" +) + +type User struct { + ID uint `gorm:"primaryKey"` + Name string `gorm:"size:255"` + Email string `gorm:"uniqueIndex"` +} + +func main() { + dsn := "host=localhost user=youruser password=yourpassword dbname=mydb port=5432 sslmode=disable" + db, err := gorm.Open(postgres.Open(dsn), &gorm.Config{}) + if err != nil { + log.Fatal(err) + } + + db.AutoMigrate(&User{}) + + app := fiber.New() + + app.Get("/", func(c *fiber.Ctx) error { + return c.SendString("Hello, GORM with PostgreSQL!") + }) + + app.Post("/users", func(c *fiber.Ctx) error { + user := new(User) + if err := c.BodyParser(user); err != nil { + return c.Status(400).SendString(err.Error()) + } + db.Create(user) + return c.JSON(user) + }) + + log.Fatal(app.Listen(":3000")) +} +``` + +## References + +- [Fiber Documentation](https://docs.gofiber.io) +- [GORM Documentation](https://gorm.io/docs/) +- [PostgreSQL Documentation](https://www.postgresql.org/docs/) diff --git a/gorm/README.md b/gorm/README.md new file mode 100644 index 0000000000..1e2356fd23 --- /dev/null +++ b/gorm/README.md @@ -0,0 +1,66 @@ +--- +title: GORM +keywords: [gorm, sqlite, api, rest] +--- + +# GORM Example + +This is a sample program demonstrating how to use GORM as an ORM to connect to a SQLite database with the Fiber web framework. + +## Prerequisites + +- Go 1.18 or higher +- Go modules + +## Setup + +1. Clone the repository: + ```sh + git clone https://github.com/gofiber/recipes.git + cd recipes/gorm-example + ``` + +2. Install dependencies: + ```sh + go mod tidy + ``` + +## Running the Application + +1. Run the application: + ```sh + go run main.go + ``` + +2. The server will start on `http://localhost:3000`. + +## Endpoints + +| Method | URL | Description | +| ------ | ---------------- | -------------------------- | +| GET | /api/v1/book | Retrieves all books | +| GET | /api/v1/book/:id | Retrieves a book by ID | +| POST | /api/v1/book | Creates a new book | +| DELETE | /api/v1/book/:id | Deletes a book | + +## Example Requests + +### Get All Books +```sh +curl -X GET http://localhost:3000/api/v1/book +``` + +### Get Book by ID +```sh +curl -X GET http://localhost:3000/api/v1/book/1 +``` + +### Create a New Book +```sh +curl -X POST http://localhost:3000/api/v1/book -d '{"title": "New Book", "author": "Author Name"}' -H "Content-Type: application/json" +``` + +### Delete a Book +```sh +curl -X DELETE http://localhost:3000/api/v1/book/1 +``` diff --git a/graceful-shutdown/README.md b/graceful-shutdown/README.md index f714c8d58a..eddbe2a286 100644 --- a/graceful-shutdown/README.md +++ b/graceful-shutdown/README.md @@ -1,3 +1,8 @@ +--- +title: Graceful shutdown +keywords: [graceful, shutdown, os/signal, channel] +--- + # Graceful shutdown in Fiber ``` @@ -18,7 +23,7 @@ Running cleanup tasks... This shows how to implement a graceful shutdown with Fiber and the `os/signal` package. -### Explanation +## Explanation This example relies on the use of channels, a data type in Go that allows you to send and receive data to/from specific places in an application (read more about them [here](https://tour.golang.org/concurrency/2)). diff --git a/graphql/README.md b/graphql/README.md new file mode 100644 index 0000000000..b4b75c8981 --- /dev/null +++ b/graphql/README.md @@ -0,0 +1,82 @@ +--- +title: GraphQL +keywords: [graphql] +--- + +# GraphQL Example + +This project demonstrates how to set up a GraphQL server in a Go application using the Fiber framework. + +## Prerequisites + +Ensure you have the following installed: + +- Golang +- [Fiber](https://github.com/gofiber/fiber) package +- [gqlgen](https://github.com/99designs/gqlgen) package + +## Setup + +1. Clone the repository: + ```sh + git clone https://github.com/gofiber/recipes.git + cd recipes/graphql + ``` + +2. Install dependencies: + ```sh + go get + ``` + +3. Initialize gqlgen: + ```sh + go run github.com/99designs/gqlgen init + ``` + +## Running the Application + +1. Start the application: + ```sh + go run main.go + ``` + +2. Access the GraphQL playground at `http://localhost:3000/graphql`. + +## Example + +Here is an example `main.go` file for the Fiber application with GraphQL: + +```go +package main + +import ( + "log" + "github.com/gofiber/fiber/v2" + "github.com/99designs/gqlgen/graphql/handler" + "github.com/99designs/gqlgen/graphql/playground" +) + +func main() { + app := fiber.New() + + srv := handler.NewDefaultServer(generated.NewExecutableSchema(generated.Config{Resolvers: &resolver{}})) + + app.All("/graphql", func(c *fiber.Ctx) error { + srv.ServeHTTP(c.Context().ResponseWriter(), c.Context().Request) + return nil + }) + + app.Get("/", func(c *fiber.Ctx) error { + playground.Handler("GraphQL playground", "/graphql").ServeHTTP(c.Context().ResponseWriter(), c.Context().Request) + return nil + }) + + log.Fatal(app.Listen(":3000")) +} +``` + +## References + +- [Fiber Documentation](https://docs.gofiber.io) +- [gqlgen Documentation](https://gqlgen.com/) +- [GraphQL Documentation](https://graphql.org/) diff --git a/fiber-grpc/.gitignore b/grpc/.gitignore similarity index 100% rename from fiber-grpc/.gitignore rename to grpc/.gitignore diff --git a/grpc/README.md b/grpc/README.md new file mode 100644 index 0000000000..67d8adac62 --- /dev/null +++ b/grpc/README.md @@ -0,0 +1,62 @@ +--- +title: gRPC +keywords: [grpc, server, client] +--- + +# Example for fiber as a client to gRPC server. + +A sample program to showcase fiber as a client to a gRPC server. + +## Prerequisites + +- Go 1.16 or higher +- Go modules + +## Setup + +1. Clone the repository: + ```sh + git clone https://github.com/gofiber/recipes.git + cd recipes/grpc + ``` + +2. Install dependencies: + ```sh + go mod tidy + ``` + +## Running the Application + +1. Run the gRPC server: + ```sh + go run server/main.go + ``` + +2. Run the Fiber client: + ```sh + go run client/main.go + ``` + +3. The server will start on `http://localhost:3000`. + +## Endpoints + +| Method | URL | Return value | +| ------ | ------------- | ------------ | +| GET | /add/:a/:b | a + b | +| GET | /mult/:a/:b | a \* b | + +### Output + +```bash +-> curl http://localhost:3000/add/33445/443234 +{"result":"476679"} +-> curl http://localhost:3000/mult/33445/443234 +{"result":"14823961130"} +``` + +## Additional Information + +gRPC (gRPC Remote Procedure Calls) is a high-performance, open-source universal RPC framework initially developed by Google. It uses HTTP/2 for transport, Protocol Buffers as the interface description language, and provides features such as authentication, load balancing, and more. + +For more information, visit the [official gRPC documentation](https://grpc.io/docs/). diff --git a/fiber-grpc/client/main.go b/grpc/client/main.go similarity index 100% rename from fiber-grpc/client/main.go rename to grpc/client/main.go diff --git a/fiber-grpc/go.mod b/grpc/go.mod similarity index 100% rename from fiber-grpc/go.mod rename to grpc/go.mod diff --git a/fiber-grpc/go.sum b/grpc/go.sum similarity index 100% rename from fiber-grpc/go.sum rename to grpc/go.sum diff --git a/fiber-grpc/proto/service.pb.go b/grpc/proto/service.pb.go similarity index 100% rename from fiber-grpc/proto/service.pb.go rename to grpc/proto/service.pb.go diff --git a/fiber-grpc/proto/service.proto b/grpc/proto/service.proto similarity index 100% rename from fiber-grpc/proto/service.proto rename to grpc/proto/service.proto diff --git a/fiber-grpc/server/main.go b/grpc/server/main.go similarity index 100% rename from fiber-grpc/server/main.go rename to grpc/server/main.go diff --git a/hello-world/README.md b/hello-world/README.md new file mode 100644 index 0000000000..b98c3fc273 --- /dev/null +++ b/hello-world/README.md @@ -0,0 +1,65 @@ +--- +title: Hello World +keywords: [hello world, golang, fiber] +--- + +# Hello World Example + +This project demonstrates a simple "Hello, World!" application using the Fiber framework in Go. + +## Prerequisites + +Ensure you have the following installed: + +- Golang +- [Fiber](https://github.com/gofiber/fiber) package + +## Setup + +1. Clone the repository: + ```sh + git clone https://github.com/gofiber/recipes.git + cd recipes/hello-world + ``` + +2. Install dependencies: + ```sh + go get + ``` + +## Running the Application + +1. Start the application: + ```sh + go run main.go + ``` + +2. Access the application at `http://localhost:3000`. + +## Example + +Here is an example `main.go` file for the Fiber application: + +```go +package main + +import ( + "log" + "github.com/gofiber/fiber/v2" +) + +func main() { + app := fiber.New() + + app.Get("/", func(c *fiber.Ctx) error { + return c.SendString("Hello, World!") + }) + + log.Fatal(app.Listen(":3000")) +} +``` + +## References + +- [Fiber Documentation](https://docs.gofiber.io) +- [Golang Documentation](https://golang.org/doc/) diff --git a/heroku/README.md b/heroku/README.md new file mode 100644 index 0000000000..ff9a19faab --- /dev/null +++ b/heroku/README.md @@ -0,0 +1,94 @@ +--- +title: Heroku +keywords: [heroku, deployment] +--- + +# Heroku Deployment Example + +This project demonstrates how to deploy a Go application using the Fiber framework on Heroku. + +## Prerequisites + +Ensure you have the following installed: + +- Golang +- [Fiber](https://github.com/gofiber/fiber) package +- [Heroku CLI](https://devcenter.heroku.com/articles/heroku-cli) + +## Setup + +1. Clone the repository: + ```sh + git clone https://github.com/gofiber/recipes.git + cd recipes/heroku + ``` + +2. Install dependencies: + ```sh + go get + ``` + +3. Log in to Heroku: + ```sh + heroku login + ``` + +4. Create a new Heroku application: + ```sh + heroku create + ``` + +5. Add a `Procfile` to the project directory with the following content: + ``` + web: go run main.go + ``` + +6. Deploy the application to Heroku: + ```sh + git add . + git commit -m "Deploy to Heroku" + git push heroku master + ``` + +## Running the Application + +1. Open the application in your browser: + ```sh + heroku open + ``` + +## Example + +Here is an example `main.go` file for the Fiber application: + +```go +package main + +import ( + "log" + "github.com/gofiber/fiber/v2" +) + +func main() { + app := fiber.New() + + app.Get("/", func(c *fiber.Ctx) error { + return c.SendString("Hello, Heroku!") + }) + + log.Fatal(app.Listen(":" + getPort())) +} + +func getPort() string { + port := os.Getenv("PORT") + if port == "" { + port = "3000" + } + return port +} +``` + +## References + +- [Fiber Documentation](https://docs.gofiber.io) +- [Heroku Documentation](https://devcenter.heroku.com/) diff --git a/hexagonal/README.md b/hexagonal/README.md index 68165e1807..19fc172f00 100644 --- a/hexagonal/README.md +++ b/hexagonal/README.md @@ -1,4 +1,93 @@ +--- +title: Hexagonal Architecture +keywords: [hexagonal, architecture, mongodb] +--- + # A Hexagonal Software Architecture in Golang and MongoDB -This presents a simple product catalogue microservice to demonstrate the principles of a hexagonal software architecture. The microservice exposes a RESTful API that allows consuming applications to perform CRUD operations on a product catalogue. The microservice is developed in Golang, and the product catalogue data is persisted in a MongoDB repository. -![](Hexagonal-Arch.png) +This project presents a simple product catalogue microservice to demonstrate the principles of a hexagonal software architecture. The microservice exposes a RESTful API that allows consuming applications to perform CRUD operations on a product catalogue. The microservice is developed in Golang, and the product catalogue data is persisted in a MongoDB repository. + +![Hexagonal Architecture](Hexagonal-Arch.png) + +## Prerequisites + +- Go 1.18 or higher +- MongoDB +- Go modules + +## Setup + +1. Clone the repository: + ```sh + git clone https://github.com/gofiber/recipes.git + cd recipes/hexagonal + ``` + +2. Install dependencies: + ```sh + go mod tidy + ``` + +3. Configure the MongoDB connection in the `config.json` file: + ```json + { + "DB_URI": "your_mongodb_uri", + "DB_Name": "your_db_name" + } + ``` + +## Running the Application + +1. Run the application: + ```sh + go run main.go + ``` + +2. The server will start on `http://localhost:3000`. + +## Endpoints + +| Method | URL | Description | +| ------ | ---------------- | -------------------------------- | +| GET | /api/v1/products | Retrieves all products | +| GET | /api/v1/product/:id | Retrieves a product by ID | +| POST | /api/v1/product | Creates a new product | +| PUT | /api/v1/product/:id | Updates an existing product | +| DELETE | /api/v1/product/:id | Deletes a product | + +## Example Requests + +### Get All Products +```sh +curl -X GET http://localhost:3000/api/v1/products +``` + +### Get Product by ID +```sh +curl -X GET http://localhost:3000/api/v1/product/1 +``` + +### Create a New Product +```sh +curl -X POST http://localhost:3000/api/v1/product -d '{"name": "New Product", "price": 100}' -H "Content-Type: application/json" +``` + +### Update a Product +```sh +curl -X PUT http://localhost:3000/api/v1/product/1 -d '{"name": "Updated Product", "price": 150}' -H "Content-Type: application/json" +``` + +### Delete a Product +```sh +curl -X DELETE http://localhost:3000/api/v1/product/1 +``` + +## Hexagonal Architecture + +Hexagonal architecture, also known as ports and adapters architecture, is a design pattern used to create loosely coupled application components that can be easily connected to their software environment by means of ports and adapters. This architecture allows an application to be equally driven by users, programs, automated tests, or batch scripts, and to be developed and tested in isolation from its eventual runtime devices and databases. + +## Additional Information + +For more information on hexagonal architecture, you can refer to the following resources: +- [Hexagonal Architecture](https://alistair.cockburn.us/hexagonal-architecture/) +- [Hexagonal Architecture in Golang](https://medium.com/@matryer/hexagonal-architecture-in-go-2b5e0df2d8f8) diff --git a/https-pkcs12-tls/README.md b/https-pkcs12-tls/README.md new file mode 100644 index 0000000000..7fa3d0ca7d --- /dev/null +++ b/https-pkcs12-tls/README.md @@ -0,0 +1,107 @@ +--- +title: HTTPS with PKCS12 TLS +keywords: [https, tls, pkcs12] +--- + +# HTTPS with PKCS12 TLS Example + +This project demonstrates how to set up an HTTPS server with PKCS12 TLS in a Go application using the Fiber framework. + +## Prerequisites + +Ensure you have the following installed: + +- Golang +- [Fiber](https://github.com/gofiber/fiber) package +- PKCS12 certificate file (`cert.p12`) + +## Setup + +1. Clone the repository: + ```sh + git clone https://github.com/gofiber/recipes.git + cd recipes/https-pkcs12-tls + ``` + +2. Install dependencies: + ```sh + go get + ``` + +3. Place your PKCS12 certificate file (`cert.p12`) in the project directory. + +## Running the Application + +1. Start the application: + ```sh + go run main.go + ``` + +2. Access the application at `https://localhost:3000`. + +## Example + +Here is an example of how to set up an HTTPS server with PKCS12 TLS in a Fiber application: + +```go +package main + +import ( + "crypto/tls" + "crypto/x509" + "encoding/pem" + "io/ioutil" + "log" + + "github.com/gofiber/fiber/v2" + "golang.org/x/crypto/pkcs12" +) + +func main() { + // Load PKCS12 certificate + p12Data, err := ioutil.ReadFile("cert.p12") + if err != nil { + log.Fatal(err) + } + + // Decode PKCS12 certificate + blocks, err := pkcs12.ToPEM(p12Data, "password") + if err != nil { + log.Fatal(err) + } + + var pemData []byte + for _, b := range blocks { + pemData = append(pemData, pem.EncodeToMemory(b)...) + } + + // Load certificate and key + cert, err := tls.X509KeyPair(pemData, pemData) + if err != nil { + log.Fatal(err) + } + + // Create TLS configuration + tlsConfig := &tls.Config{ + Certificates: []tls.Certificate{cert}, + ClientCAs: x509.NewCertPool(), + } + + // Fiber instance + app := fiber.New() + + // Routes + app.Get("/", func(c *fiber.Ctx) error { + return c.SendString("Hello, HTTPS with PKCS12 TLS!") + }) + + // Start server with TLS + log.Fatal(app.ListenTLS(":3000", tlsConfig)) +} +``` + +## References + +- [Fiber Documentation](https://docs.gofiber.io) +- [TLS in Go](https://golang.org/pkg/crypto/tls/) +- [PKCS12 in Go](https://pkg.go.dev/golang.org/x/crypto/pkcs12) diff --git a/https-tls/README.md b/https-tls/README.md new file mode 100644 index 0000000000..3f9a2284c9 --- /dev/null +++ b/https-tls/README.md @@ -0,0 +1,69 @@ +--- +title: HTTPS with TLS +keywords: [https, tls, ssl, self-signed] +--- + +# HTTPS with TLS Example + +This project demonstrates how to set up an HTTPS server with TLS in a Go application using the Fiber framework. + +## Prerequisites + +Ensure you have the following installed: + +- Golang +- [Fiber](https://github.com/gofiber/fiber) package +- TLS certificates (self-signed or from a trusted CA) + +## Setup + +1. Clone the repository: + ```sh + git clone https://github.com/gofiber/recipes.git + cd recipes/https-tls + ``` + +2. Install dependencies: + ```sh + go get + ``` + +3. Place your TLS certificate (`cert.pem`) and private key (`key.pem`) in the project directory. + +## Running the Application + +1. Start the application: + ```sh + go run main.go + ``` + +2. Access the application at `https://localhost:3000`. + +## Example + +Here is an example of how to set up an HTTPS server with TLS in a Fiber application: + +```go +package main + +import ( + "log" + "github.com/gofiber/fiber/v2" +) + +func main() { + app := fiber.New() + + app.Get("/", func(c *fiber.Ctx) error { + return c.SendString("Hello, HTTPS with TLS!") + }) + + // Start server with TLS + log.Fatal(app.ListenTLS(":3000", "cert.pem", "key.pem")) +} +``` + +## References + +- [Fiber Documentation](https://docs.gofiber.io) +- [TLS in Go](https://golang.org/pkg/crypto/tls/) diff --git a/i18n/README.md b/i18n/README.md index ac301b2422..8b847ff72b 100644 --- a/i18n/README.md +++ b/i18n/README.md @@ -1,3 +1,8 @@ +--- +title: I18n +keywords: [i18n, go-i18n, internationalization] +--- + # Fiber with i18n This is a quick example of how to use [nicksnyder/go-i18n](https://github.com/nicksnyder/go-i18n) package to translate your Fiber application into multiple languages. diff --git a/jwt/README.md b/jwt/README.md index 76f7fd578a..9f93df3c9e 100644 --- a/jwt/README.md +++ b/jwt/README.md @@ -1,3 +1,58 @@ +--- +title: JWT +keywords: [jwt, json web token, authentication] +--- + # Fiber with JWT -Postman examples [here](https://www.getpostman.com/collections/0e83876e0f2a0c8ecd70). \ No newline at end of file +This example demonstrates how to use JSON Web Tokens (JWT) for authentication in a Fiber application. + +## Prerequisites + +- Go 1.16 or higher +- Go modules + +## Setup + +1. Clone the repository: + ```sh + git clone https://github.com/gofiber/recipes.git + cd recipes/jwt + ``` + +2. Install dependencies: + ```sh + go mod tidy + ``` + +## Running the Application + +1. Run the application: + ```sh + go run main.go + ``` + +2. The server will start on `http://localhost:3000`. + +## Endpoints + +| Method | URL | Description | +| ------ | ------------- | -------------------------- | +| POST | /login | Authenticates a user and returns a JWT | +| GET | /restricted | Accesses a restricted route with JWT | + +## Example Requests + +### Login +```sh +curl -X POST http://localhost:3000/login -d '{"username": "user", "password": "pass"}' -H "Content-Type: application/json" +``` + +### Access Restricted Route +```sh +curl -X GET http://localhost:3000/restricted -H "Authorization: Bearer " +``` + +## Postman Collection + +You can find Postman examples [here](https://www.getpostman.com/collections/0e83876e0f2a0c8ecd70). diff --git a/k8s/README.md b/k8s/README.md new file mode 100644 index 0000000000..0671d44c6e --- /dev/null +++ b/k8s/README.md @@ -0,0 +1,148 @@ +--- +title: Kubernetes +keywords: [kubernetes, cloud, deployment, gcloud, aws, azure] +--- + +# Kubernetes Example + +This project demonstrates how to deploy a Go application using the Fiber framework on a Kubernetes cluster. + +## Prerequisites + +Ensure you have the following installed: + +- Golang +- [Fiber](https://github.com/gofiber/fiber) package +- Docker +- Kubernetes +- kubectl +- [Minikube](https://minikube.sigs.k8s.io/docs/start/) (for local development) + +## Setup + +1. Clone the repository: + ```sh + git clone https://github.com/gofiber/recipes.git + cd recipes/kubernetes + ``` + +2. Install dependencies: + ```sh + go get + ``` + +3. Build the Docker image: + ```sh + docker build -t fiber-k8s-example . + ``` + +4. Start Minikube (if using Minikube): + ```sh + minikube start + ``` + +5. Deploy the application to Kubernetes: + ```sh + kubectl apply -f deployment.yaml + ``` + +## Running the Application + +1. Check the status of the pods: + ```sh + kubectl get pods + ``` + +2. Forward the port to access the application: + ```sh + kubectl port-forward svc/fiber-k8s-example 3000:3000 + ``` + +3. Access the application at `http://localhost:3000`. + +## Example + +Here is an example `main.go` file for the Fiber application: + +```go +package main + +import ( + "log" + "github.com/gofiber/fiber/v2" +) + +func main() { + app := fiber.New() + + app.Get("/", func(c *fiber.Ctx) error { + return c.SendString("Hello, Kubernetes!") + }) + + log.Fatal(app.Listen(":3000")) +} +``` + +Here is an example `Dockerfile` for the application: + +```Dockerfile +FROM golang:1.20-alpine + +WORKDIR /app + +COPY go.mod ./ +COPY go.sum ./ +RUN go mod download + +COPY *.go ./ + +RUN go build -o /fiber-k8s-example + +EXPOSE 3000 + +CMD ["/fiber-k8s-example"] +``` + +Here is an example `deployment.yaml` file for deploying the application to Kubernetes: + +```yaml +apiVersion: apps/v1 +kind: Deployment +metadata: + name: fiber-k8s-example +spec: + replicas: 2 + selector: + matchLabels: + app: fiber-k8s-example + template: + metadata: + labels: + app: fiber-k8s-example + spec: + containers: + - name: fiber-k8s-example + image: fiber-k8s-example:latest + ports: + - containerPort: 3000 +--- +apiVersion: v1 +kind: Service +metadata: + name: fiber-k8s-example +spec: + type: NodePort + selector: + app: fiber-k8s-example + ports: + - protocol: TCP + port: 3000 + targetPort: 3000 + nodePort: 30001 +``` + +## References + +- [Fiber Documentation](https://docs.gofiber.io) +- [Kubernetes Documentation](https://kubernetes.io/docs/) +- [Docker Documentation](https://docs.docker.com/) diff --git a/memgraph/README.md b/memgraph/README.md index 033769be36..923d90ac7d 100644 --- a/memgraph/README.md +++ b/memgraph/README.md @@ -1,4 +1,9 @@ -# Fiber and Memgraph +--- +title: Memgraph +keywords: [memgraph, graph, database] +--- + +# Fiber and Memgraph This is a cookbook recipe for setting up Fiber backend and Memgraph database. 🚀 @@ -13,7 +18,7 @@ go get -u github.com/gofiber/fiber/v2 go get github.com/neo4j/neo4j-go-driver/v5 ``` -## Run Memgraph +## Run Memgraph The easiest way to run Memgraph is to use Docker. Once docker is installed on your machine, you can run Memgraph with the following command: @@ -28,10 +33,10 @@ After you have installed all the prerequisites, you can run the recipe with the ``` cd memgraph -go run ./main.go +go run ./main.go ``` -This will do the following: +This will do the following: 1. Connect Fiber backend to Memgraph database 2. Generate mock data to populate the database @@ -50,4 +55,4 @@ http://localhost:3000/developer/Andy For extra information use the documentation on the following links: - Fiber: https://docs.gofiber.io/ -- Memgraph: https://memgraph.com/docs \ No newline at end of file +- Memgraph: https://memgraph.com/docs diff --git a/minio/README.md b/minio/README.md index 385ba7317d..08c3eab87c 100644 --- a/minio/README.md +++ b/minio/README.md @@ -1,3 +1,8 @@ +--- +title: MinIO +keywords: [minio, file upload, file download] +--- + # MinIO File Upload & Download Example This example demonstrates a simple Go Fiber application that includes modules for uploading both single and multiple files, as well as downloading files from MinIO. Each module provides REST API endpoints for file upload and retrieval, serving as a foundation for applications requiring file storage and access. diff --git a/mongodb/README.md b/mongodb/README.md new file mode 100644 index 0000000000..71ff1b3951 --- /dev/null +++ b/mongodb/README.md @@ -0,0 +1,89 @@ +--- +title: MongoDB Example +keywords: [mongodb, database] +--- + +# MongoDB Example + +This project demonstrates how to connect to a MongoDB database in a Go application using the Fiber framework. + +## Prerequisites + +Ensure you have the following installed: + +- Golang +- [Fiber](https://github.com/gofiber/fiber) package +- MongoDB +- [MongoDB Go Driver](https://github.com/mongodb/mongo-go-driver) + +## Setup + +1. Clone the repository: + ```sh + git clone https://github.com/gofiber/recipes.git + cd recipes/mongodb + ``` + +2. Install dependencies: + ```sh + go get + ``` + +3. Set up your MongoDB database and update the connection string in the code. + +## Running the Application + +1. Start the application: + ```sh + go run main.go + ``` + +## Example + +Here is an example of how to connect to a MongoDB database in a Fiber application: + +```go +package main + +import ( + "context" + "log" + "time" + + "github.com/gofiber/fiber/v2" + "go.mongodb.org/mongo-driver/mongo" + "go.mongodb.org/mongo-driver/mongo/options" +) + +func main() { + // MongoDB connection + client, err := mongo.NewClient(options.Client().ApplyURI("mongodb://localhost:27017")) + if err != nil { + log.Fatal(err) + } + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + err = client.Connect(ctx) + if err != nil { + log.Fatal(err) + } + defer client.Disconnect(ctx) + + // Fiber instance + app := fiber.New() + + // Routes + app.Get("/", func(c *fiber.Ctx) error { + return c.SendString("Hello, MongoDB!") + }) + + // Start server + log.Fatal(app.Listen(":3000")) +} +``` + +## References + +- [Fiber Documentation](https://docs.gofiber.io) +- [MongoDB Documentation](https://docs.mongodb.com) +- [MongoDB Go Driver Documentation](https://pkg.go.dev/go.mongodb.org/mongo-driver) diff --git a/multiple-ports/README.md b/multiple-ports/README.md new file mode 100644 index 0000000000..19f717277a --- /dev/null +++ b/multiple-ports/README.md @@ -0,0 +1,81 @@ +--- +title: Multiple Ports +keywords: [multiple ports, server, port] +--- + +# Multiple Ports Example + +This project demonstrates how to run a Go application using the Fiber framework on multiple ports. + +## Prerequisites + +Ensure you have the following installed: + +- Golang +- [Fiber](https://github.com/gofiber/fiber) package + +## Setup + +1. Clone the repository: + ```sh + git clone https://github.com/gofiber/recipes.git + cd recipes/multiple-ports + ``` + +2. Install dependencies: + ```sh + go get + ``` + +## Running the Application + +1. Start the application: + ```sh + go run main.go + ``` + +## Example + +Here is an example of how to run a Fiber application on multiple ports: + +```go +package main + +import ( + "log" + "sync" + + "github.com/gofiber/fiber/v2" +) + +func main() { + app := fiber.New() + + app.Get("/", func(c *fiber.Ctx) error { + return c.SendString("Hello, World!") + }) + + ports := []string{":3000", ":3001"} + + var wg sync.WaitGroup + for _, port := range ports { + wg.Add(1) + go func(p string) { + defer wg.Done() + if err := app.Listen(p); err != nil { + log.Printf("Error starting server on port %s: %v", p, err) + } + }(port) + } + + wg.Wait() +} +``` + +In this example: +- The application listens on multiple ports (`:3000` and `:3001`). +- A `sync.WaitGroup` is used to wait for all goroutines to finish. + +## References + +- [Fiber Documentation](https://docs.gofiber.io) diff --git a/mysql/README.md b/mysql/README.md new file mode 100644 index 0000000000..b50a526f34 --- /dev/null +++ b/mysql/README.md @@ -0,0 +1,87 @@ +--- +title: MySQL +keywords: [mysql] +--- + +# MySQL Example + +This project demonstrates how to connect to a MySQL database in a Go application using the Fiber framework. + +## Prerequisites + +Ensure you have the following installed: + +- Golang +- [Fiber](https://github.com/gofiber/fiber) package +- MySQL +- [Go MySQL Driver](https://github.com/go-sql-driver/mysql) + +## Setup + +1. Clone the repository: + ```sh + git clone https://github.com/gofiber/recipes.git + cd recipes/mysql + ``` + +2. Install dependencies: + ```sh + go get + ``` + +3. Set up your MySQL database and update the connection string in the code. + +## Running the Application + +1. Start the application: + ```sh + go run main.go + ``` + +## Example + +Here is an example of how to connect to a MySQL database in a Fiber application: + +```go +package main + +import ( + "database/sql" + "log" + + "github.com/gofiber/fiber/v2" + _ "github.com/go-sql-driver/mysql" +) + +func main() { + // Database connection + dsn := "username:password@tcp(127.0.0.1:3306)/dbname" + db, err := sql.Open("mysql", dsn) + if err != nil { + log.Fatal(err) + } + defer db.Close() + + // Fiber instance + app := fiber.New() + + // Routes + app.Get("/", func(c *fiber.Ctx) error { + var greeting string + err := db.QueryRow("SELECT 'Hello, World!'").Scan(&greeting) + if err != nil { + return err + } + return c.SendString(greeting) + }) + + // Start server + log.Fatal(app.Listen(":3000")) +} +``` + +## References + +- [Fiber Documentation](https://docs.gofiber.io) +- [MySQL Documentation](https://dev.mysql.com/doc/) +- [Go MySQL Driver Documentation](https://pkg.go.dev/github.com/go-sql-driver/mysql) diff --git a/neo4j/README.md b/neo4j/README.md new file mode 100644 index 0000000000..2e4e4b0fbe --- /dev/null +++ b/neo4j/README.md @@ -0,0 +1,94 @@ +--- +title: Neo4j +keywords: [neo4j, database] +--- + +# Neo4j Example + +This project demonstrates how to connect to a Neo4j database in a Go application using the Fiber framework. + +## Prerequisites + +Ensure you have the following installed: + +- Golang +- [Fiber](https://github.com/gofiber/fiber) package +- Neo4j +- [Neo4j Go Driver](https://github.com/neo4j/neo4j-go-driver) + +## Setup + +1. Clone the repository: + ```sh + git clone https://github.com/gofiber/recipes.git + cd recipes/neo4j + ``` + +2. Install dependencies: + ```sh + go get + ``` + +3. Set up your Neo4j database and update the connection string in the code. + +## Running the Application + +1. Start the application: + ```sh + go run main.go + ``` + +## Example + +Here is an example of how to connect to a Neo4j database in a Fiber application: + +```go +package main + +import ( + "log" + "github.com/gofiber/fiber/v2" + "github.com/neo4j/neo4j-go-driver/v5/neo4j" +) + +func main() { + // Neo4j connection + uri := "neo4j://localhost:7687" + username := "neo4j" + password := "password" + driver, err := neo4j.NewDriver(uri, neo4j.BasicAuth(username, password, "")) + if err != nil { + log.Fatal(err) + } + defer driver.Close() + + // Fiber instance + app := fiber.New() + + // Routes + app.Get("/", func(c *fiber.Ctx) error { + session := driver.NewSession(neo4j.SessionConfig{}) + defer session.Close() + + result, err := session.Run("RETURN 'Hello, World!'", nil) + if err != nil { + return err + } + + if result.Next() { + return c.SendString(result.Record().Values[0].(string)) + } + + return c.SendStatus(500) + }) + + // Start server + log.Fatal(app.Listen(":3000")) +} +``` + +## References + +- [Fiber Documentation](https://docs.gofiber.io) +- [Neo4j Documentation](https://neo4j.com/docs/) +- [Neo4j Go Driver Documentation](https://pkg.go.dev/github.com/neo4j/neo4j-go-driver) diff --git a/oauth2-google/README.md b/oauth2-google/README.md index bb04c28a9d..8508379c78 100644 --- a/oauth2-google/README.md +++ b/oauth2-google/README.md @@ -1,14 +1,69 @@ +--- +title: Google OAuth2 +keywords: [oauth2, google, authentication] +--- + # Fiber with Google OAuth2 -### Implementation of Google OAuth2 with fiber, some packages used are mentioned below -Obtain OAuth credentials from https://console.developers.google.com/ +This example demonstrates how to implement Google OAuth2 authentication in a Fiber application. + +## Prerequisites + +- Go 1.16 or higher +- Go modules + +## Setup + +1. Clone the repository: + ```sh + git clone https://github.com/gofiber/recipes.git + cd recipes/oauth2-google + ``` + +2. Install dependencies: + ```sh + go mod tidy + ``` + +3. Obtain OAuth credentials from [Google Developers Console](https://console.developers.google.com/). + +4. Create a `.env` file in the root directory and add your Google OAuth credentials: + ```env + GOOGLE_CLIENT_ID=your_client_id + GOOGLE_CLIENT_SECRET=your_client_secret + GOOGLE_REDIRECT_URL=http://localhost:3000/api/auth/google/callback + ``` -## Endpoints -- /api/ - redirects to login url +## Running the Application -- /api/auth/google/callback - gives a callback to google and on success return's user's email +1. Run the application: + ```sh + go run main.go + ``` + +2. The server will start on `http://localhost:3000`. + +## Endpoints + +| Method | URL | Description | +| ------ | ---------------------------- | ------------------------------------------------ | +| GET | /api/ | Redirects to Google login URL | +| GET | /api/auth/google/callback | Handles Google OAuth2 callback and returns user's email | + +## Example Requests + +### Redirect to Google Login +```sh +curl -X GET http://localhost:3000/api/ +``` + +### Google OAuth2 Callback +```sh +curl -X GET http://localhost:3000/api/auth/google/callback?state=state&code=code +``` ## Packages Used + - [Godotenv](https://github.com/joho/godotenv) - [Fiber](https://github.com/gofiber/fiber) -- [OAuth2](https://github.com/golang/oauth2) \ No newline at end of file +- [OAuth2](https://github.com/golang/oauth2) diff --git a/testOauth2/.env b/oauth2/.env similarity index 100% rename from testOauth2/.env rename to oauth2/.env diff --git a/testOauth2/.gitignore b/oauth2/.gitignore similarity index 100% rename from testOauth2/.gitignore rename to oauth2/.gitignore diff --git a/oauth2/README.md b/oauth2/README.md new file mode 100644 index 0000000000..28b678e15e --- /dev/null +++ b/oauth2/README.md @@ -0,0 +1,86 @@ +```markdown +--- +title: OAuth2 +keywords: [oauth2, golang, authentication, api] +--- + +# OAuth2 + +This project demonstrates how to implement OAuth2 authentication in a Go application. + +## Prerequisites + +Ensure you have the following installed: + +- Golang +- [OAuth2](https://github.com/golang/oauth2) package + +## Setup + +1. Clone the repository: + ```sh + git clone https://github.com/gofiber/recipes.git + cd recipes/oauth2 + ``` + +2. Install dependencies: + ```sh + go get + ``` + +## Running the Application + +1. Start the application: + ```sh + go run main.go + ``` + +## Environment Variables + +Create a `.env` file in the root directory and add the following variables: + +```shell +# CLIENT_ID is the OAuth2 client ID +CLIENT_ID= + +# CLIENT_SECRET is the OAuth2 client secret +CLIENT_SECRET= + +# REDIRECT_URL is the OAuth2 redirect URL +REDIRECT_URL= + +# AUTH_URL is the OAuth2 authorization URL +AUTH_URL= + +# TOKEN_URL is the OAuth2 token URL +TOKEN_URL= +``` + +## Example + +Here is an example of how to set up an OAuth2 configuration: + +```go +package main + +import ( + "golang.org/x/oauth2" + "golang.org/x/oauth2/google" +) + +func main() { + conf := &oauth2.Config{ + ClientID: "your-client-id", + ClientSecret: "your-client-secret", + RedirectURL: "your-redirect-url", + Endpoint: google.Endpoint, + } + + // Your code here +} +``` + +## References + +- [OAuth2 Package Documentation](https://pkg.go.dev/golang.org/x/oauth2) +- [Google OAuth2 Documentation](https://developers.google.com/identity/protocols/oauth2) diff --git a/testOauth2/app.go b/oauth2/app.go similarity index 97% rename from testOauth2/app.go rename to oauth2/app.go index 18ee35f48f..485541aeac 100644 --- a/testOauth2/app.go +++ b/oauth2/app.go @@ -5,12 +5,12 @@ import ( "fmt" "io/fs" "net/http" + "oauth2/config" + "oauth2/models" + "oauth2/router" "os" "os/signal" "syscall" - "testOauth2/config" - "testOauth2/models" - "testOauth2/router" "time" "github.com/antigloss/go/logger" diff --git a/testOauth2/config/config.go b/oauth2/config/config.go similarity index 100% rename from testOauth2/config/config.go rename to oauth2/config/config.go diff --git a/testOauth2/go.mod b/oauth2/go.mod similarity index 98% rename from testOauth2/go.mod rename to oauth2/go.mod index 13ab561f16..9b19c08de3 100644 --- a/testOauth2/go.mod +++ b/oauth2/go.mod @@ -1,4 +1,4 @@ -module testOauth2 +module oauth2 go 1.18 diff --git a/testOauth2/go.sum b/oauth2/go.sum similarity index 100% rename from testOauth2/go.sum rename to oauth2/go.sum diff --git a/testOauth2/handlers/handlers.go b/oauth2/handlers/handlers.go similarity index 97% rename from testOauth2/handlers/handlers.go rename to oauth2/handlers/handlers.go index 46804c0c72..7b42455cc7 100644 --- a/testOauth2/handlers/handlers.go +++ b/oauth2/handlers/handlers.go @@ -1,7 +1,7 @@ package handlers import ( - "testOauth2/models" + "oauth2/models" "github.com/gofiber/fiber/v2" ) diff --git a/oauth2/makefile b/oauth2/makefile new file mode 100644 index 0000000000..7a8ed7846b --- /dev/null +++ b/oauth2/makefile @@ -0,0 +1,25 @@ +NPROCS = $(shell grep -c 'processor' /proc/cpuinfo) +MAKEFLAGS += -j$(NPROCS) + +.PHONY: clean +clean: + @rm -fv ./oauth2 + @rm -fv ./logs/* + + +.PHONY: run +run: clean + @GOOS=linux go build -o ./oauth2 ./*.go + ./oauth2 + +.PHONY: build +build: clean + @GOOS=linux go build -o ./oauth2 ./*.go + +.PHONY: buildrelease +buildrelease: + @GOOS=linux go build -ldflags="-s -w" -o ./oauth2 ./*.go + @upx --brute ./oauth2 + +.PHONY: release +release: clean buildrelease diff --git a/testOauth2/middleware/auth.go b/oauth2/middleware/auth.go similarity index 99% rename from testOauth2/middleware/auth.go rename to oauth2/middleware/auth.go index 3b21c9eb59..976c0299c5 100644 --- a/testOauth2/middleware/auth.go +++ b/oauth2/middleware/auth.go @@ -2,7 +2,7 @@ package middleware import ( "fmt" - "testOauth2/models" + "oauth2/models" "github.com/gofiber/fiber/v2" "github.com/gofiber/fiber/v2/middleware/session" diff --git a/testOauth2/models/models.go b/oauth2/models/models.go similarity index 100% rename from testOauth2/models/models.go rename to oauth2/models/models.go diff --git a/testOauth2/router/router.go b/oauth2/router/router.go similarity index 96% rename from testOauth2/router/router.go rename to oauth2/router/router.go index 81c9330bba..a4ac6fe6db 100644 --- a/testOauth2/router/router.go +++ b/oauth2/router/router.go @@ -1,8 +1,8 @@ package router import ( - "testOauth2/handlers" - "testOauth2/middleware" + "oauth2/handlers" + "oauth2/middleware" "github.com/gofiber/fiber/v2" "github.com/gofiber/fiber/v2/middleware/cors" diff --git a/testOauth2/www/errpage.html b/oauth2/www/errpage.html similarity index 100% rename from testOauth2/www/errpage.html rename to oauth2/www/errpage.html diff --git a/testOauth2/www/index.html b/oauth2/www/index.html similarity index 100% rename from testOauth2/www/index.html rename to oauth2/www/index.html diff --git a/testOauth2/www/protected.html b/oauth2/www/protected.html similarity index 100% rename from testOauth2/www/protected.html rename to oauth2/www/protected.html diff --git a/testOauth2/www/welcome.html b/oauth2/www/welcome.html similarity index 100% rename from testOauth2/www/welcome.html rename to oauth2/www/welcome.html diff --git a/optional-parameter/README.md b/optional-parameter/README.md new file mode 100644 index 0000000000..83fdfce8fc --- /dev/null +++ b/optional-parameter/README.md @@ -0,0 +1,66 @@ +--- +title: Optional Parameter Example +keywords: [optional, parameter] +--- + +# Optional Parameter Example + +This project demonstrates how to handle optional parameters in a Go application using the Fiber framework. + +## Prerequisites + +Ensure you have the following installed: + +- Golang +- [Fiber](https://github.com/gofiber/fiber) package + +## Setup + +1. Clone the repository: + ```sh + git clone https://github.com/gofiber/recipes.git + cd recipes/optional-parameter + ``` + +2. Install dependencies: + ```sh + go get + ``` + +## Running the Application + +1. Start the application: + ```sh + go run main.go + ``` + +## Example + +Here is an example of how to handle optional parameters in a Fiber application: + +```go +package main + +import ( + "github.com/gofiber/fiber/v2" +) + +func main() { + app := fiber.New() + + app.Get("/user/:id?", func(c *fiber.Ctx) error { + id := c.Params("id", "defaultID") + return c.SendString("User ID: " + id) + }) + + app.Listen(":3000") +} +``` + +In this example: +- The `:id?` parameter in the route is optional. +- If the `id` parameter is not provided, it defaults to `"defaultID"`. + +## References + +- [Fiber Documentation](https://docs.gofiber.io) diff --git a/overview.go b/overview.go new file mode 100644 index 0000000000..cd3b399277 --- /dev/null +++ b/overview.go @@ -0,0 +1,126 @@ +package main + +import ( + "fmt" + "os" + "path/filepath" + "regexp" + "strings" +) + +//go:generate go run overview.go +func main() { + // fetch current file directory + root, _ := os.Getwd() + toc := "" + missingReadmeDirs := []string{} + missingTitleDirs := []string{} + missingKeywordsDirs := []string{} + + err := filepath.Walk(root, func(path string, info os.FileInfo, err error) error { + if err != nil { + return err + } + if info.IsDir() && path != root && filepath.Dir(path) == root && !strings.HasPrefix(info.Name(), ".") { + readmePath := filepath.Join(path, "README.md") + relativePath, err := filepath.Rel(root, path) + if err != nil { + return err + } + if _, err := os.Stat(readmePath); err == nil { + title, keywords, err := extractTitleAndKeywords(readmePath) + if err != nil { + return err + } + if title == "" { + missingTitleDirs = append(missingTitleDirs, relativePath) + } + if len(keywords) == 0 { + missingKeywordsDirs = append(missingKeywordsDirs, relativePath) + } + if title == "" { + title = "No title" + } + toc += fmt.Sprintf("- [%s](./%s)\n", title, relativePath) + } else { + missingReadmeDirs = append(missingReadmeDirs, relativePath) + } + } + return nil + }) + if err != nil { + fmt.Println("Error:", err) + return + } + + readmePath := filepath.Join(root, "README.md") + content, err := os.ReadFile(readmePath) + if err != nil { + fmt.Println("Error:", err) + return + } + + re := regexp.MustCompile(`(?s)(.*?)`) + newContent := re.ReplaceAllString(string(content), fmt.Sprintf("\n%s", toc)) + + err = os.WriteFile(readmePath, []byte(newContent), 0644) + if err != nil { + fmt.Println("Error:", err) + return + } + + fmt.Println("Table of contents updated successfully.") + + if len(missingReadmeDirs) > 0 { + fmt.Println("Directories without README.md:") + for _, dir := range missingReadmeDirs { + fmt.Println("-", dir) + } + } + + if len(missingTitleDirs) > 0 { + fmt.Println("Directories without Docusaurus title:") + for _, dir := range missingTitleDirs { + fmt.Println("-", dir) + } + } + + if len(missingKeywordsDirs) > 0 { + fmt.Println("Directories without Docusaurus keywords:") + for _, dir := range missingKeywordsDirs { + fmt.Println("-", dir) + } + } + + if len(missingReadmeDirs) > 0 || len(missingTitleDirs) > 0 || len(missingKeywordsDirs) > 0 { + fmt.Println("Error: Some directories are missing README.md files, Docusaurus title, or keywords.") + os.Exit(1) + } +} + +func extractTitleAndKeywords(readmePath string) (string, []string, error) { + content, err := os.ReadFile(readmePath) + if err != nil { + return "", nil, err + } + titleRe := regexp.MustCompile(`(?m)^title: (.+)`) + keywordsRe := regexp.MustCompile(`(?m)^keywords: \[(.+)\]`) + + titleMatches := titleRe.FindSubmatch(content) + keywordsMatches := keywordsRe.FindSubmatch(content) + + var title string + if len(titleMatches) > 1 { + title = string(titleMatches[1]) + } + + var keywords []string + if len(keywordsMatches) > 1 { + keywords = strings.Split(string(keywordsMatches[1]), ",") + for i := range keywords { + keywords[i] = strings.TrimSpace(keywords[i]) + } + } + + return title, keywords, nil +} diff --git a/parsley/README.md b/parsley/README.md index e28e258b05..555b4b6cef 100644 --- a/parsley/README.md +++ b/parsley/README.md @@ -1,3 +1,8 @@ +--- +title: Parsley +keywords: [parsley, dependency injection, di, inversion of control, ioc] +--- + # Fiber with Dependency Injection (via Parsley) This example demonstrates integrating the [Parsley dependency injection framework](https://github.com/matzefriedrich/parsley) into a GoFiber web application. The goal is to showcase how dependency injection can create a clean, maintainable, and modular structure in your GoFiber projects. @@ -29,4 +34,4 @@ To run this example: * Clone the repository and navigate to the example directory. * Run `go run main.go` to start the application. -* Access the application by navigating to `http://localhost:5502/say-hello?name=YourName`. This will return a greeting message, demonstrating the integration of Parsley with GoFiber. \ No newline at end of file +* Access the application by navigating to `http://localhost:5502/say-hello?name=YourName`. This will return a greeting message, demonstrating the integration of Parsley with GoFiber. diff --git a/postgresql/README.md b/postgresql/README.md new file mode 100644 index 0000000000..845b8bbef5 --- /dev/null +++ b/postgresql/README.md @@ -0,0 +1,86 @@ +--- +title: PostgreSQL Example +keywords: [postgresql] +--- + +# PostgreSQL Example + +This project demonstrates how to connect to a PostgreSQL database in a Go application using the Fiber framework. + +## Prerequisites + +Ensure you have the following installed: + +- Golang +- [Fiber](https://github.com/gofiber/fiber) package +- PostgreSQL + +## Setup + +1. Clone the repository: + ```sh + git clone https://github.com/gofiber/recipes.git + cd recipes/postgresql + ``` + +2. Install dependencies: + ```sh + go get + ``` + +Here is an example of how to connect to a PostgreSQL database in a Fiber application: + +```go +package main + +import ( + "database/sql" + "log" + + "github.com/gofiber/fiber/v2" + _ "github.com/lib/pq" +) + +func main() { + // Database connection +3. Set up your PostgreSQL database and update the connection string in the code. + +## Running the Application + +1. Start the application: + ```sh + go run main.go + ``` + +## Example + + connStr := "user=username dbname=mydb sslmode=disable" + db, err := sql.Open("postgres", connStr) + if err != nil { + log.Fatal(err) + } + defer db.Close() + + // Fiber instance + app := fiber.New() + + // Routes + app.Get("/", func(c *fiber.Ctx) error { + var greeting string + err := db.QueryRow("SELECT 'Hello, World!'").Scan(&greeting) + if err != nil { + return err + } + return c.SendString(greeting) + }) + + // Start server + log.Fatal(app.Listen(":3000")) +} +``` + +## References + +- [Fiber Documentation](https://docs.gofiber.io) +- [PostgreSQL Documentation](https://www.postgresql.org/docs/) +- [pq Driver Documentation](https://pkg.go.dev/github.com/lib/pq) diff --git a/prefork/README.md b/prefork/README.md new file mode 100644 index 0000000000..86e1d58785 --- /dev/null +++ b/prefork/README.md @@ -0,0 +1,69 @@ +--- +title: Prefork Example +keywords: [prefork] +--- + +# Prefork Example + +This project demonstrates how to use the `Prefork` feature in a Go application using the Fiber framework. Preforking can improve performance by utilizing multiple CPU cores. + +## Prerequisites + +Ensure you have the following installed: + +- Golang +- [Fiber](https://github.com/gofiber/fiber) package + +## Setup + +1. Clone the repository: + ```sh + git clone https://github.com/gofiber/recipes.git + cd recipes/prefork + ``` + +2. Install dependencies: + ```sh + go get + ``` + +## Running the Application + +1. Start the application: + ```sh + go run main.go + ``` + +## Example + +Here is an example of how to set up the `Prefork` feature in a Fiber application: + +```go +package main + +import ( + "log" + + "github.com/gofiber/fiber/v2" +) + +func main() { + // Fiber instance with Prefork enabled + app := fiber.New(fiber.Config{ + Prefork: true, + }) + + // Routes + app.Get("/", func(c *fiber.Ctx) error { + return c.SendString("Hello, World!") + }) + + // Start server + log.Fatal(app.Listen(":3000")) +} +``` + +## References + +- [Fiber Documentation](https://docs.gofiber.io) +- [Fiber Prefork Documentation](https://docs.gofiber.io/api/fiber#prefork) diff --git a/rabbitmq/README.md b/rabbitmq/README.md index 229e17d742..b1e2c51989 100644 --- a/rabbitmq/README.md +++ b/rabbitmq/README.md @@ -1,3 +1,8 @@ +--- +title: RabbitMQ +keywords: [rabbitmq, amqp, messaging, queue] +--- + # Fiber and RabbitMQ example 1. Create Docker network: diff --git a/react-router/README.md b/react-router/README.md index 2e39c5f20b..e73c653005 100644 --- a/react-router/README.md +++ b/react-router/README.md @@ -1,3 +1,8 @@ +--- +title: React +keywords: [react, react-router, client-side, spa, docker] +--- + # React Fiber A sample application to showcase serving React (with Router) with an almost bare Fiber. Hopefully, this application can be of use (as a reference or others) for those who wants to serve their client-side SPA with Fiber. diff --git a/recover/README.md b/recover/README.md new file mode 100644 index 0000000000..3e54a28077 --- /dev/null +++ b/recover/README.md @@ -0,0 +1,67 @@ +--- +title: Recover Middleware Example +keywords: [recover, middleware] +--- + +# Recover Middleware Example + +This project demonstrates how to implement a recovery mechanism in a Go application using the Fiber framework's `Recover` middleware. + +## Prerequisites + +Ensure you have the following installed: + +- Golang +- [Fiber](https://github.com/gofiber/fiber) package + +## Setup + +1. Clone the repository: + ```sh + git clone https://github.com/gofiber/recipes.git + cd recipes/recover + ``` + +2. Install dependencies: + ```sh + go get + ``` + +## Running the Application + +1. Start the application: + ```sh + go run main.go + ``` + +## Example + +Here is an example of how to set up the `Recover` middleware in a Fiber application: + +```go +package main + +import ( + "github.com/gofiber/fiber/v2" + "github.com/gofiber/fiber/v2/middleware/recover" +) + +func main() { + app := fiber.New() + + // Use the Recover middleware + app.Use(recover.New()) + + app.Get("/", func(c *fiber.Ctx) error { + // This will cause a panic + panic("something went wrong") + }) + + app.Listen(":3000") +} +``` + +## References + +- [Fiber Documentation](https://docs.gofiber.io) +- [Fiber Recover Middleware Documentation](https://docs.gofiber.io/api/middleware/recover) diff --git a/rss-feed/README.md b/rss-feed/README.md new file mode 100644 index 0000000000..30b2f1d968 --- /dev/null +++ b/rss-feed/README.md @@ -0,0 +1,95 @@ +--- +title: RSS Feed +keywords: [rss, feed] +--- + +# RSS Feed + +This project demonstrates how to create an RSS feed in a Go application using the Fiber framework. + +## Prerequisites + +Ensure you have the following installed: + +- Golang +- [Fiber](https://github.com/gofiber/fiber) package + +## Setup + +1. Clone the repository: + ```sh + git clone https://github.com/gofiber/recipes.git + cd recipes/rss-feed + ``` + +2. Install dependencies: + ```sh + go get + ``` + +## Running the Application + +1. Start the application: + ```sh + go run main.go + ``` + +## Example + +Here is an example of how to create an RSS feed in a Fiber application: + +```go +package main + +import ( + "github.com/gofiber/fiber/v2" + "github.com/gorilla/feeds" + "time" +) + +func main() { + app := fiber.New() + + app.Get("/rss", func(c *fiber.Ctx) error { + feed := &feeds.Feed{ + Title: "Example RSS Feed", + Link: &feeds.Link{Href: "http://example.com/rss"}, + Description: "This is an example RSS feed", + Author: &feeds.Author{Name: "John Doe", Email: "john@example.com"}, + Created: time.Now(), + } + + feed.Items = []*feeds.Item{ + { + Title: "First Post", + Link: &feeds.Link{Href: "http://example.com/post/1"}, + Description: "This is the first post", + Author: &feeds.Author{Name: "John Doe", Email: "john@example.com"}, + Created: time.Now(), + }, + { + Title: "Second Post", + Link: &feeds.Link{Href: "http://example.com/post/2"}, + Description: "This is the second post", + Author: &feeds.Author{Name: "Jane Doe", Email: "jane@example.com"}, + Created: time.Now(), + }, + } + + rss, err := feed.ToRss() + if err != nil { + return err + } + + c.Set("Content-Type", "application/rss+xml") + return c.SendString(rss) + }) + + app.Listen(":3000") +} +``` + +## References + +- [Fiber Documentation](https://docs.gofiber.io) +- [Gorilla Feeds Documentation](https://pkg.go.dev/github.com/gorilla/feeds) diff --git a/server-timing/README.md b/server-timing/README.md new file mode 100644 index 0000000000..3a204f0196 --- /dev/null +++ b/server-timing/README.md @@ -0,0 +1,71 @@ +--- +title: Server Timing +keywords: [server timing] +--- + +# Server Timing + +This project demonstrates how to implement Server-Timing headers in a Go application using the Fiber framework. + +## Prerequisites + +Ensure you have the following installed: + +- Golang +- [Fiber](https://github.com/gofiber/fiber) package + +## Setup + +1. Clone the repository: + ```sh + git clone https://github.com/gofiber/recipes.git + cd recipes/server-timing + ``` + +2. Install dependencies: + ```sh + go get + ``` + +## Running the Application + +1. Start the application: + ```sh + go run main.go + ``` + +## Example + +Here is an example of how to set up Server-Timing headers in a Fiber application: + +```go +package main + +import ( + "github.com/gofiber/fiber/v2" + "time" +) + +func main() { + app := fiber.New() + + app.Use(func(c *fiber.Ctx) error { + start := time.Now() + err := c.Next() + duration := time.Since(start) + c.Append("Server-Timing", "app;dur="+duration.String()) + return err + }) + + app.Get("/", func(c *fiber.Ctx) error { + return c.SendString("Hello, World!") + }) + + app.Listen(":3000") +} +``` + +## References + +- [Fiber Documentation](https://docs.gofiber.io) +- [Server-Timing Header Documentation](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Server-Timing) diff --git a/sessions-sqlite3/README.md b/sessions-sqlite3/README.md index f3db7fc474..9dba0b3f47 100644 --- a/sessions-sqlite3/README.md +++ b/sessions-sqlite3/README.md @@ -1,9 +1,49 @@ +--- +title: Sessions + SQLite3 +keywords: [sessions, sqlite3, storage] +--- + # Sessions - SQLite3 -A real-world example of how to use Fiber sessions with Storage package.\ -Run localhost:3000 from multiple browsers to see active sessions for different users. +This example demonstrates how to use Fiber sessions with the SQLite3 storage package. Run `localhost:3000` from multiple browsers to see active sessions for different users. + +## Prerequisites + +- Go 1.16 or higher +- Go modules + +## Setup + +1. Clone the repository: + ```sh + git clone https://github.com/gofiber/recipes.git + cd recipes/sessions-sqlite3 + ``` + +2. Install dependencies: + ```sh + go mod tidy + ``` + +3. Create the sessions table in SQLite3: + ```sql + CREATE TABLE sessions ( + key TEXT PRIMARY KEY, + data BLOB, + expiry INTEGER, + u TEXT + ); + ``` + +## Running the Application + +1. Run the application: + ```sh + go run main.go + ``` + +2. The server will start on `http://localhost:3000`. ## Explanation -This example uses SQLite3 Storage package to persist users sessions.\ -Storage package can create sessions table for you at init time but for the purpose of this example I created it manually expanding its structure with an "u" column to better query all user-related sessions. \ No newline at end of file +This example uses the SQLite3 storage package to persist user sessions. The storage package can create the sessions table for you at initialization, but for the purpose of this example, the table is created manually with an additional "u" column to better query all user-related sessions. diff --git a/socketio/README.md b/socketio/README.md index 21fbaf320c..9c70b3df41 100644 --- a/socketio/README.md +++ b/socketio/README.md @@ -1,20 +1,53 @@ -### Disclaimer: -__This an example of a basic chat, connecting multiple sockets.__ +--- +title: Socketio +keywords: [websocket, chat, socketio, chatroom, contrib] +--- -## Websocket Chat Example -With this example, you can create a simple chatroom using Websockets. This example supports multiple users and allows them to send messages to each other. +# WebSocket Chat Example -### Connect to the websocket +This example demonstrates how to create a simple chatroom using WebSockets. The chatroom supports multiple users and allows them to send messages to each other. + +## Prerequisites + +- Go 1.16 or higher +- Go modules + +## Setup + +1. Clone the repository: + ```sh + git clone https://github.com/gofiber/recipes.git + cd recipes/socketio-chat + ``` + +2. Install dependencies: + ```sh + go mod tidy + ``` + +## Running the Application + +1. Run the application: + ```sh + go run main.go + ``` + +2. The server will start on `http://localhost:3000`. + +## Connecting to the WebSocket + +To connect to the WebSocket, use the following URL: ``` ws://localhost:3000/ws/ ``` -### Message object example -``` +## Message Object Example + +Here is an example of a message object that can be sent between users: +```json { -"from": "", -"to": "", -"data": "hello" + "from": "", + "to": "", + "data": "hello" } ``` - diff --git a/spa/README.md b/spa/README.md new file mode 100644 index 0000000000..de1dac4468 --- /dev/null +++ b/spa/README.md @@ -0,0 +1,97 @@ +--- +title: Single Page Application (SPA) +keywords: [spa, react, tailwindcss, parcel] +--- + +# Single Page Application (SPA) + +This project demonstrates how to set up a Single Page Application (SPA) using React for the frontend and Go with the Fiber framework for the backend. + +## Prerequisites + +Ensure you have the following installed: + +- Golang +- Node.js +- npm + +## Setup + +1. Clone the repository: + ```sh + git clone https://github.com/gofiber/recipes.git + cd recipes/spa + ``` + +2. Install frontend dependencies: + ```sh + cd frontend + npm install + ``` + +3. Install backend dependencies: + ```sh + cd ../backend + go get + ``` + +## Usage + +### Building Frontend Assets + +1. Build the frontend assets: + ```sh + cd frontend + npm run build + ``` + +2. Watch frontend assets for changes: + ```sh + npm run dev + ``` + +### Running the Application + +1. Start the Fiber backend application: + ```sh + cd backend + go run main.go + ``` + +## Example + +Here is an example of how to set up a basic route in the Fiber backend to serve the React frontend: + +```go +package main + +import ( + "github.com/gofiber/fiber/v2" + "github.com/gofiber/fiber/v2/middleware/logger" +) + +func main() { + app := fiber.New() + + // Middleware + app.Use(logger.New()) + + // Serve static files + app.Static("/", "./frontend/dist") + + // API routes + app.Get("/api/hello", func(c *fiber.Ctx) error { + return c.JSON(fiber.Map{"message": "Hello, World!"}) + }) + + // Start server + app.Listen(":3000") +} +``` + +## References + +- [Fiber Documentation](https://docs.gofiber.io) +- [React Documentation](https://reactjs.org/docs/getting-started.html) +- [Tailwind CSS Documentation](https://tailwindcss.com/docs) +- [Parcel Documentation](https://parceljs.org/docs) diff --git a/sqlboiler/README.md b/sqlboiler/README.md index d216a02177..79b9f0ef17 100644 --- a/sqlboiler/README.md +++ b/sqlboiler/README.md @@ -1,3 +1,8 @@ +--- +title: Sqlboiler +keywords: [sqlboiler, database, docker] +--- + # Fiber with sqlboiler > #### 🎯 [Fiber](https://github.com/gofiber/fiber) + [Sqlboiler](https://github.com/volatiletech/sqlboiler) Example diff --git a/sqlc/README.md b/sqlc/README.md index efc24c8c1a..d92df594a5 100644 --- a/sqlc/README.md +++ b/sqlc/README.md @@ -1,3 +1,8 @@ +--- +title: Sqlc +keywords: [database, sqlc, postgresql] +--- + # Fiber with sqlc > #### 🎯 [fiber](https://github.com/gofiber/fiber) + [sqlc](https://github.com/sqlc-dev/sqlc) Example @@ -132,4 +137,4 @@ sqlc/ ├── post.sql.go ``` #### 5. Reference -[sqlc document](https://docs.sqlc.dev/en/stable/) \ No newline at end of file +[sqlc document](https://docs.sqlc.dev/en/stable/) diff --git a/sse/README.md b/sse/README.md index 1f332d5aa6..505d4b3417 100644 --- a/sse/README.md +++ b/sse/README.md @@ -1,8 +1,67 @@ +--- +title: Server-Sent Events +keywords: [sse, server-sent events, real-time] +--- + # Server-Sent Events with Fiber -[More info](https://en.wikipedia.org/wiki/Server-sent_events) about SSE. +This example demonstrates how to implement Server-Sent Events (SSE) in a Fiber application. + +## Description + +Server-Sent Events (SSE) allow servers to push updates to the client over a single HTTP connection. This is useful for real-time applications where the server needs to continuously send data to the client, such as live feeds, notifications, or real-time charts. + +## Prerequisites + +- Go 1.16 or higher +- Go modules + +## Setup + +1. Clone the repository: + ```sh + git clone https://github.com/gofiber/recipes.git + cd recipes/sse + ``` + +2. Install dependencies: + ```sh + go mod tidy + ``` + +## Running the Application + +1. Run the application: + ```sh + go run main.go + ``` + +2. The server will start on `http://localhost:3000`. ## Endpoints -- GET / - _Index_ -- GET /sse - _SSE Route_ +- **GET /**: Index page +- **GET /sse**: SSE route + +## Example Usage + +1. Open your browser and navigate to `http://localhost:3000`. +2. The client will automatically connect to the SSE endpoint and start receiving updates from the server. + +## Code Overview + +### `main.go` + +The main Go file sets up the Fiber application and handles the SSE connections. It includes the necessary configuration to send events to the client. + +### `index.html` + +The HTML file provides a simple user interface to connect to the SSE endpoint and display the received messages. + +## Additional Information + +Server-Sent Events (SSE) is a standard allowing servers to push data to web clients over HTTP. Unlike WebSockets, which require a full-duplex connection, SSE uses a unidirectional connection from the server to the client. This makes SSE simpler to implement and more efficient for scenarios where only the server needs to send updates. + +For more information on SSE, you can refer to the following resources: +- [Server-Sent Events on MDN](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events) +- [Server-Sent Events on Wikipedia](https://en.wikipedia.org/wiki/Server-sent_events) diff --git a/stream-request-body/README.md b/stream-request-body/README.md new file mode 100644 index 0000000000..93df4ff1fd --- /dev/null +++ b/stream-request-body/README.md @@ -0,0 +1,77 @@ +--- +title: Stream Request Body +keywords: [stream, request body] +--- + +# Stream Request Body + +This project demonstrates how to handle streaming request bodies in a Go application using the Fiber framework. + +## Prerequisites + +Ensure you have the following installed: + +- Golang +- [Fiber](https://github.com/gofiber/fiber) package + +## Setup + +1. Clone the repository: + ```sh + git clone https://github.com/gofiber/recipes.git + cd recipes/stream-request-body + ``` + +2. Install dependencies: + ```sh + go get + ``` + +## Running the Application + +1. Start the application: + ```sh + go run main.go + ``` + +## Example + +Here is an example of how to handle a streaming request body in Go using Fiber: + +```go +package main + +import ( + "github.com/gofiber/fiber/v2" + "io" + "log" +) + +func main() { + app := fiber.New() + + app.Post("/upload", func(c *fiber.Ctx) error { + // Open a file to write the streamed data + file, err := os.Create("uploaded_file") + if err != nil { + return err + } + defer file.Close() + + // Stream the request body to the file + _, err = io.Copy(file, c.BodyStream()) + if err != nil { + return err + } + + return c.SendString("File uploaded successfully") + }) + + log.Fatal(app.Listen(":3000")) +} +``` + +## References + +- [Fiber Documentation](https://docs.gofiber.io) +- [Go io Package Documentation](https://pkg.go.dev/io) diff --git a/fiber-svelte-netlify/.gitignore b/svelte-netlify/.gitignore similarity index 100% rename from fiber-svelte-netlify/.gitignore rename to svelte-netlify/.gitignore diff --git a/fiber-svelte-netlify/LICENSE b/svelte-netlify/LICENSE similarity index 100% rename from fiber-svelte-netlify/LICENSE rename to svelte-netlify/LICENSE diff --git a/fiber-svelte-netlify/README.md b/svelte-netlify/README.md similarity index 90% rename from fiber-svelte-netlify/README.md rename to svelte-netlify/README.md index 79fe60b777..c1f687a9a6 100644 --- a/fiber-svelte-netlify/README.md +++ b/svelte-netlify/README.md @@ -1,3 +1,8 @@ +--- +title: Svelte Netlify +keywords: [netlify, deploy, svelte] +--- + # Deploying fiber on Netlify [![Netlify Status](https://api.netlify.com/api/v1/badges/143c3c42-60f7-427a-b3fd-8ca3947a2d40/deploy-status)](https://app.netlify.com/sites/gofiber-svelte/deploys) @@ -6,7 +11,7 @@ #### Based on the fiber-lambda API written by Fenny. Since the code hasn't been merged yet, I borrowed it into `adapter/adapter.go` -The app uses static pages under `public` directory. These are compiled using sveltejs and the complete template can be found [here](https://github.com/amalshaji/gofiber-sveltejs-netlify). +The app uses static pages under `public` directory. These are compiled using sveltejs and the complete template can be found [here](https://github.com/amalshaji/gofiber-sveltejs-netlify). ```toml @@ -37,4 +42,4 @@ Deploying `net/http to Netlify` explains what these functions are doing. You can - status = 200 for server side redirects #### Important -Netlify functions allows you to have up to 125,000 requests a month. This means you can have 2.89 requests per minute. Make sure you use `Cache` in you request handlers. \ No newline at end of file +Netlify functions allows you to have up to 125,000 requests a month. This means you can have 2.89 requests per minute. Make sure you use `Cache` in you request handlers. diff --git a/fiber-svelte-netlify/adapter/adapter.go b/svelte-netlify/adapter/adapter.go similarity index 100% rename from fiber-svelte-netlify/adapter/adapter.go rename to svelte-netlify/adapter/adapter.go diff --git a/fiber-svelte-netlify/build.sh b/svelte-netlify/build.sh similarity index 100% rename from fiber-svelte-netlify/build.sh rename to svelte-netlify/build.sh diff --git a/fiber-svelte-netlify/cmd/gateway/main.go b/svelte-netlify/cmd/gateway/main.go similarity index 100% rename from fiber-svelte-netlify/cmd/gateway/main.go rename to svelte-netlify/cmd/gateway/main.go diff --git a/fiber-svelte-netlify/functions/.keep b/svelte-netlify/functions/.keep similarity index 100% rename from fiber-svelte-netlify/functions/.keep rename to svelte-netlify/functions/.keep diff --git a/fiber-svelte-netlify/go.mod b/svelte-netlify/go.mod similarity index 100% rename from fiber-svelte-netlify/go.mod rename to svelte-netlify/go.mod diff --git a/fiber-svelte-netlify/go.sum b/svelte-netlify/go.sum similarity index 100% rename from fiber-svelte-netlify/go.sum rename to svelte-netlify/go.sum diff --git a/fiber-svelte-netlify/handler/handler.go b/svelte-netlify/handler/handler.go similarity index 100% rename from fiber-svelte-netlify/handler/handler.go rename to svelte-netlify/handler/handler.go diff --git a/fiber-svelte-netlify/netlify.toml b/svelte-netlify/netlify.toml similarity index 100% rename from fiber-svelte-netlify/netlify.toml rename to svelte-netlify/netlify.toml diff --git a/fiber-svelte-netlify/public/build/bundle.css b/svelte-netlify/public/build/bundle.css similarity index 100% rename from fiber-svelte-netlify/public/build/bundle.css rename to svelte-netlify/public/build/bundle.css diff --git a/fiber-svelte-netlify/public/build/bundle.css.map b/svelte-netlify/public/build/bundle.css.map similarity index 100% rename from fiber-svelte-netlify/public/build/bundle.css.map rename to svelte-netlify/public/build/bundle.css.map diff --git a/fiber-svelte-netlify/public/build/bundle.js b/svelte-netlify/public/build/bundle.js similarity index 100% rename from fiber-svelte-netlify/public/build/bundle.js rename to svelte-netlify/public/build/bundle.js diff --git a/fiber-svelte-netlify/public/build/bundle.js.map b/svelte-netlify/public/build/bundle.js.map similarity index 100% rename from fiber-svelte-netlify/public/build/bundle.js.map rename to svelte-netlify/public/build/bundle.js.map diff --git a/fiber-svelte-netlify/public/global.css b/svelte-netlify/public/global.css similarity index 100% rename from fiber-svelte-netlify/public/global.css rename to svelte-netlify/public/global.css diff --git a/fiber-svelte-netlify/public/index.html b/svelte-netlify/public/index.html similarity index 100% rename from fiber-svelte-netlify/public/index.html rename to svelte-netlify/public/index.html diff --git a/sveltekit-embed/README.md b/sveltekit-embed/README.md index e8590efdb5..19161793bf 100644 --- a/sveltekit-embed/README.md +++ b/sveltekit-embed/README.md @@ -1,3 +1,8 @@ +--- +title: Sveltekit Embed +keywords: [sveltekit, tailwindcss, embed] +--- + # Fiber Sveltekit Embed App ![image](https://github.com/gofiber/recipes/assets/40540244/2aa084b8-9bbc-46f3-9759-930857429f05) diff --git a/swagger/README.md b/swagger/README.md index b872c90bf8..662190dcb2 100644 --- a/swagger/README.md +++ b/swagger/README.md @@ -1,53 +1,72 @@ -# Simple Swagger Implementation for [Fiber](https://github.com/gofiber/fiber) +--- +title: Swagger +keywords: [swagger, api, documentation, contrib] +--- -This example use [fiber-swagger](https://github.com/arsmn/fiber-swagger) and [swaggo](https://github.com/swaggo/swag) (Go converter to Swagger Documentation 2.0) +# Swagger API Documentation -## Usage +This project demonstrates how to integrate Swagger for API documentation in a Go application. -1. Download [swaggo](https://github.com/swaggo/swag) by using: +## Prerequisites - ```bash - $ go get -u github.com/swaggo/swag/cmd/swag +Ensure you have the following installed: - # 1.16 or newer - $ go install github.com/swaggo/swag/cmd/swag@latest - ``` +- Golang +- [Swag](https://github.com/swaggo/swag) for generating Swagger docs -2. Add comments to your API source code (example: `handlers/book.go`) or more details: [swaggo documentation](https://swaggo.github.io/swaggo.io/declarative_comments_format/). +## Setup -3. Download [fiber-swagger](https://github.com/arsmn/fiber-swagger) by using: +1. Clone the repository: + ```sh + git clone https://github.com/gofiber/recipes.git + cd recipes/swagger + ``` - ```bash - $ go get -u github.com/arsmn/fiber-swagger/v2 - ``` +2. Install dependencies: + ```sh + go get -u github.com/swaggo/swag/cmd/swag + go get -u github.com/swaggo/gin-swagger + go get -u github.com/swaggo/files + ``` -4. Import to your routes file (example: `routes/routes.go`): +## Generating Swagger Docs - ```go - import swagger "github.com/arsmn/fiber-swagger/v2" - ``` +1. Generate the Swagger documentation: + ```sh + swag init + ``` -5. Add swagger handler to routes as a middleware (example: `routes/routes.go`): +## Running the Application - ```go - app.Get("/docs/*", swagger.Handler) // default - - app.Get("/docs/*", swagger.New(swagger.Config{ // custom - URL: "http://example.com/doc.json", - DeepLinking: false, - })) - ``` +1. Start the application: + ```sh + go run main.go + ``` -6. Run the [swaggo](https://github.com/swaggo/swag) command in your Go project root directory which contain `main.go` file. This command will generate required files (`docs` and `docs/doc.go`) +2. Access the Swagger UI: + Open your browser and navigate to `http://localhost:8080/swagger/index.html` - ```bash - $ swag init - ``` +## Example -7. Import docs directory that generated by Swag CLI to your `main.go` file: +Here is an example of how to document an API endpoint using Swag: - ```go - import _ "swagger/docs" - ``` +```go +// @Summary Show an account +// @Description get string by ID +// @ID get-string-by-int +// @Accept json +// @Produce json +// @Param id path int true "Account ID" +// @Success 200 {object} model.Account +// @Failure 400 {object} http.Response +// @Failure 404 {object} http.Response +// @Router /accounts/{id} [get] +func GetAccount(c *gin.Context) { + // Your code here +} +``` -8. Horray! You're ready to Go 🚀 \ No newline at end of file +## References + +- [Swag Documentation](https://github.com/swaggo/swag) +- [Gin Swagger Middleware](https://github.com/swaggo/gin-swagger) diff --git a/tableflip/README.md b/tableflip/README.md index c0454838cd..b8ab8dbc78 100644 --- a/tableflip/README.md +++ b/tableflip/README.md @@ -1,34 +1,51 @@ -## tableflip example -### What is [tableflip](https://github.com/cloudflare/tableflip) -> It is sometimes useful to update the running code and / or configuration of a network service, without disrupting existing connections. Usually, this is achieved by starting a new process, somehow transferring clients to it and then exiting the old process. - -> There are many ways to implement graceful upgrades. They vary wildly in the trade-offs they make, and how much control they afford the user. This library has the following goals: -> - No old code keeps running after a successful upgrade -> - The new process has a grace period for performing initialisation -> - Crashing during initialisation is OK -> - Only a single upgrade is ever run in parallel -> - tableflip works on Linux and macOS. - -### Steps -1. Build v0.0.1 demo. - ```bash - go build -o demo main.go - ``` -2. Run the demo and create a get request to `127.0.0.1:8080/version`, here is the output: - ```bash - [PID: 123] v0.0.1 - ``` -3. Prepare a new version. change the main.go, let the version be "v0.0.2" and rebuild it. - ```bash - go build -o demo main.go - ``` -4. Now, kill the old one ! - ```bash - kill -s HUP 123 - ``` -5. Create the request to version api again, but output is changed: - ```bash - [PID: 123] v0.0.2 - ``` +--- +title: Tableflip Example +keywords: [tableflip, golang, graceful upgrade] +--- + +# Tableflip Example + +This example demonstrates how to use [tableflip](https://github.com/cloudflare/tableflip) for graceful upgrades in a Go application. + +## What is Tableflip? + +Tableflip is a library that allows you to update the running code and/or configuration of a network service without disrupting existing connections. It achieves this by starting a new process, transferring clients to it, and then exiting the old process. + +### Goals of Tableflip + +- No old code keeps running after a successful upgrade. +- The new process has a grace period for initialization. +- Crashing during initialization is acceptable. +- Only a single upgrade is ever run in parallel. +- Tableflip works on Linux and macOS. + +## Steps + +1. **Build v0.0.1 Demo:** + ```bash + go build -o demo main.go + ``` + +2. **Run the Demo and Create a GET Request to `127.0.0.1:8080/version`:** + ```bash + [PID: 123] v0.0.1 + ``` + +3. **Prepare a New Version:** + - Change the `main.go` to update the version to "v0.0.2". + - Rebuild the demo: + ```bash + go build -o demo main.go + ``` + +4. **Kill the Old Process:** + ```bash + kill -s HUP 123 + ``` + +5. **Create the Request to the Version API Again:** + ```bash + [PID: 123] v0.0.2 + ``` The client is completely immune to server upgrades and reboots, and our application updates gracefully! diff --git a/template-asset-bundling/README.md b/template-asset-bundling/README.md index dabf5eaa09..4946995cbd 100644 --- a/template-asset-bundling/README.md +++ b/template-asset-bundling/README.md @@ -1,27 +1,50 @@ -# template-asset-bundling +--- +title: Template Asset Bundling +keywords: [template, tailwindcss, parcel] +--- -This is a quick example of how to do asset bundling. -It's using [gofiber/template](https://github.com/gofiber/template), [Tailwind CSS](https://tailwindcss.com) and [Parcel](https://parceljs.org). +# Template Asset Bundling -## Additional requirements -- node.js +This is a quick example of how to do asset bundling using [gofiber/template](https://github.com/gofiber/template), [Tailwind CSS](https://tailwindcss.com), and [Parcel](https://parceljs.org). + +## Prerequisites + +Ensure you have the following installed: + +- Golang +- Node.js - npm +## Setup + +1. Clone the repository: + ```sh + git clone https://github.com/gofiber/recipes.git + cd recipes/template-asset-bundling + ``` + +2. Install dependencies: + ```sh + npm install + ``` + ## Usage -First build the assets -```bash -# Install dependencies -npm install +### Building Assets + +1. Build the assets: + ```sh + npm run build + ``` -# Build assets -npm run build +2. Watch assets for changes: + ```sh + npm run dev + ``` -# Watch assets for changes -npm run dev -``` +### Running the Application -Then run the fiber app -```bash -go run main.go -``` +1. Start the Fiber application: + ```sh + go run main.go + ``` diff --git a/template/README.md b/template/README.md new file mode 100644 index 0000000000..4be99f9b2e --- /dev/null +++ b/template/README.md @@ -0,0 +1,89 @@ +--- +title: Template +keywords: [template, tailwindcss, parcel] +--- + +# Template Project + +This project demonstrates how to set up a Go application with template rendering, Tailwind CSS, and Parcel for asset bundling. + +## Prerequisites + +Ensure you have the following installed: + +- Golang +- Node.js +- npm + +## Setup + +1. Clone the repository: + ```sh + git clone https://github.com/gofiber/recipes.git + cd recipes/template + ``` + +2. Install dependencies: + ```sh + npm install + ``` + +## Usage + +### Building Assets + +1. Build the assets: + ```sh + npm run build + ``` + +2. Watch assets for changes: + ```sh + npm run dev + ``` + +### Running the Application + +1. Start the Fiber application: + ```sh + go run main.go + ``` + +## Example + +Here is an example of how to set up a basic route with template rendering in Go: + +```go +package main + +import ( + "github.com/gofiber/fiber/v2" + "github.com/gofiber/template/html/v2" +) + +func main() { + // Initialize the template engine + engine := html.New("./views", ".html") + + // Create a new Fiber instance with the template engine + app := fiber.New(fiber.Config{ + Views: engine, + }) + + // Define a route + app.Get("/", func(c *fiber.Ctx) error { + return c.Render("index", fiber.Map{ + "Title": "Hello, World!", + }) + }) + + // Start the server + app.Listen(":3000") +} +``` + +## References + +- [Fiber Documentation](https://docs.gofiber.io) +- [Tailwind CSS Documentation](https://tailwindcss.com/docs) +- [Parcel Documentation](https://parceljs.org/docs) diff --git a/testOauth2/.vscode/launch.json b/testOauth2/.vscode/launch.json deleted file mode 100644 index a58003fdca..0000000000 --- a/testOauth2/.vscode/launch.json +++ /dev/null @@ -1,15 +0,0 @@ -{ - // Use IntelliSense to learn about possible attributes. - // Hover to view descriptions of existing attributes. - // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 - "version": "0.2.0", - "configurations": [ - { - "name": "Launch Package", - "type": "go", - "request": "launch", - "mode": "debug", - "program": "${workspaceFolder}" - } - ] -} \ No newline at end of file diff --git a/testOauth2/makefile b/testOauth2/makefile deleted file mode 100644 index c212cbb91a..0000000000 --- a/testOauth2/makefile +++ /dev/null @@ -1,25 +0,0 @@ -NPROCS = $(shell grep -c 'processor' /proc/cpuinfo) -MAKEFLAGS += -j$(NPROCS) - -.PHONY: clean -clean: - @rm -fv ./testoauth2 - @rm -fv ./logs/* - - -.PHONY: run -run: clean - @GOOS=linux go build -o ./testoauth2 ./*.go - ./testoauth2 - -.PHONY: build -build: clean - @GOOS=linux go build -o ./testoauth2 ./*.go - -.PHONY: buildrelease -buildrelease: - @GOOS=linux go build -ldflags="-s -w" -o ./testoauth2 ./*.go - @upx --brute ./testoauth2 - -.PHONY: release -release: clean buildrelease \ No newline at end of file diff --git a/todo-app-with-auth-gorm/README.md b/todo-app-with-auth-gorm/README.md index 81c05fad21..bd4778b3c5 100644 --- a/todo-app-with-auth-gorm/README.md +++ b/todo-app-with-auth-gorm/README.md @@ -1,20 +1,43 @@ -# Prerequisite +--- +title: Todo App + Auth + GORM +keywords: [todo app, gorm, authentication] +--- -1. Make sure you have the following installed outside the current project directory and available in your `GOPATH` - - golang - - [air](https://github.com/air-verse/air) for hot reloading - - [godotenv](https://github.com/joho/godotenv) for loading `.env` file +# Todo App with Auth using GORM -# Installation +This project demonstrates a Todo application with authentication using GORM. -1. Clone this repo -2. Run `go get` +## Prerequisites -# Running +Ensure you have the following installed and available in your `GOPATH`: -1. Type `air` in the command line +- Golang +- [Air](https://github.com/air-verse/air) for hot reloading +- [Godotenv](https://github.com/joho/godotenv) for loading `.env` file -# Environment Variables +## Installation + +1. Clone the repository: + ```sh + git clone https://github.com/gofiber/recipes.git + cd recipes/todo-app-with-auth-gorm + ``` + +2. Install dependencies: + ```sh + go get + ``` + +## Running the Application + +1. Start the application: + ```sh + air + ``` + +## Environment Variables + +Create a `.env` file in the root directory and add the following variables: ```shell # PORT returns the server listening port diff --git a/unit-test/README.md b/unit-test/README.md index 4c256acf7f..b3a7b44b98 100644 --- a/unit-test/README.md +++ b/unit-test/README.md @@ -1,3 +1,8 @@ +--- +title: Unit Testing +keywords: [unit testing, testing, stretchr/testify] +--- + # Unit Testing Example This example demonstrates how to write unit tests for a Go Fiber application using the `stretchr/testify` package. diff --git a/upload-file/README.md b/upload-file/README.md index 99e7d51e20..e3eba36c94 100644 --- a/upload-file/README.md +++ b/upload-file/README.md @@ -1,3 +1,8 @@ +--- +title: File Upload +keywords: [file upload, upload, form, multipart] +--- + # File Upload Example This example demonstrates how to handle file uploads using Go Fiber. diff --git a/url-shortener-api/README.md b/url-shortener-api/README.md index b003be083a..01df75e49f 100644 --- a/url-shortener-api/README.md +++ b/url-shortener-api/README.md @@ -1,34 +1,44 @@ -#### Tech Stack +--- +title: URL Shortener +keywords: [url shortener, redis, api] +--- + +# URL Shortener API + +This project provides a URL shortening service with a simple API. + +## Tech Stack - Golang - Redis -### API Documentation +## API Documentation + +> API endpoint: `http://localhost:3000/api/v1/` -> API endpoint: http://localhost:3000/api/v1/ +### API Payload -#### API Payload +- `url` - Original URL +- `short` - Custom short URL (Optional) +- `expiry` - Time to expire: int (hours) -- "url" - Original URL -- "short" - Custom short URL(Optional) -- "expiry" - Time to expire: int(hours) +### API Response -#### API Response +- `url` - Original URL +- `short` - Custom short URL +- `expiry` - Time to expire: int (hours) +- `rate_limit` - Number of API calls remaining: int +- `rate_limit_reset` - Time to rate limit reset: int (minutes) -- "url" - Original URL -- "short" - Custom short URL -- "expiry" - Time to expire: int(hours) -- "rate_limit" - # of API calls remaining: int -- "rate_limit_reset" - Time to rate limit reset: int(minutes) +> API is rate limited to 10 calls every 30 minutes. +> These values can be changed in the `.env` file. Have fun. -> API is rate limited to 10 calls every 30mins. -> These values can be changed in the .env file. Have fun. +## Setup -#### Demo +1. Start the containers: + ```sh + docker-compose up -d + ``` -1. Start the containers -``` -docker-compose up -d -``` -2. Test the API -![test.gif](test.gif) +2. Test the API: + ![test.gif](test.gif) diff --git a/validation/README.md b/validation/README.md index 4e59021d3d..81a32d0060 100644 --- a/validation/README.md +++ b/validation/README.md @@ -1,3 +1,8 @@ +--- +title: Validation +keywords: [validation, input, go-playground, validator] +--- + # Validation with [Fiber](https://gofiber.io) This example demonstrates how to use [go-playground/validator](https://github.com/go-playground/validator) for input validation in a Go Fiber application. diff --git a/vercel/README.md b/vercel/README.md index f37f23f515..96f17da3af 100644 --- a/vercel/README.md +++ b/vercel/README.md @@ -1,3 +1,8 @@ +--- +title: Vercel +keywords: [vercel, deploy, serverless] +--- + # Vercel Example This example demonstrates how to deploy a Go Fiber application to Vercel. diff --git a/websocket-chat/README.md b/websocket-chat/README.md index 7a463a4d53..2afe7270af 100644 --- a/websocket-chat/README.md +++ b/websocket-chat/README.md @@ -1,3 +1,8 @@ +--- +title: WebSocket Chat +keywords: [websocket, chat, chatroom, contrib] +--- + # WebSocket Chat Example This example demonstrates a simple chat application using Go Fiber and WebSockets. diff --git a/websocket/README.md b/websocket/README.md index b78e8d7a02..eede000601 100644 --- a/websocket/README.md +++ b/websocket/README.md @@ -1,3 +1,8 @@ +--- +title: WebSocket +keywords: [websocket, real-time, chat, contrib] +--- + # WebSocket Example This example demonstrates a simple WebSocket application using Go Fiber. From 67fef9977c963ab956cc02645693e58518cc44a4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ren=C3=A9?= Date: Tue, 26 Nov 2024 14:49:10 +0100 Subject: [PATCH 04/14] docusaurus preparations --- postgresql/README.md | 26 ++++++++++++++------------ 1 file changed, 14 insertions(+), 12 deletions(-) diff --git a/postgresql/README.md b/postgresql/README.md index 845b8bbef5..7ca4da11fd 100644 --- a/postgresql/README.md +++ b/postgresql/README.md @@ -1,5 +1,5 @@ --- -title: PostgreSQL Example +title: PostgreSQL keywords: [postgresql] --- @@ -28,6 +28,19 @@ Ensure you have the following installed: go get ``` +3. Set up your PostgreSQL database and update the connection string in the code. + +## Running the Application + +1. Start the application: + ```sh + go run main.go + ``` + +2. Access the application at `http://localhost:3000`. + +## Example + Here is an example of how to connect to a PostgreSQL database in a Fiber application: ```go @@ -43,17 +56,6 @@ import ( func main() { // Database connection -3. Set up your PostgreSQL database and update the connection string in the code. - -## Running the Application - -1. Start the application: - ```sh - go run main.go - ``` - -## Example - connStr := "user=username dbname=mydb sslmode=disable" db, err := sql.Open("postgres", connStr) if err != nil { From 297145097e96ce280ee8e580fe7ea2b552b32775 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ren=C3=A9?= Date: Tue, 26 Nov 2024 17:51:02 +0100 Subject: [PATCH 05/14] docusaurus preparations --- .github/scripts/sync_local.sh | 2 +- README.md | 2 +- colly-gorm/app/internals/services/database/models.go | 1 - k8s/README.md | 2 +- overview.go | 11 +++++++---- sessions-sqlite3/README.md | 8 +++++++- 6 files changed, 17 insertions(+), 9 deletions(-) diff --git a/.github/scripts/sync_local.sh b/.github/scripts/sync_local.sh index fd3f401497..cd899f4d5b 100755 --- a/.github/scripts/sync_local.sh +++ b/.github/scripts/sync_local.sh @@ -4,7 +4,7 @@ set -e REPO_DIR="recipes" # determine root repo directory -ROOT=$(cd "$(dirname "$0")/.." && dirname "$(pwd -P)") +ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd -P)" # remove all files in the docs directory rm -rf $ROOT/../fiberDocs/docs/${REPO_DIR}/* diff --git a/README.md b/README.md index e64176e61f..601a53bf3b 100644 --- a/README.md +++ b/README.md @@ -64,7 +64,7 @@ Here you can find the most **delicious** recipes to cook delicious meals using o - [Google OAuth2](./oauth2-google) - [Optional Parameter Example](./optional-parameter) - [Parsley](./parsley) -- [PostgreSQL Example](./postgresql) +- [PostgreSQL](./postgresql) - [Prefork Example](./prefork) - [RabbitMQ](./rabbitmq) - [React](./react-router) diff --git a/colly-gorm/app/internals/services/database/models.go b/colly-gorm/app/internals/services/database/models.go index 6805688858..b12206b6e2 100644 --- a/colly-gorm/app/internals/services/database/models.go +++ b/colly-gorm/app/internals/services/database/models.go @@ -3,7 +3,6 @@ package database import "gorm.io/gorm" type Quote struct { - ID int `json:"id"` Author string `json:"author"` Text string `json:"quote"` gorm.Model diff --git a/k8s/README.md b/k8s/README.md index 0671d44c6e..76f392b220 100644 --- a/k8s/README.md +++ b/k8s/README.md @@ -23,7 +23,7 @@ Ensure you have the following installed: 1. Clone the repository: ```sh git clone https://github.com/gofiber/recipes.git - cd recipes/kubernetes + cd recipes/k8s ``` 2. Install dependencies: diff --git a/overview.go b/overview.go index cd3b399277..6e9d4dc79d 100644 --- a/overview.go +++ b/overview.go @@ -8,6 +8,11 @@ import ( "strings" ) +var ( + titleRegex = regexp.MustCompile(`(?m)^title: (.+)`) + keywordsRegex = regexp.MustCompile(`(?m)^keywords: \[(.+)\]`) +) + //go:generate go run overview.go func main() { // fetch current file directory @@ -103,11 +108,9 @@ func extractTitleAndKeywords(readmePath string) (string, []string, error) { if err != nil { return "", nil, err } - titleRe := regexp.MustCompile(`(?m)^title: (.+)`) - keywordsRe := regexp.MustCompile(`(?m)^keywords: \[(.+)\]`) - titleMatches := titleRe.FindSubmatch(content) - keywordsMatches := keywordsRe.FindSubmatch(content) + titleMatches := titleRegex.FindSubmatch(content) + keywordsMatches := keywordsRegex.FindSubmatch(content) var title string if len(titleMatches) > 1 { diff --git a/sessions-sqlite3/README.md b/sessions-sqlite3/README.md index 9dba0b3f47..fa8d8cc709 100644 --- a/sessions-sqlite3/README.md +++ b/sessions-sqlite3/README.md @@ -5,7 +5,13 @@ keywords: [sessions, sqlite3, storage] # Sessions - SQLite3 -This example demonstrates how to use Fiber sessions with the SQLite3 storage package. Run `localhost:3000` from multiple browsers to see active sessions for different users. +This example uses the SQLite3 storage package to persist user sessions. While the storage package can automatically create the sessions table at initialization, we create it manually to add an additional "u" column. This custom column serves several purposes: + +- Enables efficient querying of sessions by user identifier +- Allows tracking of multiple sessions per user +- Facilitates session cleanup for specific users + +The default table schema only stores session data and expiry, making it difficult to associate sessions with specific users. The "u" column solves this limitation. ## Prerequisites From a6f4b272f6f689b49ad7c2d07e1ef31f092aed6b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ren=C3=A9?= Date: Tue, 26 Nov 2024 17:56:30 +0100 Subject: [PATCH 06/14] docusaurus preparations --- README.md | 4 ++-- overview.go | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 601a53bf3b..189c18177a 100644 --- a/README.md +++ b/README.md @@ -29,7 +29,7 @@ Here you can find the most **delicious** recipes to cook delicious meals using o - [CSRF + Session](./csrf-with-session) - [Docker + MariaDB](./docker-mariadb-clean-arch) - [Docker + Nginx](./docker-nginx-loadbalancer) -- [Dummy JSON Proxy ](./dummyjson) +- [Dummy JSON Proxy](./dummyjson) - [Entgo ORM (MySQL)](./ent-mysql) - [Entgo Sveltekit](./entgo-sveltekit) - [Envoy External Authorization](./envoy-extauthz) @@ -80,7 +80,7 @@ Here you can find the most **delicious** recipes to cook delicious meals using o - [Stream Request Body](./stream-request-body) - [Svelte Netlify](./svelte-netlify) - [Sveltekit Embed](./sveltekit-embed) -- [Swagger ](./swagger) +- [Swagger](./swagger) - [Tableflip Example](./tableflip) - [Template](./template) - [Template Asset Bundling](./template-asset-bundling) diff --git a/overview.go b/overview.go index 6e9d4dc79d..2e019f6bac 100644 --- a/overview.go +++ b/overview.go @@ -114,7 +114,7 @@ func extractTitleAndKeywords(readmePath string) (string, []string, error) { var title string if len(titleMatches) > 1 { - title = string(titleMatches[1]) + title = strings.TrimSpace(string(titleMatches[1])) } var keywords []string From c1bd70da681f45275cc745f98c3e89cc86feee9a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ren=C3=A9?= Date: Tue, 26 Nov 2024 18:00:00 +0100 Subject: [PATCH 07/14] docusaurus preparations --- README.md | 158 ++++++++++++++++++++++++++-------------------------- overview.go | 2 +- 2 files changed, 80 insertions(+), 80 deletions(-) diff --git a/README.md b/README.md index 189c18177a..e8731a80ce 100644 --- a/README.md +++ b/README.md @@ -13,85 +13,85 @@ Here you can find the most **delicious** recipes to cook delicious meals using o ## 🌽 Table of contents -- [404 Handler](./404-handler) -- [Air Live Reloading](./air) -- [Auth + Docker + Postgres + JWT](./auth-docker-postgres-jwt) -- [Auth + JWT](./auth-jwt) -- [Autocert](./autocert) -- [AWS Elastic Beanstalk](./aws-eb) -- [AWS SAM](./aws-sam) -- [AWS SAM Container](./aws-sam-container) -- [Bootstrap](./bootstrap) -- [Clean Architecture](./clean-architecture) -- [Cloud Run](./cloud-run) -- [Colly Gorm](./colly-gorm) -- [CSRF](./csrf) -- [CSRF + Session](./csrf-with-session) -- [Docker + MariaDB](./docker-mariadb-clean-arch) -- [Docker + Nginx](./docker-nginx-loadbalancer) -- [Dummy JSON Proxy](./dummyjson) -- [Entgo ORM (MySQL)](./ent-mysql) -- [Entgo Sveltekit](./entgo-sveltekit) -- [Envoy External Authorization](./envoy-extauthz) -- [File Server](./file-server) -- [Firebase Authentication](./firebase-auth) -- [Firebase Functions](./firebase-functions) -- [Firebase GCloud](./gcloud) -- [Google Cloud Firebase](./gcloud-firebase) -- [GeoIP](./geoip) -- [GeoIP + MaxMind](./geoip-maxmind) -- [GORM](./gorm) -- [GORM MySQL](./gorm-mysql) -- [GORM + PostgreSQL](./gorm-postgres) -- [Graceful shutdown](./graceful-shutdown) -- [GraphQL](./graphql) -- [gRPC](./grpc) -- [Hello World](./hello-world) -- [Heroku](./heroku) -- [Hexagonal Architecture](./hexagonal) -- [HTTPS with PKCS12 TLS](./https-pkcs12-tls) -- [HTTPS with TLS](./https-tls) -- [I18n](./i18n) -- [JWT](./jwt) -- [Kubernetes](./k8s) -- [Memgraph](./memgraph) -- [MinIO](./minio) -- [MongoDB Example](./mongodb) -- [Multiple Ports](./multiple-ports) -- [MySQL](./mysql) -- [Neo4j](./neo4j) -- [OAuth2](./oauth2) -- [Google OAuth2](./oauth2-google) -- [Optional Parameter Example](./optional-parameter) -- [Parsley](./parsley) -- [PostgreSQL](./postgresql) -- [Prefork Example](./prefork) -- [RabbitMQ](./rabbitmq) -- [React](./react-router) -- [Recover Middleware Example](./recover) -- [RSS Feed](./rss-feed) -- [Server Timing](./server-timing) -- [Sessions + SQLite3](./sessions-sqlite3) -- [Socketio](./socketio) -- [Single Page Application (SPA)](./spa) -- [Sqlboiler](./sqlboiler) -- [Sqlc](./sqlc) -- [Server-Sent Events](./sse) -- [Stream Request Body](./stream-request-body) -- [Svelte Netlify](./svelte-netlify) -- [Sveltekit Embed](./sveltekit-embed) -- [Swagger](./swagger) -- [Tableflip Example](./tableflip) -- [Template](./template) -- [Template Asset Bundling](./template-asset-bundling) -- [Todo App + Auth + GORM](./todo-app-with-auth-gorm) -- [Unit Testing](./unit-test) -- [File Upload](./upload-file) -- [URL Shortener](./url-shortener-api) -- [Validation](./validation) -- [Vercel](./vercel) -- [WebSocket](./websocket) -- [WebSocket Chat](./websocket-chat) +- [404 Handler](./404-handler/README.md) +- [Air Live Reloading](./air/README.md) +- [Auth + Docker + Postgres + JWT](./auth-docker-postgres-jwt/README.md) +- [Auth + JWT](./auth-jwt/README.md) +- [Autocert](./autocert/README.md) +- [AWS Elastic Beanstalk](./aws-eb/README.md) +- [AWS SAM](./aws-sam/README.md) +- [AWS SAM Container](./aws-sam-container/README.md) +- [Bootstrap](./bootstrap/README.md) +- [Clean Architecture](./clean-architecture/README.md) +- [Cloud Run](./cloud-run/README.md) +- [Colly Gorm](./colly-gorm/README.md) +- [CSRF](./csrf/README.md) +- [CSRF + Session](./csrf-with-session/README.md) +- [Docker + MariaDB](./docker-mariadb-clean-arch/README.md) +- [Docker + Nginx](./docker-nginx-loadbalancer/README.md) +- [Dummy JSON Proxy](./dummyjson/README.md) +- [Entgo ORM (MySQL)](./ent-mysql/README.md) +- [Entgo Sveltekit](./entgo-sveltekit/README.md) +- [Envoy External Authorization](./envoy-extauthz/README.md) +- [File Server](./file-server/README.md) +- [Firebase Authentication](./firebase-auth/README.md) +- [Firebase Functions](./firebase-functions/README.md) +- [Firebase GCloud](./gcloud/README.md) +- [Google Cloud Firebase](./gcloud-firebase/README.md) +- [GeoIP](./geoip/README.md) +- [GeoIP + MaxMind](./geoip-maxmind/README.md) +- [GORM](./gorm/README.md) +- [GORM MySQL](./gorm-mysql/README.md) +- [GORM + PostgreSQL](./gorm-postgres/README.md) +- [Graceful shutdown](./graceful-shutdown/README.md) +- [GraphQL](./graphql/README.md) +- [gRPC](./grpc/README.md) +- [Hello World](./hello-world/README.md) +- [Heroku](./heroku/README.md) +- [Hexagonal Architecture](./hexagonal/README.md) +- [HTTPS with PKCS12 TLS](./https-pkcs12-tls/README.md) +- [HTTPS with TLS](./https-tls/README.md) +- [I18n](./i18n/README.md) +- [JWT](./jwt/README.md) +- [Kubernetes](./k8s/README.md) +- [Memgraph](./memgraph/README.md) +- [MinIO](./minio/README.md) +- [MongoDB Example](./mongodb/README.md) +- [Multiple Ports](./multiple-ports/README.md) +- [MySQL](./mysql/README.md) +- [Neo4j](./neo4j/README.md) +- [OAuth2](./oauth2/README.md) +- [Google OAuth2](./oauth2-google/README.md) +- [Optional Parameter Example](./optional-parameter/README.md) +- [Parsley](./parsley/README.md) +- [PostgreSQL](./postgresql/README.md) +- [Prefork Example](./prefork/README.md) +- [RabbitMQ](./rabbitmq/README.md) +- [React](./react-router/README.md) +- [Recover Middleware Example](./recover/README.md) +- [RSS Feed](./rss-feed/README.md) +- [Server Timing](./server-timing/README.md) +- [Sessions + SQLite3](./sessions-sqlite3/README.md) +- [Socketio](./socketio/README.md) +- [Single Page Application (SPA)](./spa/README.md) +- [Sqlboiler](./sqlboiler/README.md) +- [Sqlc](./sqlc/README.md) +- [Server-Sent Events](./sse/README.md) +- [Stream Request Body](./stream-request-body/README.md) +- [Svelte Netlify](./svelte-netlify/README.md) +- [Sveltekit Embed](./sveltekit-embed/README.md) +- [Swagger](./swagger/README.md) +- [Tableflip Example](./tableflip/README.md) +- [Template](./template/README.md) +- [Template Asset Bundling](./template-asset-bundling/README.md) +- [Todo App + Auth + GORM](./todo-app-with-auth-gorm/README.md) +- [Unit Testing](./unit-test/README.md) +- [File Upload](./upload-file/README.md) +- [URL Shortener](./url-shortener-api/README.md) +- [Validation](./validation/README.md) +- [Vercel](./vercel/README.md) +- [WebSocket](./websocket/README.md) +- [WebSocket Chat](./websocket-chat/README.md) ## 👩‍🍳 Have a delicious recipe? diff --git a/overview.go b/overview.go index 2e019f6bac..f8b36d9b7e 100644 --- a/overview.go +++ b/overview.go @@ -46,7 +46,7 @@ func main() { if title == "" { title = "No title" } - toc += fmt.Sprintf("- [%s](./%s)\n", title, relativePath) + toc += fmt.Sprintf("- [%s](./%s/README.md)\n", title, relativePath) } else { missingReadmeDirs = append(missingReadmeDirs, relativePath) } From cc5cd546c985ef1c5140f950616b96948f5d0015 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ren=C3=A9?= Date: Tue, 26 Nov 2024 18:09:06 +0100 Subject: [PATCH 08/14] docusaurus preparations --- firebase-auth/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/firebase-auth/README.md b/firebase-auth/README.md index 80ae73c187..923b21025a 100644 --- a/firebase-auth/README.md +++ b/firebase-auth/README.md @@ -5,7 +5,7 @@ keywords: [firebase, authentication, middleware] # Go Fiber Firebase Authentication Example -This example use [gofiber-firebaseauth middleware ](https://github.com/sacsand/gofiber-firebaseauth) to authenticate the endpoints. Find the documentation for middlewae here for more confgurtion oprions [docs ](https://github.com/sacsand/gofiber-firebaseauth) +This example use [gofiber-firebaseauth middleware](https://github.com/sacsand/gofiber-firebaseauth) to authenticate the endpoints. Find the documentation for middleware here for more configurations options [docs](https://github.com/sacsand/gofiber-firebaseauth) ## Setting Up From 4146b8d4b5d1945c39b3da49de5c22329f575c34 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ren=C3=A9?= Date: Tue, 26 Nov 2024 19:03:07 +0100 Subject: [PATCH 09/14] docusaurus preparations --- 404-handler/README.md | 2 ++ air/README.md | 2 ++ auth-docker-postgres-jwt/README.md | 2 ++ auth-jwt/README.md | 2 ++ autocert/README.md | 2 ++ aws-eb/README.md | 2 ++ aws-sam-container/README.md | 2 ++ aws-sam/README.md | 2 ++ bootstrap/README.md | 3 ++ clean-architecture/README.md | 2 ++ cloud-run/README.md | 2 ++ colly-gorm/README.md | 2 ++ csrf-with-session/README.md | 2 ++ csrf/README.md | 2 ++ docker-mariadb-clean-arch/README.md | 2 ++ docker-nginx-loadbalancer/README.md | 2 ++ dummyjson/README.md | 4 ++- ent-mysql/README.md | 2 ++ entgo-sveltekit/README.md | 3 ++ envoy-extauthz/README.md | 2 ++ file-server/README.md | 2 ++ firebase-auth/README.md | 2 ++ firebase-functions/README.md | 2 ++ gcloud-firebase/README.md | 2 ++ gcloud/README.md | 2 ++ geoip-maxmind/README.md | 2 ++ geoip/README.md | 2 ++ gorm-mysql/README.md | 2 ++ gorm-postgres/README.md | 2 ++ gorm/README.md | 2 ++ graceful-shutdown/README.md | 2 ++ graphql/README.md | 2 ++ grpc/README.md | 2 ++ hello-world/README.md | 2 ++ heroku/README.md | 2 ++ hexagonal/README.md | 2 ++ https-pkcs12-tls/README.md | 2 ++ https-tls/README.md | 2 ++ i18n/README.md | 2 ++ jwt/README.md | 2 ++ k8s/README.md | 2 ++ memgraph/README.md | 2 ++ minio/README.md | 2 ++ mongodb/README.md | 2 ++ multiple-ports/README.md | 2 ++ mysql/README.md | 2 ++ neo4j/README.md | 2 ++ oauth2-google/README.md | 2 ++ oauth2/README.md | 2 ++ optional-parameter/README.md | 2 ++ overview.go | 55 +++++++++++++++++++++++++++-- parsley/README.md | 2 ++ postgresql/README.md | 2 ++ prefork/README.md | 2 ++ rabbitmq/README.md | 2 ++ react-router/README.md | 2 ++ recover/README.md | 2 ++ rss-feed/README.md | 2 ++ server-timing/README.md | 2 ++ sessions-sqlite3/README.md | 2 ++ socketio/README.md | 2 ++ spa/README.md | 2 ++ sqlboiler/README.md | 2 ++ sqlc/README.md | 2 ++ sse/README.md | 2 ++ stream-request-body/README.md | 2 ++ svelte-netlify/README.md | 2 ++ sveltekit-embed/README.md | 3 ++ swagger/README.md | 4 ++- tableflip/README.md | 2 ++ template-asset-bundling/README.md | 2 ++ template/README.md | 2 ++ todo-app-with-auth-gorm/README.md | 2 ++ unit-test/README.md | 2 ++ upload-file/README.md | 2 ++ url-shortener-api/README.md | 2 ++ validation/README.md | 2 ++ vercel/README.md | 2 ++ websocket-chat/README.md | 2 ++ websocket/README.md | 2 ++ 80 files changed, 215 insertions(+), 5 deletions(-) diff --git a/404-handler/README.md b/404-handler/README.md index 6969b5a1ce..5a92c2b26b 100644 --- a/404-handler/README.md +++ b/404-handler/README.md @@ -5,6 +5,8 @@ keywords: [404, not found, handler, errorhandler, custom] # Custom 404 Not Found Handler Example +[![Github](https://img.shields.io/static/v1?label=&message=Github&color=2ea44f&style=for-the-badge&logo=github)](https://github.com/gofiber/recipes/tree/master/404-handler) [![StackBlitz](https://img.shields.io/static/v1?label=&message=StackBlitz&color=2ea44f&style=for-the-badge&logo=StackBlitz)](https://stackblitz.com/github/gofiber/recipes/tree/master/404-handler) + This example demonstrates how to implement a custom 404 Not Found handler using the [Fiber](https://gofiber.io) web framework in Go. The purpose of this example is to show how to handle requests to undefined routes gracefully by returning a 404 status code. ## Description diff --git a/air/README.md b/air/README.md index eaf11a69b8..431deb0f04 100644 --- a/air/README.md +++ b/air/README.md @@ -5,6 +5,8 @@ keywords: [air, live reloading, development, air tool, hot reload, watch, change # Live Reloading with Air Example +[![Github](https://img.shields.io/static/v1?label=&message=Github&color=2ea44f&style=for-the-badge&logo=github)](https://github.com/gofiber/recipes/tree/master/air) [![StackBlitz](https://img.shields.io/static/v1?label=&message=StackBlitz&color=2ea44f&style=for-the-badge&logo=StackBlitz)](https://stackblitz.com/github/gofiber/recipes/tree/master/air) + This example demonstrates how to set up live reloading for a Go application using the [Air](https://github.com/cosmtrek/air) tool. The purpose of this example is to show how to automatically reload your application during development whenever you make changes to the source code. ## Description diff --git a/auth-docker-postgres-jwt/README.md b/auth-docker-postgres-jwt/README.md index c105c02642..1e66dcf3a8 100644 --- a/auth-docker-postgres-jwt/README.md +++ b/auth-docker-postgres-jwt/README.md @@ -5,6 +5,8 @@ keywords: [auth, docker, postgres, jwt] # Auth Docker Postgres JWT Example +[![Github](https://img.shields.io/static/v1?label=&message=Github&color=2ea44f&style=for-the-badge&logo=github)](https://github.com/gofiber/recipes/tree/master/auth-docker-postgres-jwt) [![StackBlitz](https://img.shields.io/static/v1?label=&message=StackBlitz&color=2ea44f&style=for-the-badge&logo=StackBlitz)](https://stackblitz.com/github/gofiber/recipes/tree/master/auth-docker-postgres-jwt) + This example demonstrates a boilerplate setup for a Go Fiber application that uses Docker, PostgreSQL, and JWT for authentication. ## Description diff --git a/auth-jwt/README.md b/auth-jwt/README.md index eff05e3199..4335e100a7 100644 --- a/auth-jwt/README.md +++ b/auth-jwt/README.md @@ -5,6 +5,8 @@ keywords: [auth, jwt, gorm, fiber] # Auth JWT Example +[![Github](https://img.shields.io/static/v1?label=&message=Github&color=2ea44f&style=for-the-badge&logo=github)](https://github.com/gofiber/recipes/tree/master/auth-jwt) [![StackBlitz](https://img.shields.io/static/v1?label=&message=StackBlitz&color=2ea44f&style=for-the-badge&logo=StackBlitz)](https://stackblitz.com/github/gofiber/recipes/tree/master/auth-jwt) + This example demonstrates a boilerplate setup for a Go Fiber application that uses JWT for authentication. ## Description diff --git a/autocert/README.md b/autocert/README.md index 2a3eab5613..9c04b9b946 100644 --- a/autocert/README.md +++ b/autocert/README.md @@ -5,6 +5,8 @@ keywords: [autocert, tls, letsencrypt, ssl, https] # Autocert Example +[![Github](https://img.shields.io/static/v1?label=&message=Github&color=2ea44f&style=for-the-badge&logo=github)](https://github.com/gofiber/recipes/tree/master/autocert) [![StackBlitz](https://img.shields.io/static/v1?label=&message=StackBlitz&color=2ea44f&style=for-the-badge&logo=StackBlitz)](https://stackblitz.com/github/gofiber/recipes/tree/master/autocert) + This example demonstrates how to set up a secure Go Fiber application using Let's Encrypt for automatic TLS certificate management with `autocert`. ## Description diff --git a/aws-eb/README.md b/aws-eb/README.md index a890d8886d..0f66990d4f 100644 --- a/aws-eb/README.md +++ b/aws-eb/README.md @@ -5,6 +5,8 @@ keywords: [aws, elastic beanstalk, deploy, amazon, aws-eb] # AWS Elastic Beanstalk Example +[![Github](https://img.shields.io/static/v1?label=&message=Github&color=2ea44f&style=for-the-badge&logo=github)](https://github.com/gofiber/recipes/tree/master/aws-eb) [![StackBlitz](https://img.shields.io/static/v1?label=&message=StackBlitz&color=2ea44f&style=for-the-badge&logo=StackBlitz)](https://stackblitz.com/github/gofiber/recipes/tree/master/aws-eb) + This example demonstrates how to deploy a Go Fiber application to AWS Elastic Beanstalk. ## Description diff --git a/aws-sam-container/README.md b/aws-sam-container/README.md index a7c1bb252a..c79ff82cb0 100644 --- a/aws-sam-container/README.md +++ b/aws-sam-container/README.md @@ -5,6 +5,8 @@ keywords: [aws, sam, serverless, lambda, container] # AWS SAM Container +[![Github](https://img.shields.io/static/v1?label=&message=Github&color=2ea44f&style=for-the-badge&logo=github)](https://github.com/gofiber/recipes/tree/master/aws-sam-container) [![StackBlitz](https://img.shields.io/static/v1?label=&message=StackBlitz&color=2ea44f&style=for-the-badge&logo=StackBlitz)](https://stackblitz.com/github/gofiber/recipes/tree/master/aws-sam-container) + This is a sample template for app - Below is a brief explanation of what we have generated for you: ```bash diff --git a/aws-sam/README.md b/aws-sam/README.md index 36b0b6e0a3..da028de1ae 100644 --- a/aws-sam/README.md +++ b/aws-sam/README.md @@ -5,6 +5,8 @@ keywords: [aws, sam, serverless, lambda] # AWS SAM +[![Github](https://img.shields.io/static/v1?label=&message=Github&color=2ea44f&style=for-the-badge&logo=github)](https://github.com/gofiber/recipes/tree/master/aws-sam) [![StackBlitz](https://img.shields.io/static/v1?label=&message=StackBlitz&color=2ea44f&style=for-the-badge&logo=StackBlitz)](https://stackblitz.com/github/gofiber/recipes/tree/master/aws-sam) + This is a sample template for sam-app - Below is a brief explanation of what we have generated for you: ```bash diff --git a/bootstrap/README.md b/bootstrap/README.md index 54dea15481..921341e3f6 100644 --- a/bootstrap/README.md +++ b/bootstrap/README.md @@ -4,6 +4,9 @@ keywords: [bootstrap, gorm, validator, env] --- # Bootstrap + +[![Github](https://img.shields.io/static/v1?label=&message=Github&color=2ea44f&style=for-the-badge&logo=github)](https://github.com/gofiber/recipes/tree/master/bootstrap) [![StackBlitz](https://img.shields.io/static/v1?label=&message=StackBlitz&color=2ea44f&style=for-the-badge&logo=StackBlitz)](https://stackblitz.com/github/gofiber/recipes/tree/master/bootstrap) + Fiber bootstrap for rapid development using Go-Fiber / Gorm / Validator. # Components diff --git a/clean-architecture/README.md b/clean-architecture/README.md index 7bd536f76a..d0c6762db5 100644 --- a/clean-architecture/README.md +++ b/clean-architecture/README.md @@ -5,6 +5,8 @@ keywords: [clean, architecture, fiber, mongodb, go] # Clean Architecture Example +[![Github](https://img.shields.io/static/v1?label=&message=Github&color=2ea44f&style=for-the-badge&logo=github)](https://github.com/gofiber/recipes/tree/master/clean-architecture) [![StackBlitz](https://img.shields.io/static/v1?label=&message=StackBlitz&color=2ea44f&style=for-the-badge&logo=StackBlitz)](https://stackblitz.com/github/gofiber/recipes/tree/master/clean-architecture) + This example demonstrates a Go Fiber application following the principles of Clean Architecture. ## Description diff --git a/cloud-run/README.md b/cloud-run/README.md index 36593231e0..930a4c3ba3 100644 --- a/cloud-run/README.md +++ b/cloud-run/README.md @@ -5,6 +5,8 @@ keywords: [cloud run, deploy, google, docker, gcp] # Cloud Run Example +[![Github](https://img.shields.io/static/v1?label=&message=Github&color=2ea44f&style=for-the-badge&logo=github)](https://github.com/gofiber/recipes/tree/master/cloud-run) [![StackBlitz](https://img.shields.io/static/v1?label=&message=StackBlitz&color=2ea44f&style=for-the-badge&logo=StackBlitz)](https://stackblitz.com/github/gofiber/recipes/tree/master/cloud-run) + This example demonstrates how to deploy a Go Fiber application to Google Cloud Run. ## Description diff --git a/colly-gorm/README.md b/colly-gorm/README.md index 7826743ea6..ee4b00486b 100644 --- a/colly-gorm/README.md +++ b/colly-gorm/README.md @@ -5,6 +5,8 @@ keywords: [colly, gorm, postgresql] # Simple Web Scraping Colly App with Fiber +[![Github](https://img.shields.io/static/v1?label=&message=Github&color=2ea44f&style=for-the-badge&logo=github)](https://github.com/gofiber/recipes/tree/master/colly-gorm) [![StackBlitz](https://img.shields.io/static/v1?label=&message=StackBlitz&color=2ea44f&style=for-the-badge&logo=StackBlitz)](https://stackblitz.com/github/gofiber/recipes/tree/master/colly-gorm) + This is a basic Go application using the Fiber framework to create scraping tasks in colly. ## How to Run diff --git a/csrf-with-session/README.md b/csrf-with-session/README.md index 1a2f1f2d0c..15e80eec08 100644 --- a/csrf-with-session/README.md +++ b/csrf-with-session/README.md @@ -5,6 +5,8 @@ keywords: [csrf, security, hacking, vulnerability, session] # CSRF-with-session Example +[![Github](https://img.shields.io/static/v1?label=&message=Github&color=2ea44f&style=for-the-badge&logo=github)](https://github.com/gofiber/recipes/tree/master/csrf-with-session) [![StackBlitz](https://img.shields.io/static/v1?label=&message=StackBlitz&color=2ea44f&style=for-the-badge&logo=StackBlitz)](https://stackblitz.com/github/gofiber/recipes/tree/master/csrf-with-session) + Example GoFiber web app using Cross Site Request Forgery (CSRF) middleware with session. This example impliments multiple best-practices for CSRF protection: diff --git a/csrf/README.md b/csrf/README.md index 4ffa489cca..a772936ec1 100644 --- a/csrf/README.md +++ b/csrf/README.md @@ -5,6 +5,8 @@ keywords: [csrf, security, hacking, vulnerability] # CSRF Examples +[![Github](https://img.shields.io/static/v1?label=&message=Github&color=2ea44f&style=for-the-badge&logo=github)](https://github.com/gofiber/recipes/tree/master/csrf) [![StackBlitz](https://img.shields.io/static/v1?label=&message=StackBlitz&color=2ea44f&style=for-the-badge&logo=StackBlitz)](https://stackblitz.com/github/gofiber/recipes/tree/master/csrf) + Example Cross Site Request Forgery (CSRF) vulnerabilities in action. diff --git a/docker-mariadb-clean-arch/README.md b/docker-mariadb-clean-arch/README.md index 1eb04c41b7..d904dedcd1 100644 --- a/docker-mariadb-clean-arch/README.md +++ b/docker-mariadb-clean-arch/README.md @@ -5,6 +5,8 @@ keywords: [docker, mariadb, clean architecture, makefile] # Docker MariaDB Clean Architecture +[![Github](https://img.shields.io/static/v1?label=&message=Github&color=2ea44f&style=for-the-badge&logo=github)](https://github.com/gofiber/recipes/tree/master/docker-mariadb-clean-arch) [![StackBlitz](https://img.shields.io/static/v1?label=&message=StackBlitz&color=2ea44f&style=for-the-badge&logo=StackBlitz)](https://stackblitz.com/github/gofiber/recipes/tree/master/docker-mariadb-clean-arch) + A slightly complex REST application with Fiber to showcase Clean Architecture with MariaDB as a dependency with Docker. ## Prerequisites diff --git a/docker-nginx-loadbalancer/README.md b/docker-nginx-loadbalancer/README.md index 89604de475..b1af8d6974 100644 --- a/docker-nginx-loadbalancer/README.md +++ b/docker-nginx-loadbalancer/README.md @@ -5,6 +5,8 @@ keywords: [docker, nginx, loadbalancer, reverse proxy] # Docker + Nginx +[![Github](https://img.shields.io/static/v1?label=&message=Github&color=2ea44f&style=for-the-badge&logo=github)](https://github.com/gofiber/recipes/tree/master/docker-nginx-loadbalancer) [![StackBlitz](https://img.shields.io/static/v1?label=&message=StackBlitz&color=2ea44f&style=for-the-badge&logo=StackBlitz)](https://stackblitz.com/github/gofiber/recipes/tree/master/docker-nginx-loadbalancer) + ## Features - **Docker and Nginx** : Deploy in docker using 5 replicas and load balancer with Nginx diff --git a/dummyjson/README.md b/dummyjson/README.md index 37238836ed..7506f82922 100644 --- a/dummyjson/README.md +++ b/dummyjson/README.md @@ -4,7 +4,9 @@ keywords: [dummyjson, proxy, json, server] --- # Simple Fiber Proxy Server - + +[![Github](https://img.shields.io/static/v1?label=&message=Github&color=2ea44f&style=for-the-badge&logo=github)](https://github.com/gofiber/recipes/tree/master/dummyjson) [![StackBlitz](https://img.shields.io/static/v1?label=&message=StackBlitz&color=2ea44f&style=for-the-badge&logo=StackBlitz)](https://stackblitz.com/github/gofiber/recipes/tree/master/dummyjson) + This is a basic Go application using the Fiber framework to create a web server. The server listens on port 3000 and has a single route (`GET /`) that fetches data from an external URL (`https://dummyjson.com/products/1`) and forwards it to the client. ### How to Run diff --git a/ent-mysql/README.md b/ent-mysql/README.md index 5d406a99ca..9da67fb648 100644 --- a/ent-mysql/README.md +++ b/ent-mysql/README.md @@ -5,6 +5,8 @@ keywords: [ent, mysql, orm, rest] # Example ent ORM for fiber with MySQL +[![Github](https://img.shields.io/static/v1?label=&message=Github&color=2ea44f&style=for-the-badge&logo=github)](https://github.com/gofiber/recipes/tree/master/ent-mysql) [![StackBlitz](https://img.shields.io/static/v1?label=&message=StackBlitz&color=2ea44f&style=for-the-badge&logo=StackBlitz)](https://stackblitz.com/github/gofiber/recipes/tree/master/ent-mysql) + A sample program how to connect ent ORM ## How to start (If no ent dir) diff --git a/entgo-sveltekit/README.md b/entgo-sveltekit/README.md index e5b1ee2587..bafe11f03e 100644 --- a/entgo-sveltekit/README.md +++ b/entgo-sveltekit/README.md @@ -4,6 +4,9 @@ keywords: [ent, sveltekit, tailwindcss, sqlite, rest] --- # Todo Application + +[![Github](https://img.shields.io/static/v1?label=&message=Github&color=2ea44f&style=for-the-badge&logo=github)](https://github.com/gofiber/recipes/tree/master/entgo-sveltekit) [![StackBlitz](https://img.shields.io/static/v1?label=&message=StackBlitz&color=2ea44f&style=for-the-badge&logo=StackBlitz)](https://stackblitz.com/github/gofiber/recipes/tree/master/entgo-sveltekit) + ![image](https://github.com/ugurkorkmaz/gofiber-recipes/assets/40540244/08c6ee52-724a-4cf4-8352-9cf6f5b007ef) This Todo application is a full-stack project built using Sveltekit, Tailwind CSS, Fiber, Entgo, and SQLite. It showcases the construction of a monolithic architecture for a full-stack application. diff --git a/envoy-extauthz/README.md b/envoy-extauthz/README.md index 45f4ec711e..47e4c40f8b 100644 --- a/envoy-extauthz/README.md +++ b/envoy-extauthz/README.md @@ -5,6 +5,8 @@ keywords: [envoy, external authorization, keyauth] # Fiber as an Envoy External Authorization HTTP Service +[![Github](https://img.shields.io/static/v1?label=&message=Github&color=2ea44f&style=for-the-badge&logo=github)](https://github.com/gofiber/recipes/tree/master/envoy-extauthz) [![StackBlitz](https://img.shields.io/static/v1?label=&message=StackBlitz&color=2ea44f&style=for-the-badge&logo=StackBlitz)](https://stackblitz.com/github/gofiber/recipes/tree/master/envoy-extauthz) + One way of extending the popular [Envoy](https://www.envoyproxy.io) proxy is by developing an [external authorization service](https://www.envoyproxy.io/docs/envoy/latest/api-v3/service/auth/v3/external_auth.proto). diff --git a/file-server/README.md b/file-server/README.md index e6ca43b6ef..70aa55a15a 100644 --- a/file-server/README.md +++ b/file-server/README.md @@ -5,6 +5,8 @@ keywords: [file server, static files] # File Server Example +[![Github](https://img.shields.io/static/v1?label=&message=Github&color=2ea44f&style=for-the-badge&logo=github)](https://github.com/gofiber/recipes/tree/master/file-server) [![StackBlitz](https://img.shields.io/static/v1?label=&message=StackBlitz&color=2ea44f&style=for-the-badge&logo=StackBlitz)](https://stackblitz.com/github/gofiber/recipes/tree/master/file-server) + This project demonstrates how to set up a simple file server in a Go application using the Fiber framework. ## Prerequisites diff --git a/firebase-auth/README.md b/firebase-auth/README.md index 923b21025a..0ca7810a89 100644 --- a/firebase-auth/README.md +++ b/firebase-auth/README.md @@ -5,6 +5,8 @@ keywords: [firebase, authentication, middleware] # Go Fiber Firebase Authentication Example +[![Github](https://img.shields.io/static/v1?label=&message=Github&color=2ea44f&style=for-the-badge&logo=github)](https://github.com/gofiber/recipes/tree/master/firebase-auth) [![StackBlitz](https://img.shields.io/static/v1?label=&message=StackBlitz&color=2ea44f&style=for-the-badge&logo=StackBlitz)](https://stackblitz.com/github/gofiber/recipes/tree/master/firebase-auth) + This example use [gofiber-firebaseauth middleware](https://github.com/sacsand/gofiber-firebaseauth) to authenticate the endpoints. Find the documentation for middleware here for more configurations options [docs](https://github.com/sacsand/gofiber-firebaseauth) ## Setting Up diff --git a/firebase-functions/README.md b/firebase-functions/README.md index ff34be0a5f..1c70dff109 100644 --- a/firebase-functions/README.md +++ b/firebase-functions/README.md @@ -4,6 +4,8 @@ keywords: [firebase, functions, deployment, gcloud, cloud] --- # Deploying GoFiber Application to Firebase Functions +[![Github](https://img.shields.io/static/v1?label=&message=Github&color=2ea44f&style=for-the-badge&logo=github)](https://github.com/gofiber/recipes/tree/master/firebase-functions) [![StackBlitz](https://img.shields.io/static/v1?label=&message=StackBlitz&color=2ea44f&style=for-the-badge&logo=StackBlitz)](https://stackblitz.com/github/gofiber/recipes/tree/master/firebase-functions) + Welcome to this step-by-step guide on deploying a GoFiber application to Firebase Functions. If you’re looking to leverage the power of GoFiber, a fast and lightweight web framework for Go, and host your application on Firebase, you’re in the right place. In this tutorial, we’ll walk through the process of setting up your GoFiber app to run seamlessly on Firebase Functions. ## Prerequisites diff --git a/gcloud-firebase/README.md b/gcloud-firebase/README.md index 953ab41029..00f141f8c8 100644 --- a/gcloud-firebase/README.md +++ b/gcloud-firebase/README.md @@ -5,6 +5,8 @@ keywords: [firebase, gcloud, cloud run, cloud function, app engine] # Deploy Fiber to Google Cloud with Firebase +[![Github](https://img.shields.io/static/v1?label=&message=Github&color=2ea44f&style=for-the-badge&logo=github)](https://github.com/gofiber/recipes/tree/master/gcloud-firebase) [![StackBlitz](https://img.shields.io/static/v1?label=&message=StackBlitz&color=2ea44f&style=for-the-badge&logo=StackBlitz)](https://stackblitz.com/github/gofiber/recipes/tree/master/gcloud-firebase) + Examples on how to run an application using Fiber on Google Cloud and connecting to Firebase Realtime Database. ## Running Locally diff --git a/gcloud/README.md b/gcloud/README.md index 550a854b66..8f75a0a3de 100644 --- a/gcloud/README.md +++ b/gcloud/README.md @@ -5,6 +5,8 @@ keywords: [firebase, gcloud, cloud run, cloud function, app engine] # Deploy Fiber to Google Cloud with Firebase +[![Github](https://img.shields.io/static/v1?label=&message=Github&color=2ea44f&style=for-the-badge&logo=github)](https://github.com/gofiber/recipes/tree/master/gcloud) [![StackBlitz](https://img.shields.io/static/v1?label=&message=StackBlitz&color=2ea44f&style=for-the-badge&logo=StackBlitz)](https://stackblitz.com/github/gofiber/recipes/tree/master/gcloud) + Examples on how to run an application using Fiber on Google Cloud. ## Running Locally diff --git a/geoip-maxmind/README.md b/geoip-maxmind/README.md index 3d8174f6aa..7bde0ffcd0 100644 --- a/geoip-maxmind/README.md +++ b/geoip-maxmind/README.md @@ -5,6 +5,8 @@ keywords: [geoip, maxmind, databases] # GeoIP (with MaxMind databases) +[![Github](https://img.shields.io/static/v1?label=&message=Github&color=2ea44f&style=for-the-badge&logo=github)](https://github.com/gofiber/recipes/tree/master/geoip-maxmind) [![StackBlitz](https://img.shields.io/static/v1?label=&message=StackBlitz&color=2ea44f&style=for-the-badge&logo=StackBlitz)](https://stackblitz.com/github/gofiber/recipes/tree/master/geoip-maxmind) + This is an alternative method to resolve IP addresses to real-world location data using MaxMind GeoLite2 City databases. ## Prerequisites diff --git a/geoip/README.md b/geoip/README.md index feda901105..53f2204ef6 100644 --- a/geoip/README.md +++ b/geoip/README.md @@ -5,6 +5,8 @@ keywords: [geoip, maxmind, ip] # GeoIP Example +[![Github](https://img.shields.io/static/v1?label=&message=Github&color=2ea44f&style=for-the-badge&logo=github)](https://github.com/gofiber/recipes/tree/master/geoip) [![StackBlitz](https://img.shields.io/static/v1?label=&message=StackBlitz&color=2ea44f&style=for-the-badge&logo=StackBlitz)](https://stackblitz.com/github/gofiber/recipes/tree/master/geoip) + This project demonstrates how to set up a GeoIP lookup service in a Go application using the Fiber framework. ## Prerequisites diff --git a/gorm-mysql/README.md b/gorm-mysql/README.md index 5d0da4adba..8dfb672ba8 100644 --- a/gorm-mysql/README.md +++ b/gorm-mysql/README.md @@ -5,6 +5,8 @@ keywords: [gorm, mysql, database, rest, api] # GORM MySQL Example +[![Github](https://img.shields.io/static/v1?label=&message=Github&color=2ea44f&style=for-the-badge&logo=github)](https://github.com/gofiber/recipes/tree/master/gorm-mysql) [![StackBlitz](https://img.shields.io/static/v1?label=&message=StackBlitz&color=2ea44f&style=for-the-badge&logo=StackBlitz)](https://stackblitz.com/github/gofiber/recipes/tree/master/gorm-mysql) + This is a sample program demonstrating how to use GORM as an ORM to connect to a MySQL database with the Fiber web framework. ## Prerequisites diff --git a/gorm-postgres/README.md b/gorm-postgres/README.md index 816b79013d..bf99a60b0b 100644 --- a/gorm-postgres/README.md +++ b/gorm-postgres/README.md @@ -5,6 +5,8 @@ keywords: [gorm, postgres, database] # GORM with PostgreSQL Example +[![Github](https://img.shields.io/static/v1?label=&message=Github&color=2ea44f&style=for-the-badge&logo=github)](https://github.com/gofiber/recipes/tree/master/gorm-postgres) [![StackBlitz](https://img.shields.io/static/v1?label=&message=StackBlitz&color=2ea44f&style=for-the-badge&logo=StackBlitz)](https://stackblitz.com/github/gofiber/recipes/tree/master/gorm-postgres) + This project demonstrates how to set up a Go application using the Fiber framework with GORM and PostgreSQL. ## Prerequisites diff --git a/gorm/README.md b/gorm/README.md index 1e2356fd23..c66f9f2021 100644 --- a/gorm/README.md +++ b/gorm/README.md @@ -5,6 +5,8 @@ keywords: [gorm, sqlite, api, rest] # GORM Example +[![Github](https://img.shields.io/static/v1?label=&message=Github&color=2ea44f&style=for-the-badge&logo=github)](https://github.com/gofiber/recipes/tree/master/gorm) [![StackBlitz](https://img.shields.io/static/v1?label=&message=StackBlitz&color=2ea44f&style=for-the-badge&logo=StackBlitz)](https://stackblitz.com/github/gofiber/recipes/tree/master/gorm) + This is a sample program demonstrating how to use GORM as an ORM to connect to a SQLite database with the Fiber web framework. ## Prerequisites diff --git a/graceful-shutdown/README.md b/graceful-shutdown/README.md index eddbe2a286..bc808b5e6d 100644 --- a/graceful-shutdown/README.md +++ b/graceful-shutdown/README.md @@ -5,6 +5,8 @@ keywords: [graceful, shutdown, os/signal, channel] # Graceful shutdown in Fiber +[![Github](https://img.shields.io/static/v1?label=&message=Github&color=2ea44f&style=for-the-badge&logo=github)](https://github.com/gofiber/recipes/tree/master/graceful-shutdown) [![StackBlitz](https://img.shields.io/static/v1?label=&message=StackBlitz&color=2ea44f&style=for-the-badge&logo=StackBlitz)](https://stackblitz.com/github/gofiber/recipes/tree/master/graceful-shutdown) + ``` fiberRecipes/graceful-shutdown on graceful-shutdown (f0834df) [?] via 🐹 v1.15.2 took 4s ❯ go run graceful-shutdown diff --git a/graphql/README.md b/graphql/README.md index b4b75c8981..0d7a8a939c 100644 --- a/graphql/README.md +++ b/graphql/README.md @@ -5,6 +5,8 @@ keywords: [graphql] # GraphQL Example +[![Github](https://img.shields.io/static/v1?label=&message=Github&color=2ea44f&style=for-the-badge&logo=github)](https://github.com/gofiber/recipes/tree/master/graphql) [![StackBlitz](https://img.shields.io/static/v1?label=&message=StackBlitz&color=2ea44f&style=for-the-badge&logo=StackBlitz)](https://stackblitz.com/github/gofiber/recipes/tree/master/graphql) + This project demonstrates how to set up a GraphQL server in a Go application using the Fiber framework. ## Prerequisites diff --git a/grpc/README.md b/grpc/README.md index 67d8adac62..01594060f8 100644 --- a/grpc/README.md +++ b/grpc/README.md @@ -5,6 +5,8 @@ keywords: [grpc, server, client] # Example for fiber as a client to gRPC server. +[![Github](https://img.shields.io/static/v1?label=&message=Github&color=2ea44f&style=for-the-badge&logo=github)](https://github.com/gofiber/recipes/tree/master/grpc) [![StackBlitz](https://img.shields.io/static/v1?label=&message=StackBlitz&color=2ea44f&style=for-the-badge&logo=StackBlitz)](https://stackblitz.com/github/gofiber/recipes/tree/master/grpc) + A sample program to showcase fiber as a client to a gRPC server. ## Prerequisites diff --git a/hello-world/README.md b/hello-world/README.md index b98c3fc273..51d57461f1 100644 --- a/hello-world/README.md +++ b/hello-world/README.md @@ -5,6 +5,8 @@ keywords: [hello world, golang, fiber] # Hello World Example +[![Github](https://img.shields.io/static/v1?label=&message=Github&color=2ea44f&style=for-the-badge&logo=github)](https://github.com/gofiber/recipes/tree/master/hello-world) [![StackBlitz](https://img.shields.io/static/v1?label=&message=StackBlitz&color=2ea44f&style=for-the-badge&logo=StackBlitz)](https://stackblitz.com/github/gofiber/recipes/tree/master/hello-world) + This project demonstrates a simple "Hello, World!" application using the Fiber framework in Go. ## Prerequisites diff --git a/heroku/README.md b/heroku/README.md index ff9a19faab..9481c88373 100644 --- a/heroku/README.md +++ b/heroku/README.md @@ -5,6 +5,8 @@ keywords: [heroku, deployment] # Heroku Deployment Example +[![Github](https://img.shields.io/static/v1?label=&message=Github&color=2ea44f&style=for-the-badge&logo=github)](https://github.com/gofiber/recipes/tree/master/heroku) [![StackBlitz](https://img.shields.io/static/v1?label=&message=StackBlitz&color=2ea44f&style=for-the-badge&logo=StackBlitz)](https://stackblitz.com/github/gofiber/recipes/tree/master/heroku) + This project demonstrates how to deploy a Go application using the Fiber framework on Heroku. ## Prerequisites diff --git a/hexagonal/README.md b/hexagonal/README.md index 19fc172f00..1d48d4f650 100644 --- a/hexagonal/README.md +++ b/hexagonal/README.md @@ -5,6 +5,8 @@ keywords: [hexagonal, architecture, mongodb] # A Hexagonal Software Architecture in Golang and MongoDB +[![Github](https://img.shields.io/static/v1?label=&message=Github&color=2ea44f&style=for-the-badge&logo=github)](https://github.com/gofiber/recipes/tree/master/hexagonal) [![StackBlitz](https://img.shields.io/static/v1?label=&message=StackBlitz&color=2ea44f&style=for-the-badge&logo=StackBlitz)](https://stackblitz.com/github/gofiber/recipes/tree/master/hexagonal) + This project presents a simple product catalogue microservice to demonstrate the principles of a hexagonal software architecture. The microservice exposes a RESTful API that allows consuming applications to perform CRUD operations on a product catalogue. The microservice is developed in Golang, and the product catalogue data is persisted in a MongoDB repository. ![Hexagonal Architecture](Hexagonal-Arch.png) diff --git a/https-pkcs12-tls/README.md b/https-pkcs12-tls/README.md index 7fa3d0ca7d..bc8270bddc 100644 --- a/https-pkcs12-tls/README.md +++ b/https-pkcs12-tls/README.md @@ -5,6 +5,8 @@ keywords: [https, tls, pkcs12] # HTTPS with PKCS12 TLS Example +[![Github](https://img.shields.io/static/v1?label=&message=Github&color=2ea44f&style=for-the-badge&logo=github)](https://github.com/gofiber/recipes/tree/master/https-pkcs12-tls) [![StackBlitz](https://img.shields.io/static/v1?label=&message=StackBlitz&color=2ea44f&style=for-the-badge&logo=StackBlitz)](https://stackblitz.com/github/gofiber/recipes/tree/master/https-pkcs12-tls) + This project demonstrates how to set up an HTTPS server with PKCS12 TLS in a Go application using the Fiber framework. ## Prerequisites diff --git a/https-tls/README.md b/https-tls/README.md index 3f9a2284c9..7f3f1a0c83 100644 --- a/https-tls/README.md +++ b/https-tls/README.md @@ -5,6 +5,8 @@ keywords: [https, tls, ssl, self-signed] # HTTPS with TLS Example +[![Github](https://img.shields.io/static/v1?label=&message=Github&color=2ea44f&style=for-the-badge&logo=github)](https://github.com/gofiber/recipes/tree/master/https-tls) [![StackBlitz](https://img.shields.io/static/v1?label=&message=StackBlitz&color=2ea44f&style=for-the-badge&logo=StackBlitz)](https://stackblitz.com/github/gofiber/recipes/tree/master/https-tls) + This project demonstrates how to set up an HTTPS server with TLS in a Go application using the Fiber framework. ## Prerequisites diff --git a/i18n/README.md b/i18n/README.md index 8b847ff72b..1548924c10 100644 --- a/i18n/README.md +++ b/i18n/README.md @@ -5,6 +5,8 @@ keywords: [i18n, go-i18n, internationalization] # Fiber with i18n +[![Github](https://img.shields.io/static/v1?label=&message=Github&color=2ea44f&style=for-the-badge&logo=github)](https://github.com/gofiber/recipes/tree/master/i18n) [![StackBlitz](https://img.shields.io/static/v1?label=&message=StackBlitz&color=2ea44f&style=for-the-badge&logo=StackBlitz)](https://stackblitz.com/github/gofiber/recipes/tree/master/i18n) + This is a quick example of how to use [nicksnyder/go-i18n](https://github.com/nicksnyder/go-i18n) package to translate your Fiber application into multiple languages. ## Demo diff --git a/jwt/README.md b/jwt/README.md index 9f93df3c9e..0ebc6931d4 100644 --- a/jwt/README.md +++ b/jwt/README.md @@ -5,6 +5,8 @@ keywords: [jwt, json web token, authentication] # Fiber with JWT +[![Github](https://img.shields.io/static/v1?label=&message=Github&color=2ea44f&style=for-the-badge&logo=github)](https://github.com/gofiber/recipes/tree/master/jwt) [![StackBlitz](https://img.shields.io/static/v1?label=&message=StackBlitz&color=2ea44f&style=for-the-badge&logo=StackBlitz)](https://stackblitz.com/github/gofiber/recipes/tree/master/jwt) + This example demonstrates how to use JSON Web Tokens (JWT) for authentication in a Fiber application. ## Prerequisites diff --git a/k8s/README.md b/k8s/README.md index 76f392b220..f32879f8d0 100644 --- a/k8s/README.md +++ b/k8s/README.md @@ -5,6 +5,8 @@ keywords: [kubernetes, cloud, deployment, gcloud, aws, azure] # Kubernetes Example +[![Github](https://img.shields.io/static/v1?label=&message=Github&color=2ea44f&style=for-the-badge&logo=github)](https://github.com/gofiber/recipes/tree/master/k8s) [![StackBlitz](https://img.shields.io/static/v1?label=&message=StackBlitz&color=2ea44f&style=for-the-badge&logo=StackBlitz)](https://stackblitz.com/github/gofiber/recipes/tree/master/k8s) + This project demonstrates how to deploy a Go application using the Fiber framework on a Kubernetes cluster. ## Prerequisites diff --git a/memgraph/README.md b/memgraph/README.md index 923d90ac7d..d298c4752c 100644 --- a/memgraph/README.md +++ b/memgraph/README.md @@ -5,6 +5,8 @@ keywords: [memgraph, graph, database] # Fiber and Memgraph +[![Github](https://img.shields.io/static/v1?label=&message=Github&color=2ea44f&style=for-the-badge&logo=github)](https://github.com/gofiber/recipes/tree/master/memgraph) [![StackBlitz](https://img.shields.io/static/v1?label=&message=StackBlitz&color=2ea44f&style=for-the-badge&logo=StackBlitz)](https://stackblitz.com/github/gofiber/recipes/tree/master/memgraph) + This is a cookbook recipe for setting up Fiber backend and Memgraph database. 🚀 ## Prerequisites diff --git a/minio/README.md b/minio/README.md index 08c3eab87c..dd83a85b96 100644 --- a/minio/README.md +++ b/minio/README.md @@ -5,6 +5,8 @@ keywords: [minio, file upload, file download] # MinIO File Upload & Download Example +[![Github](https://img.shields.io/static/v1?label=&message=Github&color=2ea44f&style=for-the-badge&logo=github)](https://github.com/gofiber/recipes/tree/master/minio) [![StackBlitz](https://img.shields.io/static/v1?label=&message=StackBlitz&color=2ea44f&style=for-the-badge&logo=StackBlitz)](https://stackblitz.com/github/gofiber/recipes/tree/master/minio) + This example demonstrates a simple Go Fiber application that includes modules for uploading both single and multiple files, as well as downloading files from MinIO. Each module provides REST API endpoints for file upload and retrieval, serving as a foundation for applications requiring file storage and access. ## Prerequisites diff --git a/mongodb/README.md b/mongodb/README.md index 71ff1b3951..dde4f8af15 100644 --- a/mongodb/README.md +++ b/mongodb/README.md @@ -5,6 +5,8 @@ keywords: [mongodb, database] # MongoDB Example +[![Github](https://img.shields.io/static/v1?label=&message=Github&color=2ea44f&style=for-the-badge&logo=github)](https://github.com/gofiber/recipes/tree/master/mongodb) [![StackBlitz](https://img.shields.io/static/v1?label=&message=StackBlitz&color=2ea44f&style=for-the-badge&logo=StackBlitz)](https://stackblitz.com/github/gofiber/recipes/tree/master/mongodb) + This project demonstrates how to connect to a MongoDB database in a Go application using the Fiber framework. ## Prerequisites diff --git a/multiple-ports/README.md b/multiple-ports/README.md index 19f717277a..1545b7d5c9 100644 --- a/multiple-ports/README.md +++ b/multiple-ports/README.md @@ -5,6 +5,8 @@ keywords: [multiple ports, server, port] # Multiple Ports Example +[![Github](https://img.shields.io/static/v1?label=&message=Github&color=2ea44f&style=for-the-badge&logo=github)](https://github.com/gofiber/recipes/tree/master/multiple-ports) [![StackBlitz](https://img.shields.io/static/v1?label=&message=StackBlitz&color=2ea44f&style=for-the-badge&logo=StackBlitz)](https://stackblitz.com/github/gofiber/recipes/tree/master/multiple-ports) + This project demonstrates how to run a Go application using the Fiber framework on multiple ports. ## Prerequisites diff --git a/mysql/README.md b/mysql/README.md index b50a526f34..c3fced94e5 100644 --- a/mysql/README.md +++ b/mysql/README.md @@ -5,6 +5,8 @@ keywords: [mysql] # MySQL Example +[![Github](https://img.shields.io/static/v1?label=&message=Github&color=2ea44f&style=for-the-badge&logo=github)](https://github.com/gofiber/recipes/tree/master/mysql) [![StackBlitz](https://img.shields.io/static/v1?label=&message=StackBlitz&color=2ea44f&style=for-the-badge&logo=StackBlitz)](https://stackblitz.com/github/gofiber/recipes/tree/master/mysql) + This project demonstrates how to connect to a MySQL database in a Go application using the Fiber framework. ## Prerequisites diff --git a/neo4j/README.md b/neo4j/README.md index 2e4e4b0fbe..5b7d1b1608 100644 --- a/neo4j/README.md +++ b/neo4j/README.md @@ -5,6 +5,8 @@ keywords: [neo4j, database] # Neo4j Example +[![Github](https://img.shields.io/static/v1?label=&message=Github&color=2ea44f&style=for-the-badge&logo=github)](https://github.com/gofiber/recipes/tree/master/neo4j) [![StackBlitz](https://img.shields.io/static/v1?label=&message=StackBlitz&color=2ea44f&style=for-the-badge&logo=StackBlitz)](https://stackblitz.com/github/gofiber/recipes/tree/master/neo4j) + This project demonstrates how to connect to a Neo4j database in a Go application using the Fiber framework. ## Prerequisites diff --git a/oauth2-google/README.md b/oauth2-google/README.md index 8508379c78..ec8d743d55 100644 --- a/oauth2-google/README.md +++ b/oauth2-google/README.md @@ -5,6 +5,8 @@ keywords: [oauth2, google, authentication] # Fiber with Google OAuth2 +[![Github](https://img.shields.io/static/v1?label=&message=Github&color=2ea44f&style=for-the-badge&logo=github)](https://github.com/gofiber/recipes/tree/master/oauth2-google) [![StackBlitz](https://img.shields.io/static/v1?label=&message=StackBlitz&color=2ea44f&style=for-the-badge&logo=StackBlitz)](https://stackblitz.com/github/gofiber/recipes/tree/master/oauth2-google) + This example demonstrates how to implement Google OAuth2 authentication in a Fiber application. ## Prerequisites diff --git a/oauth2/README.md b/oauth2/README.md index 28b678e15e..3c2382e117 100644 --- a/oauth2/README.md +++ b/oauth2/README.md @@ -6,6 +6,8 @@ keywords: [oauth2, golang, authentication, api] # OAuth2 +[![Github](https://img.shields.io/static/v1?label=&message=Github&color=2ea44f&style=for-the-badge&logo=github)](https://github.com/gofiber/recipes/tree/master/oauth2) [![StackBlitz](https://img.shields.io/static/v1?label=&message=StackBlitz&color=2ea44f&style=for-the-badge&logo=StackBlitz)](https://stackblitz.com/github/gofiber/recipes/tree/master/oauth2) + This project demonstrates how to implement OAuth2 authentication in a Go application. ## Prerequisites diff --git a/optional-parameter/README.md b/optional-parameter/README.md index 83fdfce8fc..fada14f916 100644 --- a/optional-parameter/README.md +++ b/optional-parameter/README.md @@ -5,6 +5,8 @@ keywords: [optional, parameter] # Optional Parameter Example +[![Github](https://img.shields.io/static/v1?label=&message=Github&color=2ea44f&style=for-the-badge&logo=github)](https://github.com/gofiber/recipes/tree/master/optional-parameter) [![StackBlitz](https://img.shields.io/static/v1?label=&message=StackBlitz&color=2ea44f&style=for-the-badge&logo=StackBlitz)](https://stackblitz.com/github/gofiber/recipes/tree/master/optional-parameter) + This project demonstrates how to handle optional parameters in a Go application using the Fiber framework. ## Prerequisites diff --git a/overview.go b/overview.go index f8b36d9b7e..19c743f55b 100644 --- a/overview.go +++ b/overview.go @@ -11,6 +11,7 @@ import ( var ( titleRegex = regexp.MustCompile(`(?m)^title: (.+)`) keywordsRegex = regexp.MustCompile(`(?m)^keywords: \[(.+)\]`) + headerRegex = regexp.MustCompile(`(?m)^# .+`) ) //go:generate go run overview.go @@ -18,9 +19,9 @@ func main() { // fetch current file directory root, _ := os.Getwd() toc := "" - missingReadmeDirs := []string{} - missingTitleDirs := []string{} - missingKeywordsDirs := []string{} + var missingReadmeDirs []string + var missingTitleDirs []string + var missingKeywordsDirs []string err := filepath.Walk(root, func(path string, info os.FileInfo, err error) error { if err != nil { @@ -47,6 +48,10 @@ func main() { title = "No title" } toc += fmt.Sprintf("- [%s](./%s/README.md)\n", title, relativePath) + err = addLinksToReadme(readmePath, info.Name()) + if err != nil { + return err + } } else { missingReadmeDirs = append(missingReadmeDirs, relativePath) } @@ -127,3 +132,47 @@ func extractTitleAndKeywords(readmePath string) (string, []string, error) { return title, keywords, nil } + +func addLinksToReadme(readmePath, dirName string) error { + content, err := os.ReadFile(readmePath) + if err != nil { + return err + } + + links := fmt.Sprintf( + "[![Github](https://img.shields.io/static/v1?label=&message=Github&color=2ea44f&style=for-the-badge&logo=github)](https://github.com/gofiber/recipes/tree/master/%s) "+ + "[![StackBlitz](https://img.shields.io/static/v1?label=&message=StackBlitz&color=2ea44f&style=for-the-badge&logo=StackBlitz)](https://stackblitz.com/github/gofiber/recipes/tree/master/%s)", + dirName, dirName) + + lines := strings.Split(string(content), "\n") + headerIndex := -1 + + // Find the first headline + for i, line := range lines { + if headerRegex.MatchString(line) { + headerIndex = i + break + } + } + + if headerIndex == -1 { + return fmt.Errorf("no headline found in %s", readmePath) + } + + // Find the start and end of the section to be replaced + start := headerIndex + 1 + end := len(lines) + for i := start; i < len(lines); i++ { + if strings.TrimSpace(lines[i]) == "" || strings.Contains(lines[i], "![Github]") || strings.Contains(lines[i], "![StackBlitz]") { + continue + } + end = i + break + } + + // Replace the section with the new links and surrounding empty lines + cleanedLines := append(lines[:start], append([]string{"", links, ""}, lines[end:]...)...) + + content = []byte(strings.Join(cleanedLines, "\n")) + return os.WriteFile(readmePath, content, 0644) +} diff --git a/parsley/README.md b/parsley/README.md index 555b4b6cef..ad78d267f3 100644 --- a/parsley/README.md +++ b/parsley/README.md @@ -5,6 +5,8 @@ keywords: [parsley, dependency injection, di, inversion of control, ioc] # Fiber with Dependency Injection (via Parsley) +[![Github](https://img.shields.io/static/v1?label=&message=Github&color=2ea44f&style=for-the-badge&logo=github)](https://github.com/gofiber/recipes/tree/master/parsley) [![StackBlitz](https://img.shields.io/static/v1?label=&message=StackBlitz&color=2ea44f&style=for-the-badge&logo=StackBlitz)](https://stackblitz.com/github/gofiber/recipes/tree/master/parsley) + This example demonstrates integrating the [Parsley dependency injection framework](https://github.com/matzefriedrich/parsley) into a GoFiber web application. The goal is to showcase how dependency injection can create a clean, maintainable, and modular structure in your GoFiber projects. ## Overview diff --git a/postgresql/README.md b/postgresql/README.md index 7ca4da11fd..7f28692aee 100644 --- a/postgresql/README.md +++ b/postgresql/README.md @@ -5,6 +5,8 @@ keywords: [postgresql] # PostgreSQL Example +[![Github](https://img.shields.io/static/v1?label=&message=Github&color=2ea44f&style=for-the-badge&logo=github)](https://github.com/gofiber/recipes/tree/master/postgresql) [![StackBlitz](https://img.shields.io/static/v1?label=&message=StackBlitz&color=2ea44f&style=for-the-badge&logo=StackBlitz)](https://stackblitz.com/github/gofiber/recipes/tree/master/postgresql) + This project demonstrates how to connect to a PostgreSQL database in a Go application using the Fiber framework. ## Prerequisites diff --git a/prefork/README.md b/prefork/README.md index 86e1d58785..ed713bf370 100644 --- a/prefork/README.md +++ b/prefork/README.md @@ -5,6 +5,8 @@ keywords: [prefork] # Prefork Example +[![Github](https://img.shields.io/static/v1?label=&message=Github&color=2ea44f&style=for-the-badge&logo=github)](https://github.com/gofiber/recipes/tree/master/prefork) [![StackBlitz](https://img.shields.io/static/v1?label=&message=StackBlitz&color=2ea44f&style=for-the-badge&logo=StackBlitz)](https://stackblitz.com/github/gofiber/recipes/tree/master/prefork) + This project demonstrates how to use the `Prefork` feature in a Go application using the Fiber framework. Preforking can improve performance by utilizing multiple CPU cores. ## Prerequisites diff --git a/rabbitmq/README.md b/rabbitmq/README.md index b1e2c51989..e294d8fa5d 100644 --- a/rabbitmq/README.md +++ b/rabbitmq/README.md @@ -5,6 +5,8 @@ keywords: [rabbitmq, amqp, messaging, queue] # Fiber and RabbitMQ example +[![Github](https://img.shields.io/static/v1?label=&message=Github&color=2ea44f&style=for-the-badge&logo=github)](https://github.com/gofiber/recipes/tree/master/rabbitmq) [![StackBlitz](https://img.shields.io/static/v1?label=&message=StackBlitz&color=2ea44f&style=for-the-badge&logo=StackBlitz)](https://stackblitz.com/github/gofiber/recipes/tree/master/rabbitmq) + 1. Create Docker network: ```bash diff --git a/react-router/README.md b/react-router/README.md index e73c653005..c1a2d4fc74 100644 --- a/react-router/README.md +++ b/react-router/README.md @@ -5,6 +5,8 @@ keywords: [react, react-router, client-side, spa, docker] # React Fiber +[![Github](https://img.shields.io/static/v1?label=&message=Github&color=2ea44f&style=for-the-badge&logo=github)](https://github.com/gofiber/recipes/tree/master/react-router) [![StackBlitz](https://img.shields.io/static/v1?label=&message=StackBlitz&color=2ea44f&style=for-the-badge&logo=StackBlitz)](https://stackblitz.com/github/gofiber/recipes/tree/master/react-router) + A sample application to showcase serving React (with Router) with an almost bare Fiber. Hopefully, this application can be of use (as a reference or others) for those who wants to serve their client-side SPA with Fiber. ## Technologies diff --git a/recover/README.md b/recover/README.md index 3e54a28077..5a139b1427 100644 --- a/recover/README.md +++ b/recover/README.md @@ -5,6 +5,8 @@ keywords: [recover, middleware] # Recover Middleware Example +[![Github](https://img.shields.io/static/v1?label=&message=Github&color=2ea44f&style=for-the-badge&logo=github)](https://github.com/gofiber/recipes/tree/master/recover) [![StackBlitz](https://img.shields.io/static/v1?label=&message=StackBlitz&color=2ea44f&style=for-the-badge&logo=StackBlitz)](https://stackblitz.com/github/gofiber/recipes/tree/master/recover) + This project demonstrates how to implement a recovery mechanism in a Go application using the Fiber framework's `Recover` middleware. ## Prerequisites diff --git a/rss-feed/README.md b/rss-feed/README.md index 30b2f1d968..18a491766f 100644 --- a/rss-feed/README.md +++ b/rss-feed/README.md @@ -5,6 +5,8 @@ keywords: [rss, feed] # RSS Feed +[![Github](https://img.shields.io/static/v1?label=&message=Github&color=2ea44f&style=for-the-badge&logo=github)](https://github.com/gofiber/recipes/tree/master/rss-feed) [![StackBlitz](https://img.shields.io/static/v1?label=&message=StackBlitz&color=2ea44f&style=for-the-badge&logo=StackBlitz)](https://stackblitz.com/github/gofiber/recipes/tree/master/rss-feed) + This project demonstrates how to create an RSS feed in a Go application using the Fiber framework. ## Prerequisites diff --git a/server-timing/README.md b/server-timing/README.md index 3a204f0196..57cf25de32 100644 --- a/server-timing/README.md +++ b/server-timing/README.md @@ -5,6 +5,8 @@ keywords: [server timing] # Server Timing +[![Github](https://img.shields.io/static/v1?label=&message=Github&color=2ea44f&style=for-the-badge&logo=github)](https://github.com/gofiber/recipes/tree/master/server-timing) [![StackBlitz](https://img.shields.io/static/v1?label=&message=StackBlitz&color=2ea44f&style=for-the-badge&logo=StackBlitz)](https://stackblitz.com/github/gofiber/recipes/tree/master/server-timing) + This project demonstrates how to implement Server-Timing headers in a Go application using the Fiber framework. ## Prerequisites diff --git a/sessions-sqlite3/README.md b/sessions-sqlite3/README.md index fa8d8cc709..6426f0e1e6 100644 --- a/sessions-sqlite3/README.md +++ b/sessions-sqlite3/README.md @@ -5,6 +5,8 @@ keywords: [sessions, sqlite3, storage] # Sessions - SQLite3 +[![Github](https://img.shields.io/static/v1?label=&message=Github&color=2ea44f&style=for-the-badge&logo=github)](https://github.com/gofiber/recipes/tree/master/sessions-sqlite3) [![StackBlitz](https://img.shields.io/static/v1?label=&message=StackBlitz&color=2ea44f&style=for-the-badge&logo=StackBlitz)](https://stackblitz.com/github/gofiber/recipes/tree/master/sessions-sqlite3) + This example uses the SQLite3 storage package to persist user sessions. While the storage package can automatically create the sessions table at initialization, we create it manually to add an additional "u" column. This custom column serves several purposes: - Enables efficient querying of sessions by user identifier diff --git a/socketio/README.md b/socketio/README.md index 9c70b3df41..20edb8040f 100644 --- a/socketio/README.md +++ b/socketio/README.md @@ -5,6 +5,8 @@ keywords: [websocket, chat, socketio, chatroom, contrib] # WebSocket Chat Example +[![Github](https://img.shields.io/static/v1?label=&message=Github&color=2ea44f&style=for-the-badge&logo=github)](https://github.com/gofiber/recipes/tree/master/socketio) [![StackBlitz](https://img.shields.io/static/v1?label=&message=StackBlitz&color=2ea44f&style=for-the-badge&logo=StackBlitz)](https://stackblitz.com/github/gofiber/recipes/tree/master/socketio) + This example demonstrates how to create a simple chatroom using WebSockets. The chatroom supports multiple users and allows them to send messages to each other. ## Prerequisites diff --git a/spa/README.md b/spa/README.md index de1dac4468..ea06526827 100644 --- a/spa/README.md +++ b/spa/README.md @@ -5,6 +5,8 @@ keywords: [spa, react, tailwindcss, parcel] # Single Page Application (SPA) +[![Github](https://img.shields.io/static/v1?label=&message=Github&color=2ea44f&style=for-the-badge&logo=github)](https://github.com/gofiber/recipes/tree/master/spa) [![StackBlitz](https://img.shields.io/static/v1?label=&message=StackBlitz&color=2ea44f&style=for-the-badge&logo=StackBlitz)](https://stackblitz.com/github/gofiber/recipes/tree/master/spa) + This project demonstrates how to set up a Single Page Application (SPA) using React for the frontend and Go with the Fiber framework for the backend. ## Prerequisites diff --git a/sqlboiler/README.md b/sqlboiler/README.md index 79b9f0ef17..a61b296552 100644 --- a/sqlboiler/README.md +++ b/sqlboiler/README.md @@ -5,6 +5,8 @@ keywords: [sqlboiler, database, docker] # Fiber with sqlboiler +[![Github](https://img.shields.io/static/v1?label=&message=Github&color=2ea44f&style=for-the-badge&logo=github)](https://github.com/gofiber/recipes/tree/master/sqlboiler) [![StackBlitz](https://img.shields.io/static/v1?label=&message=StackBlitz&color=2ea44f&style=for-the-badge&logo=StackBlitz)](https://stackblitz.com/github/gofiber/recipes/tree/master/sqlboiler) + > #### 🎯 [Fiber](https://github.com/gofiber/fiber) + [Sqlboiler](https://github.com/volatiletech/sqlboiler) Example ## 👀 Usage diff --git a/sqlc/README.md b/sqlc/README.md index d92df594a5..c3e2fab935 100644 --- a/sqlc/README.md +++ b/sqlc/README.md @@ -5,6 +5,8 @@ keywords: [database, sqlc, postgresql] # Fiber with sqlc +[![Github](https://img.shields.io/static/v1?label=&message=Github&color=2ea44f&style=for-the-badge&logo=github)](https://github.com/gofiber/recipes/tree/master/sqlc) [![StackBlitz](https://img.shields.io/static/v1?label=&message=StackBlitz&color=2ea44f&style=for-the-badge&logo=StackBlitz)](https://stackblitz.com/github/gofiber/recipes/tree/master/sqlc) + > #### 🎯 [fiber](https://github.com/gofiber/fiber) + [sqlc](https://github.com/sqlc-dev/sqlc) Example ## 👀 Usage diff --git a/sse/README.md b/sse/README.md index 505d4b3417..ebee76e764 100644 --- a/sse/README.md +++ b/sse/README.md @@ -5,6 +5,8 @@ keywords: [sse, server-sent events, real-time] # Server-Sent Events with Fiber +[![Github](https://img.shields.io/static/v1?label=&message=Github&color=2ea44f&style=for-the-badge&logo=github)](https://github.com/gofiber/recipes/tree/master/sse) [![StackBlitz](https://img.shields.io/static/v1?label=&message=StackBlitz&color=2ea44f&style=for-the-badge&logo=StackBlitz)](https://stackblitz.com/github/gofiber/recipes/tree/master/sse) + This example demonstrates how to implement Server-Sent Events (SSE) in a Fiber application. ## Description diff --git a/stream-request-body/README.md b/stream-request-body/README.md index 93df4ff1fd..d315fbe83e 100644 --- a/stream-request-body/README.md +++ b/stream-request-body/README.md @@ -5,6 +5,8 @@ keywords: [stream, request body] # Stream Request Body +[![Github](https://img.shields.io/static/v1?label=&message=Github&color=2ea44f&style=for-the-badge&logo=github)](https://github.com/gofiber/recipes/tree/master/stream-request-body) [![StackBlitz](https://img.shields.io/static/v1?label=&message=StackBlitz&color=2ea44f&style=for-the-badge&logo=StackBlitz)](https://stackblitz.com/github/gofiber/recipes/tree/master/stream-request-body) + This project demonstrates how to handle streaming request bodies in a Go application using the Fiber framework. ## Prerequisites diff --git a/svelte-netlify/README.md b/svelte-netlify/README.md index c1f687a9a6..c1512de5b0 100644 --- a/svelte-netlify/README.md +++ b/svelte-netlify/README.md @@ -5,6 +5,8 @@ keywords: [netlify, deploy, svelte] # Deploying fiber on Netlify +[![Github](https://img.shields.io/static/v1?label=&message=Github&color=2ea44f&style=for-the-badge&logo=github)](https://github.com/gofiber/recipes/tree/master/svelte-netlify) [![StackBlitz](https://img.shields.io/static/v1?label=&message=StackBlitz&color=2ea44f&style=for-the-badge&logo=StackBlitz)](https://stackblitz.com/github/gofiber/recipes/tree/master/svelte-netlify) + [![Netlify Status](https://api.netlify.com/api/v1/badges/143c3c42-60f7-427a-b3fd-8ca3947a2d40/deploy-status)](https://app.netlify.com/sites/gofiber-svelte/deploys) ### Demo @ https://gofiber-svelte.netlify.app/ diff --git a/sveltekit-embed/README.md b/sveltekit-embed/README.md index 19161793bf..3dad48a1b5 100644 --- a/sveltekit-embed/README.md +++ b/sveltekit-embed/README.md @@ -4,6 +4,9 @@ keywords: [sveltekit, tailwindcss, embed] --- # Fiber Sveltekit Embed App + +[![Github](https://img.shields.io/static/v1?label=&message=Github&color=2ea44f&style=for-the-badge&logo=github)](https://github.com/gofiber/recipes/tree/master/sveltekit-embed) [![StackBlitz](https://img.shields.io/static/v1?label=&message=StackBlitz&color=2ea44f&style=for-the-badge&logo=StackBlitz)](https://stackblitz.com/github/gofiber/recipes/tree/master/sveltekit-embed) + ![image](https://github.com/gofiber/recipes/assets/40540244/2aa084b8-9bbc-46f3-9759-930857429f05) This application is a full-stack project built using Sveltekit, Tailwind CSS, Fiber. It showcases the construction of a monolithic architecture for a full-stack application. diff --git a/swagger/README.md b/swagger/README.md index 662190dcb2..983c7711fb 100644 --- a/swagger/README.md +++ b/swagger/README.md @@ -4,7 +4,9 @@ keywords: [swagger, api, documentation, contrib] --- # Swagger API Documentation - + +[![Github](https://img.shields.io/static/v1?label=&message=Github&color=2ea44f&style=for-the-badge&logo=github)](https://github.com/gofiber/recipes/tree/master/swagger) [![StackBlitz](https://img.shields.io/static/v1?label=&message=StackBlitz&color=2ea44f&style=for-the-badge&logo=StackBlitz)](https://stackblitz.com/github/gofiber/recipes/tree/master/swagger) + This project demonstrates how to integrate Swagger for API documentation in a Go application. ## Prerequisites diff --git a/tableflip/README.md b/tableflip/README.md index b8ab8dbc78..59087458e9 100644 --- a/tableflip/README.md +++ b/tableflip/README.md @@ -5,6 +5,8 @@ keywords: [tableflip, golang, graceful upgrade] # Tableflip Example +[![Github](https://img.shields.io/static/v1?label=&message=Github&color=2ea44f&style=for-the-badge&logo=github)](https://github.com/gofiber/recipes/tree/master/tableflip) [![StackBlitz](https://img.shields.io/static/v1?label=&message=StackBlitz&color=2ea44f&style=for-the-badge&logo=StackBlitz)](https://stackblitz.com/github/gofiber/recipes/tree/master/tableflip) + This example demonstrates how to use [tableflip](https://github.com/cloudflare/tableflip) for graceful upgrades in a Go application. ## What is Tableflip? diff --git a/template-asset-bundling/README.md b/template-asset-bundling/README.md index 4946995cbd..daf0925855 100644 --- a/template-asset-bundling/README.md +++ b/template-asset-bundling/README.md @@ -5,6 +5,8 @@ keywords: [template, tailwindcss, parcel] # Template Asset Bundling +[![Github](https://img.shields.io/static/v1?label=&message=Github&color=2ea44f&style=for-the-badge&logo=github)](https://github.com/gofiber/recipes/tree/master/template-asset-bundling) [![StackBlitz](https://img.shields.io/static/v1?label=&message=StackBlitz&color=2ea44f&style=for-the-badge&logo=StackBlitz)](https://stackblitz.com/github/gofiber/recipes/tree/master/template-asset-bundling) + This is a quick example of how to do asset bundling using [gofiber/template](https://github.com/gofiber/template), [Tailwind CSS](https://tailwindcss.com), and [Parcel](https://parceljs.org). ## Prerequisites diff --git a/template/README.md b/template/README.md index 4be99f9b2e..dfbc333e69 100644 --- a/template/README.md +++ b/template/README.md @@ -5,6 +5,8 @@ keywords: [template, tailwindcss, parcel] # Template Project +[![Github](https://img.shields.io/static/v1?label=&message=Github&color=2ea44f&style=for-the-badge&logo=github)](https://github.com/gofiber/recipes/tree/master/template) [![StackBlitz](https://img.shields.io/static/v1?label=&message=StackBlitz&color=2ea44f&style=for-the-badge&logo=StackBlitz)](https://stackblitz.com/github/gofiber/recipes/tree/master/template) + This project demonstrates how to set up a Go application with template rendering, Tailwind CSS, and Parcel for asset bundling. ## Prerequisites diff --git a/todo-app-with-auth-gorm/README.md b/todo-app-with-auth-gorm/README.md index bd4778b3c5..5cc5dcac17 100644 --- a/todo-app-with-auth-gorm/README.md +++ b/todo-app-with-auth-gorm/README.md @@ -5,6 +5,8 @@ keywords: [todo app, gorm, authentication] # Todo App with Auth using GORM +[![Github](https://img.shields.io/static/v1?label=&message=Github&color=2ea44f&style=for-the-badge&logo=github)](https://github.com/gofiber/recipes/tree/master/todo-app-with-auth-gorm) [![StackBlitz](https://img.shields.io/static/v1?label=&message=StackBlitz&color=2ea44f&style=for-the-badge&logo=StackBlitz)](https://stackblitz.com/github/gofiber/recipes/tree/master/todo-app-with-auth-gorm) + This project demonstrates a Todo application with authentication using GORM. ## Prerequisites diff --git a/unit-test/README.md b/unit-test/README.md index b3a7b44b98..27c4b2e4f0 100644 --- a/unit-test/README.md +++ b/unit-test/README.md @@ -5,6 +5,8 @@ keywords: [unit testing, testing, stretchr/testify] # Unit Testing Example +[![Github](https://img.shields.io/static/v1?label=&message=Github&color=2ea44f&style=for-the-badge&logo=github)](https://github.com/gofiber/recipes/tree/master/unit-test) [![StackBlitz](https://img.shields.io/static/v1?label=&message=StackBlitz&color=2ea44f&style=for-the-badge&logo=StackBlitz)](https://stackblitz.com/github/gofiber/recipes/tree/master/unit-test) + This example demonstrates how to write unit tests for a Go Fiber application using the `stretchr/testify` package. ## Description diff --git a/upload-file/README.md b/upload-file/README.md index e3eba36c94..2ce496c12a 100644 --- a/upload-file/README.md +++ b/upload-file/README.md @@ -5,6 +5,8 @@ keywords: [file upload, upload, form, multipart] # File Upload Example +[![Github](https://img.shields.io/static/v1?label=&message=Github&color=2ea44f&style=for-the-badge&logo=github)](https://github.com/gofiber/recipes/tree/master/upload-file) [![StackBlitz](https://img.shields.io/static/v1?label=&message=StackBlitz&color=2ea44f&style=for-the-badge&logo=StackBlitz)](https://stackblitz.com/github/gofiber/recipes/tree/master/upload-file) + This example demonstrates how to handle file uploads using Go Fiber. ## Description diff --git a/url-shortener-api/README.md b/url-shortener-api/README.md index 01df75e49f..3ced490be4 100644 --- a/url-shortener-api/README.md +++ b/url-shortener-api/README.md @@ -5,6 +5,8 @@ keywords: [url shortener, redis, api] # URL Shortener API +[![Github](https://img.shields.io/static/v1?label=&message=Github&color=2ea44f&style=for-the-badge&logo=github)](https://github.com/gofiber/recipes/tree/master/url-shortener-api) [![StackBlitz](https://img.shields.io/static/v1?label=&message=StackBlitz&color=2ea44f&style=for-the-badge&logo=StackBlitz)](https://stackblitz.com/github/gofiber/recipes/tree/master/url-shortener-api) + This project provides a URL shortening service with a simple API. ## Tech Stack diff --git a/validation/README.md b/validation/README.md index 81a32d0060..1a1fe73aac 100644 --- a/validation/README.md +++ b/validation/README.md @@ -5,6 +5,8 @@ keywords: [validation, input, go-playground, validator] # Validation with [Fiber](https://gofiber.io) +[![Github](https://img.shields.io/static/v1?label=&message=Github&color=2ea44f&style=for-the-badge&logo=github)](https://github.com/gofiber/recipes/tree/master/validation) [![StackBlitz](https://img.shields.io/static/v1?label=&message=StackBlitz&color=2ea44f&style=for-the-badge&logo=StackBlitz)](https://stackblitz.com/github/gofiber/recipes/tree/master/validation) + This example demonstrates how to use [go-playground/validator](https://github.com/go-playground/validator) for input validation in a Go Fiber application. ## Description diff --git a/vercel/README.md b/vercel/README.md index 96f17da3af..8344dd5132 100644 --- a/vercel/README.md +++ b/vercel/README.md @@ -5,6 +5,8 @@ keywords: [vercel, deploy, serverless] # Vercel Example +[![Github](https://img.shields.io/static/v1?label=&message=Github&color=2ea44f&style=for-the-badge&logo=github)](https://github.com/gofiber/recipes/tree/master/vercel) [![StackBlitz](https://img.shields.io/static/v1?label=&message=StackBlitz&color=2ea44f&style=for-the-badge&logo=StackBlitz)](https://stackblitz.com/github/gofiber/recipes/tree/master/vercel) + This example demonstrates how to deploy a Go Fiber application to Vercel. ## Description diff --git a/websocket-chat/README.md b/websocket-chat/README.md index 2afe7270af..3c4b75d3e4 100644 --- a/websocket-chat/README.md +++ b/websocket-chat/README.md @@ -5,6 +5,8 @@ keywords: [websocket, chat, chatroom, contrib] # WebSocket Chat Example +[![Github](https://img.shields.io/static/v1?label=&message=Github&color=2ea44f&style=for-the-badge&logo=github)](https://github.com/gofiber/recipes/tree/master/websocket-chat) [![StackBlitz](https://img.shields.io/static/v1?label=&message=StackBlitz&color=2ea44f&style=for-the-badge&logo=StackBlitz)](https://stackblitz.com/github/gofiber/recipes/tree/master/websocket-chat) + This example demonstrates a simple chat application using Go Fiber and WebSockets. ## Description diff --git a/websocket/README.md b/websocket/README.md index eede000601..426cc5ef21 100644 --- a/websocket/README.md +++ b/websocket/README.md @@ -5,6 +5,8 @@ keywords: [websocket, real-time, chat, contrib] # WebSocket Example +[![Github](https://img.shields.io/static/v1?label=&message=Github&color=2ea44f&style=for-the-badge&logo=github)](https://github.com/gofiber/recipes/tree/master/websocket) [![StackBlitz](https://img.shields.io/static/v1?label=&message=StackBlitz&color=2ea44f&style=for-the-badge&logo=StackBlitz)](https://stackblitz.com/github/gofiber/recipes/tree/master/websocket) + This example demonstrates a simple WebSocket application using Go Fiber. ## Description From 017a25cd0bd5445f0f65bd2198813c4db4b6dd79 Mon Sep 17 00:00:00 2001 From: RW Date: Tue, 26 Nov 2024 19:07:02 +0100 Subject: [PATCH 10/14] Update .github/scripts/sync_local.sh Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com> --- .github/scripts/sync_local.sh | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/.github/scripts/sync_local.sh b/.github/scripts/sync_local.sh index cd899f4d5b..079fe23b94 100755 --- a/.github/scripts/sync_local.sh +++ b/.github/scripts/sync_local.sh @@ -1,7 +1,16 @@ #!/usr/bin/env bash set -e -REPO_DIR="recipes" +if [ "$#" -eq 1 ]; then + REPO_DIR="$1" +else + REPO_DIR="recipes" # default value +fi + +if [[ ! "$REPO_DIR" =~ ^[a-zA-Z0-9_-]+$ ]]; then + echo "Error: REPO_DIR must contain only alphanumeric characters, underscores, and hyphens" >&2 + exit 1 +fi # determine root repo directory ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd -P)" From e937d9aae8519544483f7a51e2a4f81f35b308d4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ren=C3=A9?= Date: Tue, 26 Nov 2024 19:21:11 +0100 Subject: [PATCH 11/14] docusaurus preparations --- .github/CONTRIBUTING.md | 18 ++-- 404-handler/README.md | 1 + air/README.md | 6 ++ auth-docker-postgres-jwt/README.md | 7 ++ auth-docker-postgres-jwt/cmd/main.go | 3 +- auth-docker-postgres-jwt/database/connect.go | 7 +- auth-docker-postgres-jwt/handler/auth.go | 9 +- auth-docker-postgres-jwt/handler/product.go | 2 - auth-docker-postgres-jwt/handler/user.go | 5 +- auth-jwt/README.md | 8 ++ auth-jwt/database/connect.go | 8 +- auth-jwt/handler/product.go | 2 - auth-jwt/handler/user.go | 4 - auth-jwt/main.go | 3 +- auth-jwt/middleware/auth.go | 4 +- autocert/README.md | 4 + aws-eb/README.md | 8 ++ aws-sam-container/README.md | 21 +++-- aws-sam-container/app/main.go | 3 +- aws-sam/README.md | 6 +- aws-sam/app/main.go | 3 +- bootstrap/README.md | 5 + bootstrap/app/controllers/main_controller.go | 1 - bootstrap/main.go | 3 +- bootstrap/pkg/database/setup.go | 1 + bootstrap/pkg/env/env.go | 1 - bootstrap/pkg/router/api_router.go | 3 +- bootstrap/pkg/router/http_router.go | 3 +- bootstrap/pkg/router/setup.go | 1 + clean-architecture/README.md | 32 +++++-- .../api/handlers/book_handler.go | 3 +- clean-architecture/main.go | 5 +- clean-architecture/pkg/book/repository.go | 6 +- clean-architecture/pkg/entities/book.go | 3 +- cloud-run/README.md | 7 ++ colly-gorm/README.md | 1 - colly-gorm/app/cmd/api/main.go | 1 - .../internals/services/database/database.go | 4 +- .../services/scrapers/coursera_courses.go | 3 - .../internals/services/scrapers/toscrape.go | 5 +- csrf-with-session/README.md | 46 +++++----- csrf/README.md | 20 ++-- csrf/routes/mainServer.go | 13 +-- .../internal/city/domain.go | 1 + .../internal/city/handler.go | 1 + .../internal/infrastructure/fiber.go | 5 +- docker-nginx-loadbalancer/README.md | 3 +- docker-nginx-loadbalancer/main.go | 4 +- dummyjson/main.go | 92 +++++++++---------- ent-mysql/README.md | 14 ++- entgo-sveltekit/README.md | 19 ++-- entgo-sveltekit/template/README.md | 14 ++- file-server/README.md | 3 + firebase-auth/README.md | 1 + firebase-functions/README.md | 3 +- firebase-functions/cmd/main.go | 1 - firebase-functions/functions.go | 1 - firebase-functions/src/database/database.go | 1 - gcloud-firebase/README.md | 4 + gcloud-firebase/cmd/main.go | 1 - gcloud-firebase/functions.go | 1 - gcloud-firebase/main.go | 9 +- gcloud/README.md | 4 + gcloud/cmd/main.go | 1 - gcloud/functions.go | 1 - geoip-maxmind/README.md | 4 +- geoip-maxmind/handlers/handlers.go | 1 - geoip/README.md | 3 + gorm-mysql/README.md | 9 ++ gorm-mysql/database/database.go | 7 +- gorm-mysql/routes/routes.go | 13 +-- gorm-postgres/README.md | 4 + gorm-postgres/database/database.go | 1 - gorm/README.md | 7 ++ gorm/database/database.go | 4 +- gorm/main.go | 5 +- graceful-shutdown/main.go | 3 +- graphql/README.md | 4 + grpc/README.md | 6 +- grpc/client/main.go | 2 - hello-world/README.md | 3 + heroku/README.md | 7 ++ hexagonal/README.md | 10 ++ hexagonal/config/config.go | 3 +- hexagonal/main.go | 2 - hexagonal/repository/mongo.go | 11 +-- hexagonal/service/logic.go | 2 + https-pkcs12-tls/README.md | 3 + https-pkcs12-tls/main.go | 1 - https-tls/README.md | 3 + jwt/README.md | 5 + jwt/database/connect.go | 6 +- jwt/main.go | 3 +- jwt/middleware/auth.go | 4 +- k8s/README.md | 7 ++ memgraph/README.md | 5 +- memgraph/main.go | 29 +++--- minio/README.md | 2 + minio/multiple/main.go | 4 - minio/single/main.go | 4 - mongodb/README.md | 3 + mongodb/main.go | 15 ++- multiple-ports/README.md | 4 + mysql/README.md | 3 + neo4j/README.md | 3 + oauth2-google/README.md | 6 ++ oauth2-google/auth/auth.go | 12 ++- oauth2-google/handler/handler.go | 2 - oauth2-google/main.go | 1 - oauth2-google/router/router.go | 1 - oauth2/app.go | 8 +- oauth2/handlers/handlers.go | 2 +- oauth2/middleware/auth.go | 4 +- oauth2/router/router.go | 1 - optional-parameter/README.md | 4 + optional-parameter/main.go | 1 - overview.go | 4 +- parsley/cmd/main.go | 2 +- parsley/internal/application.go | 2 +- parsley/internal/modules/fiber_module.go | 1 - .../internal/modules/route_handlers_module.go | 1 - parsley/internal/route_handlers/greeter.go | 4 +- parsley/internal/services/greeter.go | 3 +- postgresql/README.md | 3 + prefork/README.md | 3 + recover/README.md | 3 + rss-feed/README.md | 3 + server-timing/README.md | 3 + sessions-sqlite3/README.md | 4 + sessions-sqlite3/main.go | 2 +- socketio/README.md | 5 + socketio/main.go | 11 +-- spa/README.md | 6 ++ sqlboiler/README.md | 48 ++++++++-- sqlboiler/api/controller/author_controller.go | 3 +- sqlboiler/api/controller/post_controller.go | 3 +- sqlboiler/main.go | 3 +- sqlc/README.md | 51 ++++++++-- sqlc/api/controller/author_controller.go | 5 +- sqlc/api/controller/post_controller.go | 5 +- sqlc/main.go | 3 +- sse/README.md | 4 + stream-request-body/README.md | 3 + svelte-netlify/README.md | 5 +- svelte-netlify/adapter/adapter.go | 1 - sveltekit-embed/README.md | 17 ++-- swagger/README.md | 4 + swagger/database/connection.go | 1 - swagger/routes/routes.go | 2 +- tableflip/README.md | 10 +- tableflip/main.go | 5 +- template-asset-bundling/README.md | 5 + template-asset-bundling/app.go | 6 +- template/README.md | 5 + template/main.go | 1 - todo-app-with-auth-gorm/README.md | 3 + .../app/services/auth.service.go | 1 + .../app/services/todo.service.go | 1 + .../config/database/database.go | 4 +- todo-app-with-auth-gorm/main.go | 1 + todo-app-with-auth-gorm/utils/jwt/jwt.go | 6 +- .../utils/middleware/authentication.go | 4 +- .../utils/password/password.go | 1 - todo-app-with-auth-gorm/utils/validator.go | 1 - unit-test/README.md | 4 + upload-file/README.md | 11 +++ upload-file/multiple/main.go | 1 - upload-file/single_relative_path/main.go | 2 +- url-shortener-api/README.md | 1 + url-shortener-api/api/database/database.go | 3 +- url-shortener-api/api/main.go | 2 +- url-shortener-api/api/routes/shorten.go | 2 +- validation/README.md | 5 + validation/main.go | 1 + vercel/README.md | 5 + vercel/api/index.go | 5 +- websocket-chat/README.md | 3 + websocket-chat/main.go | 12 ++- websocket/README.md | 3 + websocket/main.go | 2 +- 180 files changed, 692 insertions(+), 382 deletions(-) diff --git a/.github/CONTRIBUTING.md b/.github/CONTRIBUTING.md index 2156217b93..e8c27d5384 100644 --- a/.github/CONTRIBUTING.md +++ b/.github/CONTRIBUTING.md @@ -8,7 +8,8 @@ Thank you for considering contributing to this project! To ensure a smooth and e 2. **Add a `README.md`**: Each example must include a `README.md` file in its directory. This file should contain the following: - - **Docusaurus Metadata**: Add the following metadata at the top of the `README.md` file: +- **Docusaurus Metadata**: Add the following metadata at the top of the `README.md` file: + ```markdown --- title: Your Example Title @@ -16,16 +17,17 @@ Thank you for considering contributing to this project! To ensure a smooth and e --- ``` - - `title`: A short and descriptive title for your example. - - `keywords`: A list of relevant keywords (excluding "fiber"). + - `title`: A short and descriptive title for your example. + - `keywords`: A list of relevant keywords (excluding "fiber"). - - **Content**: The `README.md` should provide a detailed explanation of the example, including: - - The idea behind the example. - - The components used in the example. - - Instructions on how to run the example. - - Any other relevant information. +- **Content**: The `README.md` should provide a detailed explanation of the example, including: + - The idea behind the example. + - The components used in the example. + - Instructions on how to run the example. + - Any other relevant information. 3. **Update the Overview**: After adding your example, run the following command in the root directory to update the overview table of contents: + ```bash make generate ``` diff --git a/404-handler/README.md b/404-handler/README.md index 5a92c2b26b..0e122f9c02 100644 --- a/404-handler/README.md +++ b/404-handler/README.md @@ -21,6 +21,7 @@ In web applications, it's common to encounter requests to routes that do not exi ## Running the Example To run the example, use the following command: + ```bash go run main.go ``` diff --git a/air/README.md b/air/README.md index 431deb0f04..f120a0c797 100644 --- a/air/README.md +++ b/air/README.md @@ -22,17 +22,20 @@ Live reloading is a useful feature during development as it saves time by automa ## Setup 1. Clone the repository: + ```bash git clone https://github.com/gofiber/recipes.git cd recipes/air ``` 2. Install the dependencies: + ```bash go mod download ``` 3. Install Air: + ```bash go install github.com/cosmtrek/air@latest ``` @@ -47,10 +50,13 @@ Air is configured using the `air/.air.conf` file. This file specifies the build ## Running the Example To run the example with live reloading, use the following command: + ```bash air -c .air.linux.conf ``` + or for Windows: + ```bash air -c .air.windows.conf ``` diff --git a/auth-docker-postgres-jwt/README.md b/auth-docker-postgres-jwt/README.md index 1e66dcf3a8..4d4a14f66b 100644 --- a/auth-docker-postgres-jwt/README.md +++ b/auth-docker-postgres-jwt/README.md @@ -22,12 +22,14 @@ This project provides a starting point for building a web application with user ## Setup 1. Clone the repository: + ```bash git clone https://github.com/gofiber/recipes.git cd recipes/auth-docker-postgres-jwt ``` 2. Set the environment variables in a `.env` file: + ```env DB_PORT=5432 DB_USER=example_user @@ -37,6 +39,7 @@ This project provides a starting point for building a web application with user ``` 3. Build and start the Docker containers: + ```bash docker-compose build docker-compose up @@ -47,6 +50,7 @@ The API and the database should now be running. ## Database Management You can manage the database via `psql` with the following command: + ```bash docker-compose exec db psql -U ``` @@ -66,16 +70,19 @@ The following endpoints are available in the API: ## Example Usage 1. Register a new user: + ```bash curl -X POST http://localhost:3000/api/auth/register -d '{"username":"testuser", "password":"testpassword"}' -H "Content-Type: application/json" ``` 2. Login to get a JWT: + ```bash curl -X POST http://localhost:3000/api/auth/login -d '{"username":"testuser", "password":"testpassword"}' -H "Content-Type: application/json" ``` 3. Access a protected route: + ```bash curl -H "Authorization: Bearer " http://localhost:3000/api/user/1 ``` diff --git a/auth-docker-postgres-jwt/cmd/main.go b/auth-docker-postgres-jwt/cmd/main.go index 4e8edde022..8d25bebf41 100644 --- a/auth-docker-postgres-jwt/cmd/main.go +++ b/auth-docker-postgres-jwt/cmd/main.go @@ -1,9 +1,10 @@ package main import ( + "log" + "app/database" "app/router" - "log" "github.com/gofiber/fiber/v2" // "github.com/gofiber/fiber/v2/middleware/cors" diff --git a/auth-docker-postgres-jwt/database/connect.go b/auth-docker-postgres-jwt/database/connect.go index 9ee10f387b..8ee16c63dd 100644 --- a/auth-docker-postgres-jwt/database/connect.go +++ b/auth-docker-postgres-jwt/database/connect.go @@ -1,11 +1,12 @@ package database import ( - "app/config" - "app/model" "fmt" "strconv" + "app/config" + "app/model" + "gorm.io/driver/postgres" "gorm.io/gorm" ) @@ -15,7 +16,6 @@ func ConnectDB() { var err error p := config.Config("DB_PORT") port, err := strconv.ParseUint(p, 10, 32) - if err != nil { panic("failed to parse database port") } @@ -28,7 +28,6 @@ func ConnectDB() { config.Config("DB_NAME"), ) DB, err = gorm.Open(postgres.Open(dsn), &gorm.Config{}) - if err != nil { panic("failed to connect database") } diff --git a/auth-docker-postgres-jwt/handler/auth.go b/auth-docker-postgres-jwt/handler/auth.go index 26b044336e..37848c371a 100644 --- a/auth-docker-postgres-jwt/handler/auth.go +++ b/auth-docker-postgres-jwt/handler/auth.go @@ -1,14 +1,15 @@ package handler import ( - "app/config" - "app/database" - "app/model" "errors" "log" "net/mail" "time" + "app/config" + "app/database" + "app/model" + "gorm.io/gorm" "github.com/gofiber/fiber/v2" @@ -80,7 +81,7 @@ func Login(c *fiber.Ctx) error { } else { userModel, err = getUserByUsername(identity) } - + if err != nil { return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{"status": "error", "message": "Internal Server Error", "data": err}) } else if userModel == nil { diff --git a/auth-docker-postgres-jwt/handler/product.go b/auth-docker-postgres-jwt/handler/product.go index 639d8fdb1c..a8f06e8ff2 100644 --- a/auth-docker-postgres-jwt/handler/product.go +++ b/auth-docker-postgres-jwt/handler/product.go @@ -23,7 +23,6 @@ func GetProduct(c *fiber.Ctx) error { db.Find(&product, id) if product.Title == "" { return c.Status(404).JSON(fiber.Map{"status": "error", "message": "No product found with ID", "data": nil}) - } return c.JSON(fiber.Map{"status": "success", "message": "Product found", "data": product}) } @@ -48,7 +47,6 @@ func DeleteProduct(c *fiber.Ctx) error { db.First(&product, id) if product.Title == "" { return c.Status(404).JSON(fiber.Map{"status": "error", "message": "No product found with ID", "data": nil}) - } db.Delete(&product) return c.JSON(fiber.Map{"status": "success", "message": "Product successfully deleted", "data": nil}) diff --git a/auth-docker-postgres-jwt/handler/user.go b/auth-docker-postgres-jwt/handler/user.go index c66a85c839..a3746d3285 100644 --- a/auth-docker-postgres-jwt/handler/user.go +++ b/auth-docker-postgres-jwt/handler/user.go @@ -1,9 +1,10 @@ package handler import ( + "strconv" + "app/database" "app/model" - "strconv" "github.com/go-playground/validator/v10" "github.com/gofiber/fiber/v2" @@ -129,12 +130,10 @@ func DeleteUser(c *fiber.Ctx) error { if !validToken(token, id) { return c.Status(500).JSON(fiber.Map{"status": "error", "message": "Invalid token id", "data": nil}) - } if !validUser(id, pi.Password) { return c.Status(500).JSON(fiber.Map{"status": "error", "message": "Not valid user", "data": nil}) - } db := database.DB diff --git a/auth-jwt/README.md b/auth-jwt/README.md index 4335e100a7..18820889b6 100644 --- a/auth-jwt/README.md +++ b/auth-jwt/README.md @@ -21,12 +21,14 @@ This project provides a starting point for building a web application with user ## Setup 1. Clone the repository: + ```bash git clone https://github.com/gofiber/recipes.git cd recipes/auth-jwt ``` 2. Set the environment variables in a `.env` file: + ```env DB_PORT=5432 DB_USER=example_user @@ -36,11 +38,13 @@ This project provides a starting point for building a web application with user ``` 3. Install the dependencies: + ```bash go mod download ``` 4. Run the application: + ```bash go run main.go ``` @@ -50,6 +54,7 @@ The API should now be running on `http://localhost:3000`. ## Database Management You can manage the database via `psql` with the following command: + ```bash psql -U -d -h localhost -p ``` @@ -74,16 +79,19 @@ The following endpoints are available in the API: ## Example Usage 1. Register a new user: + ```bash curl -X POST http://localhost:3000/api/auth/register -d '{"username":"testuser", "password":"testpassword", "email":"test@example.com"}' -H "Content-Type: application/json" ``` 2. Login to get a JWT: + ```bash curl -X POST http://localhost:3000/api/auth/login -d '{"username":"testuser", "password":"testpassword"}' -H "Content-Type: application/json" ``` 3. Access a protected route: + ```bash curl -H "Authorization: Bearer " http://localhost:3000/api/user/1 ``` diff --git a/auth-jwt/database/connect.go b/auth-jwt/database/connect.go index c0fc86e0b9..3584ebf14a 100644 --- a/auth-jwt/database/connect.go +++ b/auth-jwt/database/connect.go @@ -1,12 +1,14 @@ package database import ( + "fmt" + "strconv" + "api-fiber-gorm/config" "api-fiber-gorm/model" - "fmt" + "gorm.io/driver/postgres" "gorm.io/gorm" - "strconv" ) // ConnectDB connect to db @@ -14,14 +16,12 @@ func ConnectDB() { var err error p := config.Config("DB_PORT") port, err := strconv.ParseUint(p, 10, 32) - if err != nil { panic("failed to parse database port") } dsn := fmt.Sprintf("host=%s port=%d user=%s password=%s dbname=%s sslmode=disable", config.Config("DB_HOST"), port, config.Config("DB_USER"), config.Config("DB_PASSWORD"), config.Config("DB_NAME")) DB, err = gorm.Open(postgres.Open(dsn), &gorm.Config{}) - if err != nil { panic("failed to connect database") } diff --git a/auth-jwt/handler/product.go b/auth-jwt/handler/product.go index e1b372e764..e3316dcd86 100644 --- a/auth-jwt/handler/product.go +++ b/auth-jwt/handler/product.go @@ -23,7 +23,6 @@ func GetProduct(c *fiber.Ctx) error { db.Find(&product, id) if product.Title == "" { return c.Status(404).JSON(fiber.Map{"status": "error", "message": "No product found with ID", "data": nil}) - } return c.JSON(fiber.Map{"status": "success", "message": "Product found", "data": product}) } @@ -48,7 +47,6 @@ func DeleteProduct(c *fiber.Ctx) error { db.First(&product, id) if product.Title == "" { return c.Status(404).JSON(fiber.Map{"status": "error", "message": "No product found with ID", "data": nil}) - } db.Delete(&product) return c.JSON(fiber.Map{"status": "success", "message": "Product successfully deleted", "data": nil}) diff --git a/auth-jwt/handler/user.go b/auth-jwt/handler/user.go index 440c411716..feb04fa625 100644 --- a/auth-jwt/handler/user.go +++ b/auth-jwt/handler/user.go @@ -64,13 +64,11 @@ func CreateUser(c *fiber.Ctx) error { user := new(model.User) if err := c.BodyParser(user); err != nil { return c.Status(500).JSON(fiber.Map{"status": "error", "message": "Review your input", "data": err}) - } hash, err := hashPassword(user.Password) if err != nil { return c.Status(500).JSON(fiber.Map{"status": "error", "message": "Couldn't hash password", "data": err}) - } user.Password = hash @@ -126,12 +124,10 @@ func DeleteUser(c *fiber.Ctx) error { if !validToken(token, id) { return c.Status(500).JSON(fiber.Map{"status": "error", "message": "Invalid token id", "data": nil}) - } if !validUser(id, pi.Password) { return c.Status(500).JSON(fiber.Map{"status": "error", "message": "Not valid user", "data": nil}) - } db := database.DB diff --git a/auth-jwt/main.go b/auth-jwt/main.go index f74fcea119..e840abfce2 100644 --- a/auth-jwt/main.go +++ b/auth-jwt/main.go @@ -1,9 +1,10 @@ package main import ( + "log" + "api-fiber-gorm/database" "api-fiber-gorm/router" - "log" "github.com/gofiber/fiber/v2" "github.com/gofiber/fiber/v2/middleware/cors" diff --git a/auth-jwt/middleware/auth.go b/auth-jwt/middleware/auth.go index a61ecb52e9..73ed530ae5 100644 --- a/auth-jwt/middleware/auth.go +++ b/auth-jwt/middleware/auth.go @@ -3,14 +3,14 @@ package middleware import ( "api-fiber-gorm/config" - "github.com/gofiber/fiber/v2" jwtware "github.com/gofiber/contrib/jwt" + "github.com/gofiber/fiber/v2" ) // Protected protect routes func Protected() fiber.Handler { return jwtware.New(jwtware.Config{ - SigningKey: jwtware.SigningKey{Key: []byte(config.Config("SECRET"))}, + SigningKey: jwtware.SigningKey{Key: []byte(config.Config("SECRET"))}, ErrorHandler: jwtError, }) } diff --git a/autocert/README.md b/autocert/README.md index 9c04b9b946..02e16750ed 100644 --- a/autocert/README.md +++ b/autocert/README.md @@ -21,17 +21,20 @@ This project provides a starting point for building a secure web application wit ## Setup 1. Clone the repository: + ```bash git clone https://github.com/gofiber/recipes.git cd recipes/autocert ``` 2. Install the dependencies: + ```bash go mod download ``` 3. Update the `HostPolicy` in `main.go` with your domain: + ```go m := &autocert.Manager{ Prompt: autocert.AcceptTOS, @@ -41,6 +44,7 @@ This project provides a starting point for building a secure web application wit ``` 4. Run the application: + ```bash go run main.go ``` diff --git a/aws-eb/README.md b/aws-eb/README.md index 0f66990d4f..eb8f0ed113 100644 --- a/aws-eb/README.md +++ b/aws-eb/README.md @@ -23,22 +23,26 @@ This project provides a starting point for deploying a Go Fiber application to A ## Setup 1. Clone the repository: + ```bash git clone https://github.com/gofiber/recipes.git cd recipes/aws-eb ``` 2. Initialize Elastic Beanstalk: + ```bash eb init ``` 3. Create an Elastic Beanstalk environment: + ```bash eb create ``` 4. Deploy the application: + ```bash eb deploy ``` @@ -48,11 +52,13 @@ This project provides a starting point for deploying a Go Fiber application to A The build process is defined in the `Buildfile` and `build.sh` scripts. - `Buildfile`: + ```ruby make: ./build.sh ``` - `build.sh`: + ```bash #!/bin/bash -xe # Get dependencies @@ -68,6 +74,7 @@ The build process is defined in the `Buildfile` and `build.sh` scripts. ## Application Code The main application code is in `application.go`: + ```go package main @@ -100,6 +107,7 @@ func main() { ## .gitignore The `.gitignore` file includes configurations to ignore Elastic Beanstalk specific files: + ```plaintext # Elastic Beanstalk Files .elasticbeanstalk/* diff --git a/aws-sam-container/README.md b/aws-sam-container/README.md index c79ff82cb0..2c10bd9a92 100644 --- a/aws-sam-container/README.md +++ b/aws-sam-container/README.md @@ -26,12 +26,13 @@ This is a sample template for app - Below is a brief explanation of what we have ## Requirements -* AWS CLI already configured with Administrator permission -* [Docker installed](https://www.docker.com/community-edition) -* SAM CLI - [Install the SAM CLI](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-sam-cli-install.html) +- AWS CLI already configured with Administrator permission +- [Docker installed](https://www.docker.com/community-edition) +- SAM CLI - [Install the SAM CLI](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-sam-cli-install.html) You may need the following for local testing. -* [Golang](https://golang.org) + +- [Golang](https://golang.org) ## Setup process @@ -59,11 +60,11 @@ sam deploy --guided The command will package and deploy your application to AWS, with a series of prompts: -* **Stack Name**: The name of the stack to deploy to CloudFormation. This should be unique to your account and region, and a good starting point would be something matching your project name. -* **AWS Region**: The AWS region you want to deploy your app to. -* **Confirm changes before deploy**: If set to yes, any change sets will be shown to you before execution for manual review. If set to no, the AWS SAM CLI will automatically deploy application changes. -* **Allow SAM CLI IAM role creation**: Many AWS SAM templates, including this example, create AWS IAM roles required for the AWS Lambda function(s) included to access AWS services. By default, these are scoped down to minimum required permissions. To deploy an AWS CloudFormation stack which creates or modifies IAM roles, the `CAPABILITY_IAM` value for `capabilities` must be provided. If permission isn't provided through this prompt, to deploy this example you must explicitly pass `--capabilities CAPABILITY_IAM` to the `sam deploy` command. -* **Save arguments to samconfig.toml**: If set to yes, your choices will be saved to a configuration file inside the project, so that in the future you can just re-run `sam deploy` without parameters to deploy changes to your application. +- **Stack Name**: The name of the stack to deploy to CloudFormation. This should be unique to your account and region, and a good starting point would be something matching your project name. +- **AWS Region**: The AWS region you want to deploy your app to. +- **Confirm changes before deploy**: If set to yes, any change sets will be shown to you before execution for manual review. If set to no, the AWS SAM CLI will automatically deploy application changes. +- **Allow SAM CLI IAM role creation**: Many AWS SAM templates, including this example, create AWS IAM roles required for the AWS Lambda function(s) included to access AWS services. By default, these are scoped down to minimum required permissions. To deploy an AWS CloudFormation stack which creates or modifies IAM roles, the `CAPABILITY_IAM` value for `capabilities` must be provided. If permission isn't provided through this prompt, to deploy this example you must explicitly pass `--capabilities CAPABILITY_IAM` to the `sam deploy` command. +- **Save arguments to samconfig.toml**: If set to yes, your choices will be saved to a configuration file inside the project, so that in the future you can just re-run `sam deploy` without parameters to deploy changes to your application. You can find your API Gateway Endpoint URL in the output values displayed after deployment. @@ -96,7 +97,7 @@ This command grants permission to all principals (*) to invoke your Lambda funct ### Golang installation -Please ensure Go 1.x (where 'x' is the latest version) is installed as per the instructions on the official golang website: https://golang.org/doc/install +Please ensure Go 1.x (where 'x' is the latest version) is installed as per the instructions on the official golang website: A quickstart way would be to use Homebrew, chocolatey or your linux package manager. diff --git a/aws-sam-container/app/main.go b/aws-sam-container/app/main.go index f1ab7977c5..95f914c70a 100644 --- a/aws-sam-container/app/main.go +++ b/aws-sam-container/app/main.go @@ -1,8 +1,9 @@ package main import ( - "github.com/gofiber/fiber/v2" "log" + + "github.com/gofiber/fiber/v2" ) func main() { diff --git a/aws-sam/README.md b/aws-sam/README.md index da028de1ae..b954bcef5f 100644 --- a/aws-sam/README.md +++ b/aws-sam/README.md @@ -46,9 +46,6 @@ curl -XPOST "http://localhost:3001/2015-03-31/functions/sam-app/invocations" {"statusCode":200,"headers":null,"multiValueHeaders":{"Content-Type":["application/json"]},"body":"{\"message\":\"Hello World\"}"}% ``` - - - ## Packaging and deployment AWS Lambda Golang runtime requires a flat folder with the executable generated on build step. SAM will use `CodeUri` property to know where to look up for the application: @@ -78,7 +75,6 @@ The command will package and deploy your application to AWS, with a series of pr You can find your API Gateway Endpoint URL in the output values displayed after deployment. - ## Add Permission to the Lambda Function for Public Access After deploying your Lambda function with an associated function URL, you might encounter a scenario where the function URL is not accessible due to missing permissions for public access. This is common when the authentication type for the function URL is set to "None," indicating that the function is intended to be publicly accessible without authentication. @@ -108,7 +104,7 @@ This command grants permission to all principals (*) to invoke your Lambda funct ### Golang installation -Please ensure Go 1.x (where 'x' is the latest version) is installed as per the instructions on the official golang website: https://golang.org/doc/install +Please ensure Go 1.x (where 'x' is the latest version) is installed as per the instructions on the official golang website: A quickstart way would be to use Homebrew, chocolatey or your linux package manager. diff --git a/aws-sam/app/main.go b/aws-sam/app/main.go index ec3dbb506c..0f9637ab21 100644 --- a/aws-sam/app/main.go +++ b/aws-sam/app/main.go @@ -2,9 +2,10 @@ package main import ( "context" - "github.com/gofiber/fiber/v2" "log" + "github.com/gofiber/fiber/v2" + "github.com/aws/aws-lambda-go/events" "github.com/aws/aws-lambda-go/lambda" fiberAdapter "github.com/awslabs/aws-lambda-go-api-proxy/fiber" diff --git a/bootstrap/README.md b/bootstrap/README.md index 921341e3f6..c3b8d584e4 100644 --- a/bootstrap/README.md +++ b/bootstrap/README.md @@ -10,6 +10,7 @@ keywords: [bootstrap, gorm, validator, env] Fiber bootstrap for rapid development using Go-Fiber / Gorm / Validator. # Components + * Fiber * Html Engine Template * Logger @@ -20,12 +21,14 @@ Fiber bootstrap for rapid development using Go-Fiber / Gorm / Validator. * Env File # Router + API Router `/api` with rate limiter middleware Http Router `/` with CORS and CSRF middleware # Setup 1. Copy the example env file over: + ``` cp .env.example .env ``` @@ -33,7 +36,9 @@ Http Router `/` with CORS and CSRF middleware 2. Modify the env file you just copied `.env` with the correct credentials for your database. Make sure the database you entered in `DB_NAME` has been created. 3. Run the API: + ``` go run main.go ``` + Your api should be running at `http://localhost:4000/` if the port is in use you may modify it in the `.env` you just created. diff --git a/bootstrap/app/controllers/main_controller.go b/bootstrap/app/controllers/main_controller.go index f2cad9690e..f9643f38ae 100644 --- a/bootstrap/app/controllers/main_controller.go +++ b/bootstrap/app/controllers/main_controller.go @@ -3,7 +3,6 @@ package controllers import "github.com/gofiber/fiber/v2" func RenderHello(c *fiber.Ctx) error { - return c.Render("index", fiber.Map{ "FiberTitle": "Hello From Fiber Html Engine", }) diff --git a/bootstrap/main.go b/bootstrap/main.go index e51b1d7c54..e1ea8da950 100644 --- a/bootstrap/main.go +++ b/bootstrap/main.go @@ -2,9 +2,10 @@ package main import ( "fmt" + "log" + "github.com/kooroshh/fiber-boostrap/bootstrap" "github.com/kooroshh/fiber-boostrap/pkg/env" - "log" ) func main() { diff --git a/bootstrap/pkg/database/setup.go b/bootstrap/pkg/database/setup.go index 337d1e5211..55ecf2bc6e 100644 --- a/bootstrap/pkg/database/setup.go +++ b/bootstrap/pkg/database/setup.go @@ -2,6 +2,7 @@ package database import ( "fmt" + "github.com/kooroshh/fiber-boostrap/app/models" "github.com/kooroshh/fiber-boostrap/pkg/env" "gorm.io/gorm" diff --git a/bootstrap/pkg/env/env.go b/bootstrap/pkg/env/env.go index c637711809..d761fda425 100644 --- a/bootstrap/pkg/env/env.go +++ b/bootstrap/pkg/env/env.go @@ -18,5 +18,4 @@ func SetupEnvFile() { if err != nil { panic(err) } - } diff --git a/bootstrap/pkg/router/api_router.go b/bootstrap/pkg/router/api_router.go index 4351683248..5047ab5615 100644 --- a/bootstrap/pkg/router/api_router.go +++ b/bootstrap/pkg/router/api_router.go @@ -5,8 +5,7 @@ import ( "github.com/gofiber/fiber/v2/middleware/limiter" ) -type ApiRouter struct { -} +type ApiRouter struct{} func (h ApiRouter) InstallRouter(app *fiber.App) { api := app.Group("/api", limiter.New()) diff --git a/bootstrap/pkg/router/http_router.go b/bootstrap/pkg/router/http_router.go index 756a39ed1d..3e31269d5c 100644 --- a/bootstrap/pkg/router/http_router.go +++ b/bootstrap/pkg/router/http_router.go @@ -7,8 +7,7 @@ import ( "github.com/kooroshh/fiber-boostrap/app/controllers" ) -type HttpRouter struct { -} +type HttpRouter struct{} func (h HttpRouter) InstallRouter(app *fiber.App) { group := app.Group("", cors.New(), csrf.New()) diff --git a/bootstrap/pkg/router/setup.go b/bootstrap/pkg/router/setup.go index 05815ea43c..a8971cc449 100644 --- a/bootstrap/pkg/router/setup.go +++ b/bootstrap/pkg/router/setup.go @@ -7,6 +7,7 @@ import ( func InstallRouter(app *fiber.App) { setup(app, NewApiRouter(), NewHttpRouter()) } + func setup(app *fiber.App, router ...Router) { for _, r := range router { r.InstallRouter(app) diff --git a/clean-architecture/README.md b/clean-architecture/README.md index d0c6762db5..50518d1080 100644 --- a/clean-architecture/README.md +++ b/clean-architecture/README.md @@ -28,23 +28,27 @@ This project provides a starting point for building a web application with a cle ## Setup 1. Clone the repository: + ```bash git clone https://github.com/gofiber/recipes.git cd recipes/clean-architecture ``` 2. Set the environment variables in a `.env` file: + ```env DB_URI=mongodb://localhost:27017 DB_NAME=example_db ``` 3. Install the dependencies: + ```bash go mod download ``` 4. Run the application: + ```bash go run cmd/main.go ``` @@ -63,21 +67,25 @@ The following endpoints are available in the API: ## Example Usage 1. Add a new book: + ```bash curl -X POST http://localhost:3000/books -d '{"title":"Book Title", "author":"Author Name"}' -H "Content-Type: application/json" ``` 2. List all books: + ```bash curl http://localhost:3000/books ``` 3. Update a book: + ```bash curl -X PUT http://localhost:3000/books -d '{"id":"", "title":"Updated Title", "author":"Updated Author"}' -H "Content-Type: application/json" ``` 4. Remove a book: + ```bash curl -X DELETE http://localhost:3000/books -d '{"id":""}' -H "Content-Type: application/json" ``` @@ -91,20 +99,24 @@ Clean Architecture is a software design philosophy that emphasizes the separatio ### Layers in Clean Architecture 1. **Entities (Core Business Logic)** - - Located in the `pkg/entities` directory. - - Contains the core business logic and domain models, which are independent of any external frameworks or technologies. + +- Located in the `pkg/entities` directory. +- Contains the core business logic and domain models, which are independent of any external frameworks or technologies. 2. **Use Cases (Application Logic)** - - Located in the `pkg/book` directory. - - Contains the application-specific business rules and use cases. This layer orchestrates the flow of data to and from the entities. + +- Located in the `pkg/book` directory. +- Contains the application-specific business rules and use cases. This layer orchestrates the flow of data to and from the entities. 3. **Interface Adapters (Adapters and Presenters)** - - Located in the `api` directory. - - Contains the HTTP handlers, routes, and presenters. This layer is responsible for converting data from the use cases into a format suitable for the web framework (Fiber in this case). + +- Located in the `api` directory. +- Contains the HTTP handlers, routes, and presenters. This layer is responsible for converting data from the use cases into a format suitable for the web framework (Fiber in this case). 4. **Frameworks and Drivers (External Interfaces)** - - Located in the `cmd` directory. - - Contains the main application entry point and any external dependencies like the web server setup. + +- Located in the `cmd` directory. +- Contains the main application entry point and any external dependencies like the web server setup. ### Example Breakdown @@ -116,6 +128,7 @@ Clean Architecture is a software design philosophy that emphasizes the separatio ### Code Example #### `entities/book.go` + ```go package entities @@ -129,6 +142,7 @@ type Book struct { ``` #### `pkg/book/service.go` + ```go package book @@ -143,6 +157,7 @@ type Service interface { ``` #### `api/handlers/book_handler.go` + ```go package handlers @@ -178,6 +193,7 @@ func AddBook(service book.Service) fiber.Handler { ``` #### `cmd/main.go` + ```go package main diff --git a/clean-architecture/api/handlers/book_handler.go b/clean-architecture/api/handlers/book_handler.go index ad0a3684ee..b350441f58 100644 --- a/clean-architecture/api/handlers/book_handler.go +++ b/clean-architecture/api/handlers/book_handler.go @@ -1,12 +1,13 @@ package handlers import ( + "net/http" + "clean-architecture/api/presenter" "clean-architecture/pkg/book" "clean-architecture/pkg/entities" "github.com/gofiber/fiber/v2" "github.com/pkg/errors" - "net/http" ) // AddBook is handler/controller which creates Books in the BookShop diff --git a/clean-architecture/main.go b/clean-architecture/main.go index c3d2d41b59..70647529db 100644 --- a/clean-architecture/main.go +++ b/clean-architecture/main.go @@ -1,13 +1,14 @@ package main import ( - "clean-architecture/api/routes" - "clean-architecture/pkg/book" "context" "fmt" "log" "time" + "clean-architecture/api/routes" + "clean-architecture/pkg/book" + "github.com/gofiber/fiber/v2" "github.com/gofiber/fiber/v2/middleware/cors" "go.mongodb.org/mongo-driver/mongo" diff --git a/clean-architecture/pkg/book/repository.go b/clean-architecture/pkg/book/repository.go index 99f68fc18c..4794517d16 100644 --- a/clean-architecture/pkg/book/repository.go +++ b/clean-architecture/pkg/book/repository.go @@ -1,13 +1,15 @@ package book import ( + "context" + "time" + "clean-architecture/api/presenter" "clean-architecture/pkg/entities" - "context" + "go.mongodb.org/mongo-driver/bson" "go.mongodb.org/mongo-driver/bson/primitive" "go.mongodb.org/mongo-driver/mongo" - "time" ) // Repository interface allows us to access the CRUD Operations in mongo here. diff --git a/clean-architecture/pkg/entities/book.go b/clean-architecture/pkg/entities/book.go index 0877342977..a87b3e709e 100644 --- a/clean-architecture/pkg/entities/book.go +++ b/clean-architecture/pkg/entities/book.go @@ -1,8 +1,9 @@ package entities import ( - "go.mongodb.org/mongo-driver/bson/primitive" "time" + + "go.mongodb.org/mongo-driver/bson/primitive" ) // Book Constructs your Book model under entities. diff --git a/cloud-run/README.md b/cloud-run/README.md index 930a4c3ba3..10262c1711 100644 --- a/cloud-run/README.md +++ b/cloud-run/README.md @@ -23,22 +23,26 @@ This project provides a starting point for deploying a Go Fiber application to G ## Setup 1. Clone the repository: + ```bash git clone https://github.com/gofiber/recipes.git cd recipes/cloud-run ``` 2. Install the dependencies: + ```bash go mod download ``` 3. Build the Docker image: + ```bash docker build -t cloud-run-example . ``` 4. Run the Docker container: + ```bash docker run -p 3000:3000 cloud-run-example ``` @@ -48,17 +52,20 @@ The application should now be running on `http://localhost:3000`. ## Deploy to Google Cloud Run 1. Set up Google Cloud SDK and authenticate: + ```bash gcloud auth login gcloud config set project [YOUR_PROJECT_ID] ``` 2. Build and push the Docker image using Google Cloud Build: + ```bash gcloud builds submit --tag gcr.io/[YOUR_PROJECT_ID]/cloud-run-example ``` 3. Deploy the image to Cloud Run: + ```bash gcloud run deploy cloud-run-example --image gcr.io/[YOUR_PROJECT_ID]/cloud-run-example --platform managed --region [YOUR_REGION] --allow-unauthenticated ``` diff --git a/colly-gorm/README.md b/colly-gorm/README.md index ee4b00486b..2b103d7ecc 100644 --- a/colly-gorm/README.md +++ b/colly-gorm/README.md @@ -17,7 +17,6 @@ This is a basic Go application using the Fiber framework to create scraping task 4. Visit `http://127.0.0.1:3000/api/healthchecker` in a web browser or use a tool like `curl` to test it. 5. Send `GET` request to `http://127.0.0.1:3000/scrape/coursera` to start scraping Coursera courses. And `http://127.0.0.1:3000/scrape/quotes` to scrape `quotes.toscrape.com`. - ## What It Does - Scrapes data from websites and stores in PostgreSQL database. diff --git a/colly-gorm/app/cmd/api/main.go b/colly-gorm/app/cmd/api/main.go index 1c3ff79958..5d01c45f6a 100644 --- a/colly-gorm/app/cmd/api/main.go +++ b/colly-gorm/app/cmd/api/main.go @@ -13,7 +13,6 @@ import ( ) func main() { - config, err := consts.LoadConfig(".") if err != nil { log.Fatalln("Failed to load environment variables!\n", err.Error()) diff --git a/colly-gorm/app/internals/services/database/database.go b/colly-gorm/app/internals/services/database/database.go index 2127ff5cc4..c69afc3419 100644 --- a/colly-gorm/app/internals/services/database/database.go +++ b/colly-gorm/app/internals/services/database/database.go @@ -1,10 +1,11 @@ package database import ( - "fiber-colly-gorm/internals/consts" "fmt" "log" + "fiber-colly-gorm/internals/consts" + "gorm.io/driver/postgres" "gorm.io/gorm" "gorm.io/gorm/logger" @@ -22,7 +23,6 @@ func ConnectDb(config *consts.Config) { db, err := gorm.Open(postgres.Open(dsn), &gorm.Config{ Logger: logger.Default.LogMode(logger.Info), }) - if err != nil { log.Fatal("Failed to connect to database. \n", err) } diff --git a/colly-gorm/app/internals/services/scrapers/coursera_courses.go b/colly-gorm/app/internals/services/scrapers/coursera_courses.go index 3cb40db69f..5d41539047 100644 --- a/colly-gorm/app/internals/services/scrapers/coursera_courses.go +++ b/colly-gorm/app/internals/services/scrapers/coursera_courses.go @@ -12,7 +12,6 @@ import ( // CourseraCourses is based on Colly's official examples: // https://github.com/gocolly/colly/blob/master/_examples/coursera_courses/coursera_courses.go func CourseraCourses() { - c := colly.NewCollector( colly.AllowedDomains("coursera.org", "www.coursera.org"), @@ -24,7 +23,6 @@ func CourseraCourses() { detailCollector := c.Clone() c.OnHTML("a[href]", func(e *colly.HTMLElement) { - if e.Attr("class") == "Button_1qxkboh-o_O-primary_cv02ee-o_O-md_28awn8-o_O-primaryLink_109aggg" { return } @@ -77,5 +75,4 @@ func CourseraCourses() { if err != nil { return } - } diff --git a/colly-gorm/app/internals/services/scrapers/toscrape.go b/colly-gorm/app/internals/services/scrapers/toscrape.go index a0fe270afd..72bd4b7645 100644 --- a/colly-gorm/app/internals/services/scrapers/toscrape.go +++ b/colly-gorm/app/internals/services/scrapers/toscrape.go @@ -1,9 +1,10 @@ package scrapers import ( - "fiber-colly-gorm/internals/services/database" "log" + "fiber-colly-gorm/internals/services/database" + "github.com/gocolly/colly" ) @@ -24,7 +25,6 @@ func Quotes() { }) c.OnHTML("div.quote", func(e *colly.HTMLElement) { - newQuote := database.Quote{} newQuote.Text = e.ChildText("span.text") @@ -41,5 +41,4 @@ func Quotes() { }) c.Visit("https://quotes.toscrape.com/") - } diff --git a/csrf-with-session/README.md b/csrf-with-session/README.md index 15e80eec08..87d0d85099 100644 --- a/csrf-with-session/README.md +++ b/csrf-with-session/README.md @@ -14,37 +14,41 @@ This example impliments multiple best-practices for CSRF protection: - CSRF Tokens are linked to the user's session. - Pre-sessions are used, so that CSRF tokens are always available, even for anonymous users (eg for login forms). - Cookies are set with a defense-in-depth approach: - - Secure: true - - HttpOnly: true - - SameSite: Lax - - Expiration: 30 minutes (of inactivity) - - Cookie names are prefixed with "__Host-" (see [MDN-Set-Cookie](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie) for more information)) + - Secure: true + - HttpOnly: true + - SameSite: Lax + - Expiration: 30 minutes (of inactivity) + - Cookie names are prefixed with "__Host-" (see [MDN-Set-Cookie](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie) for more information)) ## Requirements -* [git](https://git-scm.com/downloads) -* [Golang](https://golang.org/) - +- [git](https://git-scm.com/downloads) +- [Golang](https://golang.org/) ## Install Go Modules Like any golang project, you will need to download and install the required modules for the project to run. Change into the "csrf-with-session" directory: + ```bash cd csrf-with-session ``` And then: + ```bash go mod vendor && go mod download && go mod tidy ``` + This command installs the golang dependencies needed to run the project in a new directory named `vendor`. Once the modules have finished installing, you can run the project like this: + ```bash go run main.go ``` You should see the following if everything is OK: + ``` Server started and listening at 127.0.0.1:8443 ``` @@ -52,13 +56,14 @@ Server started and listening at 127.0.0.1:8443 ## Try the demo Start the server by running: + ```bash go run main.go ``` -Open your browser to and navigate to [127.0.0.1:8443](http://127.0.0.1:8443). +Open your browser to and navigate to [127.0.0.1:8443](http://127.0.0.1:8443). -### Accept the self-signed certificate warning and visit the site. +### Accept the self-signed certificate warning and visit the site In Chrome: @@ -75,29 +80,26 @@ In Safari: - Click on "Show Details" - Click on "visit this website" - ### Try to access the /protected page Login using one of the test accounts: -* Username: `user1` -* Password: `password1` + +- Username: `user1` +- Password: `password1` OR -* Username: `user2` -* Password: `password2` +- Username: `user2` +- Password: `password2` Once logged in, you will be able to see the /protected page. - ### Submit the form on the /protected page Once logged in, you will be able to see the /protected page. The /protected page contains a form that submits to the /protected page. If you try to submit the form without a valid CSRF token, you will get a 403 Forbidden error. - ## CSRF Protection All methods except GET, HEAD, OPTIONS, and TRACE are checked for the CSRF token. If the token is not present or does not match the token in the session, the request is aborted with a 403 Forbidden error. - ## Token Lifecycle The CSRF token is generated when the user visits any page on the site. The token is stored in the session and is valid for until it expires, or the authorization scope changes (e.g. the user logs in, or logs out). @@ -106,20 +108,18 @@ It is important that CSRF tokens do not persist beyond the scope of the user's s The CSRF middleware has a `SingleUseToken` configuration option that can be used to generate a new token for each request. This is useful for some applications, but is not used in this example. Single use tokens have usability implications in scenarios where the user has multiple tabs open, or when the user uses the back button in their browser. - ## Session Storage Sessions are stored in memory for this example, but you can use any session store you like. See the [Fiber session documentation](https://docs.gofiber.io/api/middleware/session) for more information. - ### Note on pre-sessions GoFiber's CSRF middleware will automatically create a session if one does not exist. That means that we always have pre-sessions when using the CSRF middleware. In this example we set a session variable `loggedIn` to `true` when the user logs in, in order to distinguish between logged in and logged out users. - ## Going further Here are some useful links where you can learn more about this topic: -* https://en.wikipedia.org/wiki/Cross-site_request_forgery -* https://www.owasp.org/index.php/Cross-Site_Request_Forgery_(CSRF) + +- +- diff --git a/csrf/README.md b/csrf/README.md index a772936ec1..49a17dc83e 100644 --- a/csrf/README.md +++ b/csrf/README.md @@ -9,36 +9,41 @@ keywords: [csrf, security, hacking, vulnerability] Example Cross Site Request Forgery (CSRF) vulnerabilities in action. - ## Requirements * [git](https://git-scm.com/downloads) * [Golang](https://golang.org/) - ## Install Go Modules Like any golang project, you will need to download and install the required modules for the project to run. Change into the "csrf" directory: + ```bash cd csrf ``` And then: + ```bash go mod vendor && go mod download && go mod tidy ``` + This command installs the golang dependencies needed to run the project in a new directory named `vendor`. Once the modules have finished installing, you can run the project like this: + ```bash go run main.go ``` + OR + ```bash go run main.go withoutCsrf ``` You should see the following if everything is OK: + ``` Server started and listening at localhost:3000 ``` @@ -46,21 +51,24 @@ Server started and listening at localhost:3000 ## Try the demo Start the server without csrf, to see the dangers of these attacks + ```bash go run main.go withoutCsrf ``` + Open your browser to and navigate to [localhost:3000](http://localhost:3000). Login using the test account: + * Username: `bob` * Password: `test` In a new tab, navigate to [localhost:3001](http://localhost:3001) to view some examples of CSRF exploits. You will notice that the balance goes down everytime you load that page. This is because the page is successfully exploiting a CSRF vulnerability. - ## See the "fixed" version To see the csrf version of this demo, just stop the server by pressing __CTRL + C__ to kill the server process and then run + ```bash go run main.go ``` @@ -71,9 +79,9 @@ And once more try the page with the CSRF exploits: [localhost:3001](http://local You will notice now that the account balance is unchanged. - ## Going further Here are some useful links where you can learn more about this topic: -* https://en.wikipedia.org/wiki/Cross-site_request_forgery -* https://www.owasp.org/index.php/Cross-Site_Request_Forgery_(CSRF) + +* +* diff --git a/csrf/routes/mainServer.go b/csrf/routes/mainServer.go index 7464f1e780..acaae1fb23 100644 --- a/csrf/routes/mainServer.go +++ b/csrf/routes/mainServer.go @@ -12,7 +12,7 @@ import ( "github.com/gofiber/fiber/v2/utils" ) -//region struct definitions +// region struct definitions // User contains the login user information type User struct { @@ -26,10 +26,11 @@ type TransferItem struct { Amount int `json:"amount" xml:"amount" form:"amount"` } -//endregion - -var sessionStore = session.New() -var csrfActivated = true +// endregion +var ( + sessionStore = session.New() + csrfActivated = true +) func init() { sessionStore.RegisterType(fiber.Map{}) @@ -62,7 +63,7 @@ func RegisterRoutes(app *fiber.App) { } // Simple accounts ledger. // This information would normally be stored in a database like MySQL, PostgreSQL, etc. - var accounts = map[string]int{ + accounts := map[string]int{ "bob": 500, "alice": 500, } diff --git a/docker-mariadb-clean-arch/internal/city/domain.go b/docker-mariadb-clean-arch/internal/city/domain.go index 692dbb2e66..cbc27feb96 100644 --- a/docker-mariadb-clean-arch/internal/city/domain.go +++ b/docker-mariadb-clean-arch/internal/city/domain.go @@ -2,6 +2,7 @@ package city import ( "context" + "docker-mariadb-clean-arch/internal/user" ) diff --git a/docker-mariadb-clean-arch/internal/city/handler.go b/docker-mariadb-clean-arch/internal/city/handler.go index c2471d19ed..5554e382b7 100644 --- a/docker-mariadb-clean-arch/internal/city/handler.go +++ b/docker-mariadb-clean-arch/internal/city/handler.go @@ -2,6 +2,7 @@ package city import ( "context" + "docker-mariadb-clean-arch/internal/auth" "github.com/gofiber/fiber/v2" diff --git a/docker-mariadb-clean-arch/internal/infrastructure/fiber.go b/docker-mariadb-clean-arch/internal/infrastructure/fiber.go index 4116a389b4..394d394c06 100644 --- a/docker-mariadb-clean-arch/internal/infrastructure/fiber.go +++ b/docker-mariadb-clean-arch/internal/infrastructure/fiber.go @@ -1,12 +1,13 @@ package infrastructure import ( + "fmt" + "log" + "docker-mariadb-clean-arch/internal/auth" "docker-mariadb-clean-arch/internal/city" "docker-mariadb-clean-arch/internal/misc" "docker-mariadb-clean-arch/internal/user" - "fmt" - "log" _ "github.com/go-sql-driver/mysql" "github.com/gofiber/fiber/v2" diff --git a/docker-nginx-loadbalancer/README.md b/docker-nginx-loadbalancer/README.md index b1af8d6974..8bb1995847 100644 --- a/docker-nginx-loadbalancer/README.md +++ b/docker-nginx-loadbalancer/README.md @@ -26,8 +26,9 @@ To get a local copy up and running, follow these steps: 2. Navigate to the project directory. 3. Build the Docker image with docker compose 4. Run the Docker compose composition + ```bash docker compose up --build ``` -5. Access the application at `http://localhost:8080/hello`. +5. Access the application at `http://localhost:8080/hello`. diff --git a/docker-nginx-loadbalancer/main.go b/docker-nginx-loadbalancer/main.go index 9c4027b6f0..e2785647a4 100644 --- a/docker-nginx-loadbalancer/main.go +++ b/docker-nginx-loadbalancer/main.go @@ -1,11 +1,13 @@ package main import ( + "log" + "github.com/gofiber/fiber/v2" // Importing the fiber package for handling HTTP requests "github.com/gofiber/fiber/v2/middleware/cors" // Middleware for handling Cross-Origin Resource Sharing (CORS) "github.com/gofiber/fiber/v2/middleware/favicon" // Middleware for serving favicon "github.com/gofiber/fiber/v2/middleware/logger" // Middleware for logging HTTP requests - "log" // Package for logging errors + // Package for logging errors ) func main() { diff --git a/dummyjson/main.go b/dummyjson/main.go index df98dead8d..f0076691ce 100644 --- a/dummyjson/main.go +++ b/dummyjson/main.go @@ -1,46 +1,46 @@ -package main - -import ( - "io" - "log" - "net/http" - "time" - - "github.com/gofiber/fiber/v2" -) - -var client = http.Client{ - Timeout: 10 * time.Second, -} - -func main() { - app := fiber.New() - - app.Get("/", func(c *fiber.Ctx) error { - resp, err := client.Get("https://dummyjson.com/products/1") - if err != nil { - return c.Status(fiber.StatusInternalServerError).JSON(&fiber.Map{ - "success": false, - "error": err.Error(), - }) - } - - defer resp.Body.Close() - if resp.StatusCode != http.StatusOK { - return c.Status(resp.StatusCode).JSON(&fiber.Map{ - "success": false, - "error": err.Error(), - }) - } - - if _, err := io.Copy(c.Response().BodyWriter(), resp.Body); err != nil { - return c.Status(fiber.StatusInternalServerError).JSON(&fiber.Map{ - "success": false, - "error": err.Error(), - }) - } - return c.SendStatus(fiber.StatusOK) - }) - - log.Fatal(app.Listen(":3000")) -} +package main + +import ( + "io" + "log" + "net/http" + "time" + + "github.com/gofiber/fiber/v2" +) + +var client = http.Client{ + Timeout: 10 * time.Second, +} + +func main() { + app := fiber.New() + + app.Get("/", func(c *fiber.Ctx) error { + resp, err := client.Get("https://dummyjson.com/products/1") + if err != nil { + return c.Status(fiber.StatusInternalServerError).JSON(&fiber.Map{ + "success": false, + "error": err.Error(), + }) + } + + defer resp.Body.Close() + if resp.StatusCode != http.StatusOK { + return c.Status(resp.StatusCode).JSON(&fiber.Map{ + "success": false, + "error": err.Error(), + }) + } + + if _, err := io.Copy(c.Response().BodyWriter(), resp.Body); err != nil { + return c.Status(fiber.StatusInternalServerError).JSON(&fiber.Map{ + "success": false, + "error": err.Error(), + }) + } + return c.SendStatus(fiber.StatusOK) + }) + + log.Fatal(app.Listen(":3000")) +} diff --git a/ent-mysql/README.md b/ent-mysql/README.md index 9da67fb648..16c111a415 100644 --- a/ent-mysql/README.md +++ b/ent-mysql/README.md @@ -10,21 +10,27 @@ keywords: [ent, mysql, orm, rest] A sample program how to connect ent ORM ## How to start (If no ent dir) + Execute command first + ```bash go run -mod=mod entgo.io/ent/cmd/ent new Book ``` + go to `./ent/schema/book.go` and add fields(you want) to Book Schema + ```go // Fields of the Book. func (Book) Fields() []ent.Field { - return []ent.Field{ - field.String("title").NotEmpty(), - field.String("author").NotEmpty(), - } + return []ent.Field{ + field.String("title").NotEmpty(), + field.String("author").NotEmpty(), + } } ``` + Execute command + ```bash go generate ./ent ``` diff --git a/entgo-sveltekit/README.md b/entgo-sveltekit/README.md index bafe11f03e..1e7f35bc04 100644 --- a/entgo-sveltekit/README.md +++ b/entgo-sveltekit/README.md @@ -20,15 +20,16 @@ To run the project, follow these steps: ```bash go run ./bin all ``` + 2. Once the build process is complete, you can start the application by running: + ```bash ./app ``` - ## Available Commands -The following commands are available to manage the project: +The following commands are available to manage the project: | Command | Description | | --- | --- | @@ -48,7 +49,6 @@ To use this application, run the following command: go run ./bin ``` - API Routes ---------- @@ -65,18 +65,17 @@ The Go Fiber application provides the following API routes: Go Dependencies --------------- -- **Go Modules:** Go's built-in package manager used to manage dependencies for Go projects. -- **Entgo:** A Golang Object Relational Mapping (ORM) tool used to define and generate database schemas. -- **Fiber:** A fast and minimalist web framework for Golang. -- **Sqlite:** A small, lightweight, embedded SQL database engine. +- **Go Modules:** Go's built-in package manager used to manage dependencies for Go projects. +- **Entgo:** A Golang Object Relational Mapping (ORM) tool used to define and generate database schemas. +- **Fiber:** A fast and minimalist web framework for Golang. +- **Sqlite:** A small, lightweight, embedded SQL database engine. Npm Dependencies ---------------- -- **SvelteKit:** A JavaScript framework used to build modern web applications. -- **Tailwind CSS:** A fast and customizable CSS styling library. Can be used in SvelteKit projects. +- **SvelteKit:** A JavaScript framework used to build modern web applications. +- **Tailwind CSS:** A fast and customizable CSS styling library. Can be used in SvelteKit projects. ---------------- Author: [@ugurkorkmaz](https://github.com/ugurkorkmaz) - diff --git a/entgo-sveltekit/template/README.md b/entgo-sveltekit/template/README.md index 401c8ce125..da5f582985 100644 --- a/entgo-sveltekit/template/README.md +++ b/entgo-sveltekit/template/README.md @@ -19,22 +19,30 @@ The following scripts are available in the project's `package.json` file: To use the available scripts, you need to have Node.js and Npm (or Pnpm) installed on your system. Follow these steps: 1. Install the project dependencies by running the following command in the project's root directory: + ```bash npm install ``` - or + + or + ```bash pnpm install ``` + 2. Once the installation is complete, you can run the desired script using the following command: + ```bash npm run (code) ``` - or + + or + ```bash pnpm run (code) ``` + Replace `(code)` with one of the available scripts mentioned in the table above. 3. The corresponding action will be executed, and you can see the output in the terminal. - Please note that specific configurations and additional steps might be required depending on your project setup or requirements. Refer to the project documentation for more information. \ No newline at end of file + Please note that specific configurations and additional steps might be required depending on your project setup or requirements. Refer to the project documentation for more information. diff --git a/file-server/README.md b/file-server/README.md index 70aa55a15a..ceced8fde8 100644 --- a/file-server/README.md +++ b/file-server/README.md @@ -19,12 +19,14 @@ Ensure you have the following installed: ## Setup 1. Clone the repository: + ```sh git clone https://github.com/gofiber/recipes.git cd recipes/file-server ``` 2. Install dependencies: + ```sh go get ``` @@ -32,6 +34,7 @@ Ensure you have the following installed: ## Running the Application 1. Start the application: + ```sh go run main.go ``` diff --git a/firebase-auth/README.md b/firebase-auth/README.md index 0ca7810a89..9015c4c9da 100644 --- a/firebase-auth/README.md +++ b/firebase-auth/README.md @@ -19,6 +19,7 @@ SERVICE_ACCOUNT_JSON = "path to service account credential json" ``` ## Start + ``` go build go run main diff --git a/firebase-functions/README.md b/firebase-functions/README.md index 1c70dff109..cfa24432b5 100644 --- a/firebase-functions/README.md +++ b/firebase-functions/README.md @@ -417,4 +417,5 @@ gcloud functions deploy MyCloudFunction --runtime go120 --trigger-http Congratulations! You’ve successfully configured and deployed a GoFiber application on Firebase Functions. This powerful combination allows you to build fast and efficient serverless applications. Experiment further with GoFiber features and Firebase integrations to unlock the full potential of your serverless architecture. Happy coding! ## Medium Post -https://medium.com/@kmltrk07/how-to-deploy-gofiber-app-to-firebase-functions-8d4d537a4464 + + diff --git a/firebase-functions/cmd/main.go b/firebase-functions/cmd/main.go index 42e12fba5b..5d0b470b5b 100644 --- a/firebase-functions/cmd/main.go +++ b/firebase-functions/cmd/main.go @@ -8,7 +8,6 @@ import ( ) func main() { - port := "3001" if envPort := os.Getenv("PORT"); envPort != "" { port = envPort diff --git a/firebase-functions/functions.go b/firebase-functions/functions.go index 26cda8a3bb..c321cda5d9 100644 --- a/firebase-functions/functions.go +++ b/firebase-functions/functions.go @@ -37,7 +37,6 @@ func RouteToFiber(fiberApp *fiber.App, w http.ResponseWriter, r *http.Request, r } proxyReq, err := http.NewRequest(r.Method, url, bytes.NewReader(body)) - if err != nil { return err } diff --git a/firebase-functions/src/database/database.go b/firebase-functions/src/database/database.go index 61cffb35da..3bec6873a3 100644 --- a/firebase-functions/src/database/database.go +++ b/firebase-functions/src/database/database.go @@ -12,7 +12,6 @@ import ( ) func NewConnection() *firestore.Client { - ctx := context.Background() sa := option.WithCredentialsJSON(credentials()) diff --git a/gcloud-firebase/README.md b/gcloud-firebase/README.md index 00f141f8c8..6a7fb76797 100644 --- a/gcloud-firebase/README.md +++ b/gcloud-firebase/README.md @@ -12,6 +12,7 @@ Examples on how to run an application using Fiber on Google Cloud and connecting ## Running Locally * Run on the command line: + ``` go run cmd/main.go ``` @@ -29,6 +30,7 @@ After deploying the server on Cloud Run, you can get it's url on GCP Console ([l Or you can do it manually with those steps: * Run on the command line: + ``` export GCLOUD_PROJECT=[YOUR_PROJECT_ID] gcloud builds submit — -tag gcr.io/$GCLOUD_PROJECT/gcloud-fiber-firebase . @@ -41,6 +43,7 @@ gcloud beta run deploy --platform managed --image gcr.io/$GCLOUD_PROJECT/gcloud- This step will deploy the app to Google App Engine Standard Go enviroment. The app configuration and additional configurations can be tweaked on the `app.yaml` file. * Run on the command line: + ``` gcloud app deploy ``` @@ -52,6 +55,7 @@ This step will deploy a HTTP Cloud Function using Go enviroment. You can use the For the Cloud Functions env, Google enforces us to deploy a function that is a `http.HandlerFunc`, so on the file `functions.go` there is a workaround to reroute the HTTP call to the Fiber app instance. * Run on the command line: + ``` gcloud functions deploy HeroesAPI --runtime go111 --trigger-http ``` diff --git a/gcloud-firebase/cmd/main.go b/gcloud-firebase/cmd/main.go index 62ed40db41..7ae6638e4f 100644 --- a/gcloud-firebase/cmd/main.go +++ b/gcloud-firebase/cmd/main.go @@ -8,7 +8,6 @@ import ( ) func main() { - port := "8080" if envPort := os.Getenv("PORT"); envPort != "" { port = envPort diff --git a/gcloud-firebase/functions.go b/gcloud-firebase/functions.go index 9d2a2002e8..ba89062b19 100644 --- a/gcloud-firebase/functions.go +++ b/gcloud-firebase/functions.go @@ -37,7 +37,6 @@ func RouteToFiber(fiberApp *fiber.App, w http.ResponseWriter, r *http.Request, r } proxyReq, err := http.NewRequest(r.Method, url, bytes.NewReader(body)) - if err != nil { return err } diff --git a/gcloud-firebase/main.go b/gcloud-firebase/main.go index 44dd133c43..2451c4086d 100644 --- a/gcloud-firebase/main.go +++ b/gcloud-firebase/main.go @@ -12,9 +12,11 @@ import ( "github.com/joho/godotenv" ) -var app *fiber.App -var fbApp *firebase.App -var projectID string +var ( + app *fiber.App + fbApp *firebase.App + projectID string +) // Hero db heroes struct type Hero struct { @@ -40,7 +42,6 @@ func init() { } fbApp, err = firebase.NewApp(ctx, conf) - if err != nil { log.Fatalf("functions.init: NewApp %v\n", err) } diff --git a/gcloud/README.md b/gcloud/README.md index 8f75a0a3de..3ebeae3b6e 100644 --- a/gcloud/README.md +++ b/gcloud/README.md @@ -12,6 +12,7 @@ Examples on how to run an application using Fiber on Google Cloud. ## Running Locally * Run on the command line: + ``` go run cmd/main.go ``` @@ -27,6 +28,7 @@ After deploying the server on Cloud Run, you can get it's url on GCP Console ([l Or you can do it manually with those steps: * Run on the command line: + ``` export GCLOUD_PROJECT=[YOUR_PROJECT_ID] gcloud builds submit — -tag gcr.io/$GCLOUD_PROJECT/gcloud-fiber . @@ -38,6 +40,7 @@ gcloud beta run deploy --platform managed --image gcr.io/$GCLOUD_PROJECT/gcloud- This step will deploy the app to Google App Engine Standard Go enviroment. The app configuration and additional configurations can be tweaked on the `app.yaml` file. * Run on the command line: + ``` gcloud app deploy ``` @@ -49,6 +52,7 @@ This step will deploy a HTTP Cloud Function using Go enviroment. You can use the For the Cloud Functions env, Google enforces us to deploy a function that is a `http.HandlerFunc`, so on the file `functions.go` there is a workaround to reroute the HTTP call to the Fiber app instance. * Run on the command line: + ``` gcloud functions deploy MyCloudFunction --runtime go111 --trigger-http ``` diff --git a/gcloud/cmd/main.go b/gcloud/cmd/main.go index 25881b44a9..b8b9f4ef62 100644 --- a/gcloud/cmd/main.go +++ b/gcloud/cmd/main.go @@ -8,7 +8,6 @@ import ( ) func main() { - port := "8080" if envPort := os.Getenv("PORT"); envPort != "" { port = envPort diff --git a/gcloud/functions.go b/gcloud/functions.go index 26cda8a3bb..c321cda5d9 100644 --- a/gcloud/functions.go +++ b/gcloud/functions.go @@ -37,7 +37,6 @@ func RouteToFiber(fiberApp *fiber.App, w http.ResponseWriter, r *http.Request, r } proxyReq, err := http.NewRequest(r.Method, url, bytes.NewReader(body)) - if err != nil { return err } diff --git a/geoip-maxmind/README.md b/geoip-maxmind/README.md index 7bde0ffcd0..ca2ce33fc0 100644 --- a/geoip-maxmind/README.md +++ b/geoip-maxmind/README.md @@ -10,7 +10,8 @@ keywords: [geoip, maxmind, databases] This is an alternative method to resolve IP addresses to real-world location data using MaxMind GeoLite2 City databases. ## Prerequisites -Before you run this, you must first download a database from the MaxMind website - https://dev.maxmind.com/geoip/geoip2/geolite2/. To do this, you may need to register for a free account. + +Before you run this, you must first download a database from the MaxMind website - . To do this, you may need to register for a free account. The database you need to download is the one with the edition ID `GeoLite2-City`. Place it in this folder and run @@ -19,6 +20,7 @@ go run geoip-maxmind ``` ## Usage + Make a request to `http://127.0.0.1:3000/geo/178.62.56.160`, for example. You can omit an IP address to use your current IP address, or replace to use another. If the IP address is invalid, a HTTP 400 is returned. The response fields can be modified from the `ipLookup` struct, found in the `handlers/handlers.go` file. diff --git a/geoip-maxmind/handlers/handlers.go b/geoip-maxmind/handlers/handlers.go index 85da760335..7b56c163ef 100644 --- a/geoip-maxmind/handlers/handlers.go +++ b/geoip-maxmind/handlers/handlers.go @@ -37,7 +37,6 @@ func init() { // GeoIP is a handler for IP address lookups func GeoIP(c *fiber.Ctx) error { - ipAddr := c.Params("ip", c.IP()) // Check IP address format diff --git a/geoip/README.md b/geoip/README.md index 53f2204ef6..da2f8e59d1 100644 --- a/geoip/README.md +++ b/geoip/README.md @@ -21,12 +21,14 @@ Ensure you have the following installed: ## Setup 1. Clone the repository: + ```sh git clone https://github.com/gofiber/recipes.git cd recipes/geoip ``` 2. Install dependencies: + ```sh go get ``` @@ -36,6 +38,7 @@ Ensure you have the following installed: ## Running the Application 1. Start the application: + ```sh go run main.go ``` diff --git a/gorm-mysql/README.md b/gorm-mysql/README.md index 8dfb672ba8..c33ac9e053 100644 --- a/gorm-mysql/README.md +++ b/gorm-mysql/README.md @@ -18,17 +18,20 @@ This is a sample program demonstrating how to use GORM as an ORM to connect to a ## Setup 1. Clone the repository: + ```sh git clone https://github.com/gofiber/recipes.git cd recipes/gorm-mysql ``` 2. Install dependencies: + ```sh go mod tidy ``` 3. Configure the database connection in the `config.json` file: + ```json { "DB_Username": "your_db_username", @@ -42,6 +45,7 @@ This is a sample program demonstrating how to use GORM as an ORM to connect to a ## Running the Application 1. Run the application: + ```sh go run main.go ``` @@ -62,26 +66,31 @@ This is a sample program demonstrating how to use GORM as an ORM to connect to a ## Example Requests ### Get All Books + ```sh curl -X GET http://localhost:3000/allbooks ``` ### Get Book by ID + ```sh curl -X GET http://localhost:3000/book/1 ``` ### Create a New Book + ```sh curl -X POST http://localhost:3000/book -d '{"title": "New Book", "author": "Author Name"}' -H "Content-Type: application/json" ``` ### Update a Book + ```sh curl -X PUT http://localhost:3000/book -d '{"id": 1, "title": "Updated Book", "author": "Updated Author"}' -H "Content-Type: application/json" ``` ### Delete a Book + ```sh curl -X DELETE http://localhost:3000/book -d '{"id": 1}' -H "Content-Type: application/json" ``` diff --git a/gorm-mysql/database/database.go b/gorm-mysql/database/database.go index 6fbab2eb19..16042aa2ff 100644 --- a/gorm-mysql/database/database.go +++ b/gorm-mysql/database/database.go @@ -10,13 +10,10 @@ import ( "gorm.io/gorm" ) -var ( - DBConn *gorm.DB -) +var DBConn *gorm.DB // connectDb func ConnectDb() { - // refer https://github.com/go-sql-driver/mysql#dsn-data-source-name for details dsn := "user:pass@tcp(127.0.0.1:3306)/dbname?charset=utf8mb4&parseTime=True&loc=Local" /* @@ -26,7 +23,6 @@ func ConnectDb() { */ db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{}) - if err != nil { log.Fatal("Failed to connect to database. \n", err) os.Exit(2) @@ -35,5 +31,4 @@ func ConnectDb() { log.Println("connected") db.AutoMigrate(&models.Book{}) DBConn = db - } diff --git a/gorm-mysql/routes/routes.go b/gorm-mysql/routes/routes.go index 531b8ef19f..ea87b1ecae 100644 --- a/gorm-mysql/routes/routes.go +++ b/gorm-mysql/routes/routes.go @@ -1,19 +1,20 @@ package routes import ( + "strconv" + "gorm-mysql/database" "gorm-mysql/models" - "strconv" "github.com/gofiber/fiber/v2" ) -//Hello +// Hello func Hello(c *fiber.Ctx) error { return c.SendString("fiber") } -//AddBook +// AddBook func AddBook(c *fiber.Ctx) error { book := new(models.Book) if err := c.BodyParser(book); err != nil { @@ -33,7 +34,7 @@ func GetBook(c *fiber.Ctx) error { return c.Status(200).JSON(books) } -//AllBooks +// AllBooks func AllBooks(c *fiber.Ctx) error { books := []models.Book{} @@ -42,7 +43,7 @@ func AllBooks(c *fiber.Ctx) error { return c.Status(200).JSON(books) } -//Update +// Update func Update(c *fiber.Ctx) error { book := new(models.Book) if err := c.BodyParser(book); err != nil { @@ -55,7 +56,7 @@ func Update(c *fiber.Ctx) error { return c.Status(200).JSON("updated") } -//Delete +// Delete func Delete(c *fiber.Ctx) error { book := new(models.Book) diff --git a/gorm-postgres/README.md b/gorm-postgres/README.md index bf99a60b0b..26226b92af 100644 --- a/gorm-postgres/README.md +++ b/gorm-postgres/README.md @@ -21,17 +21,20 @@ Ensure you have the following installed: ## Setup 1. Clone the repository: + ```sh git clone https://github.com/gofiber/recipes.git cd recipes/gorm-postgres ``` 2. Install dependencies: + ```sh go get ``` 3. Set up PostgreSQL and create a database: + ```sh createdb mydb ``` @@ -41,6 +44,7 @@ Ensure you have the following installed: ## Running the Application 1. Start the application: + ```sh go run main.go ``` diff --git a/gorm-postgres/database/database.go b/gorm-postgres/database/database.go index 5f57c6c452..804c9ed36c 100644 --- a/gorm-postgres/database/database.go +++ b/gorm-postgres/database/database.go @@ -22,7 +22,6 @@ func ConnectDb() { db, err := gorm.Open(postgres.Open(dsn), &gorm.Config{ Logger: logger.Default.LogMode(logger.Info), }) - if err != nil { log.Fatal("Failed to connect to database. \n", err) } diff --git a/gorm/README.md b/gorm/README.md index c66f9f2021..084000a691 100644 --- a/gorm/README.md +++ b/gorm/README.md @@ -17,12 +17,14 @@ This is a sample program demonstrating how to use GORM as an ORM to connect to a ## Setup 1. Clone the repository: + ```sh git clone https://github.com/gofiber/recipes.git cd recipes/gorm-example ``` 2. Install dependencies: + ```sh go mod tidy ``` @@ -30,6 +32,7 @@ This is a sample program demonstrating how to use GORM as an ORM to connect to a ## Running the Application 1. Run the application: + ```sh go run main.go ``` @@ -48,21 +51,25 @@ This is a sample program demonstrating how to use GORM as an ORM to connect to a ## Example Requests ### Get All Books + ```sh curl -X GET http://localhost:3000/api/v1/book ``` ### Get Book by ID + ```sh curl -X GET http://localhost:3000/api/v1/book/1 ``` ### Create a New Book + ```sh curl -X POST http://localhost:3000/api/v1/book -d '{"title": "New Book", "author": "Author Name"}' -H "Content-Type: application/json" ``` ### Delete a Book + ```sh curl -X DELETE http://localhost:3000/api/v1/book/1 ``` diff --git a/gorm/database/database.go b/gorm/database/database.go index 3b9668e232..ffcae37e33 100644 --- a/gorm/database/database.go +++ b/gorm/database/database.go @@ -4,6 +4,4 @@ import ( "gorm.io/gorm" ) -var ( - DBConn *gorm.DB -) +var DBConn *gorm.DB diff --git a/gorm/main.go b/gorm/main.go index 9e264055b9..5252651a64 100644 --- a/gorm/main.go +++ b/gorm/main.go @@ -1,11 +1,12 @@ package main import ( - "fiber-gorm/book" - "fiber-gorm/database" "fmt" "log" + "fiber-gorm/book" + "fiber-gorm/database" + "github.com/gofiber/fiber/v2" "github.com/gofiber/fiber/v2/middleware/cors" "gorm.io/driver/sqlite" diff --git a/graceful-shutdown/main.go b/graceful-shutdown/main.go index d91c18539f..9d02e50d7b 100644 --- a/graceful-shutdown/main.go +++ b/graceful-shutdown/main.go @@ -2,12 +2,13 @@ package main import ( "fmt" - "github.com/gofiber/fiber/v2" "log" "os" "os/signal" "syscall" "time" + + "github.com/gofiber/fiber/v2" ) const idleTimeout = 5 * time.Second diff --git a/graphql/README.md b/graphql/README.md index 0d7a8a939c..c52003a635 100644 --- a/graphql/README.md +++ b/graphql/README.md @@ -20,17 +20,20 @@ Ensure you have the following installed: ## Setup 1. Clone the repository: + ```sh git clone https://github.com/gofiber/recipes.git cd recipes/graphql ``` 2. Install dependencies: + ```sh go get ``` 3. Initialize gqlgen: + ```sh go run github.com/99designs/gqlgen init ``` @@ -38,6 +41,7 @@ Ensure you have the following installed: ## Running the Application 1. Start the application: + ```sh go run main.go ``` diff --git a/grpc/README.md b/grpc/README.md index 01594060f8..cd472989da 100644 --- a/grpc/README.md +++ b/grpc/README.md @@ -3,7 +3,7 @@ title: gRPC keywords: [grpc, server, client] --- -# Example for fiber as a client to gRPC server. +# Example for fiber as a client to gRPC server [![Github](https://img.shields.io/static/v1?label=&message=Github&color=2ea44f&style=for-the-badge&logo=github)](https://github.com/gofiber/recipes/tree/master/grpc) [![StackBlitz](https://img.shields.io/static/v1?label=&message=StackBlitz&color=2ea44f&style=for-the-badge&logo=StackBlitz)](https://stackblitz.com/github/gofiber/recipes/tree/master/grpc) @@ -17,12 +17,14 @@ A sample program to showcase fiber as a client to a gRPC server. ## Setup 1. Clone the repository: + ```sh git clone https://github.com/gofiber/recipes.git cd recipes/grpc ``` 2. Install dependencies: + ```sh go mod tidy ``` @@ -30,11 +32,13 @@ A sample program to showcase fiber as a client to a gRPC server. ## Running the Application 1. Run the gRPC server: + ```sh go run server/main.go ``` 2. Run the Fiber client: + ```sh go run client/main.go ``` diff --git a/grpc/client/main.go b/grpc/client/main.go index 3ba8a2ed69..cc2678fef8 100644 --- a/grpc/client/main.go +++ b/grpc/client/main.go @@ -51,7 +51,6 @@ func main() { return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{ "error": err.Error(), }) - }) app.Get("/mult/:a/:b", func(c *fiber.Ctx) error { @@ -76,7 +75,6 @@ func main() { return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{ "error": err.Error(), }) - }) log.Fatal(app.Listen(":3000")) } diff --git a/hello-world/README.md b/hello-world/README.md index 51d57461f1..bc732019f3 100644 --- a/hello-world/README.md +++ b/hello-world/README.md @@ -19,12 +19,14 @@ Ensure you have the following installed: ## Setup 1. Clone the repository: + ```sh git clone https://github.com/gofiber/recipes.git cd recipes/hello-world ``` 2. Install dependencies: + ```sh go get ``` @@ -32,6 +34,7 @@ Ensure you have the following installed: ## Running the Application 1. Start the application: + ```sh go run main.go ``` diff --git a/heroku/README.md b/heroku/README.md index 9481c88373..f9fa6717c5 100644 --- a/heroku/README.md +++ b/heroku/README.md @@ -20,32 +20,38 @@ Ensure you have the following installed: ## Setup 1. Clone the repository: + ```sh git clone https://github.com/gofiber/recipes.git cd recipes/heroku ``` 2. Install dependencies: + ```sh go get ``` 3. Log in to Heroku: + ```sh heroku login ``` 4. Create a new Heroku application: + ```sh heroku create ``` 5. Add a `Procfile` to the project directory with the following content: + ``` web: go run main.go ``` 6. Deploy the application to Heroku: + ```sh git add . git commit -m "Deploy to Heroku" @@ -55,6 +61,7 @@ Ensure you have the following installed: ## Running the Application 1. Open the application in your browser: + ```sh heroku open ``` diff --git a/hexagonal/README.md b/hexagonal/README.md index 1d48d4f650..5a777fc952 100644 --- a/hexagonal/README.md +++ b/hexagonal/README.md @@ -20,17 +20,20 @@ This project presents a simple product catalogue microservice to demonstrate the ## Setup 1. Clone the repository: + ```sh git clone https://github.com/gofiber/recipes.git cd recipes/hexagonal ``` 2. Install dependencies: + ```sh go mod tidy ``` 3. Configure the MongoDB connection in the `config.json` file: + ```json { "DB_URI": "your_mongodb_uri", @@ -41,6 +44,7 @@ This project presents a simple product catalogue microservice to demonstrate the ## Running the Application 1. Run the application: + ```sh go run main.go ``` @@ -60,26 +64,31 @@ This project presents a simple product catalogue microservice to demonstrate the ## Example Requests ### Get All Products + ```sh curl -X GET http://localhost:3000/api/v1/products ``` ### Get Product by ID + ```sh curl -X GET http://localhost:3000/api/v1/product/1 ``` ### Create a New Product + ```sh curl -X POST http://localhost:3000/api/v1/product -d '{"name": "New Product", "price": 100}' -H "Content-Type: application/json" ``` ### Update a Product + ```sh curl -X PUT http://localhost:3000/api/v1/product/1 -d '{"name": "Updated Product", "price": 150}' -H "Content-Type: application/json" ``` ### Delete a Product + ```sh curl -X DELETE http://localhost:3000/api/v1/product/1 ``` @@ -91,5 +100,6 @@ Hexagonal architecture, also known as ports and adapters architecture, is a desi ## Additional Information For more information on hexagonal architecture, you can refer to the following resources: + - [Hexagonal Architecture](https://alistair.cockburn.us/hexagonal-architecture/) - [Hexagonal Architecture in Golang](https://medium.com/@matryer/hexagonal-architecture-in-go-2b5e0df2d8f8) diff --git a/hexagonal/config/config.go b/hexagonal/config/config.go index 7aa08505b3..2cef6ca423 100644 --- a/hexagonal/config/config.go +++ b/hexagonal/config/config.go @@ -1,8 +1,9 @@ package config import ( - "gopkg.in/yaml.v2" "os" + + "gopkg.in/yaml.v2" ) // Config struct for structuring the config data, can be extended accordingly diff --git a/hexagonal/main.go b/hexagonal/main.go index 9244c1a1d4..8b17a6dcd2 100644 --- a/hexagonal/main.go +++ b/hexagonal/main.go @@ -11,7 +11,6 @@ import ( ) func main() { - conf, _ := config.NewConfig("./config/config.yaml") repo, _ := repository.NewMongoRepository(conf.Database.URL, conf.Database.DB, conf.Database.Timeout) service := service.NewProductService(repo) @@ -29,5 +28,4 @@ func main() { r.Get("/products", handler.GetAll) r.Put("/products", handler.Put) r.Listen(":8080") - } diff --git a/hexagonal/repository/mongo.go b/hexagonal/repository/mongo.go index 334c1d7a70..20e205bff6 100644 --- a/hexagonal/repository/mongo.go +++ b/hexagonal/repository/mongo.go @@ -1,14 +1,16 @@ package repository import ( - "catalog/domain" "context" + "log" + "time" + + "catalog/domain" + "github.com/pkg/errors" "go.mongodb.org/mongo-driver/bson" "go.mongodb.org/mongo-driver/mongo" "go.mongodb.org/mongo-driver/mongo/options" - "log" - "time" ) type mongoRepository struct { @@ -73,7 +75,6 @@ func (r *mongoRepository) FindAll() ([]*domain.Product, error) { collection := r.client.Database(r.db).Collection("products") cur, err := collection.Find(context.Background(), bson.D{}) - if err != nil { log.Fatal(err) } @@ -97,7 +98,6 @@ func (r *mongoRepository) Delete(code string) error { collection := r.client.Database(r.db).Collection("items") _, err := collection.DeleteOne(ctx, filter) - if err != nil { return err } @@ -130,5 +130,4 @@ func NewMongoRepository(mongoServerURL, mongoDb string, timeout int) (domain.Rep } return repo, nil - } diff --git a/hexagonal/service/logic.go b/hexagonal/service/logic.go index b6d37787ff..5520e0c071 100644 --- a/hexagonal/service/logic.go +++ b/hexagonal/service/logic.go @@ -14,9 +14,11 @@ func NewProductService(productRepo domain.Repository) *service { func (s *service) Find(code string) (*domain.Product, error) { return s.productRepo.Find(code) } + func (s *service) Store(product *domain.Product) error { return s.productRepo.Store(product) } + func (s *service) Update(product *domain.Product) error { return s.productRepo.Update(product) } diff --git a/https-pkcs12-tls/README.md b/https-pkcs12-tls/README.md index bc8270bddc..00187b5a27 100644 --- a/https-pkcs12-tls/README.md +++ b/https-pkcs12-tls/README.md @@ -20,12 +20,14 @@ Ensure you have the following installed: ## Setup 1. Clone the repository: + ```sh git clone https://github.com/gofiber/recipes.git cd recipes/https-pkcs12-tls ``` 2. Install dependencies: + ```sh go get ``` @@ -35,6 +37,7 @@ Ensure you have the following installed: ## Running the Application 1. Start the application: + ```sh go run main.go ``` diff --git a/https-pkcs12-tls/main.go b/https-pkcs12-tls/main.go index d4289df98e..55e9942b13 100644 --- a/https-pkcs12-tls/main.go +++ b/https-pkcs12-tls/main.go @@ -28,7 +28,6 @@ func initTLSConfig(path string, password string) (*tls.Certificate, error) { } key, cert, err := pkcs12.Decode(pkcs12Data, password) - if err != nil { return nil, err } diff --git a/https-tls/README.md b/https-tls/README.md index 7f3f1a0c83..a51b8683b8 100644 --- a/https-tls/README.md +++ b/https-tls/README.md @@ -20,12 +20,14 @@ Ensure you have the following installed: ## Setup 1. Clone the repository: + ```sh git clone https://github.com/gofiber/recipes.git cd recipes/https-tls ``` 2. Install dependencies: + ```sh go get ``` @@ -35,6 +37,7 @@ Ensure you have the following installed: ## Running the Application 1. Start the application: + ```sh go run main.go ``` diff --git a/jwt/README.md b/jwt/README.md index 0ebc6931d4..22156db3d7 100644 --- a/jwt/README.md +++ b/jwt/README.md @@ -17,12 +17,14 @@ This example demonstrates how to use JSON Web Tokens (JWT) for authentication in ## Setup 1. Clone the repository: + ```sh git clone https://github.com/gofiber/recipes.git cd recipes/jwt ``` 2. Install dependencies: + ```sh go mod tidy ``` @@ -30,6 +32,7 @@ This example demonstrates how to use JSON Web Tokens (JWT) for authentication in ## Running the Application 1. Run the application: + ```sh go run main.go ``` @@ -46,11 +49,13 @@ This example demonstrates how to use JSON Web Tokens (JWT) for authentication in ## Example Requests ### Login + ```sh curl -X POST http://localhost:3000/login -d '{"username": "user", "password": "pass"}' -H "Content-Type: application/json" ``` ### Access Restricted Route + ```sh curl -X GET http://localhost:3000/restricted -H "Authorization: Bearer " ``` diff --git a/jwt/database/connect.go b/jwt/database/connect.go index 8f3fe80711..13f45f3c65 100644 --- a/jwt/database/connect.go +++ b/jwt/database/connect.go @@ -1,12 +1,14 @@ package database import ( + "fmt" + "strconv" + "api-fiber-gorm/config" "api-fiber-gorm/model" - "fmt" + "gorm.io/driver/postgres" "gorm.io/gorm" - "strconv" ) // DB gorm connector diff --git a/jwt/main.go b/jwt/main.go index 57e337feca..7423f68016 100644 --- a/jwt/main.go +++ b/jwt/main.go @@ -1,9 +1,10 @@ package main import ( + "log" + "api-fiber-gorm/database" "api-fiber-gorm/router" - "log" "github.com/gofiber/fiber/v2" "github.com/gofiber/fiber/v2/middleware/cors" diff --git a/jwt/middleware/auth.go b/jwt/middleware/auth.go index 32f4f6542a..4400506f4e 100644 --- a/jwt/middleware/auth.go +++ b/jwt/middleware/auth.go @@ -1,14 +1,14 @@ package middleware import ( - "github.com/gofiber/fiber/v2" jwtware "github.com/gofiber/contrib/jwt" + "github.com/gofiber/fiber/v2" ) // Protected protect routes func Protected() func(*fiber.Ctx) error { return jwtware.New(jwtware.Config{ - SigningKey: jwtware.SigningKey{Key: []byte("secret")}, + SigningKey: jwtware.SigningKey{Key: []byte("secret")}, ErrorHandler: jwtError, }) } diff --git a/k8s/README.md b/k8s/README.md index f32879f8d0..f4402ddf38 100644 --- a/k8s/README.md +++ b/k8s/README.md @@ -23,27 +23,32 @@ Ensure you have the following installed: ## Setup 1. Clone the repository: + ```sh git clone https://github.com/gofiber/recipes.git cd recipes/k8s ``` 2. Install dependencies: + ```sh go get ``` 3. Build the Docker image: + ```sh docker build -t fiber-k8s-example . ``` 4. Start Minikube (if using Minikube): + ```sh minikube start ``` 5. Deploy the application to Kubernetes: + ```sh kubectl apply -f deployment.yaml ``` @@ -51,11 +56,13 @@ Ensure you have the following installed: ## Running the Application 1. Check the status of the pods: + ```sh kubectl get pods ``` 2. Forward the port to access the application: + ```sh kubectl port-forward svc/fiber-k8s-example 3000:3000 ``` diff --git a/memgraph/README.md b/memgraph/README.md index d298c4752c..606d419fa8 100644 --- a/memgraph/README.md +++ b/memgraph/README.md @@ -56,5 +56,6 @@ http://localhost:3000/developer/Andy ## Additional resources For extra information use the documentation on the following links: -- Fiber: https://docs.gofiber.io/ -- Memgraph: https://memgraph.com/docs + +- Fiber: +- Memgraph: diff --git a/memgraph/main.go b/memgraph/main.go index fd9699c880..b7f04c7422 100644 --- a/memgraph/main.go +++ b/memgraph/main.go @@ -29,15 +29,14 @@ type Technology struct { // Queries to create the mock dataset func getDatasetCreationQueries() []string { - - //Create developer nodes + // Create developer nodes developer_nodes := []string{ "CREATE (n:Developer {id: 1, name:'Andy'});", "CREATE (n:Developer {id: 2, name:'John'});", "CREATE (n:Developer {id: 3, name:'Michael'});", } - //Create technology nodes + // Create technology nodes technology_nodes := []string{ "CREATE (n:Technology {id: 1, name:'Fiber'})", "CREATE (n:Technology {id: 2, name:'Memgraph'})", @@ -47,13 +46,13 @@ func getDatasetCreationQueries() []string { "CREATE (n:Technology {id: 6, name:'Kubernetes'})", "CREATE (n:Technology {id: 7, name:'Python'})", } - //Create indexes on developer and technology nodes + // Create indexes on developer and technology nodes indexes := []string{ "CREATE INDEX ON :Developer(id);", "CREATE INDEX ON :Technology(id);", } - //Create relationships between developers and technologies + // Create relationships between developers and technologies edges := []string{ "MATCH (a:Developer {id: 1}),(b:Technology {id: 1}) CREATE (a)-[r:LOVES]->(b);", "MATCH (a:Developer {id: 1}),(b:Technology {id: 2}) CREATE (a)-[r:LOVES]->(b);", @@ -70,7 +69,7 @@ func getDatasetCreationQueries() []string { "MATCH (a:Developer {id: 3}),(b:Technology {id: 3}) CREATE (a)-[r:LOVES]->(b);", } - //Create a single list of all queries for sake of simplicity + // Create a single list of all queries for sake of simplicity var allQueries []string = []string{"MATCH (n) DETACH DELETE n;"} allQueries = append(allQueries, developer_nodes...) allQueries = append(allQueries, technology_nodes...) @@ -81,7 +80,7 @@ func getDatasetCreationQueries() []string { } func ConnectDriverToDB() (neo4j.Driver, error) { - //Memgraph communicates via Bolt protocol, using port 7687 + // Memgraph communicates via Bolt protocol, using port 7687 dbUri := "bolt://localhost:7687" var ( driver neo4j.Driver @@ -95,7 +94,7 @@ func ConnectDriverToDB() (neo4j.Driver, error) { } func executeQuery(driver neo4j.Driver, query string) (neo4j.Result, error) { - //Each session opens a new connection to the database and gets a thread from the thread pool, for multi-threaded access to Memgraph open multiple sessions + // Each session opens a new connection to the database and gets a thread from the thread pool, for multi-threaded access to Memgraph open multiple sessions session, err := driver.Session(neo4j.AccessModeWrite) if err != nil { return nil, err @@ -110,8 +109,7 @@ func executeQuery(driver neo4j.Driver, query string) (neo4j.Result, error) { } func main() { - - //Connect to Memgraph + // Connect to Memgraph driver, err := ConnectDriverToDB() if err != nil { fmt.Print(err) @@ -119,7 +117,7 @@ func main() { } defer driver.Close() - //Create mock dataset + // Create mock dataset datasetCreationQueries := getDatasetCreationQueries() for _, query := range datasetCreationQueries { _, err := executeQuery(driver, query) @@ -129,7 +127,7 @@ func main() { } } - //Create a Fiber app + // Create a Fiber app app := fiber.New() // Get developer called Andy and technologies he loves, http://localhost:3000/developer/Andy @@ -174,7 +172,6 @@ func main() { default: fmt.Printf("I don't know about type %T!\n", v) } - } } @@ -185,10 +182,9 @@ func main() { } return c.JSON(data) - }) - //Get whole graph, including all nodes, and edges, http://localhost:3000/graph + // Get whole graph, including all nodes, and edges, http://localhost:3000/graph app.Get("/graph", func(c *fiber.Ctx) error { query := `MATCH (dev)-[loves]->(tech) RETURN dev, loves, tech` @@ -231,7 +227,6 @@ func main() { default: fmt.Printf("I don't know about type %T!\n", v) } - } } @@ -241,8 +236,6 @@ func main() { "technology": technology_nodes, } return c.JSON(data) - }) log.Fatal(app.Listen(":3000")) - } diff --git a/minio/README.md b/minio/README.md index dd83a85b96..ef57cb8e17 100644 --- a/minio/README.md +++ b/minio/README.md @@ -61,9 +61,11 @@ go mod download ``` 3. Upload a file using `curl` or `Postman`: + ```bash curl -F "document=@/path/to/your/file" http://localhost:3000/upload ``` + 4. Download the file by specifying its name in the request: ```bash diff --git a/minio/multiple/main.go b/minio/multiple/main.go index 35e8710228..d99b4b9107 100644 --- a/minio/multiple/main.go +++ b/minio/multiple/main.go @@ -21,7 +21,6 @@ const ( ) func main() { - // Initialize the MinIO client store := minio.New(minio.Config{ Endpoint: getEnv("FIBER_MINIO_ENDPOINT", "localhost:9000"), @@ -46,7 +45,6 @@ func main() { // Define the route for uploading multiple files app.Post("/upload", func(c *fiber.Ctx) error { - // Retrieve all files from the multipart form, under the field name "documents" multipartForm, err := c.MultipartForm() if err != nil { @@ -136,7 +134,6 @@ func main() { filePart.Size, // File size minio.ConfigDefault.PutObjectOptions, // content type for binary files ) - if err != nil { // If the upload fails, add the file to the failed list failedFiles = append(failedFiles, fiber.Map{ @@ -179,7 +176,6 @@ func main() { return c.Status(http.StatusBadRequest).JSON(fiber.Map{ "message": err.Error(), }) - } // Check if the file exists in the MinIO bucket diff --git a/minio/single/main.go b/minio/single/main.go index 87a7853211..36c7c8c45a 100644 --- a/minio/single/main.go +++ b/minio/single/main.go @@ -18,7 +18,6 @@ import ( const maxFileSize = 10 * 1024 * 1024 // 10MB func main() { - // Initialize the MinIO client store := minio.New(minio.Config{ Endpoint: getEnv("FIBER_MINIO_ENDPOINT", "localhost:9000"), @@ -43,7 +42,6 @@ func main() { // Define the route to handle file uploads app.Post("/upload", func(c *fiber.Ctx) error { - // Check file size before processing if c.Request().Header.ContentLength() > maxFileSize { return c.Status(http.StatusRequestEntityTooLarge).JSON(fiber.Map{ @@ -110,7 +108,6 @@ func main() { formFile.Size, // File size minio.ConfigDefault.PutObjectOptions, // content type for binary files ) - // If the upload fails, return Error if err != nil { return c.Status(http.StatusInternalServerError).JSON(fiber.Map{ @@ -146,7 +143,6 @@ func main() { return c.Status(http.StatusBadRequest).JSON(fiber.Map{ "message": err.Error(), }) - } // Check if the file exists in the MinIO bucket diff --git a/mongodb/README.md b/mongodb/README.md index dde4f8af15..e424812646 100644 --- a/mongodb/README.md +++ b/mongodb/README.md @@ -21,12 +21,14 @@ Ensure you have the following installed: ## Setup 1. Clone the repository: + ```sh git clone https://github.com/gofiber/recipes.git cd recipes/mongodb ``` 2. Install dependencies: + ```sh go get ``` @@ -36,6 +38,7 @@ Ensure you have the following installed: ## Running the Application 1. Start the application: + ```sh go run main.go ``` diff --git a/mongodb/main.go b/mongodb/main.go index 9b321ca255..9e38a40202 100644 --- a/mongodb/main.go +++ b/mongodb/main.go @@ -24,8 +24,10 @@ type MongoInstance struct { var mg MongoInstance // Database settings (insert your own database name and connection URI) -const dbName = "fiber_test" -const mongoURI = "mongodb://user:password@localhost:27017/" + dbName +const ( + dbName = "fiber_test" + mongoURI = "mongodb://user:password@localhost:27017/" + dbName +) // Employee struct type Employee struct { @@ -39,7 +41,6 @@ type Employee struct { // Source: https://www.mongodb.com/docs/drivers/go/current/quick-start/ func Connect() error { client, err := mongo.Connect(context.TODO(), options.Client().ApplyURI(mongoURI)) - if err != nil { return err } @@ -88,7 +89,6 @@ func main() { // iterate the cursor and decode each item into an Employee if err := cursor.All(c.Context(), &employees); err != nil { return c.Status(500).SendString(err.Error()) - } // return employees list in JSON format return c.JSON(employees) @@ -154,7 +154,6 @@ func main() { app.Put("/employee/:id", func(c *fiber.Ctx) error { idParam := c.Params("id") employeeID, err := primitive.ObjectIDFromHex(idParam) - // the provided ID might be invalid ObjectID if err != nil { return c.SendStatus(400) @@ -169,7 +168,8 @@ func main() { // Find the employee and update its data query := bson.D{{Key: "_id", Value: employeeID}} update := bson.D{ - {Key: "$set", + { + Key: "$set", Value: bson.D{ {Key: "name", Value: employee.Name}, {Key: "age", Value: employee.Age}, @@ -178,7 +178,6 @@ func main() { }, } err = mg.Db.Collection("employees").FindOneAndUpdate(c.Context(), query, update).Err() - if err != nil { // ErrNoDocuments means that the filter did not match any documents in the collection if err == mongo.ErrNoDocuments { @@ -198,7 +197,6 @@ func main() { employeeID, err := primitive.ObjectIDFromHex( c.Params("id"), ) - // the provided ID might be invalid ObjectID if err != nil { return c.SendStatus(400) @@ -207,7 +205,6 @@ func main() { // find and delete the employee with the given ID query := bson.D{{Key: "_id", Value: employeeID}} result, err := mg.Db.Collection("employees").DeleteOne(c.Context(), &query) - if err != nil { return c.SendStatus(500) } diff --git a/multiple-ports/README.md b/multiple-ports/README.md index 1545b7d5c9..4f4b38d46e 100644 --- a/multiple-ports/README.md +++ b/multiple-ports/README.md @@ -19,12 +19,14 @@ Ensure you have the following installed: ## Setup 1. Clone the repository: + ```sh git clone https://github.com/gofiber/recipes.git cd recipes/multiple-ports ``` 2. Install dependencies: + ```sh go get ``` @@ -32,6 +34,7 @@ Ensure you have the following installed: ## Running the Application 1. Start the application: + ```sh go run main.go ``` @@ -75,6 +78,7 @@ func main() { ``` In this example: + - The application listens on multiple ports (`:3000` and `:3001`). - A `sync.WaitGroup` is used to wait for all goroutines to finish. diff --git a/mysql/README.md b/mysql/README.md index c3fced94e5..044008502a 100644 --- a/mysql/README.md +++ b/mysql/README.md @@ -21,12 +21,14 @@ Ensure you have the following installed: ## Setup 1. Clone the repository: + ```sh git clone https://github.com/gofiber/recipes.git cd recipes/mysql ``` 2. Install dependencies: + ```sh go get ``` @@ -36,6 +38,7 @@ Ensure you have the following installed: ## Running the Application 1. Start the application: + ```sh go run main.go ``` diff --git a/neo4j/README.md b/neo4j/README.md index 5b7d1b1608..b2a6141412 100644 --- a/neo4j/README.md +++ b/neo4j/README.md @@ -21,12 +21,14 @@ Ensure you have the following installed: ## Setup 1. Clone the repository: + ```sh git clone https://github.com/gofiber/recipes.git cd recipes/neo4j ``` 2. Install dependencies: + ```sh go get ``` @@ -36,6 +38,7 @@ Ensure you have the following installed: ## Running the Application 1. Start the application: + ```sh go run main.go ``` diff --git a/oauth2-google/README.md b/oauth2-google/README.md index ec8d743d55..d53d344a36 100644 --- a/oauth2-google/README.md +++ b/oauth2-google/README.md @@ -17,12 +17,14 @@ This example demonstrates how to implement Google OAuth2 authentication in a Fib ## Setup 1. Clone the repository: + ```sh git clone https://github.com/gofiber/recipes.git cd recipes/oauth2-google ``` 2. Install dependencies: + ```sh go mod tidy ``` @@ -30,6 +32,7 @@ This example demonstrates how to implement Google OAuth2 authentication in a Fib 3. Obtain OAuth credentials from [Google Developers Console](https://console.developers.google.com/). 4. Create a `.env` file in the root directory and add your Google OAuth credentials: + ```env GOOGLE_CLIENT_ID=your_client_id GOOGLE_CLIENT_SECRET=your_client_secret @@ -39,6 +42,7 @@ This example demonstrates how to implement Google OAuth2 authentication in a Fib ## Running the Application 1. Run the application: + ```sh go run main.go ``` @@ -55,11 +59,13 @@ This example demonstrates how to implement Google OAuth2 authentication in a Fib ## Example Requests ### Redirect to Google Login + ```sh curl -X GET http://localhost:3000/api/ ``` ### Google OAuth2 Callback + ```sh curl -X GET http://localhost:3000/api/auth/google/callback?state=state&code=code ``` diff --git a/oauth2-google/auth/auth.go b/oauth2-google/auth/auth.go index 21cdbbfc1b..c627b8f400 100644 --- a/oauth2-google/auth/auth.go +++ b/oauth2-google/auth/auth.go @@ -2,13 +2,14 @@ package auth import ( "encoding/json" - "fiber-oauth-google/config" - "fiber-oauth-google/model" "fmt" "io" "net/http" "net/url" + "fiber-oauth-google/config" + "fiber-oauth-google/model" + "golang.org/x/oauth2" "golang.org/x/oauth2/google" ) @@ -20,7 +21,8 @@ func ConfigGoogle() *oauth2.Config { ClientSecret: config.Config("Secret"), RedirectURL: config.Config("redirect_url"), Scopes: []string{ - "https://www.googleapis.com/auth/userinfo.email"}, // you can use other scopes to get more data + "https://www.googleapis.com/auth/userinfo.email", + }, // you can use other scopes to get more data Endpoint: google.Endpoint, } return conf @@ -37,12 +39,12 @@ func GetEmail(token string) string { Method: "GET", URL: reqURL, Header: map[string][]string{ - "Authorization": {ptoken}}, + "Authorization": {ptoken}, + }, } req, err := http.DefaultClient.Do(res) if err != nil { panic(err) - } defer req.Body.Close() body, err := io.ReadAll(req.Body) diff --git a/oauth2-google/handler/handler.go b/oauth2-google/handler/handler.go index 9edac840a1..6408c5567d 100644 --- a/oauth2-google/handler/handler.go +++ b/oauth2-google/handler/handler.go @@ -11,7 +11,6 @@ func Auth(c *fiber.Ctx) error { path := auth.ConfigGoogle() url := path.AuthCodeURL("state") return c.Redirect(url) - } // Callback to receive google's response @@ -22,5 +21,4 @@ func Callback(c *fiber.Ctx) error { } email := auth.GetEmail(token.AccessToken) return c.Status(200).JSON(fiber.Map{"email": email, "login": true}) - } diff --git a/oauth2-google/main.go b/oauth2-google/main.go index 5085ddadcd..2fa5be2d18 100644 --- a/oauth2-google/main.go +++ b/oauth2-google/main.go @@ -12,5 +12,4 @@ func main() { app := fiber.New() router.Routes(app) app.Listen(":3300") - } diff --git a/oauth2-google/router/router.go b/oauth2-google/router/router.go index 4758fa0961..d64c6ce8ac 100644 --- a/oauth2-google/router/router.go +++ b/oauth2-google/router/router.go @@ -12,5 +12,4 @@ func Routes(app *fiber.App) { api := app.Group("/api", logger.New()) api.Get("/", handler.Auth) api.Get("/auth/google/callback", handler.Callback) - } diff --git a/oauth2/app.go b/oauth2/app.go index 485541aeac..5721c8db33 100644 --- a/oauth2/app.go +++ b/oauth2/app.go @@ -5,14 +5,15 @@ import ( "fmt" "io/fs" "net/http" - "oauth2/config" - "oauth2/models" - "oauth2/router" "os" "os/signal" "syscall" "time" + "oauth2/config" + "oauth2/models" + "oauth2/router" + "github.com/antigloss/go/logger" "github.com/gofiber/fiber/v2" "github.com/gofiber/fiber/v2/middleware/session" @@ -46,7 +47,6 @@ func main() { LogDest: logger.LogDestFile, //| logger.LogDestConsole, Flag: logger.ControlFlagLogDate | logger.ControlFlagLogLineNum, }) - if err != nil { panic(err) } diff --git a/oauth2/handlers/handlers.go b/oauth2/handlers/handlers.go index 7b42455cc7..89cc1f6c5c 100644 --- a/oauth2/handlers/handlers.go +++ b/oauth2/handlers/handlers.go @@ -11,7 +11,7 @@ func HTMLPages(c *fiber.Ctx) error { models.SYSLOG.Tracef("entering HtmlPages; original URL: %v", c.OriginalURL()) defer models.SYSLOG.Trace("exiting HtmlPages") - //models.SYSLOG.Tracef("inspecting header: %v", &c.Request().Header) + // models.SYSLOG.Tracef("inspecting header: %v", &c.Request().Header) p := c.Path() switch p { diff --git a/oauth2/middleware/auth.go b/oauth2/middleware/auth.go index 976c0299c5..d112f5d78d 100644 --- a/oauth2/middleware/auth.go +++ b/oauth2/middleware/auth.go @@ -2,6 +2,7 @@ package middleware import ( "fmt" + "oauth2/models" "github.com/gofiber/fiber/v2" @@ -10,7 +11,6 @@ import ( // OAUTHRedirect performs the GitHub OAUTH2 login sequence and stored the token in a session variable func OAUTHRedirect(ctx *fiber.Ctx) error { - models.SYSLOG.Tracef("entering OAUTHRedirect; original URL: %v", ctx.OriginalURL()) defer models.SYSLOG.Trace("exiting OAUTHRedirect") @@ -52,7 +52,7 @@ func OAUTHRedirect(ctx *fiber.Ctx) error { models.SYSLOG.Tracef("setting session token %v", t.AccessToken) sessData, _ := models.MySessionStore.Get(ctx) defer sessData.Save() - //models.MySessionStore.RegisterType(models.OAuthAccessResponse) + // models.MySessionStore.RegisterType(models.OAuthAccessResponse) sessData.Set("oauth-scope", t.Scope) sessData.Set("oauth-token-type", t.TokenType) sessData.Set("oauth-token", t.AccessToken) diff --git a/oauth2/router/router.go b/oauth2/router/router.go index a4ac6fe6db..e3235488ca 100644 --- a/oauth2/router/router.go +++ b/oauth2/router/router.go @@ -12,7 +12,6 @@ import ( // SetupRoutes prepares required routes func SetupRoutes(app *fiber.App) { - app.Use(cors.New(cors.Config{ // attempt to mitigate CORS issues - pay attention to last / AllowOrigins: "http://localhost:8080, http://localhost:8080/, https://api.github.com/user, https://api.github.com/user/,", // diff --git a/optional-parameter/README.md b/optional-parameter/README.md index fada14f916..43f15ae8bd 100644 --- a/optional-parameter/README.md +++ b/optional-parameter/README.md @@ -19,12 +19,14 @@ Ensure you have the following installed: ## Setup 1. Clone the repository: + ```sh git clone https://github.com/gofiber/recipes.git cd recipes/optional-parameter ``` 2. Install dependencies: + ```sh go get ``` @@ -32,6 +34,7 @@ Ensure you have the following installed: ## Running the Application 1. Start the application: + ```sh go run main.go ``` @@ -60,6 +63,7 @@ func main() { ``` In this example: + - The `:id?` parameter in the route is optional. - If the `id` parameter is not provided, it defaults to `"defaultID"`. diff --git a/optional-parameter/main.go b/optional-parameter/main.go index 10192a32fb..73da55a45a 100644 --- a/optional-parameter/main.go +++ b/optional-parameter/main.go @@ -12,7 +12,6 @@ import ( ) func main() { - // user list users := [...]string{"Alice", "Bob", "Charlie", "David"} diff --git a/overview.go b/overview.go index 19c743f55b..e616d5b523 100644 --- a/overview.go +++ b/overview.go @@ -73,7 +73,7 @@ func main() { re := regexp.MustCompile(`(?s)(.*?)`) newContent := re.ReplaceAllString(string(content), fmt.Sprintf("\n%s", toc)) - err = os.WriteFile(readmePath, []byte(newContent), 0644) + err = os.WriteFile(readmePath, []byte(newContent), 0o644) if err != nil { fmt.Println("Error:", err) return @@ -174,5 +174,5 @@ func addLinksToReadme(readmePath, dirName string) error { cleanedLines := append(lines[:start], append([]string{"", links, ""}, lines[end:]...)...) content = []byte(strings.Join(cleanedLines, "\n")) - return os.WriteFile(readmePath, content, 0644) + return os.WriteFile(readmePath, content, 0o644) } diff --git a/parsley/cmd/main.go b/parsley/cmd/main.go index 0d8f712572..fb5e62f2b0 100644 --- a/parsley/cmd/main.go +++ b/parsley/cmd/main.go @@ -2,6 +2,7 @@ package main import ( "context" + "parsley-app/internal" "parsley-app/internal/modules" @@ -9,7 +10,6 @@ import ( ) func main() { - context := context.Background() // Runs a Fiber instance as a Parsley-enabled app diff --git a/parsley/internal/application.go b/parsley/internal/application.go index 37f575880d..e78625a76d 100644 --- a/parsley/internal/application.go +++ b/parsley/internal/application.go @@ -2,6 +2,7 @@ package internal import ( "context" + "parsley-app/internal/route_handlers" "github.com/gofiber/fiber/v2" @@ -16,7 +17,6 @@ var _ bootstrap.Application = &parsleyApplication{} // NewApp Creates the main application service instance. This constructor function gets invoked by Parsley; add parameters for all required services. func NewApp(app *fiber.App, routeHandlers []route_handlers.RouteHandler) bootstrap.Application { - // Register RouteHandler services with the resolved Fiber instance. for _, routeHandler := range routeHandlers { routeHandler.Register(app) diff --git a/parsley/internal/modules/fiber_module.go b/parsley/internal/modules/fiber_module.go index 283de495af..25da25124f 100644 --- a/parsley/internal/modules/fiber_module.go +++ b/parsley/internal/modules/fiber_module.go @@ -10,7 +10,6 @@ var _ types.ModuleFunc = ConfigureFiber // ConfigureFiber Configures all services required by the Fiber app. func ConfigureFiber(registry types.ServiceRegistry) error { - registration.RegisterInstance(registry, fiber.Config{ AppName: "parsley-app-recipe", Immutable: true, diff --git a/parsley/internal/modules/route_handlers_module.go b/parsley/internal/modules/route_handlers_module.go index 3cb5bc13c0..5097eaa2de 100644 --- a/parsley/internal/modules/route_handlers_module.go +++ b/parsley/internal/modules/route_handlers_module.go @@ -17,7 +17,6 @@ import ( // Returns: // - error: Any error that occurred during the registration process. func RegisterRouteHandlers(registry types.ServiceRegistry) error { - // The Parsley app requires a list of RouteHandler instances, so we must enable it. features.RegisterList[route_handlers.RouteHandler](registry) diff --git a/parsley/internal/route_handlers/greeter.go b/parsley/internal/route_handlers/greeter.go index c9c2255a3b..4e1a76ca20 100644 --- a/parsley/internal/route_handlers/greeter.go +++ b/parsley/internal/route_handlers/greeter.go @@ -1,9 +1,10 @@ package route_handlers import ( - "parsley-app/internal/services" "strconv" + "parsley-app/internal/services" + "github.com/gofiber/fiber/v2" ) @@ -20,7 +21,6 @@ func (h *greeterRouteHandler) Register(app *fiber.App) { // HandleSayHelloRequest Handles "GET /say-hello" requests. func (h *greeterRouteHandler) HandleSayHelloRequest(ctx *fiber.Ctx) error { - name := ctx.Query("name") politeFlag := ctx.Query("polite", defaultPoliteFlag) diff --git a/parsley/internal/services/greeter.go b/parsley/internal/services/greeter.go index c6d52c80b1..be04510725 100644 --- a/parsley/internal/services/greeter.go +++ b/parsley/internal/services/greeter.go @@ -6,8 +6,7 @@ type Greeter interface { SayHello(name string, polite bool) string } -type greeter struct { -} +type greeter struct{} // SayHello Generates a greeter message for the given user. func (g *greeter) SayHello(name string, polite bool) string { diff --git a/postgresql/README.md b/postgresql/README.md index 7f28692aee..bed2593688 100644 --- a/postgresql/README.md +++ b/postgresql/README.md @@ -20,12 +20,14 @@ Ensure you have the following installed: ## Setup 1. Clone the repository: + ```sh git clone https://github.com/gofiber/recipes.git cd recipes/postgresql ``` 2. Install dependencies: + ```sh go get ``` @@ -35,6 +37,7 @@ Ensure you have the following installed: ## Running the Application 1. Start the application: + ```sh go run main.go ``` diff --git a/prefork/README.md b/prefork/README.md index ed713bf370..dc57cc2ca0 100644 --- a/prefork/README.md +++ b/prefork/README.md @@ -19,12 +19,14 @@ Ensure you have the following installed: ## Setup 1. Clone the repository: + ```sh git clone https://github.com/gofiber/recipes.git cd recipes/prefork ``` 2. Install dependencies: + ```sh go get ``` @@ -32,6 +34,7 @@ Ensure you have the following installed: ## Running the Application 1. Start the application: + ```sh go run main.go ``` diff --git a/recover/README.md b/recover/README.md index 5a139b1427..a1069ca588 100644 --- a/recover/README.md +++ b/recover/README.md @@ -19,12 +19,14 @@ Ensure you have the following installed: ## Setup 1. Clone the repository: + ```sh git clone https://github.com/gofiber/recipes.git cd recipes/recover ``` 2. Install dependencies: + ```sh go get ``` @@ -32,6 +34,7 @@ Ensure you have the following installed: ## Running the Application 1. Start the application: + ```sh go run main.go ``` diff --git a/rss-feed/README.md b/rss-feed/README.md index 18a491766f..105c1c3ceb 100644 --- a/rss-feed/README.md +++ b/rss-feed/README.md @@ -19,12 +19,14 @@ Ensure you have the following installed: ## Setup 1. Clone the repository: + ```sh git clone https://github.com/gofiber/recipes.git cd recipes/rss-feed ``` 2. Install dependencies: + ```sh go get ``` @@ -32,6 +34,7 @@ Ensure you have the following installed: ## Running the Application 1. Start the application: + ```sh go run main.go ``` diff --git a/server-timing/README.md b/server-timing/README.md index 57cf25de32..670a0936b7 100644 --- a/server-timing/README.md +++ b/server-timing/README.md @@ -19,12 +19,14 @@ Ensure you have the following installed: ## Setup 1. Clone the repository: + ```sh git clone https://github.com/gofiber/recipes.git cd recipes/server-timing ``` 2. Install dependencies: + ```sh go get ``` @@ -32,6 +34,7 @@ Ensure you have the following installed: ## Running the Application 1. Start the application: + ```sh go run main.go ``` diff --git a/sessions-sqlite3/README.md b/sessions-sqlite3/README.md index 6426f0e1e6..42cda4ca8d 100644 --- a/sessions-sqlite3/README.md +++ b/sessions-sqlite3/README.md @@ -23,17 +23,20 @@ The default table schema only stores session data and expiry, making it difficul ## Setup 1. Clone the repository: + ```sh git clone https://github.com/gofiber/recipes.git cd recipes/sessions-sqlite3 ``` 2. Install dependencies: + ```sh go mod tidy ``` 3. Create the sessions table in SQLite3: + ```sql CREATE TABLE sessions ( key TEXT PRIMARY KEY, @@ -46,6 +49,7 @@ The default table schema only stores session data and expiry, making it difficul ## Running the Application 1. Run the application: + ```sh go run main.go ``` diff --git a/sessions-sqlite3/main.go b/sessions-sqlite3/main.go index d68d986e94..b432860f4e 100755 --- a/sessions-sqlite3/main.go +++ b/sessions-sqlite3/main.go @@ -100,7 +100,7 @@ func main() { // Get session ID sid := s.ID() - //Get user ID + // Get user ID uid := req.UID // Save session data diff --git a/socketio/README.md b/socketio/README.md index 20edb8040f..ab45dc642d 100644 --- a/socketio/README.md +++ b/socketio/README.md @@ -17,12 +17,14 @@ This example demonstrates how to create a simple chatroom using WebSockets. The ## Setup 1. Clone the repository: + ```sh git clone https://github.com/gofiber/recipes.git cd recipes/socketio-chat ``` 2. Install dependencies: + ```sh go mod tidy ``` @@ -30,6 +32,7 @@ This example demonstrates how to create a simple chatroom using WebSockets. The ## Running the Application 1. Run the application: + ```sh go run main.go ``` @@ -39,6 +42,7 @@ This example demonstrates how to create a simple chatroom using WebSockets. The ## Connecting to the WebSocket To connect to the WebSocket, use the following URL: + ``` ws://localhost:3000/ws/ ``` @@ -46,6 +50,7 @@ ws://localhost:3000/ws/ ## Message Object Example Here is an example of a message object that can be sent between users: + ```json { "from": "", diff --git a/socketio/main.go b/socketio/main.go index a18161616c..2db4322430 100644 --- a/socketio/main.go +++ b/socketio/main.go @@ -9,10 +9,11 @@ package main import ( "encoding/json" "fmt" + "log" + "github.com/gofiber/contrib/socketio" "github.com/gofiber/contrib/websocket" "github.com/gofiber/fiber/v2" - "log" ) // MessageObject Basic chat message object @@ -23,7 +24,6 @@ type MessageObject struct { } func main() { - // The key for the map is message.to clients := make(map[string]string) @@ -51,7 +51,6 @@ func main() { // On message event socketio.On(socketio.EventMessage, func(ep *socketio.EventPayload) { - fmt.Println(fmt.Sprintf("Message event - User: %s - Message: %s", ep.Kws.GetStringAttribute("user_id"), string(ep.Data))) message := MessageObject{} @@ -96,7 +95,6 @@ func main() { }) app.Get("/ws/:id", socketio.New(func(kws *socketio.Websocket) { - // Retrieve the user id from endpoint userId := kws.Params("id") @@ -108,12 +106,11 @@ func main() { // Every websocket connection has an optional session key => value storage kws.SetAttribute("user_id", userId) - //Broadcast to all the connected users the newcomer + // Broadcast to all the connected users the newcomer kws.Broadcast([]byte(fmt.Sprintf("New user connected: %s and UUID: %s", userId, kws.UUID)), true) - //Write welcome message + // Write welcome message kws.Emit([]byte(fmt.Sprintf("Hello user: %s with UUID: %s", userId, kws.UUID))) })) log.Fatal(app.Listen(":3000")) - } diff --git a/spa/README.md b/spa/README.md index ea06526827..e5e42a8bfa 100644 --- a/spa/README.md +++ b/spa/README.md @@ -20,18 +20,21 @@ Ensure you have the following installed: ## Setup 1. Clone the repository: + ```sh git clone https://github.com/gofiber/recipes.git cd recipes/spa ``` 2. Install frontend dependencies: + ```sh cd frontend npm install ``` 3. Install backend dependencies: + ```sh cd ../backend go get @@ -42,12 +45,14 @@ Ensure you have the following installed: ### Building Frontend Assets 1. Build the frontend assets: + ```sh cd frontend npm run build ``` 2. Watch frontend assets for changes: + ```sh npm run dev ``` @@ -55,6 +60,7 @@ Ensure you have the following installed: ### Running the Application 1. Start the Fiber backend application: + ```sh cd backend go run main.go diff --git a/sqlboiler/README.md b/sqlboiler/README.md index a61b296552..10ccff893e 100644 --- a/sqlboiler/README.md +++ b/sqlboiler/README.md @@ -10,14 +10,19 @@ keywords: [sqlboiler, database, docker] > #### 🎯 [Fiber](https://github.com/gofiber/fiber) + [Sqlboiler](https://github.com/volatiletech/sqlboiler) Example ## 👀 Usage + #### 1. Run Postgres + ```bash -$ docker compose build +docker compose build ``` + ```bash -$ docker compose up +docker compose up ``` + #### 2. Wait 1-2 minutes + ```console [+] Running 2/0 ✔ Network sqlboiler_default Created 0.0s @@ -33,21 +38,30 @@ postgres | 2023-09-22 01:09:46.454 UTC [1] LOG: listening on Unix socket "/var postgres | 2023-09-22 01:09:46.461 UTC [30] LOG: database system was shut down at 2023-09-22 01:09:44 UTC postgres | 2023-09-22 01:09:46.468 UTC [1] LOG: database system is ready to accept connections ``` -#### 3. You have to migrate the database. -> ###### 🎯 It is a "database-first" ORM as opposed to "code-first" (like gorm/gorp). That means you must first create your database schema. -> ###### 🎯 I used [golang-migrate](https://github.com/golang-migrate/migrate) to proceed with the migrate. + +#### 3. You have to migrate the database +> +> ###### 🎯 It is a "database-first" ORM as opposed to "code-first" (like gorm/gorp). That means you must first create your database schema +> +> ###### 🎯 I used [golang-migrate](https://github.com/golang-migrate/migrate) to proceed with the migrate +> ###### 1. Make Migration files + ```bash -$ migrate create -ext sql -dir ./migrations -seq create_initial_table +migrate create -ext sql -dir ./migrations -seq create_initial_table ``` + ```console sqlboiler/migrations/000001_create_initial_table.up.sql sqlboiler/migrations/000001_create_initial_table.up.sql ``` + ###### 2. Migrate + ```bash -$ migrate -path migrations -database "postgresql://user:password@localhost:5432/fiber_demo?sslmode=disable" -verbose up +migrate -path migrations -database "postgresql://user:password@localhost:5432/fiber_demo?sslmode=disable" -verbose up ``` + ```console 2023/09/22 20:00:00 Start buffering 1/u create_initial_table 2023/09/22 20:00:00 Read and execute 1/u create_initial_table @@ -55,10 +69,13 @@ $ migrate -path migrations -database "postgresql://user:password@localhost:5432/ 2023/09/22 20:00:00 Finished after 100.661625ms 2023/09/22 20:00:00 Closing source and database ``` + ###### 3. Rollback Migrate + ```bash -$ migrate -path migrations -database "postgresql://user:password@localhost:5432/fiber_demo?sslmode=disable" -verbose down +migrate -path migrations -database "postgresql://user:password@localhost:5432/fiber_demo?sslmode=disable" -verbose down ``` + ```console 2023/09/22 20:00:00 Are you sure you want to apply all down migrations? [y/N] y @@ -68,16 +85,23 @@ y 2023/09/22 20:00:00 Finished 1/d create_initial_table (read 39.681125ms, ran 66.220125ms) 2023/09/22 20:00:00 Finished after 1.83152475s ``` + #### 4. Use sqlboiler + ###### 1. Install + ```bash # Go 1.16 and above: $ go install github.com/volatiletech/sqlboiler/v4@latest $ go install github.com/volatiletech/sqlboiler/v4/drivers/sqlboiler-psql@latest ``` + ###### 2. Create a configuration file +> > ###### 🎯 The configuration file should be named sqlboiler.toml +> ###### Example + ```toml output = "models" wipe = true @@ -93,11 +117,15 @@ add-enum-types = true schema = "schema" blacklist = ["migrations", "other"] ``` + ###### 3. Create models -> ###### 🎯 After creating a configuration file that points at the database we want to generate models for, we can invoke the sqlboiler command line utility. +> +> ###### 🎯 After creating a configuration file that points at the database we want to generate models for, we can invoke the sqlboiler command line utility + ```bash -$ sqlboiler psql +sqlboiler psql ``` + ```text models/ ├── author.go diff --git a/sqlboiler/api/controller/author_controller.go b/sqlboiler/api/controller/author_controller.go index 858b94e696..e29fe678bf 100644 --- a/sqlboiler/api/controller/author_controller.go +++ b/sqlboiler/api/controller/author_controller.go @@ -2,9 +2,10 @@ package controller import ( "context" + "strconv" + "fiber-sqlboiler/database" "fiber-sqlboiler/models" - "strconv" "github.com/gofiber/fiber/v2" "github.com/volatiletech/sqlboiler/v4/boil" diff --git a/sqlboiler/api/controller/post_controller.go b/sqlboiler/api/controller/post_controller.go index 73032d2de0..e6077eefe9 100644 --- a/sqlboiler/api/controller/post_controller.go +++ b/sqlboiler/api/controller/post_controller.go @@ -2,9 +2,10 @@ package controller import ( "context" + "strconv" + "fiber-sqlboiler/database" "fiber-sqlboiler/models" - "strconv" "github.com/gofiber/fiber/v2" "github.com/volatiletech/sqlboiler/v4/boil" diff --git a/sqlboiler/main.go b/sqlboiler/main.go index a824c472ff..d4b1655ad8 100644 --- a/sqlboiler/main.go +++ b/sqlboiler/main.go @@ -1,9 +1,10 @@ package main import ( + "log" + "fiber-sqlboiler/api/route" "fiber-sqlboiler/database" - "log" "github.com/gofiber/fiber/v2" ) diff --git a/sqlc/README.md b/sqlc/README.md index c3e2fab935..ba2aac0610 100644 --- a/sqlc/README.md +++ b/sqlc/README.md @@ -10,14 +10,19 @@ keywords: [database, sqlc, postgresql] > #### 🎯 [fiber](https://github.com/gofiber/fiber) + [sqlc](https://github.com/sqlc-dev/sqlc) Example ## 👀 Usage + #### 1. Run Postgres + ```bash -$ docker compose build +docker compose build ``` + ```bash -$ docker compose up +docker compose up ``` + #### 2. Wait 1-2 minutes + ```console [+] Running 2/0 ✔ Network sqlc_default Created 0.1s @@ -34,21 +39,30 @@ postgres | 2023-09-28 09:17:50.740 UTC [1] LOG: listening on Unix socket "/var postgres | 2023-09-28 09:17:50.751 UTC [30] LOG: database system was shut down at 2023-09-28 08:50:35 UTC postgres | 2023-09-28 09:17:50.770 UTC [1] LOG: database system is ready to accept connections ``` -#### 3. You have to migrate the database. -> ##### 🎯 It is a "database-first" ORM as opposed to "code-first" (like gorm/gorp). That means you must first create your database schema. -> ##### 🎯 I used [golang-migrate](https://github.com/golang-migrate/migrate) to proceed with the migrate. + +#### 3. You have to migrate the database +> +> ##### 🎯 It is a "database-first" ORM as opposed to "code-first" (like gorm/gorp). That means you must first create your database schema +> +> ##### 🎯 I used [golang-migrate](https://github.com/golang-migrate/migrate) to proceed with the migrate +> ###### 1. Make Migration files + ```bash -$ migrate create -ext sql -dir ./database/migrations -seq create_initial_table +migrate create -ext sql -dir ./database/migrations -seq create_initial_table ``` + ```console sqlc/database/migrations/000001_create_initial_table.up.sql sqlc/database/migrations/000001_create_initial_table.up.sql ``` + ###### 2. Migrate + ```bash -$ migrate -path database/migrations -database "postgresql://user:password@localhost:5432/fiber_demo?sslmode=disable" -verbose up +migrate -path database/migrations -database "postgresql://user:password@localhost:5432/fiber_demo?sslmode=disable" -verbose up ``` + ```console 2023/09/28 20:00:00 Start buffering 1/u create_initial_table 2023/09/28 20:00:00 Read and execute 1/u create_initial_table @@ -56,10 +70,13 @@ $ migrate -path database/migrations -database "postgresql://user:password@localh 2023/09/28 20:00:00 Finished after 100.661625ms 2023/09/28 20:00:00 Closing source and database ``` + ###### 3. Rollback Migrate + ```bash -$ migrate -path database/migrations -database "postgresql://user:password@localhost:5432/fiber_demo?sslmode=disable" -verbose down +migrate -path database/migrations -database "postgresql://user:password@localhost:5432/fiber_demo?sslmode=disable" -verbose down ``` + ```console 2023/09/28 20:00:00 Are you sure you want to apply all down migrations? [y/N] y @@ -69,8 +86,11 @@ y 2023/09/28 20:00:00 Finished 1/d create_initial_table (read 39.681125ms, ran 66.220125ms) 2023/09/28 20:00:00 Finished after 1.83152475s ``` + #### 4. Use sqlc + ###### 1. Install + ```bash # Go 1.17 and above: $ go install github.com/sqlc-dev/sqlc/cmd/sqlc@latest @@ -78,9 +98,13 @@ $ go install github.com/sqlc-dev/sqlc/cmd/sqlc@latest # Go 1.16 and below: go get github.com/sqlc-dev/sqlc/cmd/sqlc ``` + ###### 2. Create a configuration file + ###### Example + ###### sqlc.yaml + ```yaml version: "2" sql: @@ -92,7 +116,9 @@ sql: package: "sqlc" out: "database/sqlc" ``` + ###### author.sql + ```sql -- name: GetAuthors :many SELECT * FROM author; @@ -109,7 +135,9 @@ UPDATE author SET email = $1, name = $2 WHERE id = $3 RETURNING *; -- name: DeleteAuthor :exec DELETE FROM author WHERE id = $1; ``` + ###### post.sql + ```sql -- name: GetPosts :many SELECT * FROM post; @@ -127,10 +155,13 @@ UPDATE post SET title = $1, content = $2, author = $3 WHERE id = $4 RETURNING *; DELETE FROM post WHERE id = $1; ``` + ###### 3. Generate + ```bash -$ sqlc generate +sqlc generate ``` + ```text sqlc/ ├── author.sql.go @@ -138,5 +169,7 @@ sqlc/ ├── models.go ├── post.sql.go ``` + #### 5. Reference + [sqlc document](https://docs.sqlc.dev/en/stable/) diff --git a/sqlc/api/controller/author_controller.go b/sqlc/api/controller/author_controller.go index 0a5e7ae14d..d56c5e8300 100644 --- a/sqlc/api/controller/author_controller.go +++ b/sqlc/api/controller/author_controller.go @@ -2,11 +2,12 @@ package controller import ( "context" - "fiber-sqlc/database" - "fiber-sqlc/database/sqlc" "strconv" "time" + "fiber-sqlc/database" + "fiber-sqlc/database/sqlc" + "github.com/gofiber/fiber/v2" ) diff --git a/sqlc/api/controller/post_controller.go b/sqlc/api/controller/post_controller.go index 7885440266..e488505005 100644 --- a/sqlc/api/controller/post_controller.go +++ b/sqlc/api/controller/post_controller.go @@ -2,11 +2,12 @@ package controller import ( "context" - "fiber-sqlc/database" - "fiber-sqlc/database/sqlc" "strconv" "time" + "fiber-sqlc/database" + "fiber-sqlc/database/sqlc" + "github.com/gofiber/fiber/v2" ) diff --git a/sqlc/main.go b/sqlc/main.go index ac22e33d85..3311a5ee16 100644 --- a/sqlc/main.go +++ b/sqlc/main.go @@ -1,9 +1,10 @@ package main import ( + "log" + "fiber-sqlc/api/route" "fiber-sqlc/database" - "log" "github.com/gofiber/fiber/v2" ) diff --git a/sse/README.md b/sse/README.md index ebee76e764..40babc24c0 100644 --- a/sse/README.md +++ b/sse/README.md @@ -21,12 +21,14 @@ Server-Sent Events (SSE) allow servers to push updates to the client over a sing ## Setup 1. Clone the repository: + ```sh git clone https://github.com/gofiber/recipes.git cd recipes/sse ``` 2. Install dependencies: + ```sh go mod tidy ``` @@ -34,6 +36,7 @@ Server-Sent Events (SSE) allow servers to push updates to the client over a sing ## Running the Application 1. Run the application: + ```sh go run main.go ``` @@ -65,5 +68,6 @@ The HTML file provides a simple user interface to connect to the SSE endpoint an Server-Sent Events (SSE) is a standard allowing servers to push data to web clients over HTTP. Unlike WebSockets, which require a full-duplex connection, SSE uses a unidirectional connection from the server to the client. This makes SSE simpler to implement and more efficient for scenarios where only the server needs to send updates. For more information on SSE, you can refer to the following resources: + - [Server-Sent Events on MDN](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events) - [Server-Sent Events on Wikipedia](https://en.wikipedia.org/wiki/Server-sent_events) diff --git a/stream-request-body/README.md b/stream-request-body/README.md index d315fbe83e..016c29bedf 100644 --- a/stream-request-body/README.md +++ b/stream-request-body/README.md @@ -19,12 +19,14 @@ Ensure you have the following installed: ## Setup 1. Clone the repository: + ```sh git clone https://github.com/gofiber/recipes.git cd recipes/stream-request-body ``` 2. Install dependencies: + ```sh go get ``` @@ -32,6 +34,7 @@ Ensure you have the following installed: ## Running the Application 1. Start the application: + ```sh go run main.go ``` diff --git a/svelte-netlify/README.md b/svelte-netlify/README.md index c1512de5b0..1e95e3f5c5 100644 --- a/svelte-netlify/README.md +++ b/svelte-netlify/README.md @@ -9,13 +9,12 @@ keywords: [netlify, deploy, svelte] [![Netlify Status](https://api.netlify.com/api/v1/badges/143c3c42-60f7-427a-b3fd-8ca3947a2d40/deploy-status)](https://app.netlify.com/sites/gofiber-svelte/deploys) -### Demo @ https://gofiber-svelte.netlify.app/ +### Demo @ #### Based on the fiber-lambda API written by Fenny. Since the code hasn't been merged yet, I borrowed it into `adapter/adapter.go` The app uses static pages under `public` directory. These are compiled using sveltejs and the complete template can be found [here](https://github.com/amalshaji/gofiber-sveltejs-netlify). - ```toml # netlify.toml @@ -37,6 +36,7 @@ The app uses static pages under `public` directory. These are compiled using sve Deploying `net/http to Netlify` explains what these functions are doing. You can read it [here](https://blog.carlmjohnson.net/post/2020/how-to-host-golang-on-netlify-for-free/). #### TL;DR + - build command builds the whole code to binary `cmd/gateway/gateway` - we're building something called [netlify functions](https://functions.netlify.com/) (Please read) - everything under public folder will be published(entrypoint: `index.html`) @@ -44,4 +44,5 @@ Deploying `net/http to Netlify` explains what these functions are doing. You can - status = 200 for server side redirects #### Important + Netlify functions allows you to have up to 125,000 requests a month. This means you can have 2.89 requests per minute. Make sure you use `Cache` in you request handlers. diff --git a/svelte-netlify/adapter/adapter.go b/svelte-netlify/adapter/adapter.go index 30c8d4447d..65cd15f521 100644 --- a/svelte-netlify/adapter/adapter.go +++ b/svelte-netlify/adapter/adapter.go @@ -52,7 +52,6 @@ func (f *FiberLambda) ProxyWithContext(ctx context.Context, req events.APIGatewa } func (f *FiberLambda) proxyInternal(req *http.Request, err error) (events.APIGatewayProxyResponse, error) { - if err != nil { return core.GatewayTimeout(), core.NewLoggedError("Could not convert proxy event to request: %v", err) } diff --git a/sveltekit-embed/README.md b/sveltekit-embed/README.md index 3dad48a1b5..6f8a0ef9c9 100644 --- a/sveltekit-embed/README.md +++ b/sveltekit-embed/README.md @@ -20,15 +20,16 @@ To run the project, follow these steps: ```bash make all ``` + 2. Once the build process is complete, you can start the application by running: + ```bash ./app ``` - ## Available Commands -The following commands are available to manage the project: +The following commands are available to manage the project: | Command | Description | | --- | --- | @@ -45,7 +46,6 @@ To use this application, run the following command: make ``` - API Routes ---------- @@ -58,17 +58,16 @@ The Go Fiber application provides the following API routes: Go Dependencies --------------- -- **Go Modules:** Go's built-in package manager used to manage dependencies for Go projects. -- **Fiber:** A fast and minimalist web framework for Golang. +- **Go Modules:** Go's built-in package manager used to manage dependencies for Go projects. +- **Fiber:** A fast and minimalist web framework for Golang. Npm Dependencies ---------------- -- **SvelteKit:** A JavaScript framework used to build modern web applications. -- **Tailwind CSS:** A fast and customizable CSS styling library. Can be used in SvelteKit projects. -- **Skeleton UI:** This is a fully featured UI Toolkit for building reactive interfaces quickly using Svelte and Tailwind. +- **SvelteKit:** A JavaScript framework used to build modern web applications. +- **Tailwind CSS:** A fast and customizable CSS styling library. Can be used in SvelteKit projects. +- **Skeleton UI:** This is a fully featured UI Toolkit for building reactive interfaces quickly using Svelte and Tailwind. ---------------- Author: [@ugurkorkmaz](https://github.com/ugurkorkmaz) - diff --git a/swagger/README.md b/swagger/README.md index 983c7711fb..886fd00ad8 100644 --- a/swagger/README.md +++ b/swagger/README.md @@ -19,12 +19,14 @@ Ensure you have the following installed: ## Setup 1. Clone the repository: + ```sh git clone https://github.com/gofiber/recipes.git cd recipes/swagger ``` 2. Install dependencies: + ```sh go get -u github.com/swaggo/swag/cmd/swag go get -u github.com/swaggo/gin-swagger @@ -34,6 +36,7 @@ Ensure you have the following installed: ## Generating Swagger Docs 1. Generate the Swagger documentation: + ```sh swag init ``` @@ -41,6 +44,7 @@ Ensure you have the following installed: ## Running the Application 1. Start the application: + ```sh go run main.go ``` diff --git a/swagger/database/connection.go b/swagger/database/connection.go index c07701390d..be6b0a82a0 100644 --- a/swagger/database/connection.go +++ b/swagger/database/connection.go @@ -34,7 +34,6 @@ func Connect() (err error) { } sqlDB, err := DBConn.DB() - if err != nil { return err } diff --git a/swagger/routes/routes.go b/swagger/routes/routes.go index 0a2cca2847..ec52dd8741 100644 --- a/swagger/routes/routes.go +++ b/swagger/routes/routes.go @@ -20,7 +20,7 @@ func New() *fiber.App { })) swaggerCfg := swagger.Config{ - BasePath: "/docs", //swagger ui base path + BasePath: "/docs", // swagger ui base path FilePath: "./docs/swagger.json", } diff --git a/tableflip/README.md b/tableflip/README.md index 59087458e9..a4df5c754f 100644 --- a/tableflip/README.md +++ b/tableflip/README.md @@ -24,28 +24,34 @@ Tableflip is a library that allows you to update the running code and/or configu ## Steps 1. **Build v0.0.1 Demo:** + ```bash go build -o demo main.go ``` 2. **Run the Demo and Create a GET Request to `127.0.0.1:8080/version`:** + ```bash [PID: 123] v0.0.1 ``` 3. **Prepare a New Version:** - - Change the `main.go` to update the version to "v0.0.2". - - Rebuild the demo: + +- Change the `main.go` to update the version to "v0.0.2". +- Rebuild the demo: + ```bash go build -o demo main.go ``` 4. **Kill the Old Process:** + ```bash kill -s HUP 123 ``` 5. **Create the Request to the Version API Again:** + ```bash [PID: 123] v0.0.2 ``` diff --git a/tableflip/main.go b/tableflip/main.go index 12260eccde..c887bbc0a3 100644 --- a/tableflip/main.go +++ b/tableflip/main.go @@ -2,12 +2,13 @@ package main import ( "fmt" - "github.com/cloudflare/tableflip" - "github.com/gofiber/fiber/v2" "log" "os" "os/signal" "syscall" + + "github.com/cloudflare/tableflip" + "github.com/gofiber/fiber/v2" ) const version = "v0.0.1" diff --git a/template-asset-bundling/README.md b/template-asset-bundling/README.md index daf0925855..9e4a142775 100644 --- a/template-asset-bundling/README.md +++ b/template-asset-bundling/README.md @@ -20,12 +20,14 @@ Ensure you have the following installed: ## Setup 1. Clone the repository: + ```sh git clone https://github.com/gofiber/recipes.git cd recipes/template-asset-bundling ``` 2. Install dependencies: + ```sh npm install ``` @@ -35,11 +37,13 @@ Ensure you have the following installed: ### Building Assets 1. Build the assets: + ```sh npm run build ``` 2. Watch assets for changes: + ```sh npm run dev ``` @@ -47,6 +51,7 @@ Ensure you have the following installed: ### Running the Application 1. Start the Fiber application: + ```sh go run main.go ``` diff --git a/template-asset-bundling/app.go b/template-asset-bundling/app.go index 591cb615f0..9673527312 100644 --- a/template-asset-bundling/app.go +++ b/template-asset-bundling/app.go @@ -2,18 +2,16 @@ package main import ( "html/template" + "log" "os" + "path/filepath" "github.com/gofiber/recipes/template-asset-bundling/handlers" - "log" - "github.com/gofiber/fiber/v2" "github.com/gofiber/fiber/v2/middleware/logger" "github.com/gofiber/fiber/v2/middleware/recover" "github.com/gofiber/template/html/v2" - - "path/filepath" ) func main() { diff --git a/template/README.md b/template/README.md index dfbc333e69..2f917dac1f 100644 --- a/template/README.md +++ b/template/README.md @@ -20,12 +20,14 @@ Ensure you have the following installed: ## Setup 1. Clone the repository: + ```sh git clone https://github.com/gofiber/recipes.git cd recipes/template ``` 2. Install dependencies: + ```sh npm install ``` @@ -35,11 +37,13 @@ Ensure you have the following installed: ### Building Assets 1. Build the assets: + ```sh npm run build ``` 2. Watch assets for changes: + ```sh npm run dev ``` @@ -47,6 +51,7 @@ Ensure you have the following installed: ### Running the Application 1. Start the Fiber application: + ```sh go run main.go ``` diff --git a/template/main.go b/template/main.go index 432098efa3..9f6aa0e319 100644 --- a/template/main.go +++ b/template/main.go @@ -8,7 +8,6 @@ import ( ) func main() { - // Create a new engine engine := django.New("./views", ".html") diff --git a/todo-app-with-auth-gorm/README.md b/todo-app-with-auth-gorm/README.md index 5cc5dcac17..2555afd7e9 100644 --- a/todo-app-with-auth-gorm/README.md +++ b/todo-app-with-auth-gorm/README.md @@ -20,12 +20,14 @@ Ensure you have the following installed and available in your `GOPATH`: ## Installation 1. Clone the repository: + ```sh git clone https://github.com/gofiber/recipes.git cd recipes/todo-app-with-auth-gorm ``` 2. Install dependencies: + ```sh go get ``` @@ -33,6 +35,7 @@ Ensure you have the following installed and available in your `GOPATH`: ## Running the Application 1. Start the application: + ```sh air ``` diff --git a/todo-app-with-auth-gorm/app/services/auth.service.go b/todo-app-with-auth-gorm/app/services/auth.service.go index 7f7a688587..a6e7b9f4f2 100644 --- a/todo-app-with-auth-gorm/app/services/auth.service.go +++ b/todo-app-with-auth-gorm/app/services/auth.service.go @@ -2,6 +2,7 @@ package services import ( "errors" + "numtostr/gotodo/app/dal" "numtostr/gotodo/app/types" "numtostr/gotodo/utils" diff --git a/todo-app-with-auth-gorm/app/services/todo.service.go b/todo-app-with-auth-gorm/app/services/todo.service.go index 2b640c81fb..dd87c1ef73 100644 --- a/todo-app-with-auth-gorm/app/services/todo.service.go +++ b/todo-app-with-auth-gorm/app/services/todo.service.go @@ -2,6 +2,7 @@ package services import ( "errors" + "numtostr/gotodo/app/dal" "numtostr/gotodo/app/types" "numtostr/gotodo/utils" diff --git a/todo-app-with-auth-gorm/config/database/database.go b/todo-app-with-auth-gorm/config/database/database.go index e4ba0e0c74..a755a16e78 100644 --- a/todo-app-with-auth-gorm/config/database/database.go +++ b/todo-app-with-auth-gorm/config/database/database.go @@ -2,9 +2,10 @@ package database import ( "fmt" - "numtostr/gotodo/config" "time" + "numtostr/gotodo/config" + "gorm.io/driver/sqlite" "gorm.io/gorm" "gorm.io/gorm/logger" @@ -19,7 +20,6 @@ func Connect() { NowFunc: func() time.Time { return time.Now().Local() }, Logger: logger.Default.LogMode(logger.Info), }) - if err != nil { fmt.Println("[DATABASE]::CONNECTION_ERROR") panic(err) diff --git a/todo-app-with-auth-gorm/main.go b/todo-app-with-auth-gorm/main.go index 3630cbd586..388a9d984f 100644 --- a/todo-app-with-auth-gorm/main.go +++ b/todo-app-with-auth-gorm/main.go @@ -2,6 +2,7 @@ package main import ( "fmt" + "numtostr/gotodo/app/dal" "numtostr/gotodo/app/routes" "numtostr/gotodo/config" diff --git a/todo-app-with-auth-gorm/utils/jwt/jwt.go b/todo-app-with-auth-gorm/utils/jwt/jwt.go index f60efb7195..c964ab4de5 100644 --- a/todo-app-with-auth-gorm/utils/jwt/jwt.go +++ b/todo-app-with-auth-gorm/utils/jwt/jwt.go @@ -3,9 +3,10 @@ package jwt import ( "errors" "fmt" - "numtostr/gotodo/config" "time" + "numtostr/gotodo/config" + "github.com/golang-jwt/jwt/v5" ) @@ -17,7 +18,6 @@ type TokenPayload struct { // Generate generates the jwt token based on payload func Generate(payload *TokenPayload) string { v, err := time.ParseDuration(config.TOKENEXP) - if err != nil { panic("Invalid time duration. Should be time.ParseDuration string") } @@ -28,7 +28,6 @@ func Generate(payload *TokenPayload) string { }) token, err := t.SignedString([]byte(config.TOKENKEY)) - if err != nil { panic(err) } @@ -55,7 +54,6 @@ func parse(token string) (*jwt.Token, error) { // Verify verifies the jwt token against the secret func Verify(token string) (*TokenPayload, error) { parsed, err := parse(token) - if err != nil { return nil, err } diff --git a/todo-app-with-auth-gorm/utils/middleware/authentication.go b/todo-app-with-auth-gorm/utils/middleware/authentication.go index 2b323e921a..7e3d29f8ad 100644 --- a/todo-app-with-auth-gorm/utils/middleware/authentication.go +++ b/todo-app-with-auth-gorm/utils/middleware/authentication.go @@ -1,9 +1,10 @@ package middleware import ( - "numtostr/gotodo/utils/jwt" "strings" + "numtostr/gotodo/utils/jwt" + "github.com/gofiber/fiber/v2" ) @@ -26,7 +27,6 @@ func Auth(c *fiber.Ctx) error { // Verify the token which is in the chunks user, err := jwt.Verify(chunks[1]) - if err != nil { return fiber.ErrUnauthorized } diff --git a/todo-app-with-auth-gorm/utils/password/password.go b/todo-app-with-auth-gorm/utils/password/password.go index 8145b47f77..70dabb46f4 100644 --- a/todo-app-with-auth-gorm/utils/password/password.go +++ b/todo-app-with-auth-gorm/utils/password/password.go @@ -5,7 +5,6 @@ import "golang.org/x/crypto/bcrypt" // Generate return a hashed password func Generate(raw string) string { hash, err := bcrypt.GenerateFromPassword([]byte(raw), 10) - if err != nil { panic(err) } diff --git a/todo-app-with-auth-gorm/utils/validator.go b/todo-app-with-auth-gorm/utils/validator.go index a7fca6504b..fc5384b267 100644 --- a/todo-app-with-auth-gorm/utils/validator.go +++ b/todo-app-with-auth-gorm/utils/validator.go @@ -13,7 +13,6 @@ var validate = validator.New() // Validate validates the input struct func Validate(payload interface{}) *fiber.Error { err := validate.Struct(payload) - if err != nil { var errors []string for _, err := range err.(validator.ValidationErrors) { diff --git a/unit-test/README.md b/unit-test/README.md index 27c4b2e4f0..2d74bdc00f 100644 --- a/unit-test/README.md +++ b/unit-test/README.md @@ -27,12 +27,14 @@ This project provides a basic setup for unit testing in a Go Fiber application. ## Setup 1. Clone the repository: + ```bash git clone https://github.com/gofiber/recipes.git cd recipes/unit-test ``` 2. Install the dependencies: + ```bash go mod download ``` @@ -40,6 +42,7 @@ This project provides a basic setup for unit testing in a Go Fiber application. ## Running the Tests To run the tests, use the following command: + ```bash go test ./... ``` @@ -137,6 +140,7 @@ The `app.Test` method in Fiber is used to simulate HTTP requests to the Fiber ap #### Usage of the `app.Test` Method The `app.Test` method takes two parameters: + 1. **req**: An `*http.Request` object representing the HTTP request to be tested. 2. **timeout**: An `int` value specifying the maximum time in milliseconds that the request can take. A value of `-1` disables the timeout. diff --git a/upload-file/README.md b/upload-file/README.md index 2ce496c12a..9bb9ce5f9f 100644 --- a/upload-file/README.md +++ b/upload-file/README.md @@ -28,12 +28,14 @@ This project provides a basic setup for handling file uploads in a Go Fiber appl ## Setup 1. Clone the repository: + ```bash git clone https://github.com/gofiber/recipes.git cd recipes/upload-file ``` 2. Install the dependencies: + ```bash go mod download ``` @@ -43,16 +45,19 @@ This project provides a basic setup for handling file uploads in a Go Fiber appl ### Single File Upload 1. Navigate to the `single` directory: + ```bash cd single ``` 2. Run the application: + ```bash go run main.go ``` 3. Use a tool like `curl` or Postman to upload a file: + ```bash curl -F "document=@/path/to/your/file" http://localhost:3000/ ``` @@ -60,16 +65,19 @@ This project provides a basic setup for handling file uploads in a Go Fiber appl ### Single File Upload with Relative Path 1. Navigate to the `single_relative_path` directory: + ```bash cd single_relative_path ``` 2. Run the application: + ```bash go run main.go ``` 3. Use a tool like `curl` or Postman to upload a file: + ```bash curl -F "document=@/path/to/your/file" http://localhost:3000/ ``` @@ -77,16 +85,19 @@ This project provides a basic setup for handling file uploads in a Go Fiber appl ### Multiple File Upload 1. Navigate to the `multiple` directory: + ```bash cd multiple ``` 2. Run the application: + ```bash go run main.go ``` 3. Use a tool like `curl` or Postman to upload multiple files: + ```bash curl -F "documents=@/path/to/your/file1" -F "documents=@/path/to/your/file2" http://localhost:3000/ ``` diff --git a/upload-file/multiple/main.go b/upload-file/multiple/main.go index 0569cc66d0..bd7fdd0b87 100644 --- a/upload-file/multiple/main.go +++ b/upload-file/multiple/main.go @@ -34,7 +34,6 @@ func main() { // Save the files to disk: err := c.SaveFile(file, fmt.Sprintf("./%s", file.Filename)) - // Check for errors if err != nil { return err diff --git a/upload-file/single_relative_path/main.go b/upload-file/single_relative_path/main.go index e922687971..18ef158c11 100644 --- a/upload-file/single_relative_path/main.go +++ b/upload-file/single_relative_path/main.go @@ -22,7 +22,7 @@ func main() { if err != nil { return err } - //Save file inside uploads folder under current working directory: + // Save file inside uploads folder under current working directory: return c.SaveFile(file, fmt.Sprintf("./uploads/%s", file.Filename)) }) diff --git a/url-shortener-api/README.md b/url-shortener-api/README.md index 3ced490be4..880ce6323f 100644 --- a/url-shortener-api/README.md +++ b/url-shortener-api/README.md @@ -38,6 +38,7 @@ This project provides a URL shortening service with a simple API. ## Setup 1. Start the containers: + ```sh docker-compose up -d ``` diff --git a/url-shortener-api/api/database/database.go b/url-shortener-api/api/database/database.go index c6b706763a..a03c7b730a 100644 --- a/url-shortener-api/api/database/database.go +++ b/url-shortener-api/api/database/database.go @@ -2,8 +2,9 @@ package database import ( "context" - "github.com/go-redis/redis/v8" "os" + + "github.com/go-redis/redis/v8" ) var Ctx = context.Background() diff --git a/url-shortener-api/api/main.go b/url-shortener-api/api/main.go index 89f8bff4a1..289be7322e 100644 --- a/url-shortener-api/api/main.go +++ b/url-shortener-api/api/main.go @@ -32,7 +32,7 @@ func main() { } app := fiber.New() - //app.Use(csrf.New()) + // app.Use(csrf.New()) app.Use(logger.New()) setupRoutes(app) diff --git a/url-shortener-api/api/routes/shorten.go b/url-shortener-api/api/routes/shorten.go index 4258fa7f39..6d72b3a451 100644 --- a/url-shortener-api/api/routes/shorten.go +++ b/url-shortener-api/api/routes/shorten.go @@ -47,7 +47,7 @@ func ShortenURL(c *fiber.Ctx) error { _, err := r2.Get(database.Ctx, c.IP()).Result() if err == redis.Nil { - _ = r2.Set(database.Ctx, c.IP(), os.Getenv("API_QUOTA"), 30*60*time.Second).Err() //change the rate_limit_reset here, change `30` to your number + _ = r2.Set(database.Ctx, c.IP(), os.Getenv("API_QUOTA"), 30*60*time.Second).Err() // change the rate_limit_reset here, change `30` to your number } else { val, _ := r2.Get(database.Ctx, c.IP()).Result() valInt, _ := strconv.Atoi(val) diff --git a/validation/README.md b/validation/README.md index 1a1fe73aac..ed0ae44323 100644 --- a/validation/README.md +++ b/validation/README.md @@ -28,22 +28,26 @@ This project provides a basic setup for validating request data in a Go Fiber ap ## Setup 1. Clone the repository: + ```bash git clone https://github.com/gofiber/recipes.git cd recipes/validation ``` 2. Install the dependencies: + ```bash go mod download ``` 3. Create a `.env` file in the root directory with the following content: + ```dotenv PORT=":8080" ``` 4. Run the application: + ```bash go run main.go ``` @@ -53,6 +57,7 @@ The application should now be running on `http://localhost:8080`. ## Example Usage 1. Send a POST request to `http://localhost:8080/validate` with a JSON payload: + ```json { "name": "John Doe", diff --git a/validation/main.go b/validation/main.go index c9d130fcd6..47b161e8a0 100644 --- a/validation/main.go +++ b/validation/main.go @@ -2,6 +2,7 @@ package main import ( "log" + "validation/config" "github.com/go-playground/validator/v10" diff --git a/vercel/README.md b/vercel/README.md index 8344dd5132..01a85050e2 100644 --- a/vercel/README.md +++ b/vercel/README.md @@ -28,12 +28,14 @@ This project provides a starting point for deploying a Go Fiber application to V ## Setup 1. Clone the repository: + ```bash git clone https://github.com/gofiber/recipes.git cd recipes/vercel ``` 2. Install the dependencies: + ```bash go mod download ``` @@ -53,16 +55,19 @@ Ensure the `vercel.json` file is present in the root directory to handle routing ## Deploy 1. Install the Vercel CLI: + ```bash npm install -g vercel ``` 2. Log in to Vercel: + ```bash vercel login ``` 3. Deploy the application: + ```bash vercel ``` diff --git a/vercel/api/index.go b/vercel/api/index.go index e0d40320dd..1c9037aa84 100644 --- a/vercel/api/index.go +++ b/vercel/api/index.go @@ -1,9 +1,10 @@ package handler import ( - "github.com/gofiber/fiber/v2/middleware/adaptor" - "github.com/gofiber/fiber/v2" "net/http" + + "github.com/gofiber/fiber/v2" + "github.com/gofiber/fiber/v2/middleware/adaptor" ) // Handler is the main entry point of the application. Think of it like the main() method diff --git a/websocket-chat/README.md b/websocket-chat/README.md index 3c4b75d3e4..6791d2a1c8 100644 --- a/websocket-chat/README.md +++ b/websocket-chat/README.md @@ -27,17 +27,20 @@ This project provides a basic setup for a WebSocket-based chat application using ## Setup 1. Clone the repository: + ```bash git clone https://github.com/gofiber/recipes.git cd recipes/websocket-chat ``` 2. Install the dependencies: + ```bash go mod download ``` 3. Run the application: + ```bash go run main.go ``` diff --git a/websocket-chat/main.go b/websocket-chat/main.go index c192ddfbd6..1ce65269a0 100644 --- a/websocket-chat/main.go +++ b/websocket-chat/main.go @@ -5,8 +5,8 @@ import ( "log" "sync" - "github.com/gofiber/fiber/v2" "github.com/gofiber/contrib/websocket" + "github.com/gofiber/fiber/v2" ) // Add more data to this type if needed @@ -15,10 +15,12 @@ type client struct { mu sync.Mutex } -var clients = make(map[*websocket.Conn]*client) // Note: although large maps with pointer-like types (e.g. strings) as keys are slow, using pointers themselves as keys is acceptable and fast -var register = make(chan *websocket.Conn) -var broadcast = make(chan string) -var unregister = make(chan *websocket.Conn) +var ( + clients = make(map[*websocket.Conn]*client) // Note: although large maps with pointer-like types (e.g. strings) as keys are slow, using pointers themselves as keys is acceptable and fast + register = make(chan *websocket.Conn) + broadcast = make(chan string) + unregister = make(chan *websocket.Conn) +) func runHub() { for { diff --git a/websocket/README.md b/websocket/README.md index 426cc5ef21..cee83ed17e 100644 --- a/websocket/README.md +++ b/websocket/README.md @@ -26,17 +26,20 @@ This project provides a basic setup for a WebSocket server using Go Fiber. It in ## Setup 1. Clone the repository: + ```bash git clone https://github.com/gofiber/recipes.git cd recipes/websocket ``` 2. Install the dependencies: + ```bash go mod download ``` 3. Run the application: + ```bash go run main.go ``` diff --git a/websocket/main.go b/websocket/main.go index 9837c8bf9c..8e8626bc87 100644 --- a/websocket/main.go +++ b/websocket/main.go @@ -8,8 +8,8 @@ import ( "fmt" "log" - "github.com/gofiber/fiber/v2" "github.com/gofiber/contrib/websocket" + "github.com/gofiber/fiber/v2" ) func main() { From 1bf65b3433d5f698e6e9dcc2643ce203120c40e0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ren=C3=A9?= Date: Tue, 26 Nov 2024 19:37:48 +0100 Subject: [PATCH 12/14] docusaurus preparations --- .github/CONTRIBUTING.md | 18 +- .markdownlint.yml | 248 ++++++++++++++++++++++++++++ 404-handler/README.md | 1 - air/README.md | 6 - auth-docker-postgres-jwt/README.md | 7 - auth-jwt/README.md | 8 - autocert/README.md | 4 - aws-eb/README.md | 8 - aws-sam-container/README.md | 21 ++- aws-sam/README.md | 6 +- bootstrap/README.md | 5 - clean-architecture/README.md | 32 +--- cloud-run/README.md | 7 - colly-gorm/README.md | 1 + csrf-with-session/README.md | 46 +++--- csrf/README.md | 20 +-- docker-nginx-loadbalancer/README.md | 3 +- ent-mysql/README.md | 14 +- entgo-sveltekit/README.md | 19 ++- entgo-sveltekit/template/README.md | 8 - file-server/README.md | 3 - firebase-auth/README.md | 1 - firebase-functions/README.md | 3 +- gcloud-firebase/README.md | 4 - gcloud/README.md | 4 - geoip-maxmind/README.md | 4 +- geoip/README.md | 3 - gorm-mysql/README.md | 9 - gorm-postgres/README.md | 4 - gorm/README.md | 7 - graphql/README.md | 4 - grpc/README.md | 6 +- hello-world/README.md | 3 - heroku/README.md | 7 - hexagonal/README.md | 10 -- https-pkcs12-tls/README.md | 3 - https-tls/README.md | 3 - jwt/README.md | 5 - k8s/README.md | 7 - memgraph/README.md | 5 +- minio/README.md | 2 - mongodb/README.md | 3 - multiple-ports/README.md | 4 - mysql/README.md | 3 - neo4j/README.md | 3 - oauth2-google/README.md | 6 - optional-parameter/README.md | 4 - postgresql/README.md | 3 - prefork/README.md | 3 - recover/README.md | 3 - rss-feed/README.md | 3 - server-timing/README.md | 3 - sessions-sqlite3/README.md | 4 - socketio/README.md | 5 - spa/README.md | 6 - sqlboiler/README.md | 48 ++---- sqlc/README.md | 51 +----- sse/README.md | 4 - stream-request-body/README.md | 3 - svelte-netlify/README.md | 5 +- sveltekit-embed/README.md | 17 +- swagger/README.md | 4 - tableflip/README.md | 10 +- template-asset-bundling/README.md | 5 - template/README.md | 5 - todo-app-with-auth-gorm/README.md | 3 - unit-test/README.md | 4 - upload-file/README.md | 11 -- url-shortener-api/README.md | 1 - validation/README.md | 5 - vercel/README.md | 5 - websocket-chat/README.md | 3 - websocket/README.md | 3 - 73 files changed, 361 insertions(+), 458 deletions(-) create mode 100644 .markdownlint.yml diff --git a/.github/CONTRIBUTING.md b/.github/CONTRIBUTING.md index e8c27d5384..2156217b93 100644 --- a/.github/CONTRIBUTING.md +++ b/.github/CONTRIBUTING.md @@ -8,8 +8,7 @@ Thank you for considering contributing to this project! To ensure a smooth and e 2. **Add a `README.md`**: Each example must include a `README.md` file in its directory. This file should contain the following: -- **Docusaurus Metadata**: Add the following metadata at the top of the `README.md` file: - + - **Docusaurus Metadata**: Add the following metadata at the top of the `README.md` file: ```markdown --- title: Your Example Title @@ -17,17 +16,16 @@ Thank you for considering contributing to this project! To ensure a smooth and e --- ``` - - `title`: A short and descriptive title for your example. - - `keywords`: A list of relevant keywords (excluding "fiber"). + - `title`: A short and descriptive title for your example. + - `keywords`: A list of relevant keywords (excluding "fiber"). -- **Content**: The `README.md` should provide a detailed explanation of the example, including: - - The idea behind the example. - - The components used in the example. - - Instructions on how to run the example. - - Any other relevant information. + - **Content**: The `README.md` should provide a detailed explanation of the example, including: + - The idea behind the example. + - The components used in the example. + - Instructions on how to run the example. + - Any other relevant information. 3. **Update the Overview**: After adding your example, run the following command in the root directory to update the overview table of contents: - ```bash make generate ``` diff --git a/.markdownlint.yml b/.markdownlint.yml new file mode 100644 index 0000000000..71d7b309d8 --- /dev/null +++ b/.markdownlint.yml @@ -0,0 +1,248 @@ +# Example markdownlint configuration with all properties set to their default value + +# Default state for all rules +default: true + +# Path to configuration file to extend +extends: null + +# MD001/heading-increment : Heading levels should only increment by one level at a time : https://github.com/DavidAnson/markdownlint/blob/v0.34.0/doc/md001.md +MD001: true + +# MD003/heading-style : Heading style : https://github.com/DavidAnson/markdownlint/blob/v0.34.0/doc/md003.md +MD003: + # Heading style + style: "consistent" + +# MD004/ul-style : Unordered list style : https://github.com/DavidAnson/markdownlint/blob/v0.34.0/doc/md004.md +MD004: + # List style + style: "consistent" + +# MD005/list-indent : Inconsistent indentation for list items at the same level : https://github.com/DavidAnson/markdownlint/blob/v0.34.0/doc/md005.md +MD005: true + +# MD007/ul-indent : Unordered list indentation : https://github.com/DavidAnson/markdownlint/blob/v0.34.0/doc/md007.md +MD007: + # Spaces for indent + indent: + # Whether to indent the first level of the list + start_indented: false + # Spaces for first level indent (when start_indented is set) + start_indent: 2 + +# MD009/no-trailing-spaces : Trailing spaces : https://github.com/DavidAnson/markdownlint/blob/v0.34.0/doc/md009.md +MD009: + # Spaces for line break + br_spaces: 2 + # Allow spaces for empty lines in list items + list_item_empty_lines: false + # Include unnecessary breaks + strict: true + +# MD010/no-hard-tabs : Hard tabs : https://github.com/DavidAnson/markdownlint/blob/v0.34.0/doc/md010.md +MD010: + # Include code blocks + code_blocks: true + # Fenced code languages to ignore + ignore_code_languages: [] + # Number of spaces for each hard tab + spaces_per_tab: 4 + +# MD011/no-reversed-links : Reversed link syntax : https://github.com/DavidAnson/markdownlint/blob/v0.34.0/doc/md011.md +MD011: true + +# MD012/no-multiple-blanks : Multiple consecutive blank lines : https://github.com/DavidAnson/markdownlint/blob/v0.34.0/doc/md012.md +MD012: + # Consecutive blank lines + maximum: 1 + +# MD013/line-length : Line length : https://github.com/DavidAnson/markdownlint/blob/v0.34.0/doc/md013.md +MD013: false + +# MD014/commands-show-output : Dollar signs used before commands without showing output : https://github.com/DavidAnson/markdownlint/blob/v0.34.0/doc/md014.md +MD014: true + +# MD018/no-missing-space-atx : No space after hash on atx style heading : https://github.com/DavidAnson/markdownlint/blob/v0.34.0/doc/md018.md +MD018: true + +# MD019/no-multiple-space-atx : Multiple spaces after hash on atx style heading : https://github.com/DavidAnson/markdownlint/blob/v0.34.0/doc/md019.md +MD019: true + +# MD020/no-missing-space-closed-atx : No space inside hashes on closed atx style heading : https://github.com/DavidAnson/markdownlint/blob/v0.34.0/doc/md020.md +MD020: true + +# MD021/no-multiple-space-closed-atx : Multiple spaces inside hashes on closed atx style heading : https://github.com/DavidAnson/markdownlint/blob/v0.34.0/doc/md021.md +MD021: true + +# MD022/blanks-around-headings : Headings should be surrounded by blank lines : https://github.com/DavidAnson/markdownlint/blob/v0.34.0/doc/md022.md +MD022: + # Blank lines above heading + lines_above: 1 + # Blank lines below heading + lines_below: 1 + +# MD023/heading-start-left : Headings must start at the beginning of the line : https://github.com/DavidAnson/markdownlint/blob/v0.34.0/doc/md023.md +MD023: true + +# MD024/no-duplicate-heading : Multiple headings with the same content : https://github.com/DavidAnson/markdownlint/blob/v0.34.0/doc/md024.md +MD024: false + +# MD025/single-title/single-h1 : Multiple top-level headings in the same document : https://github.com/DavidAnson/markdownlint/blob/v0.34.0/doc/md025.md +MD025: + # Heading level + level: 1 + # RegExp for matching title in front matter + front_matter_title: "^\\s*title\\s*[:=]" + +# MD026/no-trailing-punctuation : Trailing punctuation in heading : https://github.com/DavidAnson/markdownlint/blob/v0.34.0/doc/md026.md +MD026: + # Punctuation characters + punctuation: ".,;:!。,;:!" + +# MD027/no-multiple-space-blockquote : Multiple spaces after blockquote symbol : https://github.com/DavidAnson/markdownlint/blob/v0.34.0/doc/md027.md +MD027: true + +# MD028/no-blanks-blockquote : Blank line inside blockquote : https://github.com/DavidAnson/markdownlint/blob/v0.34.0/doc/md028.md +MD028: true + +# MD029/ol-prefix : Ordered list item prefix : https://github.com/DavidAnson/markdownlint/blob/v0.34.0/doc/md029.md +MD029: + # List style + style: "one_or_ordered" + +# MD030/list-marker-space : Spaces after list markers : https://github.com/DavidAnson/markdownlint/blob/v0.34.0/doc/md030.md +MD030: + # Spaces for single-line unordered list items + ul_single: 1 + # Spaces for single-line ordered list items + ol_single: 1 + # Spaces for multi-line unordered list items + ul_multi: 1 + # Spaces for multi-line ordered list items + ol_multi: 1 + +# MD031/blanks-around-fences : Fenced code blocks should be surrounded by blank lines : https://github.com/DavidAnson/markdownlint/blob/v0.34.0/doc/md031.md +MD031: + # Include list items + list_items: true + +# MD032/blanks-around-lists : Lists should be surrounded by blank lines : https://github.com/DavidAnson/markdownlint/blob/v0.34.0/doc/md032.md +MD032: true + +# MD033/no-inline-html : Inline HTML : https://github.com/DavidAnson/markdownlint/blob/v0.34.0/doc/md033.md +MD033: false + +# MD034/no-bare-urls : Bare URL used : https://github.com/DavidAnson/markdownlint/blob/v0.34.0/doc/md034.md +MD034: true + +# MD035/hr-style : Horizontal rule style : https://github.com/DavidAnson/markdownlint/blob/v0.34.0/doc/md035.md +MD035: + # Horizontal rule style + style: "consistent" + +# MD036/no-emphasis-as-heading : Emphasis used instead of a heading : https://github.com/DavidAnson/markdownlint/blob/v0.34.0/doc/md036.md +MD036: + # Punctuation characters + punctuation: ".,;:!?。,;:!?" + +# MD037/no-space-in-emphasis : Spaces inside emphasis markers : https://github.com/DavidAnson/markdownlint/blob/v0.34.0/doc/md037.md +MD037: true + +# MD038/no-space-in-code : Spaces inside code span elements : https://github.com/DavidAnson/markdownlint/blob/v0.34.0/doc/md038.md +MD038: true + +# MD039/no-space-in-links : Spaces inside link text : https://github.com/DavidAnson/markdownlint/blob/v0.34.0/doc/md039.md +MD039: true + +# MD040/fenced-code-language : Fenced code blocks should have a language specified : https://github.com/DavidAnson/markdownlint/blob/v0.34.0/doc/md040.md +MD040: + # List of languages + allowed_languages: [] + # Require language only + language_only: false + +# MD041/first-line-heading/first-line-h1 : First line in a file should be a top-level heading : https://github.com/DavidAnson/markdownlint/blob/v0.34.0/doc/md041.md +MD041: + # Heading level + level: 1 + # RegExp for matching title in front matter + front_matter_title: "^\\s*title\\s*[:=]" + +# MD042/no-empty-links : No empty links : https://github.com/DavidAnson/markdownlint/blob/v0.34.0/doc/md042.md +MD042: true + +# MD043/required-headings : Required heading structure : https://github.com/DavidAnson/markdownlint/blob/v0.34.0/doc/md043.md +MD043: false + +# MD044/proper-names : Proper names should have the correct capitalization : https://github.com/DavidAnson/markdownlint/blob/v0.34.0/doc/md044.md +MD044: + # List of proper names + names: [] + # Include code blocks + code_blocks: true + # Include HTML elements + html_elements: true + +# MD045/no-alt-text : Images should have alternate text (alt text) : https://github.com/DavidAnson/markdownlint/blob/v0.34.0/doc/md045.md +MD045: false + +# MD046/code-block-style : Code block style : https://github.com/DavidAnson/markdownlint/blob/v0.34.0/doc/md046.md +MD046: + # Block style + style: "fenced" + +# MD047/single-trailing-newline : Files should end with a single newline character : https://github.com/DavidAnson/markdownlint/blob/v0.34.0/doc/md047.md +MD047: true + +# MD048/code-fence-style : Code fence style : https://github.com/DavidAnson/markdownlint/blob/v0.34.0/doc/md048.md +MD048: + # Code fence style + style: "backtick" + +# MD049/emphasis-style : Emphasis style : https://github.com/DavidAnson/markdownlint/blob/v0.34.0/doc/md049.md +MD049: + # Emphasis style + style: "consistent" + +# MD050/strong-style : Strong style : https://github.com/DavidAnson/markdownlint/blob/v0.34.0/doc/md050.md +MD050: + # Strong style + style: "consistent" + +# MD051/link-fragments : Link fragments should be valid : https://github.com/DavidAnson/markdownlint/blob/v0.34.0/doc/md051.md +MD051: true + +# MD052/reference-links-images : Reference links and images should use a label that is defined : https://github.com/DavidAnson/markdownlint/blob/v0.34.0/doc/md052.md +MD052: + # Include shortcut syntax + shortcut_syntax: false + +# MD053/link-image-reference-definitions : Link and image reference definitions should be needed : https://github.com/DavidAnson/markdownlint/blob/v0.34.0/doc/md053.md +MD053: + # Ignored definitions + ignored_definitions: + - "//" + +# MD054/link-image-style : Link and image style : https://github.com/DavidAnson/markdownlint/blob/v0.34.0/doc/md054.md +MD054: + # Allow autolinks + autolink: false + # Allow inline links and images + inline: true + # Allow full reference links and images + full: true + # Allow collapsed reference links and images + collapsed: true + # Allow shortcut reference links and images + shortcut: true + # Allow URLs as inline links + url_inline: true + +# MD055/table-pipe-style : Table pipe style : https://github.com/DavidAnson/markdownlint/blob/v0.34.0/doc/md055.md +MD055: + # Table pipe style + style: "consistent" + +# MD056/table-column-count : Table column count : https://github.com/DavidAnson/markdownlint/blob/v0.34.0/doc/md056.md +MD056: true diff --git a/404-handler/README.md b/404-handler/README.md index 0e122f9c02..5a92c2b26b 100644 --- a/404-handler/README.md +++ b/404-handler/README.md @@ -21,7 +21,6 @@ In web applications, it's common to encounter requests to routes that do not exi ## Running the Example To run the example, use the following command: - ```bash go run main.go ``` diff --git a/air/README.md b/air/README.md index f120a0c797..431deb0f04 100644 --- a/air/README.md +++ b/air/README.md @@ -22,20 +22,17 @@ Live reloading is a useful feature during development as it saves time by automa ## Setup 1. Clone the repository: - ```bash git clone https://github.com/gofiber/recipes.git cd recipes/air ``` 2. Install the dependencies: - ```bash go mod download ``` 3. Install Air: - ```bash go install github.com/cosmtrek/air@latest ``` @@ -50,13 +47,10 @@ Air is configured using the `air/.air.conf` file. This file specifies the build ## Running the Example To run the example with live reloading, use the following command: - ```bash air -c .air.linux.conf ``` - or for Windows: - ```bash air -c .air.windows.conf ``` diff --git a/auth-docker-postgres-jwt/README.md b/auth-docker-postgres-jwt/README.md index 4d4a14f66b..1e66dcf3a8 100644 --- a/auth-docker-postgres-jwt/README.md +++ b/auth-docker-postgres-jwt/README.md @@ -22,14 +22,12 @@ This project provides a starting point for building a web application with user ## Setup 1. Clone the repository: - ```bash git clone https://github.com/gofiber/recipes.git cd recipes/auth-docker-postgres-jwt ``` 2. Set the environment variables in a `.env` file: - ```env DB_PORT=5432 DB_USER=example_user @@ -39,7 +37,6 @@ This project provides a starting point for building a web application with user ``` 3. Build and start the Docker containers: - ```bash docker-compose build docker-compose up @@ -50,7 +47,6 @@ The API and the database should now be running. ## Database Management You can manage the database via `psql` with the following command: - ```bash docker-compose exec db psql -U ``` @@ -70,19 +66,16 @@ The following endpoints are available in the API: ## Example Usage 1. Register a new user: - ```bash curl -X POST http://localhost:3000/api/auth/register -d '{"username":"testuser", "password":"testpassword"}' -H "Content-Type: application/json" ``` 2. Login to get a JWT: - ```bash curl -X POST http://localhost:3000/api/auth/login -d '{"username":"testuser", "password":"testpassword"}' -H "Content-Type: application/json" ``` 3. Access a protected route: - ```bash curl -H "Authorization: Bearer " http://localhost:3000/api/user/1 ``` diff --git a/auth-jwt/README.md b/auth-jwt/README.md index 18820889b6..4335e100a7 100644 --- a/auth-jwt/README.md +++ b/auth-jwt/README.md @@ -21,14 +21,12 @@ This project provides a starting point for building a web application with user ## Setup 1. Clone the repository: - ```bash git clone https://github.com/gofiber/recipes.git cd recipes/auth-jwt ``` 2. Set the environment variables in a `.env` file: - ```env DB_PORT=5432 DB_USER=example_user @@ -38,13 +36,11 @@ This project provides a starting point for building a web application with user ``` 3. Install the dependencies: - ```bash go mod download ``` 4. Run the application: - ```bash go run main.go ``` @@ -54,7 +50,6 @@ The API should now be running on `http://localhost:3000`. ## Database Management You can manage the database via `psql` with the following command: - ```bash psql -U -d -h localhost -p ``` @@ -79,19 +74,16 @@ The following endpoints are available in the API: ## Example Usage 1. Register a new user: - ```bash curl -X POST http://localhost:3000/api/auth/register -d '{"username":"testuser", "password":"testpassword", "email":"test@example.com"}' -H "Content-Type: application/json" ``` 2. Login to get a JWT: - ```bash curl -X POST http://localhost:3000/api/auth/login -d '{"username":"testuser", "password":"testpassword"}' -H "Content-Type: application/json" ``` 3. Access a protected route: - ```bash curl -H "Authorization: Bearer " http://localhost:3000/api/user/1 ``` diff --git a/autocert/README.md b/autocert/README.md index 02e16750ed..9c04b9b946 100644 --- a/autocert/README.md +++ b/autocert/README.md @@ -21,20 +21,17 @@ This project provides a starting point for building a secure web application wit ## Setup 1. Clone the repository: - ```bash git clone https://github.com/gofiber/recipes.git cd recipes/autocert ``` 2. Install the dependencies: - ```bash go mod download ``` 3. Update the `HostPolicy` in `main.go` with your domain: - ```go m := &autocert.Manager{ Prompt: autocert.AcceptTOS, @@ -44,7 +41,6 @@ This project provides a starting point for building a secure web application wit ``` 4. Run the application: - ```bash go run main.go ``` diff --git a/aws-eb/README.md b/aws-eb/README.md index eb8f0ed113..0f66990d4f 100644 --- a/aws-eb/README.md +++ b/aws-eb/README.md @@ -23,26 +23,22 @@ This project provides a starting point for deploying a Go Fiber application to A ## Setup 1. Clone the repository: - ```bash git clone https://github.com/gofiber/recipes.git cd recipes/aws-eb ``` 2. Initialize Elastic Beanstalk: - ```bash eb init ``` 3. Create an Elastic Beanstalk environment: - ```bash eb create ``` 4. Deploy the application: - ```bash eb deploy ``` @@ -52,13 +48,11 @@ This project provides a starting point for deploying a Go Fiber application to A The build process is defined in the `Buildfile` and `build.sh` scripts. - `Buildfile`: - ```ruby make: ./build.sh ``` - `build.sh`: - ```bash #!/bin/bash -xe # Get dependencies @@ -74,7 +68,6 @@ The build process is defined in the `Buildfile` and `build.sh` scripts. ## Application Code The main application code is in `application.go`: - ```go package main @@ -107,7 +100,6 @@ func main() { ## .gitignore The `.gitignore` file includes configurations to ignore Elastic Beanstalk specific files: - ```plaintext # Elastic Beanstalk Files .elasticbeanstalk/* diff --git a/aws-sam-container/README.md b/aws-sam-container/README.md index 2c10bd9a92..c79ff82cb0 100644 --- a/aws-sam-container/README.md +++ b/aws-sam-container/README.md @@ -26,13 +26,12 @@ This is a sample template for app - Below is a brief explanation of what we have ## Requirements -- AWS CLI already configured with Administrator permission -- [Docker installed](https://www.docker.com/community-edition) -- SAM CLI - [Install the SAM CLI](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-sam-cli-install.html) +* AWS CLI already configured with Administrator permission +* [Docker installed](https://www.docker.com/community-edition) +* SAM CLI - [Install the SAM CLI](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-sam-cli-install.html) You may need the following for local testing. - -- [Golang](https://golang.org) +* [Golang](https://golang.org) ## Setup process @@ -60,11 +59,11 @@ sam deploy --guided The command will package and deploy your application to AWS, with a series of prompts: -- **Stack Name**: The name of the stack to deploy to CloudFormation. This should be unique to your account and region, and a good starting point would be something matching your project name. -- **AWS Region**: The AWS region you want to deploy your app to. -- **Confirm changes before deploy**: If set to yes, any change sets will be shown to you before execution for manual review. If set to no, the AWS SAM CLI will automatically deploy application changes. -- **Allow SAM CLI IAM role creation**: Many AWS SAM templates, including this example, create AWS IAM roles required for the AWS Lambda function(s) included to access AWS services. By default, these are scoped down to minimum required permissions. To deploy an AWS CloudFormation stack which creates or modifies IAM roles, the `CAPABILITY_IAM` value for `capabilities` must be provided. If permission isn't provided through this prompt, to deploy this example you must explicitly pass `--capabilities CAPABILITY_IAM` to the `sam deploy` command. -- **Save arguments to samconfig.toml**: If set to yes, your choices will be saved to a configuration file inside the project, so that in the future you can just re-run `sam deploy` without parameters to deploy changes to your application. +* **Stack Name**: The name of the stack to deploy to CloudFormation. This should be unique to your account and region, and a good starting point would be something matching your project name. +* **AWS Region**: The AWS region you want to deploy your app to. +* **Confirm changes before deploy**: If set to yes, any change sets will be shown to you before execution for manual review. If set to no, the AWS SAM CLI will automatically deploy application changes. +* **Allow SAM CLI IAM role creation**: Many AWS SAM templates, including this example, create AWS IAM roles required for the AWS Lambda function(s) included to access AWS services. By default, these are scoped down to minimum required permissions. To deploy an AWS CloudFormation stack which creates or modifies IAM roles, the `CAPABILITY_IAM` value for `capabilities` must be provided. If permission isn't provided through this prompt, to deploy this example you must explicitly pass `--capabilities CAPABILITY_IAM` to the `sam deploy` command. +* **Save arguments to samconfig.toml**: If set to yes, your choices will be saved to a configuration file inside the project, so that in the future you can just re-run `sam deploy` without parameters to deploy changes to your application. You can find your API Gateway Endpoint URL in the output values displayed after deployment. @@ -97,7 +96,7 @@ This command grants permission to all principals (*) to invoke your Lambda funct ### Golang installation -Please ensure Go 1.x (where 'x' is the latest version) is installed as per the instructions on the official golang website: +Please ensure Go 1.x (where 'x' is the latest version) is installed as per the instructions on the official golang website: https://golang.org/doc/install A quickstart way would be to use Homebrew, chocolatey or your linux package manager. diff --git a/aws-sam/README.md b/aws-sam/README.md index b954bcef5f..da028de1ae 100644 --- a/aws-sam/README.md +++ b/aws-sam/README.md @@ -46,6 +46,9 @@ curl -XPOST "http://localhost:3001/2015-03-31/functions/sam-app/invocations" {"statusCode":200,"headers":null,"multiValueHeaders":{"Content-Type":["application/json"]},"body":"{\"message\":\"Hello World\"}"}% ``` + + + ## Packaging and deployment AWS Lambda Golang runtime requires a flat folder with the executable generated on build step. SAM will use `CodeUri` property to know where to look up for the application: @@ -75,6 +78,7 @@ The command will package and deploy your application to AWS, with a series of pr You can find your API Gateway Endpoint URL in the output values displayed after deployment. + ## Add Permission to the Lambda Function for Public Access After deploying your Lambda function with an associated function URL, you might encounter a scenario where the function URL is not accessible due to missing permissions for public access. This is common when the authentication type for the function URL is set to "None," indicating that the function is intended to be publicly accessible without authentication. @@ -104,7 +108,7 @@ This command grants permission to all principals (*) to invoke your Lambda funct ### Golang installation -Please ensure Go 1.x (where 'x' is the latest version) is installed as per the instructions on the official golang website: +Please ensure Go 1.x (where 'x' is the latest version) is installed as per the instructions on the official golang website: https://golang.org/doc/install A quickstart way would be to use Homebrew, chocolatey or your linux package manager. diff --git a/bootstrap/README.md b/bootstrap/README.md index c3b8d584e4..921341e3f6 100644 --- a/bootstrap/README.md +++ b/bootstrap/README.md @@ -10,7 +10,6 @@ keywords: [bootstrap, gorm, validator, env] Fiber bootstrap for rapid development using Go-Fiber / Gorm / Validator. # Components - * Fiber * Html Engine Template * Logger @@ -21,14 +20,12 @@ Fiber bootstrap for rapid development using Go-Fiber / Gorm / Validator. * Env File # Router - API Router `/api` with rate limiter middleware Http Router `/` with CORS and CSRF middleware # Setup 1. Copy the example env file over: - ``` cp .env.example .env ``` @@ -36,9 +33,7 @@ Http Router `/` with CORS and CSRF middleware 2. Modify the env file you just copied `.env` with the correct credentials for your database. Make sure the database you entered in `DB_NAME` has been created. 3. Run the API: - ``` go run main.go ``` - Your api should be running at `http://localhost:4000/` if the port is in use you may modify it in the `.env` you just created. diff --git a/clean-architecture/README.md b/clean-architecture/README.md index 50518d1080..d0c6762db5 100644 --- a/clean-architecture/README.md +++ b/clean-architecture/README.md @@ -28,27 +28,23 @@ This project provides a starting point for building a web application with a cle ## Setup 1. Clone the repository: - ```bash git clone https://github.com/gofiber/recipes.git cd recipes/clean-architecture ``` 2. Set the environment variables in a `.env` file: - ```env DB_URI=mongodb://localhost:27017 DB_NAME=example_db ``` 3. Install the dependencies: - ```bash go mod download ``` 4. Run the application: - ```bash go run cmd/main.go ``` @@ -67,25 +63,21 @@ The following endpoints are available in the API: ## Example Usage 1. Add a new book: - ```bash curl -X POST http://localhost:3000/books -d '{"title":"Book Title", "author":"Author Name"}' -H "Content-Type: application/json" ``` 2. List all books: - ```bash curl http://localhost:3000/books ``` 3. Update a book: - ```bash curl -X PUT http://localhost:3000/books -d '{"id":"", "title":"Updated Title", "author":"Updated Author"}' -H "Content-Type: application/json" ``` 4. Remove a book: - ```bash curl -X DELETE http://localhost:3000/books -d '{"id":""}' -H "Content-Type: application/json" ``` @@ -99,24 +91,20 @@ Clean Architecture is a software design philosophy that emphasizes the separatio ### Layers in Clean Architecture 1. **Entities (Core Business Logic)** - -- Located in the `pkg/entities` directory. -- Contains the core business logic and domain models, which are independent of any external frameworks or technologies. + - Located in the `pkg/entities` directory. + - Contains the core business logic and domain models, which are independent of any external frameworks or technologies. 2. **Use Cases (Application Logic)** - -- Located in the `pkg/book` directory. -- Contains the application-specific business rules and use cases. This layer orchestrates the flow of data to and from the entities. + - Located in the `pkg/book` directory. + - Contains the application-specific business rules and use cases. This layer orchestrates the flow of data to and from the entities. 3. **Interface Adapters (Adapters and Presenters)** - -- Located in the `api` directory. -- Contains the HTTP handlers, routes, and presenters. This layer is responsible for converting data from the use cases into a format suitable for the web framework (Fiber in this case). + - Located in the `api` directory. + - Contains the HTTP handlers, routes, and presenters. This layer is responsible for converting data from the use cases into a format suitable for the web framework (Fiber in this case). 4. **Frameworks and Drivers (External Interfaces)** - -- Located in the `cmd` directory. -- Contains the main application entry point and any external dependencies like the web server setup. + - Located in the `cmd` directory. + - Contains the main application entry point and any external dependencies like the web server setup. ### Example Breakdown @@ -128,7 +116,6 @@ Clean Architecture is a software design philosophy that emphasizes the separatio ### Code Example #### `entities/book.go` - ```go package entities @@ -142,7 +129,6 @@ type Book struct { ``` #### `pkg/book/service.go` - ```go package book @@ -157,7 +143,6 @@ type Service interface { ``` #### `api/handlers/book_handler.go` - ```go package handlers @@ -193,7 +178,6 @@ func AddBook(service book.Service) fiber.Handler { ``` #### `cmd/main.go` - ```go package main diff --git a/cloud-run/README.md b/cloud-run/README.md index 10262c1711..930a4c3ba3 100644 --- a/cloud-run/README.md +++ b/cloud-run/README.md @@ -23,26 +23,22 @@ This project provides a starting point for deploying a Go Fiber application to G ## Setup 1. Clone the repository: - ```bash git clone https://github.com/gofiber/recipes.git cd recipes/cloud-run ``` 2. Install the dependencies: - ```bash go mod download ``` 3. Build the Docker image: - ```bash docker build -t cloud-run-example . ``` 4. Run the Docker container: - ```bash docker run -p 3000:3000 cloud-run-example ``` @@ -52,20 +48,17 @@ The application should now be running on `http://localhost:3000`. ## Deploy to Google Cloud Run 1. Set up Google Cloud SDK and authenticate: - ```bash gcloud auth login gcloud config set project [YOUR_PROJECT_ID] ``` 2. Build and push the Docker image using Google Cloud Build: - ```bash gcloud builds submit --tag gcr.io/[YOUR_PROJECT_ID]/cloud-run-example ``` 3. Deploy the image to Cloud Run: - ```bash gcloud run deploy cloud-run-example --image gcr.io/[YOUR_PROJECT_ID]/cloud-run-example --platform managed --region [YOUR_REGION] --allow-unauthenticated ``` diff --git a/colly-gorm/README.md b/colly-gorm/README.md index 2b103d7ecc..ee4b00486b 100644 --- a/colly-gorm/README.md +++ b/colly-gorm/README.md @@ -17,6 +17,7 @@ This is a basic Go application using the Fiber framework to create scraping task 4. Visit `http://127.0.0.1:3000/api/healthchecker` in a web browser or use a tool like `curl` to test it. 5. Send `GET` request to `http://127.0.0.1:3000/scrape/coursera` to start scraping Coursera courses. And `http://127.0.0.1:3000/scrape/quotes` to scrape `quotes.toscrape.com`. + ## What It Does - Scrapes data from websites and stores in PostgreSQL database. diff --git a/csrf-with-session/README.md b/csrf-with-session/README.md index 87d0d85099..15e80eec08 100644 --- a/csrf-with-session/README.md +++ b/csrf-with-session/README.md @@ -14,41 +14,37 @@ This example impliments multiple best-practices for CSRF protection: - CSRF Tokens are linked to the user's session. - Pre-sessions are used, so that CSRF tokens are always available, even for anonymous users (eg for login forms). - Cookies are set with a defense-in-depth approach: - - Secure: true - - HttpOnly: true - - SameSite: Lax - - Expiration: 30 minutes (of inactivity) - - Cookie names are prefixed with "__Host-" (see [MDN-Set-Cookie](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie) for more information)) + - Secure: true + - HttpOnly: true + - SameSite: Lax + - Expiration: 30 minutes (of inactivity) + - Cookie names are prefixed with "__Host-" (see [MDN-Set-Cookie](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie) for more information)) ## Requirements -- [git](https://git-scm.com/downloads) -- [Golang](https://golang.org/) +* [git](https://git-scm.com/downloads) +* [Golang](https://golang.org/) + ## Install Go Modules Like any golang project, you will need to download and install the required modules for the project to run. Change into the "csrf-with-session" directory: - ```bash cd csrf-with-session ``` And then: - ```bash go mod vendor && go mod download && go mod tidy ``` - This command installs the golang dependencies needed to run the project in a new directory named `vendor`. Once the modules have finished installing, you can run the project like this: - ```bash go run main.go ``` You should see the following if everything is OK: - ``` Server started and listening at 127.0.0.1:8443 ``` @@ -56,14 +52,13 @@ Server started and listening at 127.0.0.1:8443 ## Try the demo Start the server by running: - ```bash go run main.go ``` - Open your browser to and navigate to [127.0.0.1:8443](http://127.0.0.1:8443). -### Accept the self-signed certificate warning and visit the site + +### Accept the self-signed certificate warning and visit the site. In Chrome: @@ -80,26 +75,29 @@ In Safari: - Click on "Show Details" - Click on "visit this website" + ### Try to access the /protected page Login using one of the test accounts: - -- Username: `user1` -- Password: `password1` +* Username: `user1` +* Password: `password1` OR -- Username: `user2` -- Password: `password2` +* Username: `user2` +* Password: `password2` Once logged in, you will be able to see the /protected page. + ### Submit the form on the /protected page Once logged in, you will be able to see the /protected page. The /protected page contains a form that submits to the /protected page. If you try to submit the form without a valid CSRF token, you will get a 403 Forbidden error. + ## CSRF Protection All methods except GET, HEAD, OPTIONS, and TRACE are checked for the CSRF token. If the token is not present or does not match the token in the session, the request is aborted with a 403 Forbidden error. + ## Token Lifecycle The CSRF token is generated when the user visits any page on the site. The token is stored in the session and is valid for until it expires, or the authorization scope changes (e.g. the user logs in, or logs out). @@ -108,18 +106,20 @@ It is important that CSRF tokens do not persist beyond the scope of the user's s The CSRF middleware has a `SingleUseToken` configuration option that can be used to generate a new token for each request. This is useful for some applications, but is not used in this example. Single use tokens have usability implications in scenarios where the user has multiple tabs open, or when the user uses the back button in their browser. + ## Session Storage Sessions are stored in memory for this example, but you can use any session store you like. See the [Fiber session documentation](https://docs.gofiber.io/api/middleware/session) for more information. + ### Note on pre-sessions GoFiber's CSRF middleware will automatically create a session if one does not exist. That means that we always have pre-sessions when using the CSRF middleware. In this example we set a session variable `loggedIn` to `true` when the user logs in, in order to distinguish between logged in and logged out users. + ## Going further Here are some useful links where you can learn more about this topic: - -- -- +* https://en.wikipedia.org/wiki/Cross-site_request_forgery +* https://www.owasp.org/index.php/Cross-Site_Request_Forgery_(CSRF) diff --git a/csrf/README.md b/csrf/README.md index 49a17dc83e..a772936ec1 100644 --- a/csrf/README.md +++ b/csrf/README.md @@ -9,41 +9,36 @@ keywords: [csrf, security, hacking, vulnerability] Example Cross Site Request Forgery (CSRF) vulnerabilities in action. + ## Requirements * [git](https://git-scm.com/downloads) * [Golang](https://golang.org/) + ## Install Go Modules Like any golang project, you will need to download and install the required modules for the project to run. Change into the "csrf" directory: - ```bash cd csrf ``` And then: - ```bash go mod vendor && go mod download && go mod tidy ``` - This command installs the golang dependencies needed to run the project in a new directory named `vendor`. Once the modules have finished installing, you can run the project like this: - ```bash go run main.go ``` - OR - ```bash go run main.go withoutCsrf ``` You should see the following if everything is OK: - ``` Server started and listening at localhost:3000 ``` @@ -51,24 +46,21 @@ Server started and listening at localhost:3000 ## Try the demo Start the server without csrf, to see the dangers of these attacks - ```bash go run main.go withoutCsrf ``` - Open your browser to and navigate to [localhost:3000](http://localhost:3000). Login using the test account: - * Username: `bob` * Password: `test` In a new tab, navigate to [localhost:3001](http://localhost:3001) to view some examples of CSRF exploits. You will notice that the balance goes down everytime you load that page. This is because the page is successfully exploiting a CSRF vulnerability. + ## See the "fixed" version To see the csrf version of this demo, just stop the server by pressing __CTRL + C__ to kill the server process and then run - ```bash go run main.go ``` @@ -79,9 +71,9 @@ And once more try the page with the CSRF exploits: [localhost:3001](http://local You will notice now that the account balance is unchanged. + ## Going further Here are some useful links where you can learn more about this topic: - -* -* +* https://en.wikipedia.org/wiki/Cross-site_request_forgery +* https://www.owasp.org/index.php/Cross-Site_Request_Forgery_(CSRF) diff --git a/docker-nginx-loadbalancer/README.md b/docker-nginx-loadbalancer/README.md index 8bb1995847..b1af8d6974 100644 --- a/docker-nginx-loadbalancer/README.md +++ b/docker-nginx-loadbalancer/README.md @@ -26,9 +26,8 @@ To get a local copy up and running, follow these steps: 2. Navigate to the project directory. 3. Build the Docker image with docker compose 4. Run the Docker compose composition - ```bash docker compose up --build ``` - 5. Access the application at `http://localhost:8080/hello`. + diff --git a/ent-mysql/README.md b/ent-mysql/README.md index 16c111a415..9da67fb648 100644 --- a/ent-mysql/README.md +++ b/ent-mysql/README.md @@ -10,27 +10,21 @@ keywords: [ent, mysql, orm, rest] A sample program how to connect ent ORM ## How to start (If no ent dir) - Execute command first - ```bash go run -mod=mod entgo.io/ent/cmd/ent new Book ``` - go to `./ent/schema/book.go` and add fields(you want) to Book Schema - ```go // Fields of the Book. func (Book) Fields() []ent.Field { - return []ent.Field{ - field.String("title").NotEmpty(), - field.String("author").NotEmpty(), - } + return []ent.Field{ + field.String("title").NotEmpty(), + field.String("author").NotEmpty(), + } } ``` - Execute command - ```bash go generate ./ent ``` diff --git a/entgo-sveltekit/README.md b/entgo-sveltekit/README.md index 1e7f35bc04..bafe11f03e 100644 --- a/entgo-sveltekit/README.md +++ b/entgo-sveltekit/README.md @@ -20,17 +20,16 @@ To run the project, follow these steps: ```bash go run ./bin all ``` - 2. Once the build process is complete, you can start the application by running: - ```bash ./app ``` -## Available Commands +## Available Commands The following commands are available to manage the project: + | Command | Description | | --- | --- | | `go-run` | Run the Golang project. | @@ -49,6 +48,7 @@ To use this application, run the following command: go run ./bin ``` + API Routes ---------- @@ -65,17 +65,18 @@ The Go Fiber application provides the following API routes: Go Dependencies --------------- -- **Go Modules:** Go's built-in package manager used to manage dependencies for Go projects. -- **Entgo:** A Golang Object Relational Mapping (ORM) tool used to define and generate database schemas. -- **Fiber:** A fast and minimalist web framework for Golang. -- **Sqlite:** A small, lightweight, embedded SQL database engine. +- **Go Modules:** Go's built-in package manager used to manage dependencies for Go projects. +- **Entgo:** A Golang Object Relational Mapping (ORM) tool used to define and generate database schemas. +- **Fiber:** A fast and minimalist web framework for Golang. +- **Sqlite:** A small, lightweight, embedded SQL database engine. Npm Dependencies ---------------- -- **SvelteKit:** A JavaScript framework used to build modern web applications. -- **Tailwind CSS:** A fast and customizable CSS styling library. Can be used in SvelteKit projects. +- **SvelteKit:** A JavaScript framework used to build modern web applications. +- **Tailwind CSS:** A fast and customizable CSS styling library. Can be used in SvelteKit projects. ---------------- Author: [@ugurkorkmaz](https://github.com/ugurkorkmaz) + diff --git a/entgo-sveltekit/template/README.md b/entgo-sveltekit/template/README.md index da5f582985..0cd17d1536 100644 --- a/entgo-sveltekit/template/README.md +++ b/entgo-sveltekit/template/README.md @@ -19,29 +19,21 @@ The following scripts are available in the project's `package.json` file: To use the available scripts, you need to have Node.js and Npm (or Pnpm) installed on your system. Follow these steps: 1. Install the project dependencies by running the following command in the project's root directory: - ```bash npm install ``` - or - ```bash pnpm install ``` - 2. Once the installation is complete, you can run the desired script using the following command: - ```bash npm run (code) ``` - or - ```bash pnpm run (code) ``` - Replace `(code)` with one of the available scripts mentioned in the table above. 3. The corresponding action will be executed, and you can see the output in the terminal. diff --git a/file-server/README.md b/file-server/README.md index ceced8fde8..70aa55a15a 100644 --- a/file-server/README.md +++ b/file-server/README.md @@ -19,14 +19,12 @@ Ensure you have the following installed: ## Setup 1. Clone the repository: - ```sh git clone https://github.com/gofiber/recipes.git cd recipes/file-server ``` 2. Install dependencies: - ```sh go get ``` @@ -34,7 +32,6 @@ Ensure you have the following installed: ## Running the Application 1. Start the application: - ```sh go run main.go ``` diff --git a/firebase-auth/README.md b/firebase-auth/README.md index 9015c4c9da..0ca7810a89 100644 --- a/firebase-auth/README.md +++ b/firebase-auth/README.md @@ -19,7 +19,6 @@ SERVICE_ACCOUNT_JSON = "path to service account credential json" ``` ## Start - ``` go build go run main diff --git a/firebase-functions/README.md b/firebase-functions/README.md index cfa24432b5..1c70dff109 100644 --- a/firebase-functions/README.md +++ b/firebase-functions/README.md @@ -417,5 +417,4 @@ gcloud functions deploy MyCloudFunction --runtime go120 --trigger-http Congratulations! You’ve successfully configured and deployed a GoFiber application on Firebase Functions. This powerful combination allows you to build fast and efficient serverless applications. Experiment further with GoFiber features and Firebase integrations to unlock the full potential of your serverless architecture. Happy coding! ## Medium Post - - +https://medium.com/@kmltrk07/how-to-deploy-gofiber-app-to-firebase-functions-8d4d537a4464 diff --git a/gcloud-firebase/README.md b/gcloud-firebase/README.md index 6a7fb76797..00f141f8c8 100644 --- a/gcloud-firebase/README.md +++ b/gcloud-firebase/README.md @@ -12,7 +12,6 @@ Examples on how to run an application using Fiber on Google Cloud and connecting ## Running Locally * Run on the command line: - ``` go run cmd/main.go ``` @@ -30,7 +29,6 @@ After deploying the server on Cloud Run, you can get it's url on GCP Console ([l Or you can do it manually with those steps: * Run on the command line: - ``` export GCLOUD_PROJECT=[YOUR_PROJECT_ID] gcloud builds submit — -tag gcr.io/$GCLOUD_PROJECT/gcloud-fiber-firebase . @@ -43,7 +41,6 @@ gcloud beta run deploy --platform managed --image gcr.io/$GCLOUD_PROJECT/gcloud- This step will deploy the app to Google App Engine Standard Go enviroment. The app configuration and additional configurations can be tweaked on the `app.yaml` file. * Run on the command line: - ``` gcloud app deploy ``` @@ -55,7 +52,6 @@ This step will deploy a HTTP Cloud Function using Go enviroment. You can use the For the Cloud Functions env, Google enforces us to deploy a function that is a `http.HandlerFunc`, so on the file `functions.go` there is a workaround to reroute the HTTP call to the Fiber app instance. * Run on the command line: - ``` gcloud functions deploy HeroesAPI --runtime go111 --trigger-http ``` diff --git a/gcloud/README.md b/gcloud/README.md index 3ebeae3b6e..8f75a0a3de 100644 --- a/gcloud/README.md +++ b/gcloud/README.md @@ -12,7 +12,6 @@ Examples on how to run an application using Fiber on Google Cloud. ## Running Locally * Run on the command line: - ``` go run cmd/main.go ``` @@ -28,7 +27,6 @@ After deploying the server on Cloud Run, you can get it's url on GCP Console ([l Or you can do it manually with those steps: * Run on the command line: - ``` export GCLOUD_PROJECT=[YOUR_PROJECT_ID] gcloud builds submit — -tag gcr.io/$GCLOUD_PROJECT/gcloud-fiber . @@ -40,7 +38,6 @@ gcloud beta run deploy --platform managed --image gcr.io/$GCLOUD_PROJECT/gcloud- This step will deploy the app to Google App Engine Standard Go enviroment. The app configuration and additional configurations can be tweaked on the `app.yaml` file. * Run on the command line: - ``` gcloud app deploy ``` @@ -52,7 +49,6 @@ This step will deploy a HTTP Cloud Function using Go enviroment. You can use the For the Cloud Functions env, Google enforces us to deploy a function that is a `http.HandlerFunc`, so on the file `functions.go` there is a workaround to reroute the HTTP call to the Fiber app instance. * Run on the command line: - ``` gcloud functions deploy MyCloudFunction --runtime go111 --trigger-http ``` diff --git a/geoip-maxmind/README.md b/geoip-maxmind/README.md index ca2ce33fc0..7bde0ffcd0 100644 --- a/geoip-maxmind/README.md +++ b/geoip-maxmind/README.md @@ -10,8 +10,7 @@ keywords: [geoip, maxmind, databases] This is an alternative method to resolve IP addresses to real-world location data using MaxMind GeoLite2 City databases. ## Prerequisites - -Before you run this, you must first download a database from the MaxMind website - . To do this, you may need to register for a free account. +Before you run this, you must first download a database from the MaxMind website - https://dev.maxmind.com/geoip/geoip2/geolite2/. To do this, you may need to register for a free account. The database you need to download is the one with the edition ID `GeoLite2-City`. Place it in this folder and run @@ -20,7 +19,6 @@ go run geoip-maxmind ``` ## Usage - Make a request to `http://127.0.0.1:3000/geo/178.62.56.160`, for example. You can omit an IP address to use your current IP address, or replace to use another. If the IP address is invalid, a HTTP 400 is returned. The response fields can be modified from the `ipLookup` struct, found in the `handlers/handlers.go` file. diff --git a/geoip/README.md b/geoip/README.md index da2f8e59d1..53f2204ef6 100644 --- a/geoip/README.md +++ b/geoip/README.md @@ -21,14 +21,12 @@ Ensure you have the following installed: ## Setup 1. Clone the repository: - ```sh git clone https://github.com/gofiber/recipes.git cd recipes/geoip ``` 2. Install dependencies: - ```sh go get ``` @@ -38,7 +36,6 @@ Ensure you have the following installed: ## Running the Application 1. Start the application: - ```sh go run main.go ``` diff --git a/gorm-mysql/README.md b/gorm-mysql/README.md index c33ac9e053..8dfb672ba8 100644 --- a/gorm-mysql/README.md +++ b/gorm-mysql/README.md @@ -18,20 +18,17 @@ This is a sample program demonstrating how to use GORM as an ORM to connect to a ## Setup 1. Clone the repository: - ```sh git clone https://github.com/gofiber/recipes.git cd recipes/gorm-mysql ``` 2. Install dependencies: - ```sh go mod tidy ``` 3. Configure the database connection in the `config.json` file: - ```json { "DB_Username": "your_db_username", @@ -45,7 +42,6 @@ This is a sample program demonstrating how to use GORM as an ORM to connect to a ## Running the Application 1. Run the application: - ```sh go run main.go ``` @@ -66,31 +62,26 @@ This is a sample program demonstrating how to use GORM as an ORM to connect to a ## Example Requests ### Get All Books - ```sh curl -X GET http://localhost:3000/allbooks ``` ### Get Book by ID - ```sh curl -X GET http://localhost:3000/book/1 ``` ### Create a New Book - ```sh curl -X POST http://localhost:3000/book -d '{"title": "New Book", "author": "Author Name"}' -H "Content-Type: application/json" ``` ### Update a Book - ```sh curl -X PUT http://localhost:3000/book -d '{"id": 1, "title": "Updated Book", "author": "Updated Author"}' -H "Content-Type: application/json" ``` ### Delete a Book - ```sh curl -X DELETE http://localhost:3000/book -d '{"id": 1}' -H "Content-Type: application/json" ``` diff --git a/gorm-postgres/README.md b/gorm-postgres/README.md index 26226b92af..bf99a60b0b 100644 --- a/gorm-postgres/README.md +++ b/gorm-postgres/README.md @@ -21,20 +21,17 @@ Ensure you have the following installed: ## Setup 1. Clone the repository: - ```sh git clone https://github.com/gofiber/recipes.git cd recipes/gorm-postgres ``` 2. Install dependencies: - ```sh go get ``` 3. Set up PostgreSQL and create a database: - ```sh createdb mydb ``` @@ -44,7 +41,6 @@ Ensure you have the following installed: ## Running the Application 1. Start the application: - ```sh go run main.go ``` diff --git a/gorm/README.md b/gorm/README.md index 084000a691..c66f9f2021 100644 --- a/gorm/README.md +++ b/gorm/README.md @@ -17,14 +17,12 @@ This is a sample program demonstrating how to use GORM as an ORM to connect to a ## Setup 1. Clone the repository: - ```sh git clone https://github.com/gofiber/recipes.git cd recipes/gorm-example ``` 2. Install dependencies: - ```sh go mod tidy ``` @@ -32,7 +30,6 @@ This is a sample program demonstrating how to use GORM as an ORM to connect to a ## Running the Application 1. Run the application: - ```sh go run main.go ``` @@ -51,25 +48,21 @@ This is a sample program demonstrating how to use GORM as an ORM to connect to a ## Example Requests ### Get All Books - ```sh curl -X GET http://localhost:3000/api/v1/book ``` ### Get Book by ID - ```sh curl -X GET http://localhost:3000/api/v1/book/1 ``` ### Create a New Book - ```sh curl -X POST http://localhost:3000/api/v1/book -d '{"title": "New Book", "author": "Author Name"}' -H "Content-Type: application/json" ``` ### Delete a Book - ```sh curl -X DELETE http://localhost:3000/api/v1/book/1 ``` diff --git a/graphql/README.md b/graphql/README.md index c52003a635..0d7a8a939c 100644 --- a/graphql/README.md +++ b/graphql/README.md @@ -20,20 +20,17 @@ Ensure you have the following installed: ## Setup 1. Clone the repository: - ```sh git clone https://github.com/gofiber/recipes.git cd recipes/graphql ``` 2. Install dependencies: - ```sh go get ``` 3. Initialize gqlgen: - ```sh go run github.com/99designs/gqlgen init ``` @@ -41,7 +38,6 @@ Ensure you have the following installed: ## Running the Application 1. Start the application: - ```sh go run main.go ``` diff --git a/grpc/README.md b/grpc/README.md index cd472989da..01594060f8 100644 --- a/grpc/README.md +++ b/grpc/README.md @@ -3,7 +3,7 @@ title: gRPC keywords: [grpc, server, client] --- -# Example for fiber as a client to gRPC server +# Example for fiber as a client to gRPC server. [![Github](https://img.shields.io/static/v1?label=&message=Github&color=2ea44f&style=for-the-badge&logo=github)](https://github.com/gofiber/recipes/tree/master/grpc) [![StackBlitz](https://img.shields.io/static/v1?label=&message=StackBlitz&color=2ea44f&style=for-the-badge&logo=StackBlitz)](https://stackblitz.com/github/gofiber/recipes/tree/master/grpc) @@ -17,14 +17,12 @@ A sample program to showcase fiber as a client to a gRPC server. ## Setup 1. Clone the repository: - ```sh git clone https://github.com/gofiber/recipes.git cd recipes/grpc ``` 2. Install dependencies: - ```sh go mod tidy ``` @@ -32,13 +30,11 @@ A sample program to showcase fiber as a client to a gRPC server. ## Running the Application 1. Run the gRPC server: - ```sh go run server/main.go ``` 2. Run the Fiber client: - ```sh go run client/main.go ``` diff --git a/hello-world/README.md b/hello-world/README.md index bc732019f3..51d57461f1 100644 --- a/hello-world/README.md +++ b/hello-world/README.md @@ -19,14 +19,12 @@ Ensure you have the following installed: ## Setup 1. Clone the repository: - ```sh git clone https://github.com/gofiber/recipes.git cd recipes/hello-world ``` 2. Install dependencies: - ```sh go get ``` @@ -34,7 +32,6 @@ Ensure you have the following installed: ## Running the Application 1. Start the application: - ```sh go run main.go ``` diff --git a/heroku/README.md b/heroku/README.md index f9fa6717c5..9481c88373 100644 --- a/heroku/README.md +++ b/heroku/README.md @@ -20,38 +20,32 @@ Ensure you have the following installed: ## Setup 1. Clone the repository: - ```sh git clone https://github.com/gofiber/recipes.git cd recipes/heroku ``` 2. Install dependencies: - ```sh go get ``` 3. Log in to Heroku: - ```sh heroku login ``` 4. Create a new Heroku application: - ```sh heroku create ``` 5. Add a `Procfile` to the project directory with the following content: - ``` web: go run main.go ``` 6. Deploy the application to Heroku: - ```sh git add . git commit -m "Deploy to Heroku" @@ -61,7 +55,6 @@ Ensure you have the following installed: ## Running the Application 1. Open the application in your browser: - ```sh heroku open ``` diff --git a/hexagonal/README.md b/hexagonal/README.md index 5a777fc952..1d48d4f650 100644 --- a/hexagonal/README.md +++ b/hexagonal/README.md @@ -20,20 +20,17 @@ This project presents a simple product catalogue microservice to demonstrate the ## Setup 1. Clone the repository: - ```sh git clone https://github.com/gofiber/recipes.git cd recipes/hexagonal ``` 2. Install dependencies: - ```sh go mod tidy ``` 3. Configure the MongoDB connection in the `config.json` file: - ```json { "DB_URI": "your_mongodb_uri", @@ -44,7 +41,6 @@ This project presents a simple product catalogue microservice to demonstrate the ## Running the Application 1. Run the application: - ```sh go run main.go ``` @@ -64,31 +60,26 @@ This project presents a simple product catalogue microservice to demonstrate the ## Example Requests ### Get All Products - ```sh curl -X GET http://localhost:3000/api/v1/products ``` ### Get Product by ID - ```sh curl -X GET http://localhost:3000/api/v1/product/1 ``` ### Create a New Product - ```sh curl -X POST http://localhost:3000/api/v1/product -d '{"name": "New Product", "price": 100}' -H "Content-Type: application/json" ``` ### Update a Product - ```sh curl -X PUT http://localhost:3000/api/v1/product/1 -d '{"name": "Updated Product", "price": 150}' -H "Content-Type: application/json" ``` ### Delete a Product - ```sh curl -X DELETE http://localhost:3000/api/v1/product/1 ``` @@ -100,6 +91,5 @@ Hexagonal architecture, also known as ports and adapters architecture, is a desi ## Additional Information For more information on hexagonal architecture, you can refer to the following resources: - - [Hexagonal Architecture](https://alistair.cockburn.us/hexagonal-architecture/) - [Hexagonal Architecture in Golang](https://medium.com/@matryer/hexagonal-architecture-in-go-2b5e0df2d8f8) diff --git a/https-pkcs12-tls/README.md b/https-pkcs12-tls/README.md index 00187b5a27..bc8270bddc 100644 --- a/https-pkcs12-tls/README.md +++ b/https-pkcs12-tls/README.md @@ -20,14 +20,12 @@ Ensure you have the following installed: ## Setup 1. Clone the repository: - ```sh git clone https://github.com/gofiber/recipes.git cd recipes/https-pkcs12-tls ``` 2. Install dependencies: - ```sh go get ``` @@ -37,7 +35,6 @@ Ensure you have the following installed: ## Running the Application 1. Start the application: - ```sh go run main.go ``` diff --git a/https-tls/README.md b/https-tls/README.md index a51b8683b8..7f3f1a0c83 100644 --- a/https-tls/README.md +++ b/https-tls/README.md @@ -20,14 +20,12 @@ Ensure you have the following installed: ## Setup 1. Clone the repository: - ```sh git clone https://github.com/gofiber/recipes.git cd recipes/https-tls ``` 2. Install dependencies: - ```sh go get ``` @@ -37,7 +35,6 @@ Ensure you have the following installed: ## Running the Application 1. Start the application: - ```sh go run main.go ``` diff --git a/jwt/README.md b/jwt/README.md index 22156db3d7..0ebc6931d4 100644 --- a/jwt/README.md +++ b/jwt/README.md @@ -17,14 +17,12 @@ This example demonstrates how to use JSON Web Tokens (JWT) for authentication in ## Setup 1. Clone the repository: - ```sh git clone https://github.com/gofiber/recipes.git cd recipes/jwt ``` 2. Install dependencies: - ```sh go mod tidy ``` @@ -32,7 +30,6 @@ This example demonstrates how to use JSON Web Tokens (JWT) for authentication in ## Running the Application 1. Run the application: - ```sh go run main.go ``` @@ -49,13 +46,11 @@ This example demonstrates how to use JSON Web Tokens (JWT) for authentication in ## Example Requests ### Login - ```sh curl -X POST http://localhost:3000/login -d '{"username": "user", "password": "pass"}' -H "Content-Type: application/json" ``` ### Access Restricted Route - ```sh curl -X GET http://localhost:3000/restricted -H "Authorization: Bearer " ``` diff --git a/k8s/README.md b/k8s/README.md index f4402ddf38..f32879f8d0 100644 --- a/k8s/README.md +++ b/k8s/README.md @@ -23,32 +23,27 @@ Ensure you have the following installed: ## Setup 1. Clone the repository: - ```sh git clone https://github.com/gofiber/recipes.git cd recipes/k8s ``` 2. Install dependencies: - ```sh go get ``` 3. Build the Docker image: - ```sh docker build -t fiber-k8s-example . ``` 4. Start Minikube (if using Minikube): - ```sh minikube start ``` 5. Deploy the application to Kubernetes: - ```sh kubectl apply -f deployment.yaml ``` @@ -56,13 +51,11 @@ Ensure you have the following installed: ## Running the Application 1. Check the status of the pods: - ```sh kubectl get pods ``` 2. Forward the port to access the application: - ```sh kubectl port-forward svc/fiber-k8s-example 3000:3000 ``` diff --git a/memgraph/README.md b/memgraph/README.md index 606d419fa8..d298c4752c 100644 --- a/memgraph/README.md +++ b/memgraph/README.md @@ -56,6 +56,5 @@ http://localhost:3000/developer/Andy ## Additional resources For extra information use the documentation on the following links: - -- Fiber: -- Memgraph: +- Fiber: https://docs.gofiber.io/ +- Memgraph: https://memgraph.com/docs diff --git a/minio/README.md b/minio/README.md index ef57cb8e17..dd83a85b96 100644 --- a/minio/README.md +++ b/minio/README.md @@ -61,11 +61,9 @@ go mod download ``` 3. Upload a file using `curl` or `Postman`: - ```bash curl -F "document=@/path/to/your/file" http://localhost:3000/upload ``` - 4. Download the file by specifying its name in the request: ```bash diff --git a/mongodb/README.md b/mongodb/README.md index e424812646..dde4f8af15 100644 --- a/mongodb/README.md +++ b/mongodb/README.md @@ -21,14 +21,12 @@ Ensure you have the following installed: ## Setup 1. Clone the repository: - ```sh git clone https://github.com/gofiber/recipes.git cd recipes/mongodb ``` 2. Install dependencies: - ```sh go get ``` @@ -38,7 +36,6 @@ Ensure you have the following installed: ## Running the Application 1. Start the application: - ```sh go run main.go ``` diff --git a/multiple-ports/README.md b/multiple-ports/README.md index 4f4b38d46e..1545b7d5c9 100644 --- a/multiple-ports/README.md +++ b/multiple-ports/README.md @@ -19,14 +19,12 @@ Ensure you have the following installed: ## Setup 1. Clone the repository: - ```sh git clone https://github.com/gofiber/recipes.git cd recipes/multiple-ports ``` 2. Install dependencies: - ```sh go get ``` @@ -34,7 +32,6 @@ Ensure you have the following installed: ## Running the Application 1. Start the application: - ```sh go run main.go ``` @@ -78,7 +75,6 @@ func main() { ``` In this example: - - The application listens on multiple ports (`:3000` and `:3001`). - A `sync.WaitGroup` is used to wait for all goroutines to finish. diff --git a/mysql/README.md b/mysql/README.md index 044008502a..c3fced94e5 100644 --- a/mysql/README.md +++ b/mysql/README.md @@ -21,14 +21,12 @@ Ensure you have the following installed: ## Setup 1. Clone the repository: - ```sh git clone https://github.com/gofiber/recipes.git cd recipes/mysql ``` 2. Install dependencies: - ```sh go get ``` @@ -38,7 +36,6 @@ Ensure you have the following installed: ## Running the Application 1. Start the application: - ```sh go run main.go ``` diff --git a/neo4j/README.md b/neo4j/README.md index b2a6141412..5b7d1b1608 100644 --- a/neo4j/README.md +++ b/neo4j/README.md @@ -21,14 +21,12 @@ Ensure you have the following installed: ## Setup 1. Clone the repository: - ```sh git clone https://github.com/gofiber/recipes.git cd recipes/neo4j ``` 2. Install dependencies: - ```sh go get ``` @@ -38,7 +36,6 @@ Ensure you have the following installed: ## Running the Application 1. Start the application: - ```sh go run main.go ``` diff --git a/oauth2-google/README.md b/oauth2-google/README.md index d53d344a36..ec8d743d55 100644 --- a/oauth2-google/README.md +++ b/oauth2-google/README.md @@ -17,14 +17,12 @@ This example demonstrates how to implement Google OAuth2 authentication in a Fib ## Setup 1. Clone the repository: - ```sh git clone https://github.com/gofiber/recipes.git cd recipes/oauth2-google ``` 2. Install dependencies: - ```sh go mod tidy ``` @@ -32,7 +30,6 @@ This example demonstrates how to implement Google OAuth2 authentication in a Fib 3. Obtain OAuth credentials from [Google Developers Console](https://console.developers.google.com/). 4. Create a `.env` file in the root directory and add your Google OAuth credentials: - ```env GOOGLE_CLIENT_ID=your_client_id GOOGLE_CLIENT_SECRET=your_client_secret @@ -42,7 +39,6 @@ This example demonstrates how to implement Google OAuth2 authentication in a Fib ## Running the Application 1. Run the application: - ```sh go run main.go ``` @@ -59,13 +55,11 @@ This example demonstrates how to implement Google OAuth2 authentication in a Fib ## Example Requests ### Redirect to Google Login - ```sh curl -X GET http://localhost:3000/api/ ``` ### Google OAuth2 Callback - ```sh curl -X GET http://localhost:3000/api/auth/google/callback?state=state&code=code ``` diff --git a/optional-parameter/README.md b/optional-parameter/README.md index 43f15ae8bd..fada14f916 100644 --- a/optional-parameter/README.md +++ b/optional-parameter/README.md @@ -19,14 +19,12 @@ Ensure you have the following installed: ## Setup 1. Clone the repository: - ```sh git clone https://github.com/gofiber/recipes.git cd recipes/optional-parameter ``` 2. Install dependencies: - ```sh go get ``` @@ -34,7 +32,6 @@ Ensure you have the following installed: ## Running the Application 1. Start the application: - ```sh go run main.go ``` @@ -63,7 +60,6 @@ func main() { ``` In this example: - - The `:id?` parameter in the route is optional. - If the `id` parameter is not provided, it defaults to `"defaultID"`. diff --git a/postgresql/README.md b/postgresql/README.md index bed2593688..7f28692aee 100644 --- a/postgresql/README.md +++ b/postgresql/README.md @@ -20,14 +20,12 @@ Ensure you have the following installed: ## Setup 1. Clone the repository: - ```sh git clone https://github.com/gofiber/recipes.git cd recipes/postgresql ``` 2. Install dependencies: - ```sh go get ``` @@ -37,7 +35,6 @@ Ensure you have the following installed: ## Running the Application 1. Start the application: - ```sh go run main.go ``` diff --git a/prefork/README.md b/prefork/README.md index dc57cc2ca0..ed713bf370 100644 --- a/prefork/README.md +++ b/prefork/README.md @@ -19,14 +19,12 @@ Ensure you have the following installed: ## Setup 1. Clone the repository: - ```sh git clone https://github.com/gofiber/recipes.git cd recipes/prefork ``` 2. Install dependencies: - ```sh go get ``` @@ -34,7 +32,6 @@ Ensure you have the following installed: ## Running the Application 1. Start the application: - ```sh go run main.go ``` diff --git a/recover/README.md b/recover/README.md index a1069ca588..5a139b1427 100644 --- a/recover/README.md +++ b/recover/README.md @@ -19,14 +19,12 @@ Ensure you have the following installed: ## Setup 1. Clone the repository: - ```sh git clone https://github.com/gofiber/recipes.git cd recipes/recover ``` 2. Install dependencies: - ```sh go get ``` @@ -34,7 +32,6 @@ Ensure you have the following installed: ## Running the Application 1. Start the application: - ```sh go run main.go ``` diff --git a/rss-feed/README.md b/rss-feed/README.md index 105c1c3ceb..18a491766f 100644 --- a/rss-feed/README.md +++ b/rss-feed/README.md @@ -19,14 +19,12 @@ Ensure you have the following installed: ## Setup 1. Clone the repository: - ```sh git clone https://github.com/gofiber/recipes.git cd recipes/rss-feed ``` 2. Install dependencies: - ```sh go get ``` @@ -34,7 +32,6 @@ Ensure you have the following installed: ## Running the Application 1. Start the application: - ```sh go run main.go ``` diff --git a/server-timing/README.md b/server-timing/README.md index 670a0936b7..57cf25de32 100644 --- a/server-timing/README.md +++ b/server-timing/README.md @@ -19,14 +19,12 @@ Ensure you have the following installed: ## Setup 1. Clone the repository: - ```sh git clone https://github.com/gofiber/recipes.git cd recipes/server-timing ``` 2. Install dependencies: - ```sh go get ``` @@ -34,7 +32,6 @@ Ensure you have the following installed: ## Running the Application 1. Start the application: - ```sh go run main.go ``` diff --git a/sessions-sqlite3/README.md b/sessions-sqlite3/README.md index 42cda4ca8d..6426f0e1e6 100644 --- a/sessions-sqlite3/README.md +++ b/sessions-sqlite3/README.md @@ -23,20 +23,17 @@ The default table schema only stores session data and expiry, making it difficul ## Setup 1. Clone the repository: - ```sh git clone https://github.com/gofiber/recipes.git cd recipes/sessions-sqlite3 ``` 2. Install dependencies: - ```sh go mod tidy ``` 3. Create the sessions table in SQLite3: - ```sql CREATE TABLE sessions ( key TEXT PRIMARY KEY, @@ -49,7 +46,6 @@ The default table schema only stores session data and expiry, making it difficul ## Running the Application 1. Run the application: - ```sh go run main.go ``` diff --git a/socketio/README.md b/socketio/README.md index ab45dc642d..20edb8040f 100644 --- a/socketio/README.md +++ b/socketio/README.md @@ -17,14 +17,12 @@ This example demonstrates how to create a simple chatroom using WebSockets. The ## Setup 1. Clone the repository: - ```sh git clone https://github.com/gofiber/recipes.git cd recipes/socketio-chat ``` 2. Install dependencies: - ```sh go mod tidy ``` @@ -32,7 +30,6 @@ This example demonstrates how to create a simple chatroom using WebSockets. The ## Running the Application 1. Run the application: - ```sh go run main.go ``` @@ -42,7 +39,6 @@ This example demonstrates how to create a simple chatroom using WebSockets. The ## Connecting to the WebSocket To connect to the WebSocket, use the following URL: - ``` ws://localhost:3000/ws/ ``` @@ -50,7 +46,6 @@ ws://localhost:3000/ws/ ## Message Object Example Here is an example of a message object that can be sent between users: - ```json { "from": "", diff --git a/spa/README.md b/spa/README.md index e5e42a8bfa..ea06526827 100644 --- a/spa/README.md +++ b/spa/README.md @@ -20,21 +20,18 @@ Ensure you have the following installed: ## Setup 1. Clone the repository: - ```sh git clone https://github.com/gofiber/recipes.git cd recipes/spa ``` 2. Install frontend dependencies: - ```sh cd frontend npm install ``` 3. Install backend dependencies: - ```sh cd ../backend go get @@ -45,14 +42,12 @@ Ensure you have the following installed: ### Building Frontend Assets 1. Build the frontend assets: - ```sh cd frontend npm run build ``` 2. Watch frontend assets for changes: - ```sh npm run dev ``` @@ -60,7 +55,6 @@ Ensure you have the following installed: ### Running the Application 1. Start the Fiber backend application: - ```sh cd backend go run main.go diff --git a/sqlboiler/README.md b/sqlboiler/README.md index 10ccff893e..a61b296552 100644 --- a/sqlboiler/README.md +++ b/sqlboiler/README.md @@ -10,19 +10,14 @@ keywords: [sqlboiler, database, docker] > #### 🎯 [Fiber](https://github.com/gofiber/fiber) + [Sqlboiler](https://github.com/volatiletech/sqlboiler) Example ## 👀 Usage - #### 1. Run Postgres - ```bash -docker compose build +$ docker compose build ``` - ```bash -docker compose up +$ docker compose up ``` - #### 2. Wait 1-2 minutes - ```console [+] Running 2/0 ✔ Network sqlboiler_default Created 0.0s @@ -38,30 +33,21 @@ postgres | 2023-09-22 01:09:46.454 UTC [1] LOG: listening on Unix socket "/var postgres | 2023-09-22 01:09:46.461 UTC [30] LOG: database system was shut down at 2023-09-22 01:09:44 UTC postgres | 2023-09-22 01:09:46.468 UTC [1] LOG: database system is ready to accept connections ``` - -#### 3. You have to migrate the database -> -> ###### 🎯 It is a "database-first" ORM as opposed to "code-first" (like gorm/gorp). That means you must first create your database schema -> -> ###### 🎯 I used [golang-migrate](https://github.com/golang-migrate/migrate) to proceed with the migrate -> +#### 3. You have to migrate the database. +> ###### 🎯 It is a "database-first" ORM as opposed to "code-first" (like gorm/gorp). That means you must first create your database schema. +> ###### 🎯 I used [golang-migrate](https://github.com/golang-migrate/migrate) to proceed with the migrate. ###### 1. Make Migration files - ```bash -migrate create -ext sql -dir ./migrations -seq create_initial_table +$ migrate create -ext sql -dir ./migrations -seq create_initial_table ``` - ```console sqlboiler/migrations/000001_create_initial_table.up.sql sqlboiler/migrations/000001_create_initial_table.up.sql ``` - ###### 2. Migrate - ```bash -migrate -path migrations -database "postgresql://user:password@localhost:5432/fiber_demo?sslmode=disable" -verbose up +$ migrate -path migrations -database "postgresql://user:password@localhost:5432/fiber_demo?sslmode=disable" -verbose up ``` - ```console 2023/09/22 20:00:00 Start buffering 1/u create_initial_table 2023/09/22 20:00:00 Read and execute 1/u create_initial_table @@ -69,13 +55,10 @@ migrate -path migrations -database "postgresql://user:password@localhost:5432/fi 2023/09/22 20:00:00 Finished after 100.661625ms 2023/09/22 20:00:00 Closing source and database ``` - ###### 3. Rollback Migrate - ```bash -migrate -path migrations -database "postgresql://user:password@localhost:5432/fiber_demo?sslmode=disable" -verbose down +$ migrate -path migrations -database "postgresql://user:password@localhost:5432/fiber_demo?sslmode=disable" -verbose down ``` - ```console 2023/09/22 20:00:00 Are you sure you want to apply all down migrations? [y/N] y @@ -85,23 +68,16 @@ y 2023/09/22 20:00:00 Finished 1/d create_initial_table (read 39.681125ms, ran 66.220125ms) 2023/09/22 20:00:00 Finished after 1.83152475s ``` - #### 4. Use sqlboiler - ###### 1. Install - ```bash # Go 1.16 and above: $ go install github.com/volatiletech/sqlboiler/v4@latest $ go install github.com/volatiletech/sqlboiler/v4/drivers/sqlboiler-psql@latest ``` - ###### 2. Create a configuration file -> > ###### 🎯 The configuration file should be named sqlboiler.toml -> ###### Example - ```toml output = "models" wipe = true @@ -117,15 +93,11 @@ add-enum-types = true schema = "schema" blacklist = ["migrations", "other"] ``` - ###### 3. Create models -> -> ###### 🎯 After creating a configuration file that points at the database we want to generate models for, we can invoke the sqlboiler command line utility - +> ###### 🎯 After creating a configuration file that points at the database we want to generate models for, we can invoke the sqlboiler command line utility. ```bash -sqlboiler psql +$ sqlboiler psql ``` - ```text models/ ├── author.go diff --git a/sqlc/README.md b/sqlc/README.md index ba2aac0610..c3e2fab935 100644 --- a/sqlc/README.md +++ b/sqlc/README.md @@ -10,19 +10,14 @@ keywords: [database, sqlc, postgresql] > #### 🎯 [fiber](https://github.com/gofiber/fiber) + [sqlc](https://github.com/sqlc-dev/sqlc) Example ## 👀 Usage - #### 1. Run Postgres - ```bash -docker compose build +$ docker compose build ``` - ```bash -docker compose up +$ docker compose up ``` - #### 2. Wait 1-2 minutes - ```console [+] Running 2/0 ✔ Network sqlc_default Created 0.1s @@ -39,30 +34,21 @@ postgres | 2023-09-28 09:17:50.740 UTC [1] LOG: listening on Unix socket "/var postgres | 2023-09-28 09:17:50.751 UTC [30] LOG: database system was shut down at 2023-09-28 08:50:35 UTC postgres | 2023-09-28 09:17:50.770 UTC [1] LOG: database system is ready to accept connections ``` - -#### 3. You have to migrate the database -> -> ##### 🎯 It is a "database-first" ORM as opposed to "code-first" (like gorm/gorp). That means you must first create your database schema -> -> ##### 🎯 I used [golang-migrate](https://github.com/golang-migrate/migrate) to proceed with the migrate -> +#### 3. You have to migrate the database. +> ##### 🎯 It is a "database-first" ORM as opposed to "code-first" (like gorm/gorp). That means you must first create your database schema. +> ##### 🎯 I used [golang-migrate](https://github.com/golang-migrate/migrate) to proceed with the migrate. ###### 1. Make Migration files - ```bash -migrate create -ext sql -dir ./database/migrations -seq create_initial_table +$ migrate create -ext sql -dir ./database/migrations -seq create_initial_table ``` - ```console sqlc/database/migrations/000001_create_initial_table.up.sql sqlc/database/migrations/000001_create_initial_table.up.sql ``` - ###### 2. Migrate - ```bash -migrate -path database/migrations -database "postgresql://user:password@localhost:5432/fiber_demo?sslmode=disable" -verbose up +$ migrate -path database/migrations -database "postgresql://user:password@localhost:5432/fiber_demo?sslmode=disable" -verbose up ``` - ```console 2023/09/28 20:00:00 Start buffering 1/u create_initial_table 2023/09/28 20:00:00 Read and execute 1/u create_initial_table @@ -70,13 +56,10 @@ migrate -path database/migrations -database "postgresql://user:password@localhos 2023/09/28 20:00:00 Finished after 100.661625ms 2023/09/28 20:00:00 Closing source and database ``` - ###### 3. Rollback Migrate - ```bash -migrate -path database/migrations -database "postgresql://user:password@localhost:5432/fiber_demo?sslmode=disable" -verbose down +$ migrate -path database/migrations -database "postgresql://user:password@localhost:5432/fiber_demo?sslmode=disable" -verbose down ``` - ```console 2023/09/28 20:00:00 Are you sure you want to apply all down migrations? [y/N] y @@ -86,11 +69,8 @@ y 2023/09/28 20:00:00 Finished 1/d create_initial_table (read 39.681125ms, ran 66.220125ms) 2023/09/28 20:00:00 Finished after 1.83152475s ``` - #### 4. Use sqlc - ###### 1. Install - ```bash # Go 1.17 and above: $ go install github.com/sqlc-dev/sqlc/cmd/sqlc@latest @@ -98,13 +78,9 @@ $ go install github.com/sqlc-dev/sqlc/cmd/sqlc@latest # Go 1.16 and below: go get github.com/sqlc-dev/sqlc/cmd/sqlc ``` - ###### 2. Create a configuration file - ###### Example - ###### sqlc.yaml - ```yaml version: "2" sql: @@ -116,9 +92,7 @@ sql: package: "sqlc" out: "database/sqlc" ``` - ###### author.sql - ```sql -- name: GetAuthors :many SELECT * FROM author; @@ -135,9 +109,7 @@ UPDATE author SET email = $1, name = $2 WHERE id = $3 RETURNING *; -- name: DeleteAuthor :exec DELETE FROM author WHERE id = $1; ``` - ###### post.sql - ```sql -- name: GetPosts :many SELECT * FROM post; @@ -155,13 +127,10 @@ UPDATE post SET title = $1, content = $2, author = $3 WHERE id = $4 RETURNING *; DELETE FROM post WHERE id = $1; ``` - ###### 3. Generate - ```bash -sqlc generate +$ sqlc generate ``` - ```text sqlc/ ├── author.sql.go @@ -169,7 +138,5 @@ sqlc/ ├── models.go ├── post.sql.go ``` - #### 5. Reference - [sqlc document](https://docs.sqlc.dev/en/stable/) diff --git a/sse/README.md b/sse/README.md index 40babc24c0..ebee76e764 100644 --- a/sse/README.md +++ b/sse/README.md @@ -21,14 +21,12 @@ Server-Sent Events (SSE) allow servers to push updates to the client over a sing ## Setup 1. Clone the repository: - ```sh git clone https://github.com/gofiber/recipes.git cd recipes/sse ``` 2. Install dependencies: - ```sh go mod tidy ``` @@ -36,7 +34,6 @@ Server-Sent Events (SSE) allow servers to push updates to the client over a sing ## Running the Application 1. Run the application: - ```sh go run main.go ``` @@ -68,6 +65,5 @@ The HTML file provides a simple user interface to connect to the SSE endpoint an Server-Sent Events (SSE) is a standard allowing servers to push data to web clients over HTTP. Unlike WebSockets, which require a full-duplex connection, SSE uses a unidirectional connection from the server to the client. This makes SSE simpler to implement and more efficient for scenarios where only the server needs to send updates. For more information on SSE, you can refer to the following resources: - - [Server-Sent Events on MDN](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events) - [Server-Sent Events on Wikipedia](https://en.wikipedia.org/wiki/Server-sent_events) diff --git a/stream-request-body/README.md b/stream-request-body/README.md index 016c29bedf..d315fbe83e 100644 --- a/stream-request-body/README.md +++ b/stream-request-body/README.md @@ -19,14 +19,12 @@ Ensure you have the following installed: ## Setup 1. Clone the repository: - ```sh git clone https://github.com/gofiber/recipes.git cd recipes/stream-request-body ``` 2. Install dependencies: - ```sh go get ``` @@ -34,7 +32,6 @@ Ensure you have the following installed: ## Running the Application 1. Start the application: - ```sh go run main.go ``` diff --git a/svelte-netlify/README.md b/svelte-netlify/README.md index 1e95e3f5c5..c1512de5b0 100644 --- a/svelte-netlify/README.md +++ b/svelte-netlify/README.md @@ -9,12 +9,13 @@ keywords: [netlify, deploy, svelte] [![Netlify Status](https://api.netlify.com/api/v1/badges/143c3c42-60f7-427a-b3fd-8ca3947a2d40/deploy-status)](https://app.netlify.com/sites/gofiber-svelte/deploys) -### Demo @ +### Demo @ https://gofiber-svelte.netlify.app/ #### Based on the fiber-lambda API written by Fenny. Since the code hasn't been merged yet, I borrowed it into `adapter/adapter.go` The app uses static pages under `public` directory. These are compiled using sveltejs and the complete template can be found [here](https://github.com/amalshaji/gofiber-sveltejs-netlify). + ```toml # netlify.toml @@ -36,7 +37,6 @@ The app uses static pages under `public` directory. These are compiled using sve Deploying `net/http to Netlify` explains what these functions are doing. You can read it [here](https://blog.carlmjohnson.net/post/2020/how-to-host-golang-on-netlify-for-free/). #### TL;DR - - build command builds the whole code to binary `cmd/gateway/gateway` - we're building something called [netlify functions](https://functions.netlify.com/) (Please read) - everything under public folder will be published(entrypoint: `index.html`) @@ -44,5 +44,4 @@ Deploying `net/http to Netlify` explains what these functions are doing. You can - status = 200 for server side redirects #### Important - Netlify functions allows you to have up to 125,000 requests a month. This means you can have 2.89 requests per minute. Make sure you use `Cache` in you request handlers. diff --git a/sveltekit-embed/README.md b/sveltekit-embed/README.md index 6f8a0ef9c9..3dad48a1b5 100644 --- a/sveltekit-embed/README.md +++ b/sveltekit-embed/README.md @@ -20,17 +20,16 @@ To run the project, follow these steps: ```bash make all ``` - 2. Once the build process is complete, you can start the application by running: - ```bash ./app ``` -## Available Commands +## Available Commands The following commands are available to manage the project: + | Command | Description | | --- | --- | | `info` | Info command. Displays the available commands and the purpose of the application. | @@ -46,6 +45,7 @@ To use this application, run the following command: make ``` + API Routes ---------- @@ -58,16 +58,17 @@ The Go Fiber application provides the following API routes: Go Dependencies --------------- -- **Go Modules:** Go's built-in package manager used to manage dependencies for Go projects. -- **Fiber:** A fast and minimalist web framework for Golang. +- **Go Modules:** Go's built-in package manager used to manage dependencies for Go projects. +- **Fiber:** A fast and minimalist web framework for Golang. Npm Dependencies ---------------- -- **SvelteKit:** A JavaScript framework used to build modern web applications. -- **Tailwind CSS:** A fast and customizable CSS styling library. Can be used in SvelteKit projects. -- **Skeleton UI:** This is a fully featured UI Toolkit for building reactive interfaces quickly using Svelte and Tailwind. +- **SvelteKit:** A JavaScript framework used to build modern web applications. +- **Tailwind CSS:** A fast and customizable CSS styling library. Can be used in SvelteKit projects. +- **Skeleton UI:** This is a fully featured UI Toolkit for building reactive interfaces quickly using Svelte and Tailwind. ---------------- Author: [@ugurkorkmaz](https://github.com/ugurkorkmaz) + diff --git a/swagger/README.md b/swagger/README.md index 886fd00ad8..983c7711fb 100644 --- a/swagger/README.md +++ b/swagger/README.md @@ -19,14 +19,12 @@ Ensure you have the following installed: ## Setup 1. Clone the repository: - ```sh git clone https://github.com/gofiber/recipes.git cd recipes/swagger ``` 2. Install dependencies: - ```sh go get -u github.com/swaggo/swag/cmd/swag go get -u github.com/swaggo/gin-swagger @@ -36,7 +34,6 @@ Ensure you have the following installed: ## Generating Swagger Docs 1. Generate the Swagger documentation: - ```sh swag init ``` @@ -44,7 +41,6 @@ Ensure you have the following installed: ## Running the Application 1. Start the application: - ```sh go run main.go ``` diff --git a/tableflip/README.md b/tableflip/README.md index a4df5c754f..59087458e9 100644 --- a/tableflip/README.md +++ b/tableflip/README.md @@ -24,34 +24,28 @@ Tableflip is a library that allows you to update the running code and/or configu ## Steps 1. **Build v0.0.1 Demo:** - ```bash go build -o demo main.go ``` 2. **Run the Demo and Create a GET Request to `127.0.0.1:8080/version`:** - ```bash [PID: 123] v0.0.1 ``` 3. **Prepare a New Version:** - -- Change the `main.go` to update the version to "v0.0.2". -- Rebuild the demo: - + - Change the `main.go` to update the version to "v0.0.2". + - Rebuild the demo: ```bash go build -o demo main.go ``` 4. **Kill the Old Process:** - ```bash kill -s HUP 123 ``` 5. **Create the Request to the Version API Again:** - ```bash [PID: 123] v0.0.2 ``` diff --git a/template-asset-bundling/README.md b/template-asset-bundling/README.md index 9e4a142775..daf0925855 100644 --- a/template-asset-bundling/README.md +++ b/template-asset-bundling/README.md @@ -20,14 +20,12 @@ Ensure you have the following installed: ## Setup 1. Clone the repository: - ```sh git clone https://github.com/gofiber/recipes.git cd recipes/template-asset-bundling ``` 2. Install dependencies: - ```sh npm install ``` @@ -37,13 +35,11 @@ Ensure you have the following installed: ### Building Assets 1. Build the assets: - ```sh npm run build ``` 2. Watch assets for changes: - ```sh npm run dev ``` @@ -51,7 +47,6 @@ Ensure you have the following installed: ### Running the Application 1. Start the Fiber application: - ```sh go run main.go ``` diff --git a/template/README.md b/template/README.md index 2f917dac1f..dfbc333e69 100644 --- a/template/README.md +++ b/template/README.md @@ -20,14 +20,12 @@ Ensure you have the following installed: ## Setup 1. Clone the repository: - ```sh git clone https://github.com/gofiber/recipes.git cd recipes/template ``` 2. Install dependencies: - ```sh npm install ``` @@ -37,13 +35,11 @@ Ensure you have the following installed: ### Building Assets 1. Build the assets: - ```sh npm run build ``` 2. Watch assets for changes: - ```sh npm run dev ``` @@ -51,7 +47,6 @@ Ensure you have the following installed: ### Running the Application 1. Start the Fiber application: - ```sh go run main.go ``` diff --git a/todo-app-with-auth-gorm/README.md b/todo-app-with-auth-gorm/README.md index 2555afd7e9..5cc5dcac17 100644 --- a/todo-app-with-auth-gorm/README.md +++ b/todo-app-with-auth-gorm/README.md @@ -20,14 +20,12 @@ Ensure you have the following installed and available in your `GOPATH`: ## Installation 1. Clone the repository: - ```sh git clone https://github.com/gofiber/recipes.git cd recipes/todo-app-with-auth-gorm ``` 2. Install dependencies: - ```sh go get ``` @@ -35,7 +33,6 @@ Ensure you have the following installed and available in your `GOPATH`: ## Running the Application 1. Start the application: - ```sh air ``` diff --git a/unit-test/README.md b/unit-test/README.md index 2d74bdc00f..27c4b2e4f0 100644 --- a/unit-test/README.md +++ b/unit-test/README.md @@ -27,14 +27,12 @@ This project provides a basic setup for unit testing in a Go Fiber application. ## Setup 1. Clone the repository: - ```bash git clone https://github.com/gofiber/recipes.git cd recipes/unit-test ``` 2. Install the dependencies: - ```bash go mod download ``` @@ -42,7 +40,6 @@ This project provides a basic setup for unit testing in a Go Fiber application. ## Running the Tests To run the tests, use the following command: - ```bash go test ./... ``` @@ -140,7 +137,6 @@ The `app.Test` method in Fiber is used to simulate HTTP requests to the Fiber ap #### Usage of the `app.Test` Method The `app.Test` method takes two parameters: - 1. **req**: An `*http.Request` object representing the HTTP request to be tested. 2. **timeout**: An `int` value specifying the maximum time in milliseconds that the request can take. A value of `-1` disables the timeout. diff --git a/upload-file/README.md b/upload-file/README.md index 9bb9ce5f9f..2ce496c12a 100644 --- a/upload-file/README.md +++ b/upload-file/README.md @@ -28,14 +28,12 @@ This project provides a basic setup for handling file uploads in a Go Fiber appl ## Setup 1. Clone the repository: - ```bash git clone https://github.com/gofiber/recipes.git cd recipes/upload-file ``` 2. Install the dependencies: - ```bash go mod download ``` @@ -45,19 +43,16 @@ This project provides a basic setup for handling file uploads in a Go Fiber appl ### Single File Upload 1. Navigate to the `single` directory: - ```bash cd single ``` 2. Run the application: - ```bash go run main.go ``` 3. Use a tool like `curl` or Postman to upload a file: - ```bash curl -F "document=@/path/to/your/file" http://localhost:3000/ ``` @@ -65,19 +60,16 @@ This project provides a basic setup for handling file uploads in a Go Fiber appl ### Single File Upload with Relative Path 1. Navigate to the `single_relative_path` directory: - ```bash cd single_relative_path ``` 2. Run the application: - ```bash go run main.go ``` 3. Use a tool like `curl` or Postman to upload a file: - ```bash curl -F "document=@/path/to/your/file" http://localhost:3000/ ``` @@ -85,19 +77,16 @@ This project provides a basic setup for handling file uploads in a Go Fiber appl ### Multiple File Upload 1. Navigate to the `multiple` directory: - ```bash cd multiple ``` 2. Run the application: - ```bash go run main.go ``` 3. Use a tool like `curl` or Postman to upload multiple files: - ```bash curl -F "documents=@/path/to/your/file1" -F "documents=@/path/to/your/file2" http://localhost:3000/ ``` diff --git a/url-shortener-api/README.md b/url-shortener-api/README.md index 880ce6323f..3ced490be4 100644 --- a/url-shortener-api/README.md +++ b/url-shortener-api/README.md @@ -38,7 +38,6 @@ This project provides a URL shortening service with a simple API. ## Setup 1. Start the containers: - ```sh docker-compose up -d ``` diff --git a/validation/README.md b/validation/README.md index ed0ae44323..1a1fe73aac 100644 --- a/validation/README.md +++ b/validation/README.md @@ -28,26 +28,22 @@ This project provides a basic setup for validating request data in a Go Fiber ap ## Setup 1. Clone the repository: - ```bash git clone https://github.com/gofiber/recipes.git cd recipes/validation ``` 2. Install the dependencies: - ```bash go mod download ``` 3. Create a `.env` file in the root directory with the following content: - ```dotenv PORT=":8080" ``` 4. Run the application: - ```bash go run main.go ``` @@ -57,7 +53,6 @@ The application should now be running on `http://localhost:8080`. ## Example Usage 1. Send a POST request to `http://localhost:8080/validate` with a JSON payload: - ```json { "name": "John Doe", diff --git a/vercel/README.md b/vercel/README.md index 01a85050e2..8344dd5132 100644 --- a/vercel/README.md +++ b/vercel/README.md @@ -28,14 +28,12 @@ This project provides a starting point for deploying a Go Fiber application to V ## Setup 1. Clone the repository: - ```bash git clone https://github.com/gofiber/recipes.git cd recipes/vercel ``` 2. Install the dependencies: - ```bash go mod download ``` @@ -55,19 +53,16 @@ Ensure the `vercel.json` file is present in the root directory to handle routing ## Deploy 1. Install the Vercel CLI: - ```bash npm install -g vercel ``` 2. Log in to Vercel: - ```bash vercel login ``` 3. Deploy the application: - ```bash vercel ``` diff --git a/websocket-chat/README.md b/websocket-chat/README.md index 6791d2a1c8..3c4b75d3e4 100644 --- a/websocket-chat/README.md +++ b/websocket-chat/README.md @@ -27,20 +27,17 @@ This project provides a basic setup for a WebSocket-based chat application using ## Setup 1. Clone the repository: - ```bash git clone https://github.com/gofiber/recipes.git cd recipes/websocket-chat ``` 2. Install the dependencies: - ```bash go mod download ``` 3. Run the application: - ```bash go run main.go ``` diff --git a/websocket/README.md b/websocket/README.md index cee83ed17e..426cc5ef21 100644 --- a/websocket/README.md +++ b/websocket/README.md @@ -26,20 +26,17 @@ This project provides a basic setup for a WebSocket server using Go Fiber. It in ## Setup 1. Clone the repository: - ```bash git clone https://github.com/gofiber/recipes.git cd recipes/websocket ``` 2. Install the dependencies: - ```bash go mod download ``` 3. Run the application: - ```bash go run main.go ``` From 88db22f7b5d61a5271ad46a4f03beed8312fe231 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ren=C3=A9?= Date: Tue, 26 Nov 2024 19:38:43 +0100 Subject: [PATCH 13/14] docusaurus preparations --- bootstrap/README.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/bootstrap/README.md b/bootstrap/README.md index 921341e3f6..aa0f7ef5c7 100644 --- a/bootstrap/README.md +++ b/bootstrap/README.md @@ -9,7 +9,7 @@ keywords: [bootstrap, gorm, validator, env] Fiber bootstrap for rapid development using Go-Fiber / Gorm / Validator. -# Components +## Components * Fiber * Html Engine Template * Logger @@ -19,11 +19,11 @@ Fiber bootstrap for rapid development using Go-Fiber / Gorm / Validator. * Validator * Env File -# Router +## Router API Router `/api` with rate limiter middleware Http Router `/` with CORS and CSRF middleware -# Setup +## Setup 1. Copy the example env file over: ``` From fdb7c347ea3937e073d421f9c41f79e3f59448d0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ren=C3=A9?= Date: Tue, 26 Nov 2024 19:51:25 +0100 Subject: [PATCH 14/14] docusaurus preparations --- autocert/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/autocert/README.md b/autocert/README.md index 9c04b9b946..7ce97ecd83 100644 --- a/autocert/README.md +++ b/autocert/README.md @@ -1,6 +1,6 @@ --- title: Autocert -keywords: [autocert, tls, letsencrypt, ssl, https] +keywords: [autocert, tls, letsencrypt, ssl, https, certificate] --- # Autocert Example