i want execute function and return output results on variable, this is my actual code :
package main
import (
"os"
"net/http"
"io"
"fmt"
"strings"
)
func downloadFile(url string) (err error) {
resp, err := http.Get(url)
if err != nil {
return err
}
// extrage numele fisierului din linkul redirectionat.
finalURL := resp.Request.URL.String()
parts := strings.Split(finalURL, "/")
filename := parts[len(parts)-1]
out, errr := os.Create(filename)
if errr != nil {
return errr
}
_, err = io.Copy(out, resp.Body)
if err != nil {
return err
}
defer out.Close()
defer resp.Body.Close()
return filename
}
func main() {
var url1 string = "https://transfer.sh/5e2iH/test.txt"
var filename2 string = "test test test"
filename2 := downloadFile(url1)
fmt.Println( filename2 )
}
i want execute function downloadFile and return variable filename in variable filename2, return me this error, where im wrong ? im python developer, im sure to make stupid error :)
F:\dev\GoLang\gitlab\check>go run download.go
# command-line-arguments
.\download.go:37:3: cannot use filename (type string) as type error in return ar
gument:
string does not implement error (missing Error method)
.\download.go:45:13: no new variables on left side of :=
.\download.go:45:13: cannot use downloadFile(url1) (type error) as type string i
n assignment
You can't use error
like a string in the downloadFile()
function, you should work with both variables. Golang is strongly typed and couldn't change the type of variable. You can use interfaces for polymorphism but in this case, you need just return err
and filename
together like this:
package main
import (
"os"
"net/http"
"io"
"fmt"
"strings"
)
func downloadFile(url string) (err error, filename string) {
resp, err := http.Get(url)
defer resp.Body.Close()
if err != nil {
return
}
// extrage numele fisierului din linkul redirectionat.
finalURL := resp.Request.URL.String()
parts := strings.Split(finalURL, "/")
filename = parts[len(parts)-1]
out, err := os.Create(filename)
defer out.Close()
if err != nil {
return
}
_, err = io.Copy(out, resp.Body)
if err != nil {
return
}
return
}
func main() {
var url1 string = "https://transfer.sh/5e2iH/test.txt"
err, file := downloadFile(url1)
if err != nil {
panic(err.Error())
}
fmt.Println( file )
}
Go is strongly typed, so a function cannot return either an error or a string, depending on the case.
Luckily Go can return two variables from a function, and this is the preferred way to achieve what you want. Return a string AND an error, and return nil as the error if there isn't one.
The function signature should be
func downloadFile(url string) (filename string, err error) {
.....
// and since the variables are named in the signature, at the end you can just do:
return
}
The caller function should check both the error and the returned string, just like your code is doing for example when calling os.Create(filename)