Я хочу вернуть XML ответ, который у меня уже есть, используя Go - PullRequest
0 голосов
/ 17 апреля 2020

Я хочу распечатать ответ XML, для которого я уже сделал что-то подобное ниже (см. Блок кода).

Вместо hello; распечатать весь ответ кто-нибудь знает, как я мог это сделать?

package main

import (
    "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 ]

1 голос
/ 17 апреля 2020

Я думаю, вы ожидаете что-то подобное, верно?

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>
0 голосов
/ 17 апреля 2020

Предположим, вы хотите построить документ 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())
}
...