yookoala / gofast

gofast is a FastCGI "client" library written purely in go
BSD 3-Clause "New" or "Revised" License
224 stars 49 forks source link

How to intercept response header #79

Closed cevin closed 1 year ago

cevin commented 1 year ago

like nginx X-Accel-Redirect will be intercept and remove before responed to client by nginx

ResponsePipe just write to http.Response

yookoala commented 1 year ago

@cevin: ResponsePipe does not directly write to http.Response. Instead, it uses the provided http.ResponseWriter interface instance to write response. One way to intercept and change response behaviour is to override the response writer with a middleware.

For example,

package main

import (
    "log"
    "net/http"
    "os"

    "github.com/yookoala/gofast"
)

func myMiddleware(inner http.Handler) http.Handler {
        return http.HandlerFunc(func (w http.ResponseWriter, r *http.Request) {
        myw := myResponseWriter(w) // something to wrap arround the original writer
        inner.ServeHTTP(myw, r)
    })
}

func main() {
    // Get fastcgi application server tcp address
    // from env FASTCGI_ADDR. Then configure
    // connection factory for the address.
    address := os.Getenv("FASTCGI_ADDR")
    connFactory := gofast.SimpleConnFactory("tcp", address)

    // route all requests to a single php file
    // overrides the http.ResponseWriter behaviour here with myMiddleware
    http.Handle("/", myMiddleware(gofast.NewHandler(
        gofast.NewFileEndpoint("/var/www/html/index.php")(gofast.BasicSession),
        gofast.SimpleClientFactory(connFactory),
    )))

    // serve at 8080 port
    log.Fatal(http.ListenAndServe(":8080", nil))
}

With your own response writer, you may change how your server actually create the response.

I hope this solves your issue :-)