最近在用 Grape 写个简单的微信机器人,测试的时候碰到一个问题:正常的微信接口查询是没问题(下面代码的 post 接口),但是微信校验接口总是不通过(下面代码的 get 接口);分析原因是微信接口查询默认返回的是 xml 格式,API 定义的默认返回格式也是 xml(format :xml)所以没问题,但是微信校验接口返回的是字符串,Grape 执行返回数据的 to_xml 方法时报错:cannot convert String to xml。
大家遇到 Grape API 返回不同格式时如何处理?我是想要是 Grape 只是方法级别定义返回数据格式就好了,但是查了 Grape 官方文档也看到类似的说明,Google 也没找到。
module Wechat
  class API < Grape::API
    version 'v1', :using => :path, :vendor => 'weixin'
    format :xml
    content_type :xml, "text/xml"
    helpers WechatHelper
    resource :weixin do
      desc 'check weixin sign'
      get do
        # 返回字符串
        check_sign(params)
      end
      desc 'weixin response'
      post do
        request_body = request.body.read
        status("200")
        # 返回xml对象
        get_weixin_response(request_body)
      end
    end
  end
end