亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

我想返回一個我已經使用 Go 的 XML 響應

我想返回一個我已經使用 Go 的 XML 響應

Go
忽然笑 2022-06-01 09:51:42
我想打印一個 XML 響應,我已經為此做了類似下面的事情(參考代碼塊)。而不是hello; 打印出整個回復有人知道我該怎么做嗎?package mainimport (    "fmt"    "net/http")func main() { http.HandleFunc("/hello", hello)    http.ListenAndServe(":9090", nil)}func hello(w http.ResponseWriter, req *http.Request) {      w.Header().Set("Content-Type", "application/xml")  fmt.Fprintf(w, "hello\n")}
查看完整描述

2 回答

?
Cats萌萌

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>


查看完整回答
反對 回復 2022-06-01
?
小怪獸愛吃肉

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())

}


查看完整回答
反對 回復 2022-06-01
  • 2 回答
  • 0 關注
  • 112 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號