You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

46 lines
1.3 KiB
Go

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

package server
import (
"fmt"
"reflect"
internalrequest "github.com/noahlann/nnet/internal/request"
"github.com/noahlann/nnet/pkg/codec"
protocolpkg "github.com/noahlann/nnet/pkg/protocol"
requestpkg "github.com/noahlann/nnet/pkg/request"
"github.com/noahlann/nnet/pkg/router"
)
// parseRequestBodyWithCodec 使用指定codec解码请求体优先于基于路由决策
func parseRequestBodyWithCodec(req requestpkg.Request, route router.Route, protocol protocolpkg.Protocol, c codec.Codec) error {
// 转换为内部实现类型
reqImpl := internalrequest.AsRequestSetter(req)
if reqImpl == nil {
return fmt.Errorf("invalid request type: request does not support setter methods")
}
// 获取DataBytes协议解码后的数据
dataBytes := reqImpl.DataBytes()
if len(dataBytes) == 0 {
// 如果没有DataBytes使用Raw数据
dataBytes = req.Raw()
}
// 数据解码(将字节解码为结构体)
requestType := route.RequestType()
if requestType != nil && requestType.Kind() == reflect.Ptr {
// 创建结构体实例
body := reflect.New(requestType.Elem()).Interface()
// 解码数据
if err := c.Decode(dataBytes, body); err != nil {
return fmt.Errorf("failed to decode data: %w", err)
}
// 设置到Request
reqImpl.SetData(body)
}
return nil
}