Skip to content

Instantly share code, notes, and snippets.

@jamonation
Created September 28, 2022 01:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jamonation/1fcc4a8e880ba34b7198a43570c60b8f to your computer and use it in GitHub Desktop.
Save jamonation/1fcc4a8e880ba34b7198a43570c60b8f to your computer and use it in GitHub Desktop.
Go program to download and overwrite itself with a new copy
package main
import (
"fmt"
"io"
"net/http"
"os"
"syscall"
)
func main() {
// Run `python3 -m http.server 8080` wherever there's a separate copy of
// the `main` binary for quick and dirty testing
req, err := http.Get("http://127.0.0.1:8080/main")
if err != nil {
fmt.Printf("error making http request: %v\n", err)
os.Exit(1)
}
body, err := io.ReadAll(req.Body)
if err != nil {
fmt.Printf("error reading http response body: %v\n", err)
os.Exit(1)
}
defer req.Body.Close()
// more complete version of this functionality would make a backup first
err = syscall.Unlink("main")
if err != nil {
fmt.Printf("error unlinking file: %v\n", err)
os.Exit(1)
}
f, err := os.Create("main")
if err != nil {
fmt.Printf("error creating file: %v\n", err)
os.Exit(1)
}
defer f.Close()
_, err = f.Write(body)
if err != nil {
fmt.Printf("error writing file, badness: %v\n", err)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment