gofiber / fiber

⚡️ Express inspired web framework written in Go
https://gofiber.io
MIT License
33.88k stars 1.66k forks source link

🐛 [Bug]: agent.Struct fails to unmarshal response since 2.33.0 #2134

Closed teemukataja closed 2 years ago

teemukataja commented 2 years ago

Bug Description

How to Reproduce

Working version with 2.32.0

  1. set fiber version to 2.32.0 in go.mod
  2. run go mod tidy
  3. run script
  4. response is successfully parsed

Broken version 2.33.0-2.38.1

  1. set fiber version to anything after 2.33.0 in go.mod
  2. run go mod tidy
  3. run script
  4. null pointer exception is raised

Expected Behavior

JSON response is unmarshalled into struct.

Fiber Version

2.33.0-2.38.1

Code Snippet (optional)

package main

import (
    "fmt"

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

type response struct {
    Title string `json:"title,omitempty"`
}

func main() {

    agent := fiber.AcquireAgent()
    defer agent.ConnectionClose()
    request := agent.Request()
    request.Header.SetMethod("GET")
    request.SetRequestURI("https://jsonplaceholder.typicode.com/todos/1")

    _ = agent.Parse()

    var r response
    _, _, _ = agent.Struct(&r)  // exception raised here

    fmt.Println(r)
}
$ go run cmd/main.go
panic: runtime error: invalid memory address or nil pointer dereference
[signal SIGSEGV: segmentation violation code=0x1 addr=0x0 pc=0x668e38]

goroutine 1 [running]:
github.com/gofiber/fiber/v2.(*Agent).Struct(0xc0000fa000, {0x680720, 0xc000013180})
    /home/go/1.18.6/pkg/mod/github.com/gofiber/fiber/v2@v2.38.1/client.go:829 +0xf8
main.main()
    /home/go/1.18.6/src/request-test/cmd/main.go:24 +0x1c5

Checklist:

welcome[bot] commented 2 years ago

Thanks for opening your first issue here! 🎉 Be sure to follow the issue template! If you need help or want to chat with us, join us on Discord https://gofiber.io/discord

teemukataja commented 2 years ago

I have a workaround solution by using agent.Bytes instead and unmarshalling manually:

var r response
_, body, _ := agent.Bytes()
_ = json.Unmarshal(body, &r)
li-jin-gou commented 2 years ago

use a.JSONDecoder(json.Unmarshal).Struct(&r)

ReneWerner87 commented 2 years ago

@teemukataja thanks for the hint, fixed it in the pull request #2137

will be in the next release

until then you have to set the default decoder by hand https://github.com/gofiber/fiber/issues/2134#issuecomment-1265283424