func uploadHandler(w http.ResponseWriter, r *http.Request) { file, header, err := r.FormFile("file") if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } defer file.Close() // Handle the uploaded file }
func uploadFile(filepath string, targetURL string) error { file, err := os.Open(filepath) if err != nil { return err } defer file.Close() body := &bytes.Buffer{} writer := multipart.NewWriter(body) part, err := writer.CreateFormFile("file", filepath) if err != nil { return err } _, err = io.Copy(part, file) if err != nil { return err } writer.Close() req, err := http.NewRequest("POST", targetURL, body) if err != nil { return err } req.Header.Set("Content-Type", writer.FormDataContentType()) client := &http.Client{} res, err := client.Do(req) if err != nil { return err } defer res.Body.Close() return nil }This function uploads a file to a specified URL by creating a multipart form object, appending the file to it, and then creating a POST request with the serialized form content. The net/http package is the package library used here.