Julia:如何让 HTTP.jl 从 WSL2 VM 的 ip 提供服务?

Julia: How to make HTTP.jl serve from WSL2 VM's ip?

我在 WSL2 上启动了一个简单的 http 服务器来为 localhost:8081 上的简单 HTML 页面提供服务。

我想在主机上通过 localhost:8081(或 URL 是什么)访问它。

我遵循了说明 https://docs.microsoft.com/en-us/windows/wsl/compare-versions

我用ip addr | grep eth0在inet下找到IP然后在Python和Julia

中启动了一个简单的HTTP服务器
import http.server
import socketserver

PORT = 8000

Handler = http.server.SimpleHTTPRequestHandler

httpd = socketserver.TCPServer(("", PORT), Handler)

print("serving at port", PORT)
httpd.serve_forever()

上面的 python 版本没有问题,但 Julia 服务器就是不工作。

using HTTP
using HTTP: Sockets, @ip_str
HTTP.serve() do request::HTTP.Request
   @show request
   @show request.method
   @show HTTP.header(request, "Content-Type")
   @show HTTP.payload(request)
   try
       return HTTP.Response("Hello")
   catch e
       return HTTP.Response(404, "Error: $e")
   end
end

为 HTTP 流量打开端口 8000 和 8081。然后我去了主机并做了 localhost:8081$WSL2VMIP:8081

都没用。

对于 Julia,您似乎需要提供 WSL2 VM 的 IP。使用 ip addr | grep eth0 获取 IP 并查找 172.69.13.20/20 之类的 IP 并设置 myip = ip"172.69.13.20"

请注意,使用 ip"0.0.0.0" 很方便,但可能 不安全(例如在 public 咖啡馆),因此请谨慎使用。

using HTTP
using HTTP: @ip_str
HTTP.serve(myip) do request::HTTP.Request
   @show request
   @show request.method
   @show HTTP.header(request, "Content-Type")
   @show HTTP.payload(request)
   try
       return HTTP.Response("Hello")
   catch e
       return HTTP.Response(404, "Error: $e")
   end
end