golang 模拟客户端发送http请求上传文件demo

这是一个使用 Go 语言编写的程序,它实现了从用户输入的目录中读取图片和 JSON 文件,根据用户选择进行相似度对比和人工审核设置,然后将文件上传到指定的 API 服务,并接收返回的响应。程序通过递归遍历目录查找文件,使用 multipart/form-data 格式构造 HTTP POST 请求进行文件上传。
摘要由CSDN通过智能技术生成
package main

import (
	"bytes"
	"encoding/json"
	"fmt"
	"github.com/google/uuid"
	"io"
	"log"
	"mime/multipart"
	"net/http"
	"os"
	"path/filepath"
	"strings"
	"time"
)
type Response struct {
	Msg  string `json:"msg"`
	Code int    `json:"code"`
}
func main() {
	var total int
	var response Response
	fmt.Println("是否进行相似度对比,请输入0或者1:  0:不进行对比 | 1:进行对比")
	var isdHash, isNeedChecker, root string
	fmt.Scanln(&isdHash)
	if isdHash == "0" || isdHash == "1" {
		fmt.Println("参数正确:", isdHash)
	} else {
		fmt.Println("参数错误,请重新启动程序")
		time.Sleep(time.Second)
		return
	}
	fmt.Println("是否需要人工审核: 1:需要 | 2:不需要 ")
	fmt.Scanln(&isNeedChecker)
	if isNeedChecker == "1" || isNeedChecker == "2" {
		fmt.Println("参数正确:", isNeedChecker)
	} else {
		fmt.Println("参数错误,请重新启动程序")
		time.Sleep(time.Second)
		return
	}
	fmt.Println("请输入文件目录:")
	fmt.Scanln(&root)
	fmt.Println(root)
	imgFiles := make(map[string]string, 0)
	jsonFiles := make(map[string]string, 0)
	err := getAllFiles(root, imgFiles, jsonFiles)
	if err != nil {
		fmt.Println(err)
		return
	}
	if len(imgFiles) == 0 {
		fmt.Println("该目录下无图片文件!")
		return
	}
	id := uuid.NewString()
	imgLen := len(imgFiles)
	fmt.Println("共有图片:", imgLen, "   |  json文件:", len(jsonFiles))
	extraParams := map[string]string{
		"isdHash":       isdHash,
		"isNeedChecker": isNeedChecker,
		"id":            id,
	}
	for k, v := range imgFiles { 
		request, err := newFileUploadRequest("http://192.168.1.11:8899/dataImport/v1/upload", extraParams, "imgFile", v, "jsonFile", jsonFiles[k])
		if err != nil {
			log.Fatal(err)
		}
		client := &http.Client{}
		resp, err := client.Do(request)
		if err != nil {
			log.Fatal(err)
			return
		} else {
			body := &bytes.Buffer{}
			_, err := body.ReadFrom(resp.Body)
			if err != nil {
				log.Fatal(err)
			}
			json.Unmarshal(body.Bytes(), &response)
			resp.Body.Close()
			if response.Msg == "存在相同图片" {
				total++
				fmt.Println(response.Msg, total)
			}
			if response.Code != http.StatusOK {
				fmt.Println(body)
			}
			imgLen--
			fmt.Println("还剩:", imgLen, " 张图片")
		}
	}
	fmt.Println()

	fmt.Println("------------------")
	fmt.Println("完成,5秒后退出程序")
	time.Sleep(time.Second * 5)
}

func getAllFiles(root string, imgFiles, jsonFiles map[string]string) (err error) {
	dirs, err := os.ReadDir(root)
	if err != nil {
		return err
	}
	for _, v := range dirs {
		if v.IsDir() {
			root2 := root + `\` + v.Name()
			err = getAllFiles(root2, imgFiles, jsonFiles)
		} else {
			switch filepath.Ext(v.Name()) {
			case ".jpg":
				imgFiles[strings.TrimRight(v.Name(), filepath.Ext(v.Name()))] = root + `\` + v.Name()
			case ".json":
				jsonFiles[strings.TrimRight(v.Name(), filepath.Ext(v.Name()))] = root + `\` + v.Name()
			default:
				return
			}
		}
	}
	return
}

// Creates a new file upload http request with optional extra params
func newFileUploadRequest(uri string, params map[string]string, imgFiled, imgPath, jsonFiled, jsonPath string) (*http.Request, error) {
	file, err := os.Open(imgPath)
	if err != nil {
		return nil, err
	}
	defer file.Close()

	body := &bytes.Buffer{}
	writer := multipart.NewWriter(body)
	part, err := writer.CreateFormFile(imgFiled, filepath.Base(imgPath))
	if err != nil {
		return nil, err
	}
	_, err = io.Copy(part, file)
	if err != nil {
		return nil, err
	}
	if jsonPath != "" { //有json文件
		file2, err := os.Open(jsonPath)
		if err != nil {
			return nil, err
		}
		defer file2.Close()
		part2, err := writer.CreateFormFile(jsonFiled, filepath.Base(jsonPath))
		if err != nil {
			return nil, err
		}
		_, err = io.Copy(part2, file2)
		if err != nil {
			return nil, err
		}
	}
	for key, val := range params {
		_ = writer.WriteField(key, val)
	}
	err = writer.Close()
	if err != nil {
		return nil, err
	}

	req, err := http.NewRequest("POST", uri, body)
	//origin := req.Header.Get("Origin")
	//req.Header.Set("Access-Control-Allow-Origin", origin)
	//req.Header.Set("Access-Control-Allow-Headers", "Content-Type,AccessToken,X-CSRF-Token, Authorization, Token,X-Token,X-User-Id")
	//req.Header.Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS,DELETE,PUT")
	//req.Header.Set("Access-Control-Expose-Headers", "Content-Length, Access-Control-Allow-Origin, Access-Control-Allow-Headers, Content-Type, New-Token, New-Expires-At")
	//req.Header.Set("Access-Control-Allow-Credentials", "true")
	req.Header.Add("Content-Type", writer.FormDataContentType())
	return req, err
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值