搜尋
首頁後端開發Golang聊聊golang怎麼呼叫php7

聊聊golang怎麼呼叫php7

Sep 20, 2021 pm 04:30 PM
golangphpphp7

本文由go語言教學專欄為大家介紹golang怎麼呼叫php7,希望對需要的朋友有幫助!

使用 https://github.com/taowen/go-php7
基於https: //github.com/deuill/go-php 修改而來,fork緣由(https://github.com/deuill/go-php/issues/32)

執行php檔

func Test_exec(t *testing.T) {
    engine.Initialize()
    ctx := &engine.Context{
        Output: os.Stdout,
    }
    err := engine.RequestStartup(ctx)
    if err != nil {
        fmt.Println(err)
    }
    defer engine.RequestShutdown(ctx)
    err = ctx.Exec("/tmp/index.php")
    if err != nil {
        fmt.Println(err)
    }
}

其中/tmp/index.php 的內容為

<?php echo("hello\n");

Eval,傳回值

func Test_eval(t *testing.T) {
    engine.Initialize()
    ctx := &engine.Context{}
    err := engine.RequestStartup(ctx)
    if err != nil {
        fmt.Println(err)
    }
    defer engine.RequestShutdown(ctx)
    val, err := ctx.Eval("return 'hello';")
    if err != nil {
        fmt.Println(err)
    }
    defer engine.DestroyValue(val)
    if engine.ToString(val) != "hello" {
        t.FailNow()
    }
}

傳回的value的生命週期所有權是golang程序,所以我們要負責DestroyValue

設定全域變數來傳參

func Test_argument(t *testing.T) {
    engine.Initialize()
    ctx := &engine.Context{}
    err := engine.RequestStartup(ctx)
    if err != nil {
        fmt.Println(err)
    }
    defer engine.RequestShutdown(ctx)
    err = ctx.Bind("greeting", "hello")
    if err != nil {
        fmt.Println(err)
    }
    val, err := ctx.Eval("return $greeting;")
    if err != nil {
        fmt.Println(err)
    }
    defer engine.DestroyValue(val)
    if engine.ToString(val) != "hello" {
        t.FailNow()
    }
}

傳遞進去的參數的生命週期是php控制的,在request shutdown的時候記憶體會被釋放。

PHP 回呼Golang

type greetingProvider struct {
    greeting string
}

func (provider *greetingProvider) GetGreeting() string {
    return provider.greeting
}

func newGreetingProvider(args []interface{}) interface{} {
    return &greetingProvider{
        greeting: args[0].(string),
    }
}

func Test_callback(t *testing.T) {
    engine.Initialize()
    ctx := &engine.Context{}
    err := engine.RequestStartup(ctx)
    if err != nil {
        fmt.Println(err)
    }
    defer engine.RequestShutdown(ctx)
    err = engine.Define("GreetingProvider", newGreetingProvider)
    if err != nil {
        fmt.Println(err)
    }
    val, err := ctx.Eval(`
    $greetingProvider = new GreetingProvider('hello');
    return $greetingProvider->GetGreeting();`)
    if err != nil {
        fmt.Println(err)
    }
    defer engine.DestroyValue(val)
    if engine.ToString(val) != "hello" {
        t.FailNow()
    }
}

PHP 錯誤日誌

func Test_log(t *testing.T) {
    engine.PHP_INI_PATH_OVERRIDE = "/tmp/php.ini"
    engine.Initialize()
    ctx := &engine.Context{
        Log: os.Stderr,
    }
    err := engine.RequestStartup(ctx)
    if err != nil {
        fmt.Println(err)
    }
    defer engine.RequestShutdown(ctx)
    _, err = ctx.Eval("error_log('hello', 4); trigger_error('sent from golang', E_USER_ERROR);")
    if err != nil {
        fmt.Println(err)
    }
}

其中/tmp/php.ini 的內容為

error_reporting = E_ALL
error_log = "/tmp/php-error.log"

錯誤會被輸出到/tmp/php-error.log。直接呼叫error_log會同時再輸出一份到stderr

HTTP 輸入輸出

func Test_http(t *testing.T) {
    engine.Initialize()
    recorder := httptest.NewRecorder()
    ctx := &engine.Context{
        Request: httptest.NewRequest("GET", "/hello", nil),
        ResponseWriter: recorder,
    }
    err := engine.RequestStartup(ctx)
    if err != nil {
        fmt.Println(err)
    }
    defer engine.RequestShutdown(ctx)
    _, err = ctx.Eval("echo($_SERVER['REQUEST_URI']);")
    if err != nil {
        fmt.Println(err)
    }
    body, err := ioutil.ReadAll(recorder.Result().Body)
    if err != nil {
        fmt.Println(err)
    }
    if string(body) != "/hello" {
        t.FailNow()
    }
}

所有的PHP超級全域變數都會被初始化為傳遞進去的Request的值,包括

$_SERVER
$_GET
$_POST
$_FILE
$_COOKIE
$_ENV

echo的內容,http code和http header會被寫回傳入的ResponseWriter

fastcgi_finish_request

PHP-FPM 很常用的一個功能是fastcgi_finish_request,用於在php裡做一些非同步完成的事情。這個特殊的全域函數必須支援

func Test_fastcgi_finish_reqeust(t *testing.T) {
    engine.Initialize()
    buffer := &bytes.Buffer{}
    ctx := &engine.Context{
        Output: buffer,
    }
    err := engine.RequestStartup(ctx)
    if err != nil {
        fmt.Println(err)
    }
    defer engine.RequestShutdown(ctx)
    ctx.Eval("ob_start(); echo ('hello');")
    if buffer.String() != "" {
        t.FailNow()
    }
    ctx.Eval("fastcgi_finish_request();")
    if buffer.String() != "hello" {
        t.FailNow()
    }
}

