gopkg/request/restful.go

78 lines
1.9 KiB
Go
Raw Normal View History

2021-07-26 15:37:58 +08:00
// Package request ...
//
// Author: go_developer@163.com<白茶清欢>
//
// Description:
//
// File: restful.go
//
// Version: 1.0.0
//
// Date: 2021/07/07 20:11:57
package request
import (
"fmt"
"strings"
)
// URIConfig 构建URI的配置
//
// Author : go_developer@163.com<白茶清欢>
type URIConfig struct {
Template string // url模版
IsRestful bool // 是否是restful url
Left string // 左侧分隔符,针对restful生效
Right string // 右侧分隔符,针对restful生效
RemoveURIParam bool // 移除已经适配到URI里面的参数, 针对restful生效
}
// NewDefaultNormalURIConfig构建普通URL配置
//
// Author : go_developer@163.com<白茶清欢>
func NewDefaultNormalURIConfig(urlTemplate string) *URIConfig {
return &URIConfig{
Template: urlTemplate,
IsRestful: false,
Left: "",
Right: "",
RemoveURIParam: false,
}
}
// NewDefaultNormalURIConfig 构建普通 restful URL配置
//
// Author : go_developer@163.com<白茶清欢>
func NewDefaultRestfullURIConfig(urlTemplate string, left string, right string, removeURIParam bool) *URIConfig {
return &URIConfig{
Template: urlTemplate,
IsRestful: true,
Left: left,
Right: right,
RemoveURIParam: removeURIParam,
}
}
// BuildRestfulURL 构建 restful URI
//
// Author : go_developer@163.com<白茶清欢>
//
// Date : 2021/07/07 20:14:54
func BuildURL(uriConfig *URIConfig, parameter map[string]interface{}) (string, map[string]interface{}) {
if !uriConfig.IsRestful {
return uriConfig.Template, parameter
}
uri := uriConfig.Template
finalParameter := make(map[string]interface{})
for field, val := range parameter {
if strings.Contains(uri, uriConfig.Left+field+uriConfig.Right) {
uri = strings.ReplaceAll(uri, "{"+field+"}", fmt.Sprintf("%v", val))
if uriConfig.RemoveURIParam {
continue
}
}
finalParameter[field] = val
}
return uri, finalParameter
}