Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@ghostiam
Last active February 22, 2023 12:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ghostiam/48acd974f2044e25ba43f090316e6f2d to your computer and use it in GitHub Desktop.
Save ghostiam/48acd974f2044e25ba43f090316e6f2d to your computer and use it in GitHub Desktop.
grpc-gateway - multipart/form-data unmarshaler
marshaler = &runtime.JSONPb{
    MarshalOptions: protojson.MarshalOptions{UseProtoNames: true, EmitUnpopulated: true},
}

grpcMux := runtime.NewServeMux(
    GWMultipartForm(marshaler),
    runtime.WithMarshalerOption(runtime.MIMEWildcard, marshaler),
)
curl -X POST 127.0.0.1:3000/test -F token="my_token" -F audio="@audio.wav"
MIT License
Copyright (c) 2023 Vladislav Fursov (GhostIAm)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
// Copyright (c) 2023 Vladislav Fursov (GhostIAm)
// This code is licensed under MIT license (see LICENSE for details)
// https://gist.github.com/ghostiam/48acd974f2044e25ba43f090316e6f2d
package http
import (
"bufio"
"bytes"
"encoding/base64"
"errors"
"fmt"
"io"
"mime/multipart"
"net/url"
"github.com/grpc-ecosystem/grpc-gateway/v2/runtime"
"github.com/grpc-ecosystem/grpc-gateway/v2/utilities"
"google.golang.org/protobuf/proto"
)
var _ runtime.Marshaler = (*MultipartFormPb)(nil)
type MultipartFormPb struct {
runtime.Marshaler
}
func GWMultipartForm(marshaler runtime.Marshaler) runtime.ServeMuxOption {
return runtime.WithMarshalerOption("multipart/form-data", &MultipartFormPb{
Marshaler: marshaler,
})
}
func (j *MultipartFormPb) NewDecoder(r io.Reader) runtime.Decoder {
return runtime.DecoderFunc(func(v any) error {
msg, ok := v.(proto.Message)
if !ok {
return fmt.Errorf("not proto message") // nolint:goerr113
}
br := bufio.NewReaderSize(r, 1024)
pb, err := br.Peek(100)
if err != nil {
return fmt.Errorf("peek boundary: %w", err)
}
if len(pb) < 2 {
return fmt.Errorf("boundary len < 2") // nolint:goerr113
}
boundary := bytes.TrimSpace(bytes.Split(pb, []byte("\n"))[0])[2:]
values := make(url.Values)
mr := multipart.NewReader(br, string(boundary))
for {
var p *multipart.Part
p, err = mr.NextPart()
if errors.Is(err, io.EOF) {
break
}
if err != nil {
return fmt.Errorf("read next part: %w", err)
}
var data []byte
data, err = io.ReadAll(p)
if err != nil {
return fmt.Errorf("read part body: %w", err)
}
if p.FileName() != "" {
/*
in proto file:
message Media {
string filename = 1;
string content_type = 2;
bytes content = 3;
}
*/
values.Set(p.FormName()+".filename", p.FileName())
values.Set(p.FormName()+".content_type", p.Header.Get("Content-Type"))
values.Set(p.FormName()+".content", base64.StdEncoding.EncodeToString(data))
} else {
values.Set(p.FormName(), string(data))
}
}
err = runtime.PopulateQueryParameters(msg, values, &utilities.DoubleArray{})
if err != nil {
return fmt.Errorf("papulate query params: %w", err)
}
return nil
})
}
func (j *MultipartFormPb) Unmarshal(data []byte, v any) error {
return j.NewDecoder(bytes.NewReader(data)).Decode(v) // nolint: wrapcheck
}
syntax = "proto3";
message TestRequest {
string token = 1;
message Media {
string filename = 1;
string content_type = 2;
bytes content = 3;
}
Media audio = 2;
}
message TestResponse {}
service TestService {
rpc Test (TestRequest) returns (TestResponse) {
option (google.api.http) = {
post: "/test"
body: "*"
};
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment