Uploading file
You have built a simple HTTP server that can accept a file upload from the user and store the file in the server. Now, let’s build a simple client that can upload a file to the server.
Let’s start by adding the import:
import (
"net/http"
"os"
"github.com/rs/zerolog/log"
)
Next, let’s open the file that we want to upload. We can use os.Open
to open the file. The open file is actually a *os.File
type that implements the io.Reader
interface which can be used to read the content of the file. In addition to that, we also need to close the file after we are done with it to free up the resources.
Please change the path to the file that you want to upload.
func main() {
f, err := os.Open("/path/to/testfile")
if err != nil {
log.Fatal().Err(err).Msg("Error opening file")
}
defer f.Close()
// rest of the code ...
}
Uploading the file is as simple as sending a POST request to the server with the file content as the request body. We can use the http.NewRequest
to create a new request and set the request body to the file content. Below, you will see that we can just pass the file as it is since the http.NewRequest
expects the request body to be an io.Reader
.
func main() {
// ... the previous code
req, err := http.NewRequest("POST", "http://localhost:8080/api/v1/binary", f)
if err != nil {
log.Fatal().Err(err).Msg("Error creating request")
}
req.Header.Set("Content-Type", "application/offset+octet-stream")
httpClient := &http.Client{}
resp, err := httpClient.Do(req)
if err != nil {
log.Fatal().Err(err).Msg("Error sending request")
}
defer resp.Body.Close()
log.Debug().Int("status", resp.StatusCode).Msg("Check upload response")
}
When you run the client, you should see the file uploaded to the server. You can check the server logs to see the file being uploaded.
io.Reader
and io.Writer
interfaces are very powerful and can be used to build a lot of functionalities. In the next lesson, we will learn how to use these interfaces to build a more advanced file upload system. But for now, you have learned how to utilize these interfaces to upload a file to the server from a client.