Raku Net::Google::Sheets模块调用Google Sheets .clear API失败排查
开发Raku Net::Google::Sheets模块时的clear方法URL编码问题
问题背景
我正在开发Raku的Net::Google::Sheets模块,目前已通过OAuth2::Client::Google实现Google表格二维数组的读写功能,现在想添加$sheet.clear方法以匹配Google Sheets API规范,但调用该方法时出现错误。
原实现代码
Sheet类相关代码(/lib/Net/Google/Sheets.rakumod)
class Sheet is export { has $.session; has $.id; has $.range; method url { "$sheet-base/{$!id}/values/{$!range}" } method clear { my $request = HTTP::Request.new( POST => ($.url ~ ':clear'), Authorization => "Bearer {$.session.token}", Content-length => 0, ); $ua.request($request).decoded-content.&from-json; } }
调用脚本
#!/usr/bin/env raku use Net::Google::Sheets; my $session = Session.new; my %sheets = $session.sheets; my $id = %sheets<AWS_EC2_Sizes_test>; $sheet2.clear; # <=== 报错
错误信息
The requested URL
/v4/spreadsheets/{SheetId}/values/Sheet2%3Aclearwas not found on this server. That’s all we know.
注:OAuth读写功能正常,表格ID正确,且已通过Google文档的“Try It”功能成功执行clear操作,怀疑是冒号:的编码方式导致问题。
解决方案
问题根源是直接拼接URL字符串后传递给URI时,冒号被自动编码为%3A,而Google Sheets API要求冒号保持原样。修改后的代码如下:
修改后的Sheet类代码
method uri( :$cmd ) { my $uri = URI.new: $sheet-url; my $path = "$sheet-path/{$!id}/values/{$!range}"; $path ~= ":$cmd" if $cmd; $uri.path: $path; $uri; } method clear { my $cmd = 'clear'; my $request = HTTP::Request.new( POST => $.uri( :$cmd ), Authorization => "Bearer {$.session.token}", Content-length => 0, ); $ua.request($request).decoded-content.&from-json; }
修改后该方法可正常运行。
内容的提问来源于stack exchange,提问作者librasteve
相关产品推荐
相关产品推荐

