2022-09-28 17:30:40 +00:00
|
|
|
// Copyright 2014 Manu Martinez-Almeida. All rights reserved.
|
2021-08-12 19:03:24 +00:00
|
|
|
// Use of this source code is governed by a MIT style
|
|
|
|
// license that can be found in the LICENSE file.
|
|
|
|
|
|
|
|
package binding
|
|
|
|
|
|
|
|
import (
|
2022-09-28 17:30:40 +00:00
|
|
|
"errors"
|
2023-02-25 12:12:40 +00:00
|
|
|
"io"
|
2021-08-12 19:03:24 +00:00
|
|
|
"net/http"
|
|
|
|
|
2022-09-28 17:30:40 +00:00
|
|
|
"google.golang.org/protobuf/proto"
|
2021-08-12 19:03:24 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
type protobufBinding struct{}
|
|
|
|
|
|
|
|
func (protobufBinding) Name() string {
|
|
|
|
return "protobuf"
|
|
|
|
}
|
|
|
|
|
2022-09-28 17:30:40 +00:00
|
|
|
func (b protobufBinding) Bind(req *http.Request, obj any) error {
|
2023-02-25 12:12:40 +00:00
|
|
|
buf, err := io.ReadAll(req.Body)
|
2021-08-12 19:03:24 +00:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
return b.BindBody(buf, obj)
|
|
|
|
}
|
|
|
|
|
2022-09-28 17:30:40 +00:00
|
|
|
func (protobufBinding) BindBody(body []byte, obj any) error {
|
|
|
|
msg, ok := obj.(proto.Message)
|
|
|
|
if !ok {
|
|
|
|
return errors.New("obj is not ProtoMessage")
|
|
|
|
}
|
|
|
|
if err := proto.Unmarshal(body, msg); err != nil {
|
2021-08-12 19:03:24 +00:00
|
|
|
return err
|
|
|
|
}
|
|
|
|
// Here it's same to return validate(obj), but util now we can't add
|
|
|
|
// `binding:""` to the struct which automatically generate by gen-proto
|
|
|
|
return nil
|
|
|
|
// return validate(obj)
|
|
|
|
}
|