Skip to content

http.ErrUseLastResponse setting is invalid #1005

@kamly

Description

@kamly

HI, I set http.ErrUseLastResponse in SetRedirectPolicy. Expected to disable redirects, but this setting is invalid

client.SetRedirectPolicy(resty.RedirectPolicyFunc(func(req *http.Request, via []*http.Request) error {
		return http.ErrUseLastResponse
	}))

Demo:

package main

import (
	"fmt"
	"net/http"

	"github.com/gin-gonic/gin"
	"github.com/go-resty/resty/v2"
)

// ProxyRequest
type ProxyRequest struct {
	URL     string            `json:"url" binding:"required"`
	Body    string            `json:"body"`
	Headers map[string]string `json:"headers"`
}

func proxyHandler(c *gin.Context) {
	var proxyReq ProxyRequest
	proxyReq.URL = "https://httpbin.org/anything"
	proxyReq.Body = `{"name":"test"}`
	proxyReq.Headers = map[string]string{
		"Content-Type": "application/json",
	}

	// Create a new Resty client
	client := resty.New()
	// Disable Redirect
	client.SetRedirectPolicy(resty.RedirectPolicyFunc(func(req *http.Request, via []*http.Request) error {
		fmt.Println("================")
		fmt.Println(http.ErrUseLastResponse)
		fmt.Println("================")
		return http.ErrUseLastResponse
	}))

	// Send the request
	resp, err := client.R().
		SetBody(proxyReq.Body).
		Execute(c.Request.Method, proxyReq.URL)

	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}
}

func main() {
	r := gin.Default()
	r.POST("/proxy", proxyHandler)
	r.Run(":8080")
}

Test:

func TestProxyHandler_Redirect(t *testing.T) {
	ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Location", "https://example.com")
		w.WriteHeader(http.StatusTemporaryRedirect)
	}))
	defer ts.Close()

	proxyReq := ProxyRequest{
		URL: ts.URL,
	}
	reqBody, _ := json.Marshal(proxyReq)

	w := httptest.NewRecorder()
	req, _ := http.NewRequest("POST", "/proxy", bytes.NewReader(reqBody))
	req.Header.Set("Content-Type", "application/json")

	router := setupRouter()
	router.ServeHTTP(w, req)

	fmt.Println(w.Code)
	fmt.Println(w.Body.String())
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions