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

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)
 }
2 Likes

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

2 Likes

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.