gofiber / recipes Goto Github PK
View Code? Open in Web Editor NEW๐ Examples for ๐ Fiber
Home Page: https://github.com/gofiber/fiber
License: MIT License
๐ Examples for ๐ Fiber
Home Page: https://github.com/gofiber/fiber
License: MIT License
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
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
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))
}
Question description
This is a very common use case where the front end would subscribe to topics or subjects. It would be good to have an example as a recipe.
Similar to this:
https://stackoverflow.com/questions/57783858/sending-a-websocket-message-to-a-specific-channel-in-go-using-gorilla
It will be really nice and helpful if you add an OAuth server example with fiber.
Thank you!
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
},
})
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.
hi ,
how connect to postgres database and migrate ?
thank you
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
Question description
Hello, I am curious about the RemoveDomainError function! Why not use the Contains function from the string package to check if the URL provided by the user contains the domain name! Also, amazing work.
recipes/auth-jwt/middleware/auth.go
Line 12 in 4d531e7
after verifying the token, i need the decoded jwt, and want to access it inside my route handler after all the verification.
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!
What about a new go 1.16 embedded FS example?
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.
var clients = make(map[*websocket.Conn]client)
this way is easy crash by "map concurrence write"....and it can not be recover
use sync.map is safer
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 ?
**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"))
}
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)
}
}
The SvelteKit Example (https://github.com/gofiber/recipes/tree/master/sveltekit-embed/frontend/src/routes) won't work with newer versions anymore
** 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"
)
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
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)
}
how to Graceful restart in Fiber ๏ผHope to receive the signal, shut down gracefully, and restart the process, how to use this https://github.com/cloudflare/tableflip Graceful restart & zero downtime deploy for Go servers.
like gin graceful restart https://gin-gonic.com/docs/examples/graceful-restart-or-stop/
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
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")
}
Question description
I added swagger as the demo ,but I don't know what is the url of swagger?
Code snippet (optional)
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"`
}
Is it used by fiber or has it to be replaced with "validate" or just removed?
Is your feature request related to a problem?
Yes
Describe the solution you'd like
More Websockets example like:
Describe alternatives you've considered
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)
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.
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
)
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
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.
Since the package used in the example here has been deleted or hidden by the user, the code example is invalid, I would like to delete it for now and write a new one myself if necessary.
Link Here:
https://github.com/gofiber/recipes/tree/master/fiber-grpc
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
}
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
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" }
http://localhost:3000/api/auth/login
in order to sign in. Use the previous username as identity and the password:{"identity": "newTestUser", "password": "thisIsAPass"}
POST http://localhost:3000/api/auth/login
with{"identity": "[email protected]"", "password": "thisIsAPass"}
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.
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))
}
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.
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
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)
}
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)
}
}```
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
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() {
}
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.
Hi,
I think there's a mistake in the recipes repository in the hello-world file:
https://github.com/gofiber/recipes/blob/master/hello-world/main.go
In the website (https://docs.gofiber.io/) and in the main github page (https://github.com/gofiber/fiber) the app.Get command is: app.Get("/", func(c *fiber.Ctx)
But in the receipt it's: app.Get("/hello", func(c *fiber.Ctx) - which did not work for me
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.
How can I get the file body in bytes from a posted file?
๐ฅ any progressive web app pwa example?
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)
FYI, one of the links in README is pointing to GitHub 404 page: https://github.com/gofiber/recipes/blob/master/http-tls
We would like to have a recipe for Fiber Client as well
A declarative, efficient, and flexible JavaScript library for building user interfaces.
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. ๐๐๐
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google โค๏ธ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.