๐Ÿ“ Examples for ๐Ÿš€ Fiber - Express inspired web framework written in Go

Owner
Fiber
๐Ÿš€ Fiber is an Express inspired web framework written in Go with ๐Ÿ’–
Fiber
Comments
  • fixing socket

    fixing socket

    Firefox will trigger write error: websocket: close sent (chromium seems to be unable to trigger this event, even with thousands of refreshes sent) by pressing refresh several times on a page with a load time of (network latency included) >250ms This causes the unregister <- connection to fire, however this breaks the socket entirely for ALL current connections and all future connections will connect to the websocket but the websocket is down and will not transfer / receive messages. (Messages can be sent to the server ACCORDING TO THE BROWSER but without error but they're thrown out by the server without notice of any kind).

    No idea why it happens like that, but it does. Posted fix works fine.

  • Is it possible to broadcast a WS response from a HTTPS endpoint?๐Ÿค”

    Is it possible to broadcast a WS response from a HTTPS endpoint?๐Ÿค”

    Hello everyone, I'm starting with websockets and I would like to know if it is possible to send a WS notification after some action is done inside a HTTPS endpoint. For example, I want to notify some users (I still need to figure out how to broadcast just to some users) when a new User is created on the admin panel. A POST request is made to the endpoint /agent and I would like to use websockets to send this new data and populate a data grid when a certain user is on the Agents creation screen.

    I don't know if its clear, but is it possible to be made?

    Thanks in advance.

  • ๐Ÿค” Chat example - close connection from server side

    ๐Ÿค” Chat example - close connection from server side

    Question description In this example: https://github.com/gofiber/recipes/blob/master/websocket-chat/main.go , can you please show how we would close the connection to the client say after 5 minutes. This helps the client to reconnect with a new JWT token.

    I tried adding in this into runHub but it doesn't seem to work.

    		case <-time.After(5 * time.Second):
    
    			log.Println("Reconnect")
    
    			for connection := range clients {
    				cm := websocket.FormatCloseMessage(websocket.CloseTryAgainLater, "add your message here")
    				if err := connection.WriteMessage(websocket.CloseMessage, cm); err != nil {
    					// handle error
    					log.Println(err)
    				}
    			}
    
  • What is purpose of

    What is purpose of "binding" in clean-architecture example? ๐Ÿค”

    type Book struct {
    	ID     primitive.ObjectID `json:"id"  bson:"_id,omitempty"`
    	Title  string             `json:"title" binding:"required,min=2" bson:"title"`
    	Author string             `json:"author" bson:"author,omitempty"`
    }
    

    link

    Is it used by fiber or has it to be replaced with "validate" or just removed?

  • feat: fiber opentelemetry trace example

    feat: fiber opentelemetry trace example

    Context

    OpenTelemetry is starting to be standard way to collect any metadata about running application. This example shows how to integrate it with fiber and how to use OpenTelemetry context later in nested layers of application (base on context).

    Keep in mind that OpenTelemetry is complex piece of software and depends on many parts (e.g. collectors). This is not a scope of this example. Here we gonna use Lightstep as backend but it works with any other.

    Changes

    • [x] New example with opentelemetry integration
    • [x] Comments in main.go for easier understanding
    • [x] Screenshots what you will get at the end.
  • Please update the Fiber version on each go.mod file๐Ÿž

    Please update the Fiber version on each go.mod file๐Ÿž

    I have recently try to test Fiber using several examples, and it was until an hour later I noticed my error was because all the examples on this repo are using a go.mod file with old versions of Fiber.

    I would be really helpful if all the examples were updated to the most recent version of Fiber.

  • fix interrupt signal to gracefully shutdown

    fix interrupt signal to gracefully shutdown

    previous one, i tested gracefully shutdown and i found it is not work. so i fix some code and it is ok.

    app.listen should be running in goroutine. channel waiting for interrupt signal to gracefully shutdown

  • ๐Ÿค” websocket-chat: send websocket messages in parallel

    ๐Ÿค” websocket-chat: send websocket messages in parallel

    Question description I'm about to implement something similar to the websocket-chat example in one of my projects and the following question popped into my mind: Shouldn't the websocket send the messages to each client in parallel? As far as I understand connection.WriteMessage() is a blocking operation. Doesn't that mean, that the hub blocks until each client receives the broadcasting message? If I'm not mistaken, this can be an issue on clients with a slow connection and a limitation to the hubs processing speed in general.

    The following snipped sends each message in a separate gorountine. If writing to the socket connection returns an error, the connection gets closed and send the connection back to the hub to unregister the client.

    Code snippet (optional)

    type client struct {
    	isClosing bool
    	mu        sync.Mutex
    }
    
    var clients = make(map[*websocket.Conn]*client)
    var register = make(chan *websocket.Conn)
    var broadcast = make(chan string)
    var unregister = make(chan *websocket.Conn)
    
    func runHub() {
    	for {
    		select {
    		case connection := <-register:
    			clients[connection] = &client{}
    			log.Println("connection registered")
    
    		case message := <-broadcast:
    			log.Println("message received:", message)
    			// Send the message to all clients
    			for connection, c := range clients {
    				go func(connection *websocket.Conn, c *client) { // send to each client in parallel so we don't block on a slow client
    					c.mu.Lock()
    					defer c.mu.Unlock()
    					if c.isClosing {
    						return
    					}
    					if err := connection.WriteMessage(websocket.TextMessage, []byte(message)); err != nil {
    						c.isClosing = true
    						log.Println("write error:", err)
    
    						connection.WriteMessage(websocket.CloseMessage, []byte{})
    						connection.Close()
    						unregister <- connection
    					}
    				}(connection, c)
    			}
    
    		case connection := <-unregister:
    			// Remove the client from the hub
    			delete(clients, connection)
    
    			log.Println("connection unregistered")
    		}
    	}
    }
    

    I'm happy to open a PR for this, but I thought I'd ask first if it even makes sense.

    Edit: I realized that my initial code snipped caused a race condition and possibly a panic due to concurrent write to websocket connection. Therefore I added a mutex to the client to (hopefully) prevent that.

  • ๐Ÿž gcloud, deploy to google cloud run error - app.Start: listen tcp4: address 8080: missing port in address

    ๐Ÿž gcloud, deploy to google cloud run error - app.Start: listen tcp4: address 8080: missing port in address

    Fiber version/commit

    master

    Issue description

    gcloud example: https://github.com/gofiber/recipes/blob/master/gcloud/README.md

    Error from google is:

    app.Start: listen tcp4: address 8080: missing port in address 
    

    Expected behavior

    Steps to reproduce

    Click the "Run on Google Cloud" in the README.md

  • New Boilerplate

    New Boilerplate

    JWT+Mongo+Docker+Nginx ๐Ÿš€

    Freatures

    • JWT : Custom middleware for JWT auth
    • Mongo : Connection with mongodb and configuration file with the possibility of changing the environment
    • Docker and Nginx : Deploy in docker using 5 replicas and load balancer with Nginx
    • Logger : Request logger

    Endpoints

    | Name | Rute | Parameters | State | Protected | Method | | ------------ | --------- | ---------- | --------- | --------- | ------ | | Register | /register | No | Completed | No | POST | | Login | /login | No | Completed | No | POST | | Get Profile | /profile | id | Completed | Yes | GET | | Edit Profile | /profile | No | Completed | Yes | PUT |

  • Add dependabot support to each recipe

    Add dependabot support to each recipe

    What this PR fixes:

    Currently dependabot can't update dependencies recursively as stated here: https://github.com/dependabot/dependabot-core/issues/2178 https://github.com/dependabot/dependabot-core/issues/2824

    This PR adds each directory to dependabot.yml so the go dependencies get updated.

    Related issue:

    Fixes #171

    How to replicate:

    • Git clone this repo: git clone [email protected]:gofiber/recipes.git
    • Run the following script python3 create_dependabot.py
    import os
    
    pwd = os.getcwd()
    print(f"Current working directory: {pwd}")
    
    dirs = [entry.name for entry in os.scandir(os.path.join(pwd, "recipes")) if entry.is_dir()]
    
    for entry in dirs:
        print('  - package-ecosystem: "gomod"')
        print(f'    directory: "/{entry}"')
        print('    schedule:')
        print('      interval: "daily"')
    
  • ๐Ÿ”ฅ fiber-bootstrap should have clear setup instructions

    ๐Ÿ”ฅ fiber-bootstrap should have clear setup instructions

    Is your feature request related to a problem? For certain people a bootstrap is a starting point and should include clear instructions for setup.

    Describe the solution you'd like Provide setup instructions in the README

    Describe alternatives you've considered None

    Additional context None

  • Is there any advantaje using ctx.UserContext() and pass it into GORM dbInstance.withContext() method? ๐Ÿค”

    Is there any advantaje using ctx.UserContext() and pass it into GORM dbInstance.withContext() method? ๐Ÿค”

    Is there any advantaje using ctx.UserContext() and pass it into GORM dbInstance.withContext() method?

    By example in handler method

    func Register(ctx *fiber.Ctx) error {
        err := r.db.WithContext(ctx.UserContext()).Updates(&model).Error
    }
    

    I would to know if we could have any kind of advantaje passing the userConext() into the WithContect() GORM query method, something like cancellationm boundary, etc.

    Lastly I saw in the fiber source code that UserContext() is set with context.Background() if it was not previouly set by the user (me) so looks like If I'm not setting it previously we have not any kind or advantage?

    Thanks in advance!

๐Ÿ“– Build a RESTful API on Go: Fiber, PostgreSQL, JWT and Swagger docs in isolated Docker containers.
๐Ÿ“– Build a RESTful API on Go: Fiber, PostgreSQL, JWT and Swagger docs in isolated Docker containers.

?? Tutorial: Build a RESTful API on Go Fiber, PostgreSQL, JWT and Swagger docs in isolated Docker containers. ?? The full article is published on Marc

Dec 27, 2022
Examples of Golang compared to Node.js for learning
Examples of Golang compared to Node.js for learning

This guide full of examples is intended for people learning Go that are coming from Node.js, although the vice versa can work too. This is not meant to be a complete guide and it is assumed that you've gone through the Tour of Go tutorial. This guide is meant to be barely good enough to help you at a high level understand how to do X in Y and doing further learning on your own is of course required.

Jan 9, 2023
Some examples for the programming language Go.

Golang_Examples Bubblesort: simple implementation of bubble sort algorithm in Go Level: Beginner GenericStack: a stack (LIFO collection) that can hold

Jul 28, 2022
1000+ Hand-Crafted Go Examples, Exercises, and Quizzes

A Huge Number of Go Examples, Exercises and Quizzes Best way of learning is doing. Inside this repository, you will find thousands of Go examples, exe

Jan 1, 2023
Rpcx-plus examples

Examples for the latest rpcx-plus A lot of examples for rpcx-plus How to run you should build rpcx-plus with necessary tags, otherwise only need to in

Dec 5, 2021
Collection of coding examples from "Go In Practice"

Go In Practice Go In Practice 1. Noteworthy aspects of Go 2. A solid foundation 1. Noteworthy aspects of Go Multiple returns Named return values Read

Jan 3, 2022
Go-design-pattern-examples - Golang implementations of common design patterns

Design Patterns Golang implementations of common design patterns Build project T

Oct 29, 2022
Mastering-go-exercises - Some code examples from Mihalis Tsoukalos book titled Mastering GO

Mastering go exercises This is a training repository. Here are some code example

Feb 16, 2022
Client-go examples
Client-go examples

client-go examples ๅ‚่€ƒ k8s-client-go kube-client-example client-go ๅฎžๆˆ˜็š„ๆ–‡็ซ ใ€ client-go ๅฎžๆˆ˜็š„ไปฃ็  client-go/example Kubernetes API Reference Docs ๅ…ณไบŽ Groupใ€Vers

Sep 16, 2022
Go-Notebook is inspired by Jupyter Project (link) in order to document Golang code.
Go-Notebook is inspired by Jupyter Project (link) in order to document Golang code.

Go-Notebook Go-Notebook is an app that was developed using go-echo-live-view framework, developed also by us. GitHub repository is here. For this proj

Jan 9, 2023
An experimental generic functional utility library inspired by Lodash

go-godash An experimental generic functional utility library inspired by Lodash Implemented functions Map Reduce Sum Filter Take TakeWhile Drop DropWh

May 31, 2022
Generic utility methods for Go slices / arrays / collections, heavily inspired by Lodash.

slicy import "github.com/sudhirj/slicy" Usage func All func All[S ~[]T, T any](slice S, predicate func(value T, index int, slice S) bool) bool All re

Aug 30, 2022
A complete guide to undersatnd golang programming language, web requests, JSON and creating web APIs with mongodb

Golang series A complete guide to undersatnd golang programming language, web requests, JSON and creating web APIs with mongodb LearnCodeonline.in 01

Jan 1, 2023
slang ๐Ÿ•โ€๐Ÿฆบ | a Programing language written to understand how programing languages are written

slang ??โ€?? goal was to learn how a interpreter works, in other works who does these programing languages i use on daily basis works behind the seen h

Nov 18, 2021
Web programming tutorial with Golang

Tutorial de programaรงรฃo Web com Golang Para rodar o servidor Entre na pasta web_app, onde estรก o main.go cd caminho/para/pasta/web_app Agora execute

Jan 19, 2022
A basic helloworld golang web program , just for personal use

Standard Go Project Layout Overview This is a basic helloworld golang web progra

Aug 6, 2022
Learn how to write webapps without a framework in Go.

This is an easy to understand example based tutorial aimed at those who know a little of Go and nothing of webdev and want to learn how to write a webserver in Go. You will create a to do list application as you advance the chapters.

Dec 28, 2022
roguelike tutorial in Go using the framework gruid

Gruid Go Roguelike Tutorial This tutorial follows the overall structure of the TCOD Python Tutorial, but makes use of the Go programming language and

Jul 25, 2022
Boilerplate for writing Go applications without framework using hexagonal application development approach
Boilerplate for writing Go applications without framework using hexagonal application development approach

Boilerplate for writing Go applications without framework using hexagonal application development approach

Dec 2, 2022