94 lines
1.8 KiB
Go
94 lines
1.8 KiB
Go
package main
|
|
|
|
import (
|
|
"fmt"
|
|
"io"
|
|
"log"
|
|
"net/http"
|
|
"os"
|
|
"path/filepath"
|
|
"strings"
|
|
|
|
"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")
|
|
req := fastcgi.RequestFromHttp(r)
|
|
req.Root(root)
|
|
req.Script("index.php")
|
|
|
|
fcgiClient, err := fastcgi.Dial("unix", "/var/run/php/php8.3-fpm.sock")
|
|
defer fcgiClient.Close()
|
|
|
|
if err != nil {
|
|
log.Println("err:", err)
|
|
}
|
|
|
|
resp, err := fcgiClient.Do(req)
|
|
if err != nil {
|
|
log.Println("err:", 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)
|
|
}
|
|
|
|
for k, v := range resp.Header {
|
|
log.Printf("Header received: %s: %s", k, strings.Join(v, ", "))
|
|
|
|
for _, hv := range v {
|
|
w.Header().Add(k, hv)
|
|
}
|
|
}
|
|
|
|
w.Write(content)
|
|
}
|
|
|
|
func main() {
|
|
|
|
// Server
|
|
http.HandleFunc("/", handleRequest)
|
|
|
|
fmt.Println("Starting server")
|
|
|
|
err := http.ListenAndServe(":8000", nil)
|
|
if err != nil {
|
|
log.Fatal(err)
|
|
}
|
|
}
|