是否有用于 Go 的 MarshalURLQuery 的实现?
Is there an implementation of MarshalURLQuery for Go?
给定一个像这样的 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 中做到这一点?
是,gorilla/schema,使用 encoder
:
package main
import (
"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=John
给定一个像这样的 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 中做到这一点?
是,gorilla/schema,使用 encoder
:
package main
import (
"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=John