đĻ Xml
Xml marshalls the given data parameter with the xml.Marshal function and writes the result with the given status code to the http.ResponseWriter The Content-Type header is set accordingly to application/xml
type User struct {
Firstname string `xml:"firstname"`
Surname string `xml:"surname"`
}
func ExampleXmlGet(request there.Request) there.Response{
user := User{"John", "Smith"}
return there.Xml(status.OK, user)
}
When this handler gets called, the final rendered result will be
<User><firstname>John</firstname><surname>Smith</surname></User>
If the xml.Marshal fails with an error, then an Error with StatusInternalServerError will be returned, with the error format "xml: xml.Marshal: %v"
func Xml(code int, data any) Response {
xmlData, err := xml.Marshal(data)
if err != nil {
return Error(status.InternalServerError, fmt.Errorf("xml: xml.Marshal: %v", err))
}
return xmlResponse{code: code, data: xmlData}
}
XmlError
XmlError marshalls the given data parameter with the xml.Marshal function and writes the result with the given status code to the http.ResponseWriter The Content-Type header is set accordingly to application/xml
type User struct {
Firstname string `xml:"firstname"`
Surname string `xml:"surname"`
}
func ExampleXmlErrorGet(request there.Request) there.Response {
user := User{"John", "Smith"}
resp, err := there.XmlError(status.OK, user)
if err != nil {
return there.Error(status.InternalServerError, fmt.Errorf("something went wrong: %v", err))
}
return resp
}
When this handler gets called, the final rendered result will be
<User><firstname>John</firstname><surname>Smith</surname></User>
If the xml.Marshal fails with an error, then a nil response with a non-nil error will be returned to handle.
func XmlError(code int, data any) (Response, error) {
xmlData, err := xml.Marshal(data)
if err != nil {
return nil, err
}
return xmlResponse{code: code, data: xmlData}, nil
}
type xmlResponse struct {
code int
data []byte
}
func (x xmlResponse) ServeHTTP(rw http.ResponseWriter, r *http.Request) {
rw.Header().Set(header.ContentType, ContentTypeApplicationXml)
rw.WriteHeader(x.code)
_, err := rw.Write(x.data)
if err != nil {
log.Printf("xmlResponse: ServeHttp write failed: %v", err)
}
}