-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathphp.go
More file actions
148 lines (119 loc) · 3.73 KB
/
php.go
File metadata and controls
148 lines (119 loc) · 3.73 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
package wazemmes
import (
"bytes"
"context"
_ "embed"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"os"
"strings"
"github.com/tetratelabs/wazero"
"github.com/tetratelabs/wazero/imports/wasi_snapshot_preview1"
"go.uber.org/zap"
)
type phpWASMHandler struct {
runtime wazero.Runtime
compiledModule wazero.CompiledModule
documentRoot string
}
func (h *phpWASMHandler) getScriptPath(urlPath string) string {
if urlPath == "/" || urlPath == "" {
return "index.php"
}
return h.documentRoot
}
func (h *phpWASMHandler) ServeHTTP(rw http.ResponseWriter, r *http.Request) error {
scriptPath := h.getScriptPath(r.URL.Path)
// Create a pipe to capture PHP output
outputBuffer := &strings.Builder{}
// Configure module with CGI environment
config := wazero.NewModuleConfig().
WithStdout(outputBuffer).
WithStderr(os.Stderr).
WithFS(os.DirFS("..")).
WithArgs("php-cgi", scriptPath).
WithEnv("REQUEST_METHOD", r.Method).
WithEnv("REQUEST_URI", r.RequestURI).
WithEnv("SCRIPT_FILENAME", scriptPath).
WithEnv("SCRIPT_NAME", scriptPath).
WithEnv("DOCUMENT_ROOT", h.documentRoot).
WithEnv("QUERY_STRING", r.URL.RawQuery).
WithEnv("CONTENT_TYPE", r.Header.Get("Content-Type")).
WithEnv("CONTENT_LENGTH", r.Header.Get("Content-Length")).
WithEnv("SERVER_SOFTWARE", "Go-WASM-Server/1.0").
WithEnv("SERVER_NAME", r.Host).
WithEnv("SERVER_PORT", "8080").
WithEnv("GATEWAY_INTERFACE", "CGI/1.1").
WithEnv("SERVER_PROTOCOL", r.Proto).
WithEnv("HTTP_HOST", r.Host).
WithEnv("HTTP_USER_AGENT", r.Header.Get("User-Agent")).
WithEnv("HTTP_ACCEPT", r.Header.Get("Accept")).
WithEnv("HTTP_ACCEPT_LANGUAGE", r.Header.Get("Accept-Language")).
WithEnv("HTTP_ACCEPT_ENCODING", r.Header.Get("Accept-Encoding")).
WithEnv("HTTP_CONNECTION", r.Header.Get("Connection"))
// Add custom headers as HTTP_* environment variables
for key, values := range r.Header {
if len(values) > 0 {
envKey := fmt.Sprintf("HTTP_%s", strings.ToUpper(strings.ReplaceAll(key, "-", "_")))
config = config.WithEnv(envKey, values[0])
}
}
// If there's a request body, we need to handle it
if r.Body != nil {
stdin := bytes.NewBuffer([]byte{})
_, err := io.Copy(stdin, r.Body)
if err != nil {
return err
}
r.Body = io.NopCloser(bytes.NewReader(stdin.Bytes()))
config.WithStdin(stdin)
}
module, _ := h.runtime.InstantiateModule(r.Context(), h.compiledModule, config)
defer func() {
_ = module.Close(r.Context())
}()
var response baseHandler
_ = json.NewDecoder(bytes.NewReader([]byte(strings.Split(outputBuffer.String(), "\r\n\r\n")[1]))).Decode(&response)
if response.Error != "" {
rw.WriteHeader(http.StatusInternalServerError)
_, _ = rw.Write([]byte(response.Error))
rw.(http.Flusher).Flush()
return errors.New(response.Error)
}
for key, values := range response.Response.Headers {
for _, value := range values {
rw.Header().Set(key, value)
}
}
_, _ = rw.Write([]byte(response.Response.Body))
return nil
}
//go:embed php-cgi.wasm
var phpWasm []byte
func NewWasmHandlerPHP(modulepath string, _ any, poolConfiguration map[string]interface{},
logger *zap.Logger) (*WasmHandler, error) {
ctx := context.Background()
runtime := wazero.NewRuntime(ctx)
if _, err := wasi_snapshot_preview1.Instantiate(ctx, runtime); err != nil {
return nil, fmt.Errorf("failed to instantiate WASI: %w", err)
}
compiled, err := runtime.CompileModule(ctx, phpWasm)
if err != nil {
return nil, fmt.Errorf("failed to compile WASM module: %w", err)
}
wasmHandlerPHP := &phpWASMHandler{
runtime: runtime,
compiledModule: compiled,
documentRoot: modulepath,
}
return NewWasmHandlerInstance(
func(ctx context.Context, next Handler) Handler {
return wasmHandlerPHP
},
poolConfiguration,
logger,
)
}