package main import ( "log" "net/http" "net/url" "os" "os/exec" "strings" ) func authenticationHandler(next http.HandlerFunc) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { // Check authorization header auth := strings.SplitN(r.Header.Get("Authorization"), " ", 2) if len(auth) != 2 || auth[0] != "Bearer" || auth[1] != token { log.Println("Authentication failed, got:", auth[1]) http.Error(w, "authorization failed", http.StatusUnauthorized) return } next(w, r) } } func urlOpenHandler(w http.ResponseWriter, r *http.Request) { r.ParseForm() urlStr := r.Form.Get("url") if urlStr == "" { w.WriteHeader(http.StatusBadRequest) log.Println("empty url") return } u, err := url.Parse(urlStr) if err != nil || u.Scheme == "" || u.Host == "" { w.WriteHeader(http.StatusBadRequest) log.Println("invalid url scheme/host or err:", err) return } log.Println("Opening URL", urlStr) openUrl(urlStr) } func openHandler(w http.ResponseWriter, r *http.Request) { r.ParseForm() pathStr := r.Form.Get("path") if pathStr == "" { w.WriteHeader(http.StatusBadRequest) return } s, err := os.Stat(pathStr) if os.IsNotExist(err) || s.IsDir() { w.WriteHeader(http.StatusBadRequest) return } p, err := Start(pathStr) if err != nil { w.WriteHeader(http.StatusBadRequest) return } p.Release() } func Start(args ...string) (p *os.Process, err error) { if args[0], err = exec.LookPath(args[0]); err == nil { var procAttr os.ProcAttr procAttr.Files = []*os.File{os.Stdin, os.Stdout, os.Stderr} p, err := os.StartProcess(args[0], args, &procAttr) if err == nil { return p, nil } } return nil, err }