Can't ServeFile when getting filename from exec.Command output?


(Levi Gruspe) #1

Hello.

I have a shell script that creates a random file, and prints the location of the file.

TEMP=$RANDOM.txt
touch $TEMP
echo $(pwd)/$TEMP                    

In the same directory, there’s a go progam that serves the generated files for download. serveFile gets the filename from exec.Command("bash", "foo.sh").Output() (foo is the name of the script). The problem is the server just returns a 404 page not found instead of the file. Why is it doing that?

package main
 
 import (
     "log"
     "net/http"
     "os/exec"
 )
 
 func handler(w http.ResponseWriter, r *http.Request) {
     out, err := exec.Command("bash", "foo.sh").Output()
     if err != nil {
         http.Error(w, err.Error(), http.StatusInternalServerError)
         log.Println(err)
         return
     }
     log.Println(string(out))
     http.ServeFile(w, r, string(out))
 }
 
 func main() {
     http.HandleFunc("/random", handler)
     http.ListenAndServe(":8080", nil)
 }

(Levi Gruspe) #3

i figured it out. echo adds ‘\n’ to the end of the string.