Git Product home page Git Product logo

recipes's Introduction

๐Ÿณ Examples for Fiber

Welcome to the official Fiber cookbook!

Here you can find the most delicious recipes to cook delicious meals using our web framework.

๐ŸŒฝ Table of contents

๐Ÿ‘ฉโ€๐Ÿณ Have a delicious recipe?

If you have found an amazing recipe for Fiber โ€” share it with others! We are ready to accept your PR and add your recipe to the cookbook (both on website and this repository).

recipes's People

Contributors

achoarnold avatar alvarowolfx avatar antejavor avatar asyncfinkd avatar axrav avatar darthbenro008 avatar dependabot[bot] avatar eeap avatar efectn avatar fenny avatar gaby avatar gandaldf avatar github-actions[bot] avatar hi019 avatar iamjatindersingh avatar koddr avatar lauslim12 avatar limjian avatar nawawishkid avatar psmarcin avatar rajesh6161 avatar renewerner87 avatar renovate[bot] avatar sudoalireza avatar testeaeaaz avatar the-exile-110 avatar ugurkorkmaz avatar webuti avatar wlun001 avatar zeimedee avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

recipes's Issues

๐Ÿ”ฅ gcloud deployment and versioning

at the moment the gcloud deployment works great.

it would be nice to have an example that accounts for developer needs in terms of versioning.
Versioning is a big area with CI and CD, and one basic approach is to have dev and prod as first class citizens.

typically dev is a canary that builds of the tip

prod is builds off a tag that maps to the github tag.

the SHA and other version info is sometimes included as LDFLags.

Some of the concepts are shown in this repo: https://github.com/enricofoltran/simple-go-server

fiber seems not support cancelContext like net/http ๐Ÿค”

Question description
fiber seems not support cancelContext like net/http, for demo case, see context
So code in the sub project "docker-mariadb-clean-arch"

customContext, cancel := context.WithCancel(context.Background())
	defer cancel()

should be change into

customContext, cancel := context.WithTimeout(context.Background(), 10*time.Second)
	defer cancel()

I am a green hand for golang and fiber, so i'm not sure that if i am right.

How to modify response body through fiber.Static.ModifyResponse? ๐Ÿค”

Question description
Hello, I'am using app.Static on my project and I would like to modify the HTML content of a response. I was hoping to use the ModifyResponse handler, but when it gets invoked, the c.Response().Body() is empty byte array. I would like to use this handler to modify the served HTML at this moment. Or perhaps is there another way? Thanks

Code snippet (optional)

	app.Static("/", "path/to/static/files", fiber.Static{
		Browse:    true,
		ByteRange: true,
		ModifyResponse: func(c *fiber.Ctx) error {
                         fmt.Println("HERE", string(c.Response().Body()))
			return nil
		},
	})

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.

Error with SendString(err) in gorm recipe

recipes/gorm/book/book.go
Error with c.Status(503).SendString(err)

is:

func NewBook(c *fiber.Ctx) error {
	db := database.DBConn
	book :=new(Book)
	if err := c.BodyParser(book); err != nil {
		return c.Status(503).SendString(err)
	}
	db.Create(&book)
	return c.JSON(book)
}

should be:

func NewBook(c *fiber.Ctx) error {
	db := database.DBConn
	book :=new(Book)
	if err := c.BodyParser(book); err != nil {
		return c.Status(503).SendString(err.Error())
	}
	db.Create(&book)
	return c.JSON(book)
}

๐Ÿ”ฅ URL shortener [Gofiber + Redis]

Is your feature request related to a problem? No

Describe the solution you'd like URL shortener

Describe alternatives you've considered NA

Additional context A simple URL shortener with Gofiber and Redis

๐Ÿค” Getting Authorization headers from the request object & how to perform external API calls

Getting Authorization headers from the request object & any how to perfom external API calls

Code snippet (optional)

package main

func main() {

}

How do i get the authorization headers i.e bearer token or basic auth token passed to the request object.

func handlerFunction(c *fiber.Ctx) error{
//how do i get the bearer token or auth token from context passed in this function

//something like: not real code implementation
c.Headers("Authorization")

return c.Status(400).JSON(fiber.Map{"error":true, "message":"We cannot map your request to any available api system"})
//return c.JSON(fiber.Map{"message":"The developer can freely hit this api endpoint"});
	
}

One last thing, Please note that i come from nodejs and i have got lots of experience in that area, and am stuck at this section where am supposed to an API call and attach data to just like am used with axios module in Nodejs e.g

// Make a GET request for a user with a given ID
axios.get('/user?ID=12345')
  .then(function (response) {
    // handle success
    console.log(response);
  })

//Making a POST Request
axios.post('/user', {
    firstName: 'Fred',
    lastName: 'Flintstone'
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });

//making a POST request with authentication headers
axios.post('/user', {
    firstName: 'Fred',
    lastName: 'Flintstone'
  },
headers: {
      Authorization: `Basic ${Buffer.from(
        `${accountId}:${apiKey}`
      ).toString("base64")}`,
    },
)
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });

just a recap

  • How to get request authorization infomation from the headers
  • How to perfom API fetch request

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.

๐Ÿค” Close Database connection

**On [My Sql recipe] ( https://github.com/gofiber/recipes/tree/master/gorm-mysql) connection was not closed. But I can see on this recipe connection was closed in a main function **

**

func initDatabase() {
	var err error
	database.DBConn, err = gorm.Open("sqlite3", "books.db")
	if err != nil {
		panic("failed to connect database")
	}
	fmt.Println("Connection Opened to Database")
	database.DBConn.AutoMigrate(&book.Book{})
	fmt.Println("Database Migrated")
}

func main() {
	app := fiber.New()
	app.Use(cors.New())

	initDatabase()
	defer database.DBConn.Close()  // <=== Here

	setupRoutes(app)

	log.Fatal(app.Listen(":3000"))
}

**

What if I will set up my app like this?

var (
	Db *gorm.DB
)

func ConnectDb() {
	var err error
	dsn := fmt.Sprintf("host=%s port=%d user=%s password=%s dbname=%s sslmode=disable timezone=Africa/Nairobi",
		c.Conf.AppDb.Host, c.Conf.AppDb.Port, c.Conf.AppDb.User, c.Conf.AppDb.Password, c.Conf.AppDb.Name)

	newLogger := logger.New(
		log.New(os.Stdout, "\r\n", log.LstdFlags),
		logger.Config{
			SlowThreshold: 1 * time.Minute,
			LogLevel:      c.Conf.AppDb.LogLevel,
			Colorful:      true,
		},
	)

	Db, err = gorm.Open(postgres.Open(dsn), &gorm.Config{Logger: newLogger})
	if err != nil {
		logs.ErrorLogger.Fatalln(err.Error())
	}

	sqlDb, err := Db.DB()
	if err != nil {
		logs.ErrorLogger.Fatal(err.Error())
	}

	sqlDb.SetMaxIdleConns(10)  //<<<<<<
	sqlDb.SetConnMaxIdleTime(15 * time.Minute)  //<<<<

}


func main() {
	app := fiber.New()
	app.Use(cors.New())

	database.ConnectDb()  // <=== Without defer to close db

	setupRoutes(app)

	log.Fatal(app.Listen(":3000"))
}

๐Ÿค” in the csrf, embed package is not found in golang

** in the csrf example, embed package is not found in golang**

can you advice how to resolve this ?

import (
	"embed" // this package is not in GOROOT
	"fmt"
	"log"
	"net/http"
	"os"

	"github.com/gofiber/fiber/v2"
	"github.com/gofiber/template/html"
	"main/routes"
)

graceful shutdown not work๐Ÿค”

I already try recipe for gracefull shutdown and it work. but when i used something like this in the main.go file :

router.Routes(app)

and in router.go file :

func Routes(app *fiber.App) { app.Get("/", handler.Hello) }

when i type "ctrl + c" gracefull shutdown dosnt work.
how the right implementation if i register handler/routes in that way ?

thanks

๐Ÿž error handling

Fiber version/commit
v 1.14.4

Issue description
lack of error handling?

Expected behavior
panic or a 500 status if the files directory is not present

Steps to reproduce
create a new fiber app with the code snippet

Code snippet

package main
 
import (
   "github.com/gofiber/fiber"
  "log"

 
func main() {
   app := fiber.New()

 app.Post("/",func(c *fiber.Ctx) {
	file, err := c.FormFile("file")
	if err == nil {
		c.SaveFile(file, fmt.Sprintf("./files/%s", file.Filename))
	}

})

log.Fatal(app.Listen(3000))

}

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!

๐Ÿž Autocert example is not working

Fiber version/commit
v2.32.0
Issue description
I copied example "autocert" but it is not working (Can't establish a connection with site. 127.0.0.1 refused to connect.)
Expected behavior

Steps to reproduce

Code snippet

package main

import (
	"crypto/tls"
	"log"

	"github.com/gofiber/fiber/v2"
	"golang.org/x/crypto/acme/autocert"
)

func main() {
	// Fiber instance
	app := fiber.New()

	// Routes
	app.Get("/", func(c *fiber.Ctx) error {
		return c.SendString("This is a secure server ๐Ÿ‘ฎ")
	})

	// Letโ€™s Encrypt has rate limits: https://letsencrypt.org/docs/rate-limits/
	// It's recommended to use it's staging environment to test the code:
	// https://letsencrypt.org/docs/staging-environment/

	// Certificate manager
	m := &autocert.Manager{
		Prompt: autocert.AcceptTOS,
		// Replace with your domain
		HostPolicy: autocert.HostWhitelist("example.com"),
		// Folder to store the certificates
		Cache: autocert.DirCache("./certs"),
	}

	// TLS Config
	cfg := &tls.Config{
		// Get Certificate from Let's Encrypt
		GetCertificate: m.GetCertificate,
		// By default NextProtos contains the "h2"
		// This has to be removed since Fasthttp does not support HTTP/2
		// Or it will cause a flood of PRI method logs
		// http://webconcepts.info/concepts/http-method/PRI
		NextProtos: []string{
			"http/1.1", "acme-tls/1",
		},
	}
	ln, err := tls.Listen("tcp", ":443", cfg)
	if err != nil {
		panic(err)
	}

	// Start server
	log.Fatal(app.Listener(ln))
}

๐Ÿค”A not immutable question about examples

Question description

The examples are great, but I have a question here.

Some places in the sample code use variables to save the value of c.Params And then pass these parameters to other functions. Won't there be the problem of not immutable mentioned in the fiber document?

Code snippet (optional)

https://github.com/gofiber/recipes/blob/master/gorm/book/book.go#L25

func GetBook(c *fiber.Ctx) {
	id := c.Params("id")
	db := database.DBConn
	var book Book
	db.Find(&book, id)
	c.JSON(book)
}

MongoDB Example for Fiber ๐Ÿ”ฅ

Is your feature request related to a problem? No

Describe the solution you'd like MongoDB Recipe

Describe alternatives you've considered NA

Additional context I want to use MongoDB with Fiber.

Is there a way to read the file content when its uploaded๐Ÿค”

Question description
I am wondering whether there is a way to read the content of a file and parse it, instead of saving it first as its done in the recipe

file, err := c.FormFile("data")
	if err != nil {
		return err
	}
	fmt.Println(file.Content) // See here
        fmt.Println(file.Filename) // This is possible and => file.Size

// Instead of:
        c.SaveFile(file, fmt.Sprintf("./%s", file.Filename))  // store in root
	xml_data, _ := ioutil.ReadFile(file.Filename)


๐Ÿค” 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)
				}
			}

๐Ÿค” 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.

๐Ÿค” file upload

Question description
I looked at the single file upload recipe. How do I specify a directory other than the root
Code snippet (optional)

package main

func main() {

}

๐Ÿค” Should we use Fist(&user) instead of Find(&user) in the getUserByEmail and getUserByUsername in the handler package?

Question description
Using the test if err := db.Where(&model.User{Username: u}).Find(&user).Error; err != nil {...} will not produce the intended result. We expect that this will return error = gorm.ErrRecordNotFound if username does not exist in the database. However, this will never happen if we use Find(). The behaviour is true if we use First(&user) instead.

When I tried to use the original code, I failed to properly authenticate a user... I was scratching my head for hours why I got 'unknown' as the returned UserData. Made some reading about the ErrRecordNotFound requirements and someone pointed to me to use First instead of Find function for this purpose. So I made the changes as below and viola! the code works.

Code snippet (optional)

func getUserByEmail(e string) (*model.User, error) {
	db := database.DB
	var user model.User
	if err := db.Where(&model.User{Email: e}).First(&user).Error; err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			return nil, nil
		}
		return nil, err
	}

	return &user, nil
}

panic: interface conversion: interface {} is *jwt.Token, not *jwt.Token (types from different packages)

filename: A.go
user := ctx.Locals("user").(*jwt.Token)
// panic: interface conversion: interface {} is *jwt.Token, not *jwt.Token (types from different packages)

