118 lines
2.3 KiB
Go
118 lines
2.3 KiB
Go
package main
|
|
|
|
import (
|
|
"fmt"
|
|
"io"
|
|
"log"
|
|
"net/http"
|
|
"os"
|
|
"path/filepath"
|
|
"strings"
|
|
|
|
"github.com/javif89/oasis/dnsmasq"
|
|
"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 projectFolderExists(path string) bool {
|
|
_, err := os.Stat(path)
|
|
if os.IsNotExist(err) {
|
|
return false
|
|
}
|
|
|
|
return true
|
|
}
|
|
|
|
func handleRequest(w http.ResponseWriter, r *http.Request) {
|
|
fmt.Println("Request received")
|
|
|
|
log.Printf("Host: %s", r.Host)
|
|
folder := strings.ReplaceAll(r.Host, ".test", "")
|
|
searchPath := "/home/javi/projects"
|
|
|
|
log.Printf("Checking %s for project", filepath.Join(searchPath, folder))
|
|
|
|
if !projectFolderExists(filepath.Join(searchPath, folder)) {
|
|
http.ServeFile(w, r, "./404.html")
|
|
return
|
|
}
|
|
|
|
root := filepath.Join(searchPath, folder, "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 DNSMasq Server")
|
|
go dnsmasq.Serve()
|
|
|
|
fmt.Println("Starting HTTP Server")
|
|
|
|
err := http.ListenAndServe(":80", nil)
|
|
if err != nil {
|
|
log.Fatal(err)
|
|
}
|
|
}
|