Giter VIP home page Giter VIP logo

adaptor's Introduction

⚠️ Deprecated repository

This middleware is no longer maintained, it is available within Fiber v2.

adaptor's People

Contributors

arsmn avatar dependabot[bot] avatar fenny avatar gaby avatar github-actions[bot] avatar hi019 avatar jozsefsallai avatar kiyonlin avatar leonklingele avatar lublak avatar renewerner87 avatar trim21 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

adaptor's Issues

utils.MemoryTotal undefined error after integrating gofiber adaptor

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.

Route:

v1Auth.Post("/user/uploadProfileImage", adaptor.HTTPHandlerFunc(s.uploadProfileImage))

Function definition

`/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.

github.com/gofiber/fiber

....\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.

Use it with Authboss

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?

losing contex.Params

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
}

Missing last piece of getting param

// 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?

HTTPMiddlware function does not add request headers

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.

ResponseWriter.Write() not writing to client

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
			}
		}
	}
}

Internal Server Error: When running fiber on vercel

I made a test for this. See https://github.com/AchoArnold/fiber-vercel-test

This line

remoteAddr, err := net.ResolveTCPAddr("tcp", r.RemoteAddr)
Requires the 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

https://github.com/AchoArnold/fiber-vercel-test/blob/d52c862c9102c4bbd0811366f2155decdfdf29ff/server.go#L39

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

Does adaptor.FiberApp(app) incur heavy performance penalties?

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))
}

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.