gofiber / adaptor Goto Github PK
View Code? Open in Web Editor NEW🧬 Adaptor middleware to convert net/http handlers from/to Fiber request handlers
License: MIT License
🧬 Adaptor middleware to convert net/http handlers from/to Fiber request handlers
License: MIT License
I made a test for this. See https://github.com/AchoArnold/fiber-vercel-test
This line
Line 83 in c8931f7
r.remoteAddr
to have a port
but vercel doesn't include the port in the request handler.
Can we apply some kind of wrapper around it so it includes the default port :80
if one is missing? I have a POC here
You can see the app live at https://fiber-now-test.achoarnold.vercel.app/ and if I remove the work-around, https://fiber-now-test.achoarnold.vercel.app/error
When using a net/http
middleware with the adaptor.HTTPMiddleware
function, it fails to add any added headers to the fiber context.
Fiber version:
github.com/gofiber/adaptor/v2 v2.1.0 // indirect
github.com/gofiber/fiber/v2 v2.2.2 // indirect
Poc
package main
import (
"log"
"net/http"
"github.com/gofiber/adaptor/v2"
"github.com/gofiber/fiber/v2"
)
func main() {
app := fiber.New()
route := app.Group("/test")
route.Use(adaptor.HTTPMiddleware(myMiddleWare))
route.Get("/", func(c *fiber.Ctx) error {
c.Request().Header.VisitAll(func(key, value []byte) {
log.Println(string(key), string(value))
})
log.Println("Is the header here?", c.Get("am-i-here"))
return c.SendStatus(200)
})
app.Listen(":4000")
}
func myMiddleWare(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
r.Header.Set("am-i-here", "somevalue")
next.ServeHTTP(w, r)
})
}
Output:
2020/12/01 13:26:45 Host localhost:4000
2020/12/01 13:26:45 Content-Length 0
2020/12/01 13:26:45 User-Agent HTTPie/2.3.0
2020/12/01 13:26:45 Accept-Encoding gzip, deflate
2020/12/01 13:26:45 Accept */*
2020/12/01 13:26:45 Connection keep-alive
In this example, the header am-i-here
with the value somevalue
should be accessible in the context, but it is not.
I didn't check your code direct, but i made some code based on your code and it has bug - not passsing headers to response
In this line
https://github.com/gofiber/adaptor/blob/master/main.go#L74
according to https://golang.org/pkg/net/http/#ResponseWriter
// Changing the header map after a call to WriteHeader (or
// Write) has no effect unless the modified headers are
// trailers.
You should move WriteHeader call to the end
Hi,
I have an interceptor that receives http.Handler
and returns http.Handler
and I need to use it in my Fiber app.
When I use adaptor.FiberHandlerFunc
to convert my Fiber handler to HTTP Handler and again use adaptor.HTTPHandler to convert HTTP Handler to Fiber handler and use it in my Fiber App, I lose contex.Params in my handler and I get invalid memory address or nil pointer dereference
when calling for example ctx.Params("name")
route
root.Get("/user/:name", authMiddleware(interceptor, handler.SampleHandler, nil, nil), handler.SampleHandler)
func authMiddleware(interceptor *interceptor.CidaasInterceptor, resourceHandlerFunc fiber.Handler, scopes []string, roles []string) fiber.Handler {
options := options.EndpointOptions{
Scopes: scopes,
Roles: roles,
}
return adaptor.HTTPHandler(interceptor.VerifyTokenBySignature(adaptor.FiberHandlerFunc(resourceHandlerFunc), options))
}
Handler Function
func SampleHandler(ctx *fiber.Ctx) error {
name := ctx.Params("name") // I Got `invalid memory address or nil pointer dereference`
ctx.SendString(fmt.Sprintf("URI:%s,name:%s", ctx.Request().URI().String(), name))
return nil
}
So I tried to convert a video with ffmpeg and stream the output to the client while encoding. Since fiber doesn't support streaming I tried it with net/http and it works without problems.
Then i found this adaptor and tried to wrap my function inside it but the ffmpeg output never reaches the browser.
I guess that it's got something to do with ResponseWriter.Write() and the adaptor but I don't know what.
Here is the example (make sure to have ffmpeg):
package main
import (
"fmt"
"io"
"net/http"
"os/exec"
"github.com/gofiber/adaptor/v2"
"github.com/gofiber/fiber/v2"
)
func main() {
// New fiber app
app := fiber.New()
// http.HandlerFunc -> fiber.Handler
app.Get("/", adaptor.HTTPHandlerFunc(greet))
// Listen on port 3000
app.Listen(":3000")
}
func greet(w http.ResponseWriter, r *http.Request) {
cmd := exec.Command("ffmpeg",
"-i", "https://test-streams.mux.dev/x36xhzz/url_6/193039199_mp4_h264_aac_hq_7.m3u8",
"-c", "copy",
"-bsf:a", "aac_adtstoasc",
"-movflags", "frag_keyframe+empty_moov",
"-f", "mp4",
"-")
stdout, err := cmd.StdoutPipe()
if err != nil {
panic(err)
}
if err = cmd.Start(); err != nil {
fmt.Println(err)
panic(err)
}
fmt.Println("ffmpeg running")
data := make([]byte, 1024)
for {
w.Header().Set("Content-Type", "video/mp4")
w.Header().Add("Content-Disposition", "attachment; filename=test.mp4")
n, err := stdout.Read(data)
if err == io.EOF {
fmt.Println("eof")
break
}
if n > 0 {
valid_data := data[:n]
if _, err = w.Write(valid_data); err != nil {
fmt.Println("client disconnected")
cmd.Process.Kill()
break
}
}
}
}
I'm interested in using NGINX Unit as the app server https://unit.nginx.org/. The handler is expecting the net/http handler so the adaptor.FiberApp(app) is needed. The question is does the adaptor create a small consistent overhead or does the adaptor negate all the benefits of fasthttp?
Example: https://unit.nginx.org/howto/samples/#sample-go
package main
import (
"github.com/gofiber/adaptor/v2"
"github.com/gofiber/fiber/v2"
unit "unit.nginx.org/go"
)
func main() {
app := fiber.New()
app.Get("/", func(c *fiber.Ctx) error {
return c.SendString("Hello, World!")
})
unit.ListenAndServe(":80", adaptor.FiberApp(app))
}
// assume (r *http.Request)
if rv := r.Context().Value(varsKey); rv != nil {
return rv.(map[string]string)
}
In gorilla/mux we can get the params using mux.Vars(r)
, I dig in the test cases and we don't have a param based tests such as /users/:id
Do we support passing the :id
from fiber to http.HandlerFunc
and how?
Hi Team,
In a project which I am currently working on, I have an S3 upload functionality. I have to use the http (w http.ResponseWriter, r *http.Request) along with GoFiber context.
v1Auth.Post("/user/uploadProfileImage", adaptor.HTTPHandlerFunc(s.uploadProfileImage))
`/Upload the profile image to S3 ... user/uploadProfileImage
func (s *Server) uploadProfileImage(c *fiber.Ctx, w http.ResponseWriter, r *http.Request) error {
user := c.Context().UserValue("userid")
_, ok := user.(uint32)
if ok {
maxSize := int64(3072000) // allow only 3MB of file size
err := r.ParseMultipartForm(maxSize)
if err != nil {
log.Println(err)
fmt.Fprintf(w, "Image too large. Max Size: %v", maxSize)
return nil
}
file, fileHeader, err := r.FormFile("s3ProfileImage")
if err != nil {
log.Println(err)
fmt.Fprintf(w, "Could not get uploaded file")
return nil
}
defer file.Close()
// create an AWS session which can be
// reused if we're uploading many files
s3, err := session.NewSession(&aws.Config{
Region: aws.String("us-east-2"),
Credentials: credentials.NewStaticCredentials(
"secret-id", // id
"secret-key", // secret
""), // token can be left blank for now
})
if err != nil {
fmt.Fprintf(w, "Could not upload file")
}
fileName, err := utility.S3Uploader(s3, file, fileHeader)
if err != nil {
fmt.Fprintf(w, "Could not upload file")
}
fmt.Fprintf(w, "Image uploaded successfully: %v", fileName)
return nil
} else {
return c.Status(400).JSON(utility.Response{Status: 400, Message: utility.ErrInvalidUserID})
}
}`
I have integrated **adaptor** in GoFiber. After using it, I am unable to take build using "go build". It is throwing the below error.
....\pkg\mod\github.com\gofiber\[email protected]\app.go:675:33: undefined: utils.MemoryTotal
....\pkg\mod\github.com\gofiber\[email protected]\path.go:65:17: undefined: utils.GetTrimmedParam
Can you please help me to resolve the issue? What am I doing wrong here? I am new to golang and gofiber.
If we add multiple cookies in a response, adaptor will replace headers with the same name using w.Header().Set(string(k), string(v))
.
I'm trying to use authboss with Fiber.
I can't figure out how to use LoadClientStateMiddleware
with adoptor
like this:
app := fiber.New()
app.Use(adaptor.HTTPHandler(authboss.LoadClientStateMiddleware))
the error is:
Cannot use 'authb.LoadClientStateMiddleware' (type func(h http.Handler) http.Handler) as type http.Handler Type does not implement 'http.Handler' as some methods are missing: ServeHTTP(ResponseWriter, *Request)
Is there a way I can fix this?
ResponseWriter does not implement http.Hijacker
More info: github.com/gorilla/websocket/issues/640
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.