Tomo.Log()


[Vapor3]How to make a XML Response for sitemap

[09/13, 2018]

日本語 / English

You might want to return a response as XML. So do I. I wanted to make a sitemap.xml. First, I tried using with Leaf template but "Content-Type " automatically became HTML.

So I made a response by myself and returned it. This is one of a way to response XML.

router.get("sitemap") { 
    req in
    return Article.query(on: req).all().flatMap(to: Response.self) {
        articles in
        let response : HTTPResponse = HTTPResponse(status: HTTPStatus.ok,
                                                   headers:["Content-Type":"application/xml"],
                                                   body: self.makeXml(articles: articles))
        
        return try req.makeResponse(http: response).encode(for: req)
    }
}

In this example, this func is public but the func usually be in the Controller class I think.

public func makeXML(articles: [Article]) -> String {
    var siteURL = "https://sample.com/"
    
    var xml : String = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
    xml += "<urlset xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\">"
    xml += "<url>"
    xml += "<loc>" + siteURL + "</loc>"
    xml += "<priority>1.0</priority>"
    xml += "</url>"
    
    for article in articles {
        
        xml += "<url>"
        xml += "<loc>" + article.url + "</loc>"
        
        xml += "<lastmod>" + article.lastupdatedAt + "</lastmod>"
        
        xml += "<priority>0.7</priority>"
        xml += "</url>"
    }
    
    xml += "</urlset>"

    return xml
}

I hope this helps you.