PHP 函數如何與 Go 交互
PHP 和 Go 是兩種截然不同的編程語言,具有不同的語法和特性。然而,在某些情況下,您可能需要在 PHP 應用程序和 Go 服務之間進行交互。
方法 1:使用 HTTP 請求
您可以使用標準 HTTP 請求在 PHP 和 Go 之間發送數據。
PHP 代碼:
<?php
// 發送 HTTP GET 請求
$response = file_get_contents('http://example.com/go-endpoint');
// 處理響應
$data = json_decode($response, true);
登錄后復制
Go 代碼:
package main
import (
"fmt"
"net/http"
)
func main() {
http.HandleFunc("/go-endpoint", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, "Hello from Go!")
})
http.ListenAndServe(":8080", nil)
}
登錄后復制
方法 2:使用 gRPC
gRPC 是一種跨語言遠程過程調用框架,可用于在 PHP 和 Go 之間進行通信。
PHP 代碼:
<?php
// 創建 gRPC 客戶
use Grpc\Client as GrpcClient;
$client = new GrpcClient([
'target' => 'localhost:50051'
]);
// 調用遠程方法
$request = new ExampleMessage();
$request->setName('Alice');
$response = $client->ExampleService->ExampleMethod($request)->wait();
// 處理響應
echo $response->getMessage();
登錄后復制
Go 代碼:
package main
import (
"context"
example "github.com/example/grpc/pb"
"google.golang.org/grpc"
)
func main() {
// 啟動 gRPC 服務
lis, err := net.Listen("tcp", ":50051")
if err != nil {
log.Fatalf("failed to listen: %v", err)
}
grpcServer := grpc.NewServer()
example.RegisterExampleServiceServer(grpcServer, &exampleServer{})
grpcServer.Serve(lis)
}
type exampleServer struct{}
func (s *exampleServer) ExampleMethod(ctx context.Context, req *example.ExampleMessage) (*example.ExampleMessage, error) {
return &example.ExampleMessage{Message: "Hello from Go!"}, nil
}
登錄后復制
實戰案例
假設您有一個 PHP Web 應用程序,需要與 Go 微服務通信以獲取用戶數據。您可以使用 HTTP 請求或 gRPC 根據需要與微服務進行交互。通過采用這些方法,您可以輕松地在 PHP 和 Go 之間建立通信渠道。