實際的作用就是把output提前輸出到 ResposneWriter 裡去,讓呼叫方知道結果。對於目前進程的執行其實是沒有影響的,只是影響了output。

推薦學習:《golang教學

以上是聊聊golang怎麼呼叫php7的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述
本文轉載於:segmentfault。如有侵權,請聯絡admin@php.cn刪除
測試代碼依賴於INET功能的代碼測試代碼依賴於INET功能的代碼May 03, 2025 am 12:20 AM

whentestinggocodewithinitfunctions,useexplicitseTupfunctionsorseParateTestFileSteSteTepteTementDippedDependendendencyOnInItfunctionsIdeFunctionSideFunctionsEffect.1)useexplicitsetupfunctionStocontrolglobalvaribalization.2)createSepEpontrolglobalvarialization

將GO的錯誤處理方法與其他語言進行比較將GO的錯誤處理方法與其他語言進行比較May 03, 2025 am 12:20 AM

go'serrorhandlingurturnserrorsasvalues,與Javaandpythonwhichuseexceptions.1)go'smethodensursexplitirorhanderling,propertingrobustcodebutincreasingverbosity.2)

設計有效界面的最佳實踐設計有效界面的最佳實踐May 03, 2025 am 12:18 AM

AnefactiveInterfaceingoisminimal,clear and promotesloosecoupling.1)minimizeTheInterfaceForflexibility andeaseofimplementation.2)useInterInterfaceForabStractionToswaPimplementations withoutchangingCallingCode.3)

集中式錯誤處理策略集中式錯誤處理策略May 03, 2025 am 12:17 AM

集中式錯誤處理在Go語言中可以提升代碼的可讀性和可維護性。其實現方式和優勢包括:1.將錯誤處理邏輯從業務邏輯中分離,簡化代碼。 2.通過集中處理錯誤,確保錯誤處理的一致性。 3.使用defer和recover來捕獲和處理panic,增強程序健壯性。

init in Init函數的替代方案,用於go中的包裝初始化init in Init函數的替代方案,用於go中的包裝初始化May 03, 2025 am 12:17 AM

Ingo,替代詞InivestoIniTfunctionsIncludeCustomInitializationfunctionsandsingletons.1)customInitializationfunctions hownerexpliticpliticpliticconconconconconconconconconconconconconconconconconconconconconconconconconconconconconconconconconconconconconconconconconconconconconconconconconconconconcontirization curssetupssetupssetups.2)單次固定無元素限制ininconconcurrent

與GO接口鍵入斷言和類型開關與GO接口鍵入斷言和類型開關May 02, 2025 am 12:20 AM

Gohandlesinterfacesandtypeassertionseffectively,enhancingcodeflexibilityandrobustness.1)Typeassertionsallowruntimetypechecking,asseenwiththeShapeinterfaceandCircletype.2)Typeswitcheshandlemultipletypesefficiently,usefulforvariousshapesimplementingthe

使用errors.is和錯誤。使用errors.is和錯誤。May 02, 2025 am 12:11 AM

Go語言的錯誤處理通過errors.Is和errors.As函數變得更加靈活和可讀。 1.errors.Is用於檢查錯誤是否與指定錯誤相同,適用於錯誤鏈的處理。 2.errors.As不僅能檢查錯誤類型,還能將錯誤轉換為具體類型,方便提取錯誤信息。使用這些函數可以簡化錯誤處理邏輯,但需注意錯誤鏈的正確傳遞和避免過度依賴以防代碼複雜化。

在GO中進行性能調整:優化您的應用程序在GO中進行性能調整:優化您的應用程序May 02, 2025 am 12:06 AM

tomakegoapplicationsRunfasterandMorefly,useProflingTools,leverageConCurrency,andManageMoryfectily.1)usepprofforcpuorforcpuandmemoryproflingtoidentifybottlenecks.2)upitizegorizegoroutizegoroutinesandchannelstoparalletaparelalyizetasksandimproverperformance.3)

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

MantisBT

MantisBT

Mantis是一個易於部署的基於Web的缺陷追蹤工具,用於幫助產品缺陷追蹤。它需要PHP、MySQL和一個Web伺服器。請查看我們的演示和託管服務。

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

這個專案正在遷移到osdn.net/projects/mingw的過程中,你可以繼續在那裡關注我們。 MinGW:GNU編譯器集合(GCC)的本機Windows移植版本,可自由分發的導入函式庫和用於建置本機Windows應用程式的頭檔;包括對MSVC執行時間的擴展,以支援C99功能。 MinGW的所有軟體都可以在64位元Windows平台上運作。

mPDF

mPDF

mPDF是一個PHP庫,可以從UTF-8編碼的HTML產生PDF檔案。原作者Ian Back編寫mPDF以從他的網站上「即時」輸出PDF文件,並處理不同的語言。與原始腳本如HTML2FPDF相比,它的速度較慢,並且在使用Unicode字體時產生的檔案較大,但支援CSS樣式等,並進行了大量增強。支援幾乎所有語言,包括RTL(阿拉伯語和希伯來語)和CJK(中日韓)。支援嵌套的區塊級元素(如P、DIV),

Atom編輯器mac版下載

Atom編輯器mac版下載

最受歡迎的的開源編輯器