nim c -d:ssl -r test.nim
import httpclient, streams, cookies
import system
import typetraits
const UserAgent = "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36"
var client = newHttpClient(userAgent = UserAgent)
var url:string
url = "https://www.baidu.com"
var headers = newHttpHeaders({"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8" })
#var resp:Response
try:
let resp = client.request(url, headers=headers)
echo resp.repr[..200]
except Exception as exc:
echo(exc.repr)
finally:
echo resp.repr
echo resp.code
if resp.code.is4xx or resp.code.is5xx:
raise newException(HttpRequestError, resp.status)
else:
echo resp.bodyStream.readAll()
echo resp.status
echo resp.headers
以上代码的奇怪之处就在于, 22行的resp居然没有定义, 也就是说, try: 后面的代码块里, 使用let定义了一个resp, 但是到了finally那里, 编译器就不认识了.
当然, 也没有python里的else分支,让人觉得很无助.