Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Can UnmarshalParam support custom slice of string #3970

Closed
bruceNu1l opened this issue May 16, 2024 · 0 comments · Fixed by #3971
Closed

Can UnmarshalParam support custom slice of string #3970

bruceNu1l opened this issue May 16, 2024 · 0 comments · Fixed by #3971

Comments

@bruceNu1l
Copy link
Contributor

bruceNu1l commented May 16, 2024

Feature

Support UnmarshalParam for custom string slice type in tag form.

Description

If we define a custom type of string slice and implement the Gin's interface of UnmarshalParam, then we can't get the expected result.

How to reproduce

package main

import (
	"fmt"
	"net/http"
	"strings"

	"github.com/gin-gonic/gin"
)

type CustomPath []string

func (b *CustomPath) UnmarshalParam(param string) error {
	elems := strings.Split(param, "/")
	n := len(elems)
	if n < 2 {
		return fmt.Errorf("invalid path: %s", param)
	}

	*b = elems
	return nil
}

type PathRequest struct {
	Paths CustomPath `form:"path"`
}

func main() {
	g := gin.Default()
	g.GET("", func(c *gin.Context) {
		var request PathRequest
		if err := c.ShouldBind(&request); err != nil {
			c.String(http.StatusBadRequest, "request parse err: %v", err)
			return
		}

		c.String(200, "Hello %s", request.Paths)
	})
	g.Run(":9000")
}

Expectations

$ curl 'http://127.0.0.1:9000?path=hello/world' 
CustomPath:  [hello world]

Actual result

$ curl 'http://127.0.0.1:9000?path=hello/world' 
CustomPath:  [hello/world]

Environment

  • go version: go1.22.0 darwin/arm64
  • gin version (or commit ref): v1.10.0
  • operating system: macOS 13.5
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

1 participant