56 lines
		
	
	
		
			1.5 KiB
		
	
	
	
		
			Go
		
	
	
	
	
	
			
		
		
	
	
			56 lines
		
	
	
		
			1.5 KiB
		
	
	
	
		
			Go
		
	
	
	
	
	
// Package request ...
 | 
						|
//
 | 
						|
// Description : request ...
 | 
						|
//
 | 
						|
// Author : go_developer@163.com<白茶清欢>
 | 
						|
//
 | 
						|
// Date : 2025-05-08 14:21
 | 
						|
package request
 | 
						|
 | 
						|
import (
 | 
						|
	"errors"
 | 
						|
	"git.zhangdeman.cn/zhangdeman/network/httpclient/abstract"
 | 
						|
	"resty.dev/v3"
 | 
						|
	"strings"
 | 
						|
)
 | 
						|
 | 
						|
var (
 | 
						|
	// WriteBodyInstanceTable 请求类型 => 请求类型写入的实现
 | 
						|
	WriteBodyInstanceTable = map[string]abstract.IRequestBodyWrite{
 | 
						|
		"json":                  &WriteJson{},
 | 
						|
		"xml":                   nil,
 | 
						|
		"x-www-form-urlencoded": &WriteForm{},
 | 
						|
	}
 | 
						|
)
 | 
						|
 | 
						|
func SetWriteBodyInstance(cType string, instance abstract.IRequestBodyWrite) {
 | 
						|
	WriteBodyInstanceTable[cType] = instance
 | 
						|
}
 | 
						|
 | 
						|
func DeleteWriteBodyInstance(cType string) {
 | 
						|
	delete(WriteBodyInstanceTable, cType)
 | 
						|
}
 | 
						|
 | 
						|
// WriteBody 数据写入body
 | 
						|
func WriteBody(contentType string, request *resty.Request, bodyData map[string]any) error {
 | 
						|
	if nil == bodyData {
 | 
						|
		// body为nil, 无需写入, 否则即使为空map也要正常写入
 | 
						|
		return nil
 | 
						|
	}
 | 
						|
	if nil == request {
 | 
						|
		return errors.New("request is nil")
 | 
						|
	}
 | 
						|
	contentType = strings.TrimSpace(strings.Split(contentType, ";")[0])
 | 
						|
	if len(contentType) == 0 {
 | 
						|
		return errors.New("contentType is empty or invalid")
 | 
						|
	}
 | 
						|
	contentTypeArr := strings.Split(contentType, "/")
 | 
						|
	realType := contentTypeArr[len(contentTypeArr)-1]
 | 
						|
	writeInstance, ok := WriteBodyInstanceTable[realType]
 | 
						|
	if !ok || writeInstance == nil {
 | 
						|
		return errors.New(realType + " is not support, writeInstance is nil")
 | 
						|
	}
 | 
						|
	writeInstance.Write(request, bodyData)
 | 
						|
	return nil
 | 
						|
}
 |