Skip to content

Instantly share code, notes, and snippets.

@HirbodBehnam
Last active August 31, 2020 06:36
Show Gist options
  • Select an option

  • Save HirbodBehnam/887ffeaec2d6b9c2b5fd20b804631821 to your computer and use it in GitHub Desktop.

Select an option

Save HirbodBehnam/887ffeaec2d6b9c2b5fd20b804631821 to your computer and use it in GitHub Desktop.
Spawns file server of current directory on a random port and configures firewall for it.
package main
import (
"context"
"log"
"math/rand"
"net/http"
"os"
"os/exec"
"os/signal"
"strconv"
"syscall"
"time"
)
func main(){
rand.Seed(time.Now().Unix())
port := strconv.Itoa(rand.Intn(65535) + 1)
srv := &http.Server{
Addr: ":" + port,
Handler: http.FileServer( http.Dir( "." )),
}
cmd := exec.Command("ufw", "allow", port + "/tcp") // you have to change this
stdout, err := cmd.Output()
if err != nil {
log.Fatal(err.Error())
}
log.Print("Firewall status: ", string(stdout))
// https://medium.com/honestbee-tw-engineer/gracefully-shutdown-in-go-http-server-5f5e6b83da5a
done := make(chan os.Signal, 1)
signal.Notify(done, os.Interrupt, syscall.SIGINT, syscall.SIGTERM)
go func() {
if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
log.Fatalf("listen: %s\n", err)
}
}()
log.Print("Server started on 127.0.0.1:", port) // you can change the IP of server
<-done
log.Print("Server Stopped")
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer func() {
cmd := exec.Command("ufw","delete", "allow", port + "/tcp") // you have to change this
stdout, err := cmd.Output()
if err != nil {
log.Print("Cannot delete firewall rules: ",err.Error())
}else {
log.Print("Firewall delete port status: ", string(stdout))
}
cancel()
}()
if err := srv.Shutdown(ctx); err != nil {
log.Fatalf("Server Shutdown Failed:%+v", err)
}else {
log.Print("Server Exited Properly")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment