Skip to content
This repository has been archived by the owner on Jul 25, 2024. It is now read-only.

Commit

Permalink
Simplify port handling and discourage listening on a port.
Browse files Browse the repository at this point in the history
  • Loading branch information
FireMasterK committed Sep 9, 2021
1 parent f3ef98f commit 590b3e3
Showing 1 changed file with 38 additions and 8 deletions.
46 changes: 38 additions & 8 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -219,22 +219,52 @@ func getBestThumbnail(path string) (newpath string) {
return strings.Replace(path, "maxres.jpg", "mqdefault.jpg", 1)
}

// exists returns whether the given file or directory exists
func exists(path string) (bool, error) {
_, err := os.Stat(path)
if err == nil {
return true, nil
}
if os.IsNotExist(err) {
return false, nil
}
return false, err
}

func main() {
socket := "socket" + string(os.PathSeparator) + "http-proxy.sock"
syscall.Unlink(socket)
listener, err := net.Listen("unix", socket)
env_port := os.Getenv("PORT")
port := "8080"

if env_port != "" {
port = env_port
}

srv := &http.Server{
ReadTimeout: 5 * time.Second,
WriteTimeout: 10 * time.Second,
Addr: ":8080",
Addr: ":" + port,
Handler: &requesthandler{},
}

exists, err := exists("socket/")

if err != nil {
fmt.Println("Failed to bind to UDS, falling back to TCP/IP")
fmt.Println(err.Error())
srv.ListenAndServe()
} else {
log.Panicln(err)
}

if env_port == "" && exists {
socket := "socket" + string(os.PathSeparator) + "http-proxy.sock"
syscall.Unlink(socket)
listener, err := net.Listen("unix", socket)

if err != nil {
log.Panicln(err)
}

defer listener.Close()
srv.Serve(listener)
} else {
fmt.Println("WARNING: You are listening on a HTTP Socket, you are strongly recommended to use a Unix Domain Socket when running a public instance for performance reasons.")
srv.ListenAndServe()
}
}

0 comments on commit 590b3e3

Please sign in to comment.