我有 GC 函数,我使用 Cloud Pub/Sub 模拟器在本地开发和测试。
我希望能够从 Go 代码中检查 Cloud Pub/Sub 模拟器是否已启动并运行。如果没有,我想通知开发人员,他/她应该在本地执行代码之前启动模拟器。
当模拟器启动时,我注意到一条线
信息:服务器已启动,正在侦听 8085
也许我可以检查端口是否可用或类似。
我猜你用过这个命令:
gcloud beta emulators pubsub start
您得到以下输出:
[pubsub] This is the Google Pub/Sub fake.
[pubsub] Implementation may be incomplete or differ from the real system.
[pubsub]
[pubsub] INFO: IAM integration is disabled. IAM policy methods and ACL checks are not supported
[pubsub]
[pubsub] INFO: Applied Java 7 long hostname workaround.
[pubsub]
[pubsub] INFO: Server started, listening on 8085
如果您查看第二条
INFO
消息,您会注意到进程名称将为 JAVA
。现在您可以运行此命令:
sudo lsof -i -P -n
获取所有监听端口和应用程序,输出应该是这样的:
COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME
XXXX
XXXX
java XXX XXX XX IPv4 XXX 0t0 TCP 127.0.0.1:8085 (LISTEN)
或者,您可以修改前面的命令以仅显示所需端口上发生的情况:
sudo lsof -i -P -n | grep 8085
您可以只请求 pubsub 端点,看看结果是否为
Ok
,就像这样
#!/usr/bin/env sh
# Execute the curl command and store the result.
# $1 is the port pubsub is running, passed as argument
result=$(curl -s "localhost:$1")
# Check if the result is "Ok"
if [ "$result" == "Ok" ]; then
echo "Success: The output is 'Ok'"
exit 0
else
echo "Failure: The output is not 'Ok'"
exit 1
fi