Here is my code:
main.go
package main
import (
"fmt"
"html/template"
"io/ioutil"
"log"
"net/http"
"os"
"regexp"
)
func indexHandler(w http.ResponseWriter, r *http.Request) {
tmpl, _ := template.New("index.html").ParseFiles("index.html")
server, _ := ioutil.ReadFile("main.go")
re := regexp.MustCompile(`PATCHED`)
result := re.ReplaceAll(server, []byte("PATCHED"))
tmpl.Execute(w, string(result))
}
func staticHandler(w http.ResponseWriter, r *http.Request) {
r.ParseForm()
filepath := r.Form.Get("file")
filepath = fmt.Sprintf("static/%v", filepath)
if len(filepath) == 0 {
_, err := w.Write([]byte("file parameter is required"))
if err != nil {
log.Println("Can't write response")
}
return
}
file, err := ioutil.ReadFile(filepath)
if err != nil {
http.Error(w, "Not found", http.StatusNotFound)
}
w.Write(file)
}
func main() {
http.HandleFunc("/", indexHandler)
http.HandleFunc("/static/", staticHandler)
flagFile, err := os.Open("/PATCHED")
if err != nil {
log.Println(err)
}
flagFile = flagFile
addr, _ := os.LookupEnv("ADDR")
log.Fatal(http.ListenAndServe(addr, nil))
flagFile.Close()
}