package main import ( "fmt" "io" "log" "net/http" "os" "path/filepath" "github.com/javif89/oasis/fastcgi" ) func fileExists(path string) bool { fileinfo, err := os.Stat(path) if os.IsNotExist(err) || fileinfo.IsDir() { return false } return true } func handleRequest(w http.ResponseWriter, r *http.Request) { fmt.Println("Request received") root := "/home/javi/projects/javierfeliz.com/public/" // We will first try checking if the file exists // in case a static file is being requested // such as js, css, etc. path := filepath.Join(root, r.URL.Path) log.Printf("Request path: %s", r.URL.Path) if fileExists(path) { log.Printf("Checking for file: %s", path) log.Println("Serving file") fs := http.FileServer(http.Dir(root)) fs.ServeHTTP(w, r) return } // If the request was not for a static file // we will forward the request to php-fpm // and return the result of that. log.Println("Not a file. Forwarding to php-fpm") fcgiClient, err := fastcgi.Connect("unix", "/var/run/php/php8.3-fpm.sock") defer fcgiClient.Close() if err != nil { log.Println("err:", err) } resp, err := fcgiClient.Forward(r, root, "index.php") if err != nil { log.Println("PHP-FPM Error:", err) } content, err := io.ReadAll(resp.Body) resp.Body.Close() if err != nil { log.Println("err:", err) } if resp.StatusCode != 0 { w.WriteHeader(resp.StatusCode) } // Make sure to write the headers from the php-fpm response // back to the browser so things like cookies are handled. for k, v := range resp.Header { for _, hv := range v { w.Header().Add(k, hv) } } // The response body (html/json/etc) w.Write(content) } func main() { // Server http.HandleFunc("/", handleRequest) fmt.Println("Starting server") err := http.ListenAndServe(":8000", nil) if err != nil { log.Fatal(err) } }