the code copy auth-jwt from the demos , today when i want to get auth message show the error .
login method use the lib of github.com/dgrijalva/jwt-go .

when i change the file A.go, important "github.com/form3tech-oss/jwt-go" to replace old jwt-go.
it is work. not panic error .
Why ?

๐Ÿž Bug on the auth-jwt recipe, log in with email doesn't work

Fiber version/commit
github.com/gofiber/fiber/v2 v2.44.0

Issue description
The auth-jwt recipe doesn't properly log in users when you try it with email as identity.
This happens using the following endpoint: POST api/auth/login

Expected behavior
It should log in the user after sending a POST request to http://localhost:3000/api/auth/login with the right email and password.
Instead it responds with an error.
Note: One can successfully log in the same way but using the username instead of the email.

Steps to reproduce

  • Run your database and connect it to the project.
  • Open any API Client (Postman, Rapid API, etc.) and make a POST request to http://localhost:3000/api/user/ containing the following body in order to generate a new user and it's credentials:
    { "username": "newTestUser", "email": "[email protected]", "password": "thisIsAPass" }
  • Make a new a POST request, now to http://localhost:3000/api/auth/login in order to sign in. Use the previous username as identity and the password:
    {"identity": "newTestUser", "password": "thisIsAPass"}
  • Now that everything is working great, try to log in using the email instead of the username in the same endpoint:
    POST http://localhost:3000/api/auth/login with
    {"identity": "[email protected]"", "password": "thisIsAPass"}
    This would cause the server to respond with an error.

Vue.js๐Ÿ”ฅ

I would love to see a recipe showing how to connect Vue.js, as the front-end Javascript framework, to Go Fiber. With some guidance, I am willing to help write the recipe. We could also create a recipe showing how to use Vuex and Fiber.

๐Ÿ”ฅ 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

๐Ÿค” User Login System and Admin Area

Question description
I am looking middlewares and builtin modules, it makes me confused.
how i can implement user login and session management system with gofiber without any problem.
i am not askin JWT api, because it is not complete solution. i am asking about web page login system with administration by admins.

which functions and middlewares i should use in order to create secure system.
i want to use postgresql as database and i may use key/value storage.

in my opinion,
from i learnt gofiber docs.
i may use cookie encryption, i can send session_id to cookie.
and i can save user agent and ip address in postgresql database,
this will give opportunity to tracking sessions and expire them when it is needed.
loginsession system i call it for only tracking useragent , ipv4,ipv6 and date of session created, and expired.
i also thinkg that on services which provided to user,
will also track, which session_id did the operation on user services.
it may also give opportunity to take back some actions.

now i am asking your ideas, which middlewares and builtin functions should be used and how.
which way it will be logical and hardened system for most of the attacks.

I am planing to publish my work , maybe it can be used as a recipe.

Code snippet (optional)

๐Ÿ”ฅ I have a nice feature for gorm-mysql listed below:

Is your feature request related to a problem?
This feature is related to gorm-mysql recipe in which I added several changes.
Describe the solution you'd like

  1. In Update book function in routes/routes.go instead of updating an entry by Title we can update it by specific ID and passing title from body, which is more suitable.
  2. Similarly in Delete book function instead of deleting by title lets delete it by ID simply.

Additional context
Everything looks perfect. I have added these changes locally, but if my solution looks good let me know ๐Ÿ™‚ and I will make a PR for the same.

// Update
func Update(c *fiber.Ctx) error {
	book := new(models.Book)
	if err := c.BodyParser(book); err != nil {
		return c.Status(400).JSON(err.Error())
	}
	id, _ := strconv.Atoi(c.Params("id"))

	database.DBConn.Model(&models.Book{}).Where("id = ?", id).Update("title", book.Title)

	return c.Status(400).JSON("updated")
}

// Delete
func Delete(c *fiber.Ctx) error {
	book := new(models.Book)

	id, _ := strconv.Atoi(c.Params("id"))

	database.DBConn.Where("id = ?", id).Delete(&book)

	return c.Status(200).JSON("deleted")
}

Recipe for Client ๐Ÿ”ฅ

Is your feature request related to a problem?
No.
Describe the solution you'd like
Can you add a recipe for the client? There are examples for functions in the doc but it would be great if there is a complete example with best practices.

Describe alternatives you've considered

Additional context

swagger๐Ÿค”

Question description
I added swagger as the demo ,but I don't know what is the url of swagger?

Code snippet (optional)

๐Ÿค” Issue with interface assignment in recipe "auth-jwt"? panic: interface conversion: interface {} is *jwt.Token, not *jwt.Token (types from different packages)

Learning Golang and Fiber (golang newbie, go easy!)

Hi, decided to take the next step in my Golang journey and take a look at some web frameworks, mainly those that resemble Flask in Python and ExpressJs in NodeJs. Fiber as a candidate is a great little framework and it's been fairly straightforward to get into.

However, I was experimenting with the "auth-jwt" recipe, and came across this issue in the handler/user.go functions UpdateUser and DeleteUser. As I turn on/off protected() functions and experiment with token lifespans, it's reasonably clear that the JWT middleware IS protecting my functions as i run the tests available in the POSTMan suite.

For some reason or another, whenever I try to PATCH UpdateUser or DELETE DeleteUser, I get this error:

13:15:57 | 401 |      0s |    192.168.56.1 | DELETE  | /api/user/2
panic: interface conversion: interface {} is *jwt.Token, not *jwt.Token (types from different packages)

goroutine 20 [running]:
api-fiber-gorm/handler.DeleteUser(0xc0002142c0)
        /home/ubuntu/projects/golang/auth-jwt/handler/user.go:128 +0x6ad

The line in question in BOTH cases (UpdateUser and DeleteUser) is:
token := c.Locals("user").(*jwt.Token)

I've been able to log the contents of c.Locals("user") and it looks like it does contain "healthy" user JWT information. I also can't see if there is any other JWT package interfering with the deployed recipe (i've cleaned out the build and cache multiple times)
I don't know enough golang yet to take this any further, and the only reference that I could find to a similar problem was due to a replacement for the original package for security issues, almost two years ago.

dgrijalva/jwt-go#401

Can anybody point me in the right direction please?

Thanks & regards.

My go.mod after running / building
The recipe code is almost intact from the repo as of 20 November 2022, apart from one or two log.Println()s to help me debug. Go is version 1.19.

module api-fiber-gorm

go 1.19

require (
        github.com/gofiber/fiber/v2 v2.39.0
        github.com/gofiber/jwt/v2 v2.2.7
        github.com/golang-jwt/jwt v3.2.2+incompatible
        github.com/joho/godotenv v1.4.0
        golang.org/x/crypto v0.0.0-20220722155217-630584e8d5aa
        gorm.io/driver/postgres v1.4.5
        gorm.io/gorm v1.24.1-0.20221019064659-5dd2bb482755
)

require (
        github.com/andybalholm/brotli v1.0.4 // indirect
        github.com/golang-jwt/jwt/v4 v4.0.0 // indirect
        github.com/jackc/chunkreader/v2 v2.0.1 // indirect
        github.com/jackc/pgconn v1.13.0 // indirect
        github.com/jackc/pgio v1.0.0 // indirect
        github.com/jackc/pgpassfile v1.0.0 // indirect
        github.com/jackc/pgproto3/v2 v2.3.1 // indirect
        github.com/jackc/pgservicefile v0.0.0-20200714003250-2b9c44734f2b // indirect
        github.com/jackc/pgtype v1.12.0 // indirect
        github.com/jackc/pgx/v4 v4.17.2 // indirect
        github.com/jinzhu/inflection v1.0.0 // indirect
        github.com/jinzhu/now v1.1.4 // indirect
        github.com/klauspost/compress v1.15.0 // indirect
        github.com/mattn/go-colorable v0.1.13 // indirect
        github.com/mattn/go-isatty v0.0.16 // indirect
        github.com/mattn/go-runewidth v0.0.14 // indirect
        github.com/rivo/uniseg v0.2.0 // indirect
        github.com/valyala/bytebufferpool v1.0.0 // indirect
        github.com/valyala/fasthttp v1.40.0 // indirect
        github.com/valyala/tcplisten v1.0.0 // indirect
        golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab // indirect
        golang.org/x/text v0.3.7 // indirect
)

Custom 404 Not Found in HTTPS(TLS)? ๐Ÿค”

Is it possible to make it work together with tls.listen()? With this code it doesn't redirect me to the html file. I've tried it before and it works without tls.listen(), i.e. using app.listen() directly.

package main

import (
	"crypto/tls"

	"github.com/gofiber/fiber/v2"
)

func main() {
        app := fiber.New()

        //Routes
        app.Static("/static", "./public")
	app.Static("/", "./public/index.html")

        // Error handler
	app.Use(func(c *fiber.Ctx) error {
		return c.Status(404).SendFile("./public/404.html") // => 404 "Not Found"
	})
        
        // Create tls certificate
        cer, err := tls.LoadX509KeyPair("cert.pem", "key.pem")
        if err != nil {
               log.Fatal(err)
        }

        config := &tls.Config{Certificates: []tls.Certificate{cer}}

        // Create custom listener
	ln, err := tls.Listen("tcp", ":443", config)
	if err != nil {
		panic(err)
	}
}```

recipe: add pprof example ๐Ÿ”ฅ

Is your feature request related to a problem?

Yes, but not fiber's problem, I think.

Describe the solution you'd like

I want to debug my Go project with net/http/pprof , so I writed a code snippet as below.

And I think it could be a recipe of fiber ๐Ÿ˜„

package main

import (
	"github.com/gofiber/fiber"
	"github.com/valyala/fasthttp/pprofhandler"
)

func main() {
	// Create new Fiber instance
	app := fiber.New()

	// Create new group route on path "/debug/pprof"
	app.Group("/debug/pprof", func(c *fiber.Ctx) {
		pprofhandler.PprofHandler(c.Fasthttp)
	})

	// Start server on http://localhost:3000
	app.Listen(3000)
}

If you visit http://localhost:3000/debug/pprof/ , everything is ok.

But if you visit http://localhost:3000/debug/pprof , the right subpath like http://localhost:3000/debug/pprof/goroutine will be replaced with the wrong subpath http://localhost:3000/debug/goroutine , so you will get nothing but 404.

Describe alternatives you've considered

It's because of pprof's template depends on the last / to separate different subpaths, so you should always visit http://localhost:3000/debug/pprof/ ๐Ÿ˜„

Additional context

Always use Safari to visit http://localhost:3000/debug/pprof to get 404.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.