猿问

是否有用于 Go 的 MarshalURLQuery 的实现?

给定这样的 Go 结构:


type Color struct {

    Red   int32 `url:"red"`

    Green int32 `url:"green"`

    Blue  int32 `url:"blue"`

    Alpha int32 `url:"alpha,omitempty"`

}

能够将其转换为 URL 查询会很棒,例如:


c := Color{

    Red:   255,

    Green: 127,

}


v, err := MarshalURLQuery(c)


fmt.Printf("%s", string(b))

其中 v 是一个url.Values实例,产生“ red=255&green=127&blue=0”。当然,Go 肯定已经提供了类似的东西。如何在不重新发明轮子的情况下在 Go 中做到这一点?


萧十郎
浏览 118回答 1
1回答

慕田峪4524236

是的,gorilla/schema,使用encoder:package mainimport (    "fmt"    "log"    "net/url"    "github.com/gorilla/schema")type Person struct {    Name     string `schema:"name"`    Lastname string `schema:"lastname"`}func main() {    person := &Person{Name: "John", Lastname: "Doe"}    encoder := schema.NewEncoder()    v2 := url.Values{}    if err := encoder.Encode(person, v2); err != nil {        log.Fatal(err)    }    fmt.Println(v2.Encode())}输出:lastname=Doe&name=Johnhttps://play.golang.org/p/0_7879f5BES
随时随地看视频慕课网APP

相关分类

Go
我要回答