2 回答

TA貢獻1805條經驗 獲得超9個贊
我想你期待這樣的事情,對吧?
package main
import (
"encoding/xml"
"net/http"
)
// Response XML struct
type Response struct {
Greeting string
Names []string `xml:"Names>Name"`
}
func hello(w http.ResponseWriter, r *http.Request) {
response := Response{"Hello", []string{"World", "Sarkar"}}
// Wraps the response to Response struct
x, err := xml.MarshalIndent(response, "", " ")
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/xml")
// Write
w.Write(x)
}
func main() {
http.HandleFunc("/hello", hello)
http.ListenAndServe(":9090", nil)
}
輸出:
HTTP/1.1 200 OK
Content-Type: application/xml
Date: Fri, 17 Apr 2020 07:01:46 GMT
Content-Length: 119
<Response>
<Greeting>Hello</Greeting>
<Names>
<Name>World</Name>
<Name>Sarkar</Name>
</Names>
</Response>

TA貢獻1852條經驗 獲得超1個贊
假設您要構建一個 XML 文檔,例如
<Greeting><text>hello</text></Greeting>
這可以使用encoding/xml包來完成。
package main
import (
"bytes"
"encoding/xml"
"fmt"
"os"
)
// Greeting is the struct for an XML greeting.
type Greeting struct {
Text string `xml:"text"`
}
func main() {
// Create a new greeting.
g := &Greeting{Text: "hello"}
// Encode it into a bytes buffer.
var b bytes.Buffer
enc := xml.NewEncoder(&b)
if err := enc.Encode(g); err != nil {
fmt.Printf("error: %v\n", err)
os.Exit(1)
}
// This will print <Greeting><text>hello</text></Greeting>
fmt.Println(b.String())
}
- 2 回答
- 0 關注
- 112 瀏覽
添加回答
舉報