Skip to content

net/ghttp: Multipart file upload fails: empty string causes ghttp.UploadFile conversion error #4193

@MHanL

Description

@MHanL

Go version

go version go1.24.0 windows/amd64

GoFrame version

v2.8.3

Can this bug be reproduced with the latest release?

Option Yes

What did you do?

When handling a file upload using ghttp.UploadFile, if the file field in the multipart request is an empty string (""), the server panics instead of triggering the validation rule.

Here is a minimal reproducible example:

package main

import (
	"context"
	"fmt"
	"time"

	"github.com/gogf/gf/v2/frame/g"
	"github.com/gogf/gf/v2/net/ghttp"
)

type Req struct {
	g.Meta `method:"post" mime:"multipart/form-data"`
	File   *ghttp.UploadFile `v:"required" type:"file"` // File is required
}
type Res struct{}

func main() {
	s := g.Server()
	s.BindMiddlewareDefault(ghttp.MiddlewareHandlerResponse)
	s.BindHandler("/upload", func(ctx context.Context, req *Req) (res *Res, err error) {
		return
	})
	s.SetDumpRouterMap(false)
	s.SetAccessLogEnabled(false)
	s.SetErrorLogEnabled(false)
	s.Start()
	defer s.Shutdown()
	time.Sleep(100 * time.Millisecond)

	client := g.Client()
	client.SetPrefix(fmt.Sprintf("http://127.0.0.1:%d", s.GetListenedPort()))
	content := client.PostContent(context.Background(), "/upload", g.Map{
		"file": "",
	})
	fmt.Println(content)
	// {"code":68,"message":"reflect.Value.Convert: value of type string cannot be converted to type ghttp.UploadFile","data":null}
}

What did you see happen?

When the file field is empty (""), the server crashes with the following panic:

reflect.Value.Convert: value of type string cannot be converted to type ghttp.UploadFile

This happens instead of triggering the expected validation error.

What did you expect to see?

The framework should trigger validation and return an appropriate "file is required" error instead of panicking.
Expected behavior:

  1. The request should fail with a 400 Bad Request response.
  2. The error message should be similar to "file is required" due to the v:"required" validation rule.
  3. The framework should not attempt to convert an empty string to ghttp.UploadFile, preventing the panic.

Metadata

Metadata

Assignees

Labels

bugIt is confirmed a bug, but don't worry, we'll handle it.wip

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions