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/.github/scripts/sync_docs.sh b/.github/scripts/sync_docs.sh new file mode 100755 index 0000000000..d01d958995 --- /dev/null +++ b/.github/scripts/sync_docs.sh @@ -0,0 +1,55 @@ +#!/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) + +# 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}") + + 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..079fe23b94 --- /dev/null +++ b/.github/scripts/sync_local.sh @@ -0,0 +1,25 @@ +#!/usr/bin/env bash +set -e + +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)" + +# 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) + 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/.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/.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 e46e7ec61c..5a92c2b26b 100644 --- a/404-handler/README.md +++ b/404-handler/README.md @@ -1,5 +1,12 @@ +--- +title: 404 Handler +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/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 1d5fda0dd6..e8731a80ce 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,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) -- [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) -- [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) + +- [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/air/README.md b/air/README.md index fc0411d15a..431deb0f04 100644 --- a/air/README.md +++ b/air/README.md @@ -1,5 +1,12 @@ +--- +title: Air Live Reloading +keywords: [air, live reloading, development, air tool, hot reload, watch, changes] +--- + # 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 6027a0d796..1e66dcf3a8 100644 --- a/auth-docker-postgres-jwt/README.md +++ b/auth-docker-postgres-jwt/README.md @@ -1,5 +1,12 @@ +--- +title: Auth + Docker + Postgres + JWT +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-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 4be19a3e94..4335e100a7 100644 --- a/auth-jwt/README.md +++ b/auth-jwt/README.md @@ -1,5 +1,12 @@ +--- +title: Auth + JWT +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/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 b2f2dec5da..7ce97ecd83 100644 --- a/autocert/README.md +++ b/autocert/README.md @@ -1,5 +1,12 @@ +--- +title: Autocert +keywords: [autocert, tls, letsencrypt, ssl, https, certificate] +--- + # 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 5fb8e770b8..0f66990d4f 100644 --- a/aws-eb/README.md +++ b/aws-eb/README.md @@ -1,5 +1,12 @@ +--- +title: AWS Elastic Beanstalk +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 4d71597025..c79ff82cb0 100644 --- a/aws-sam-container/README.md +++ b/aws-sam-container/README.md @@ -1,4 +1,11 @@ -# app +--- +title: AWS SAM Container +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: @@ -28,10 +35,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 +127,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-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 331b2ef091..da028de1ae 100644 --- a/aws-sam/README.md +++ b/aws-sam/README.md @@ -1,4 +1,11 @@ -# sam-app +--- +title: AWS SAM +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: @@ -19,10 +26,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 +42,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 +145,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/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/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/bootstrap/README.md b/bootstrap/README.md new file mode 100644 index 0000000000..aa0f7ef5c7 --- /dev/null +++ b/bootstrap/README.md @@ -0,0 +1,39 @@ +--- +title: Bootstrap +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 +* Fiber + * Html Engine Template + * Logger + * Monitoring +* Gorm + * PGSQL Driver +* 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 + ``` + +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/fiber-bootstrap/app/controllers/main_controller.go b/bootstrap/app/controllers/main_controller.go similarity index 99% rename from fiber-bootstrap/app/controllers/main_controller.go rename to bootstrap/app/controllers/main_controller.go index f2cad9690e..f9643f38ae 100644 --- a/fiber-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/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 99% rename from fiber-bootstrap/main.go rename to bootstrap/main.go index e51b1d7c54..e1ea8da950 100644 --- a/fiber-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/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 99% rename from fiber-bootstrap/pkg/database/setup.go rename to bootstrap/pkg/database/setup.go index 337d1e5211..55ecf2bc6e 100644 --- a/fiber-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/fiber-bootstrap/pkg/env/env.go b/bootstrap/pkg/env/env.go similarity index 99% rename from fiber-bootstrap/pkg/env/env.go rename to bootstrap/pkg/env/env.go index c637711809..d761fda425 100644 --- a/fiber-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/fiber-bootstrap/pkg/router/api_router.go b/bootstrap/pkg/router/api_router.go similarity index 93% rename from fiber-bootstrap/pkg/router/api_router.go rename to bootstrap/pkg/router/api_router.go index 4351683248..5047ab5615 100644 --- a/fiber-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/fiber-bootstrap/pkg/router/http_router.go b/bootstrap/pkg/router/http_router.go similarity index 93% rename from fiber-bootstrap/pkg/router/http_router.go rename to bootstrap/pkg/router/http_router.go index 756a39ed1d..3e31269d5c 100644 --- a/fiber-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/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 99% rename from fiber-bootstrap/pkg/router/setup.go rename to bootstrap/pkg/router/setup.go index 05815ea43c..a8971cc449 100644 --- a/fiber-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/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..d0c6762db5 100644 --- a/clean-architecture/README.md +++ b/clean-architecture/README.md @@ -1,5 +1,12 @@ +--- +title: Clean Architecture +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/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 8461d15e44..930a4c3ba3 100644 --- a/cloud-run/README.md +++ b/cloud-run/README.md @@ -1,5 +1,12 @@ +--- +title: Cloud Run +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/fiber-colly-gorm/README.md b/colly-gorm/README.md similarity index 51% rename from fiber-colly-gorm/README.md rename to colly-gorm/README.md index ff69eee2fb..ee4b00486b 100644 --- a/fiber-colly-gorm/README.md +++ b/colly-gorm/README.md @@ -1,8 +1,15 @@ -## Simple Web Scraping Colly App with Fiber +--- +title: Colly Gorm +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 +## How to Run 1. Clone the repository. 2. Navigate to the project directory. @@ -11,6 +18,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 99% rename from fiber-colly-gorm/app/cmd/api/main.go rename to colly-gorm/app/cmd/api/main.go index 1c3ff79958..5d01c45f6a 100644 --- a/fiber-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/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 index 2127ff5cc4..c69afc3419 100644 --- a/fiber-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/database/models.go b/colly-gorm/app/internals/services/database/models.go new file mode 100644 index 0000000000..b12206b6e2 --- /dev/null +++ b/colly-gorm/app/internals/services/database/models.go @@ -0,0 +1,19 @@ +package database + +import "gorm.io/gorm" + +type Quote struct { + 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 99% rename from fiber-colly-gorm/app/internals/services/scrapers/coursera_courses.go rename to colly-gorm/app/internals/services/scrapers/coursera_courses.go index 3cb40db69f..5d41539047 100644 --- a/fiber-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/fiber-colly-gorm/app/internals/services/scrapers/toscrape.go b/colly-gorm/app/internals/services/scrapers/toscrape.go similarity index 99% rename from fiber-colly-gorm/app/internals/services/scrapers/toscrape.go rename to colly-gorm/app/internals/services/scrapers/toscrape.go index a0fe270afd..72bd4b7645 100644 --- a/fiber-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/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/csrf-with-session/README.md b/csrf-with-session/README.md index 6d79710c84..15e80eec08 100644 --- a/csrf-with-session/README.md +++ b/csrf-with-session/README.md @@ -1,5 +1,12 @@ +--- +title: CSRF + Session +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: @@ -107,7 +114,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..a772936ec1 100644 --- a/csrf/README.md +++ b/csrf/README.md @@ -1,5 +1,12 @@ +--- +title: CSRF +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/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/README.md b/docker-mariadb-clean-arch/README.md index 4dcec90b2a..d904dedcd1 100644 --- a/docker-mariadb-clean-arch/README.md +++ b/docker-mariadb-clean-arch/README.md @@ -1,5 +1,12 @@ +--- +title: Docker + MariaDB +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-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 a7d83e0bae..b1af8d6974 100644 --- a/docker-nginx-loadbalancer/README.md +++ b/docker-nginx-loadbalancer/README.md @@ -1,11 +1,11 @@ -# Docker+Nginx 🚀 - - - - Fiber - - +--- +title: Docker + Nginx +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 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/README.md b/dummyjson/README.md index 8e5f9ec5c4..7506f82922 100644 --- a/dummyjson/README.md +++ b/dummyjson/README.md @@ -1,5 +1,12 @@ -## Simple Fiber Proxy Server +--- +title: Dummy JSON Proxy +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 @@ -17,4 +24,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/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 706d1a03af..9da67fb648 100644 --- a/ent-mysql/README.md +++ b/ent-mysql/README.md @@ -1,8 +1,15 @@ -### Example ent ORM for fiber with MySQL +--- +title: Entgo ORM (MySQL) +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) +## How to start (If no ent dir) Execute command first ```bash go run -mod=mod entgo.io/ent/cmd/ent new Book @@ -22,7 +29,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..bafe11f03e 100644 --- a/entgo-sveltekit/README.md +++ b/entgo-sveltekit/README.md @@ -1,4 +1,12 @@ +--- +title: Entgo Sveltekit +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/entgo-sveltekit/template/README.md b/entgo-sveltekit/template/README.md index 401c8ce125..0cd17d1536 100644 --- a/entgo-sveltekit/template/README.md +++ b/entgo-sveltekit/template/README.md @@ -22,7 +22,7 @@ To use the available scripts, you need to have Node.js and Npm (or Pnpm) install ```bash npm install ``` - or + or ```bash pnpm install ``` @@ -30,11 +30,11 @@ To use the available scripts, you need to have Node.js and Npm (or Pnpm) install ```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/fiber-envoy-extauthz/README.md b/envoy-extauthz/README.md similarity index 70% rename from fiber-envoy-extauthz/README.md rename to envoy-extauthz/README.md index d3a72ada15..47e4c40f8b 100644 --- a/fiber-envoy-extauthz/README.md +++ b/envoy-extauthz/README.md @@ -1,4 +1,11 @@ -## 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 + +[![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). @@ -8,18 +15,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 +35,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-bootstrap/README.md b/fiber-bootstrap/README.md deleted file mode 100644 index 096ca12005..0000000000 --- a/fiber-bootstrap/README.md +++ /dev/null @@ -1,31 +0,0 @@ -# Fiber Bootstrap -Fiber bootstrap for rapid development using Go-Fiber / Gorm / Validator. - -# Components -* Fiber - * Html Engine Template - * Logger - * Monitoring -* Gorm - * PGSQL Driver -* 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 - ``` - -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. \ No newline at end of file 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..70aa55a15a --- /dev/null +++ b/file-server/README.md @@ -0,0 +1,66 @@ +--- +title: File Server +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 + +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 deleted file mode 100644 index d46de01b4e..0000000000 --- a/firebase-auth/README.MD +++ /dev/null @@ -1,18 +0,0 @@ -# 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 - -* 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. - -``` -SERVICE_ACCOUNT_JSON = "path to service account credential json" -``` - -### Start -``` -go build -go run main -``` \ No newline at end of file diff --git a/firebase-auth/README.md b/firebase-auth/README.md new file mode 100644 index 0000000000..0ca7810a89 --- /dev/null +++ b/firebase-auth/README.md @@ -0,0 +1,25 @@ +--- +title: Firebase Authentication +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 + +* 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. + +``` +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 05a0674b81..1c70dff109 100644 --- a/firebase-functions/README.md +++ b/firebase-functions/README.md @@ -1,6 +1,11 @@ - +--- +title: Firebase Functions +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 @@ -412,4 +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 \ No newline at end of file +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 9179f4e20f..00f141f8c8 100644 --- a/gcloud-firebase/README.md +++ b/gcloud-firebase/README.md @@ -1,15 +1,22 @@ +--- +title: Google Cloud Firebase +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 +## 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 +36,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 +45,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-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 545826262b..8f75a0a3de 100644 --- a/gcloud/README.md +++ b/gcloud/README.md @@ -1,15 +1,22 @@ +--- +title: Firebase GCloud +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 +## 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 +33,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 +42,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 +51,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/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 957a6cb000..7bde0ffcd0 100644 --- a/geoip-maxmind/README.md +++ b/geoip-maxmind/README.md @@ -1,8 +1,15 @@ +--- +title: GeoIP + MaxMind +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 + +## 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 +18,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 +47,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-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 2db46a21e9..53f2204ef6 100644 --- a/geoip/README.md +++ b/geoip/README.md @@ -1 +1,86 @@ -![](https://i.imgur.com/yifgkJ5.png) \ No newline at end of file +--- +title: GeoIP +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 + +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..8dfb672ba8 100644 --- a/gorm-mysql/README.md +++ b/gorm-mysql/README.md @@ -1,14 +1,87 @@ -### 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 +[![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) -| Method | URL | -| ------ | --------- | -| GET | /hello | -| GET | /allbooks | -| GET | /book/:id | -| POST | /book | -| PUT | /book | -| DELETE | /book | +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 + +- 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-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 new file mode 100644 index 0000000000..bf99a60b0b --- /dev/null +++ b/gorm-postgres/README.md @@ -0,0 +1,102 @@ +--- +title: GORM + PostgreSQL +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 + +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-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 new file mode 100644 index 0000000000..c66f9f2021 --- /dev/null +++ b/gorm/README.md @@ -0,0 +1,68 @@ +--- +title: GORM +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 + +- 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/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/README.md b/graceful-shutdown/README.md index f714c8d58a..bc808b5e6d 100644 --- a/graceful-shutdown/README.md +++ b/graceful-shutdown/README.md @@ -1,5 +1,12 @@ +--- +title: Graceful shutdown +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 @@ -18,7 +25,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/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 new file mode 100644 index 0000000000..0d7a8a939c --- /dev/null +++ b/graphql/README.md @@ -0,0 +1,84 @@ +--- +title: GraphQL +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 + +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..01594060f8 --- /dev/null +++ b/grpc/README.md @@ -0,0 +1,64 @@ +--- +title: gRPC +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 + +- 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 99% rename from fiber-grpc/client/main.go rename to grpc/client/main.go index 3ba8a2ed69..cc2678fef8 100644 --- a/fiber-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/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..51d57461f1 --- /dev/null +++ b/hello-world/README.md @@ -0,0 +1,67 @@ +--- +title: Hello World +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 + +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..9481c88373 --- /dev/null +++ b/heroku/README.md @@ -0,0 +1,96 @@ +--- +title: Heroku +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 + +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..1d48d4f650 100644 --- a/hexagonal/README.md +++ b/hexagonal/README.md @@ -1,4 +1,95 @@ +--- +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) +[![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) + +## 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/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 new file mode 100644 index 0000000000..bc8270bddc --- /dev/null +++ b/https-pkcs12-tls/README.md @@ -0,0 +1,109 @@ +--- +title: HTTPS with PKCS12 TLS +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 + +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-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 new file mode 100644 index 0000000000..7f3f1a0c83 --- /dev/null +++ b/https-tls/README.md @@ -0,0 +1,71 @@ +--- +title: HTTPS with TLS +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 + +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..1548924c10 100644 --- a/i18n/README.md +++ b/i18n/README.md @@ -1,5 +1,12 @@ +--- +title: I18n +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 76f7fd578a..0ebc6931d4 100644 --- a/jwt/README.md +++ b/jwt/README.md @@ -1,3 +1,60 @@ +--- +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 +[![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 + +- 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/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 new file mode 100644 index 0000000000..f32879f8d0 --- /dev/null +++ b/k8s/README.md @@ -0,0 +1,150 @@ +--- +title: Kubernetes +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 + +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/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 + ``` + +## 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..d298c4752c 100644 --- a/memgraph/README.md +++ b/memgraph/README.md @@ -1,4 +1,11 @@ -# Fiber and Memgraph +--- +title: Memgraph +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. 🚀 @@ -13,7 +20,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 +35,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 +57,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/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 385ba7317d..dd83a85b96 100644 --- a/minio/README.md +++ b/minio/README.md @@ -1,5 +1,12 @@ +--- +title: MinIO +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/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 new file mode 100644 index 0000000000..dde4f8af15 --- /dev/null +++ b/mongodb/README.md @@ -0,0 +1,91 @@ +--- +title: MongoDB Example +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 + +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/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 new file mode 100644 index 0000000000..1545b7d5c9 --- /dev/null +++ b/multiple-ports/README.md @@ -0,0 +1,83 @@ +--- +title: Multiple Ports +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 + +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..c3fced94e5 --- /dev/null +++ b/mysql/README.md @@ -0,0 +1,89 @@ +--- +title: MySQL +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 + +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..5b7d1b1608 --- /dev/null +++ b/neo4j/README.md @@ -0,0 +1,96 @@ +--- +title: Neo4j +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 + +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..ec8d743d55 100644 --- a/oauth2-google/README.md +++ b/oauth2-google/README.md @@ -1,14 +1,71 @@ +--- +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/ +[![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 + +- 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/). -## Endpoints -- /api/ - redirects to login url +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 + ``` -- /api/auth/google/callback - gives a callback to google and on success return's user's email +## 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/ | 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/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/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..3c2382e117 --- /dev/null +++ b/oauth2/README.md @@ -0,0 +1,88 @@ +```markdown +--- +title: OAuth2 +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 + +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..5721c8db33 100644 --- a/testOauth2/app.go +++ b/oauth2/app.go @@ -8,11 +8,12 @@ import ( "os" "os/signal" "syscall" - "testOauth2/config" - "testOauth2/models" - "testOauth2/router" "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/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 89% rename from testOauth2/handlers/handlers.go rename to oauth2/handlers/handlers.go index 46804c0c72..89cc1f6c5c 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" ) @@ -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/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 98% rename from testOauth2/middleware/auth.go rename to oauth2/middleware/auth.go index 3b21c9eb59..d112f5d78d 100644 --- a/testOauth2/middleware/auth.go +++ b/oauth2/middleware/auth.go @@ -2,7 +2,8 @@ package middleware import ( "fmt" - "testOauth2/models" + + "oauth2/models" "github.com/gofiber/fiber/v2" "github.com/gofiber/fiber/v2/middleware/session" @@ -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/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..e3235488ca 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" @@ -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/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..fada14f916 --- /dev/null +++ b/optional-parameter/README.md @@ -0,0 +1,68 @@ +--- +title: Optional Parameter Example +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 + +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/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 new file mode 100644 index 0000000000..e616d5b523 --- /dev/null +++ b/overview.go @@ -0,0 +1,178 @@ +package main + +import ( + "fmt" + "os" + "path/filepath" + "regexp" + "strings" +) + +var ( + titleRegex = regexp.MustCompile(`(?m)^title: (.+)`) + keywordsRegex = regexp.MustCompile(`(?m)^keywords: \[(.+)\]`) + headerRegex = regexp.MustCompile(`(?m)^# .+`) +) + +//go:generate go run overview.go +func main() { + // fetch current file directory + root, _ := os.Getwd() + toc := "" + 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 { + 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/README.md)\n", title, relativePath) + err = addLinksToReadme(readmePath, info.Name()) + if err != nil { + return err + } + } 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), 0o644) + 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 + } + + titleMatches := titleRegex.FindSubmatch(content) + keywordsMatches := keywordsRegex.FindSubmatch(content) + + var title string + if len(titleMatches) > 1 { + title = strings.TrimSpace(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 +} + +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, 0o644) +} diff --git a/parsley/README.md b/parsley/README.md index e28e258b05..ad78d267f3 100644 --- a/parsley/README.md +++ b/parsley/README.md @@ -1,5 +1,12 @@ +--- +title: Parsley +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 @@ -29,4 +36,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/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 new file mode 100644 index 0000000000..7f28692aee --- /dev/null +++ b/postgresql/README.md @@ -0,0 +1,90 @@ +--- +title: PostgreSQL +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 + +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 + ``` + +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 +package main + +import ( + "database/sql" + "log" + + "github.com/gofiber/fiber/v2" + _ "github.com/lib/pq" +) + +func main() { + // Database connection + 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..ed713bf370 --- /dev/null +++ b/prefork/README.md @@ -0,0 +1,71 @@ +--- +title: Prefork Example +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 + +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..e294d8fa5d 100644 --- a/rabbitmq/README.md +++ b/rabbitmq/README.md @@ -1,5 +1,12 @@ +--- +title: RabbitMQ +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 2e39c5f20b..c1a2d4fc74 100644 --- a/react-router/README.md +++ b/react-router/README.md @@ -1,5 +1,12 @@ +--- +title: React +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 new file mode 100644 index 0000000000..5a139b1427 --- /dev/null +++ b/recover/README.md @@ -0,0 +1,69 @@ +--- +title: Recover Middleware Example +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 + +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..18a491766f --- /dev/null +++ b/rss-feed/README.md @@ -0,0 +1,97 @@ +--- +title: RSS Feed +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 + +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..57cf25de32 --- /dev/null +++ b/server-timing/README.md @@ -0,0 +1,73 @@ +--- +title: Server Timing +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 + +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..6426f0e1e6 100644 --- a/sessions-sqlite3/README.md +++ b/sessions-sqlite3/README.md @@ -1,9 +1,57 @@ +--- +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. +[![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 +- 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 + +- 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/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 21fbaf320c..20edb8040f 100644 --- a/socketio/README.md +++ b/socketio/README.md @@ -1,20 +1,55 @@ -### 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 +[![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 + +- 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/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 new file mode 100644 index 0000000000..ea06526827 --- /dev/null +++ b/spa/README.md @@ -0,0 +1,99 @@ +--- +title: Single Page Application (SPA) +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 + +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..a61b296552 100644 --- a/sqlboiler/README.md +++ b/sqlboiler/README.md @@ -1,5 +1,12 @@ +--- +title: Sqlboiler +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/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 efc24c8c1a..c3e2fab935 100644 --- a/sqlc/README.md +++ b/sqlc/README.md @@ -1,5 +1,12 @@ +--- +title: Sqlc +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 @@ -132,4 +139,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/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 1f332d5aa6..ebee76e764 100644 --- a/sse/README.md +++ b/sse/README.md @@ -1,8 +1,69 @@ +--- +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. +[![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 + +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..d315fbe83e --- /dev/null +++ b/stream-request-body/README.md @@ -0,0 +1,79 @@ +--- +title: Stream Request Body +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 + +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 74% rename from fiber-svelte-netlify/README.md rename to svelte-netlify/README.md index 79fe60b777..c1512de5b0 100644 --- a/fiber-svelte-netlify/README.md +++ b/svelte-netlify/README.md @@ -1,12 +1,19 @@ +--- +title: Svelte Netlify +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/ #### 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 +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. \ 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 99% rename from fiber-svelte-netlify/adapter/adapter.go rename to svelte-netlify/adapter/adapter.go index 30c8d4447d..65cd15f521 100644 --- a/fiber-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/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..3dad48a1b5 100644 --- a/sveltekit-embed/README.md +++ b/sveltekit-embed/README.md @@ -1,4 +1,12 @@ +--- +title: Sveltekit Embed +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 b872c90bf8..983c7711fb 100644 --- a/swagger/README.md +++ b/swagger/README.md @@ -1,53 +1,74 @@ -# Simple Swagger Implementation for [Fiber](https://github.com/gofiber/fiber) - -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) - -## Usage - -1. Download [swaggo](https://github.com/swaggo/swag) by using: - - ```bash - $ go get -u github.com/swaggo/swag/cmd/swag - - # 1.16 or newer - $ go install github.com/swaggo/swag/cmd/swag@latest - ``` - -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/). - -3. Download [fiber-swagger](https://github.com/arsmn/fiber-swagger) by using: - - ```bash - $ go get -u github.com/arsmn/fiber-swagger/v2 - ``` - -4. Import to your routes file (example: `routes/routes.go`): - - ```go - import swagger "github.com/arsmn/fiber-swagger/v2" - ``` - -5. Add swagger handler to routes as a middleware (example: `routes/routes.go`): - - ```go - app.Get("/docs/*", swagger.Handler) // default - - app.Get("/docs/*", swagger.New(swagger.Config{ // custom - URL: "http://example.com/doc.json", - DeepLinking: false, - })) - ``` - -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`) - - ```bash - $ swag init - ``` - -7. Import docs directory that generated by Swag CLI to your `main.go` file: - - ```go - import _ "swagger/docs" - ``` - -8. Horray! You're ready to Go 🚀 \ No newline at end of file +--- +title: Swagger +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 + +Ensure you have the following installed: + +- Golang +- [Swag](https://github.com/swaggo/swag) for generating Swagger docs + +## 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 + go get -u github.com/swaggo/files + ``` + +## Generating Swagger Docs + +1. Generate the Swagger documentation: + ```sh + swag init + ``` + +## Running the Application + +1. Start the application: + ```sh + go run main.go + ``` + +2. Access the Swagger UI: + Open your browser and navigate to `http://localhost:8080/swagger/index.html` + +## Example + +Here is an example of how to document an API endpoint using Swag: + +```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 +} +``` + +## References + +- [Swag Documentation](https://github.com/swaggo/swag) +- [Gin Swagger Middleware](https://github.com/swaggo/gin-swagger) 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 c0454838cd..59087458e9 100644 --- a/tableflip/README.md +++ b/tableflip/README.md @@ -1,34 +1,53 @@ -## 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 + +[![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? + +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/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 dabf5eaa09..daf0925855 100644 --- a/template-asset-bundling/README.md +++ b/template-asset-bundling/README.md @@ -1,27 +1,52 @@ -# 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 +[![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 + +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-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 new file mode 100644 index 0000000000..dfbc333e69 --- /dev/null +++ b/template/README.md @@ -0,0 +1,91 @@ +--- +title: Template +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 + +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/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/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..5cc5dcac17 100644 --- a/todo-app-with-auth-gorm/README.md +++ b/todo-app-with-auth-gorm/README.md @@ -1,20 +1,45 @@ -# 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 +[![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) -1. Clone this repo -2. Run `go get` +This project demonstrates a Todo application with authentication using GORM. -# Running +## Prerequisites -1. Type `air` in the command line +Ensure you have the following installed and available in your `GOPATH`: -# Environment Variables +- Golang +- [Air](https://github.com/air-verse/air) for hot reloading +- [Godotenv](https://github.com/joho/godotenv) for loading `.env` file + +## 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/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 4c256acf7f..27c4b2e4f0 100644 --- a/unit-test/README.md +++ b/unit-test/README.md @@ -1,5 +1,12 @@ +--- +title: Unit Testing +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 99e7d51e20..2ce496c12a 100644 --- a/upload-file/README.md +++ b/upload-file/README.md @@ -1,5 +1,12 @@ +--- +title: File Upload +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/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 b003be083a..3ced490be4 100644 --- a/url-shortener-api/README.md +++ b/url-shortener-api/README.md @@ -1,34 +1,46 @@ -#### Tech Stack +--- +title: URL Shortener +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 - 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/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 4e59021d3d..1a1fe73aac 100644 --- a/validation/README.md +++ b/validation/README.md @@ -1,5 +1,12 @@ +--- +title: Validation +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/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 f37f23f515..8344dd5132 100644 --- a/vercel/README.md +++ b/vercel/README.md @@ -1,5 +1,12 @@ +--- +title: Vercel +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/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 7a463a4d53..3c4b75d3e4 100644 --- a/websocket-chat/README.md +++ b/websocket-chat/README.md @@ -1,5 +1,12 @@ +--- +title: WebSocket Chat +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-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 b78e8d7a02..426cc5ef21 100644 --- a/websocket/README.md +++ b/websocket/README.md @@ -1,5 +1,12 @@ +--- +title: WebSocket +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 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() {