Created
September 28, 2022 01:10
-
-
Save jamonation/1fcc4a8e880ba34b7198a43570c60b8f to your computer and use it in GitHub Desktop.
Go program to download and overwrite itself with a new copy
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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