Skip to content

Commit

Permalink
sbserver: parse Content-Type before comparing (#99)
Browse files Browse the repository at this point in the history
Fixes issue where Content-Type is application/json; charset=utf-8
This caused the mimetype switch not fail unexpectedly.
  • Loading branch information
nopjmp authored and colonelxc committed Jun 24, 2019
1 parent 92a16cf commit bbf0d20
Showing 1 changed file with 17 additions and 10 deletions.
27 changes: 17 additions & 10 deletions cmd/sbserver/main.go
Expand Up @@ -194,6 +194,7 @@ import (
"fmt"
"html/template"
"io/ioutil"
"mime"
"net/http"
"net/url"
"os"
Expand Down Expand Up @@ -249,35 +250,41 @@ Usage: %s -apikey=$APIKEY

// unmarshal reads pbResp from req. The mime will either be JSON or ProtoBuf.
func unmarshal(req *http.Request, pbReq proto.Message) (string, error) {
var mime string
var mimeType string
mediaType, _, err := mime.ParseMediaType(req.Header.Get("Content-Type"))
if err != nil {
mediaType = req.Header.Get("Content-Type")
}

alt := req.URL.Query().Get("alt")
if alt == "" {
alt = req.Header.Get("Content-Type")
alt = mediaType
}

switch alt {
case "json", mimeJSON:
mime = mimeJSON
mimeType = mimeJSON
case "proto", mimeProto:
mime = mimeProto
mimeType = mimeProto
default:
return mime, errors.New("invalid interchange format")
return mimeType, errors.New("invalid interchange format")
}

switch req.Header.Get("Content-Type") {
switch mediaType {
case mimeJSON:
if err := jsonpb.Unmarshal(req.Body, pbReq); err != nil {
return mime, err
return mimeType, err
}
case mimeProto:
body, err := ioutil.ReadAll(req.Body)
if err != nil {
return mime, err
return mimeType, err
}
if err := proto.Unmarshal(body, pbReq); err != nil {
return mime, err
return mimeType, err
}
}
return mime, nil
return mimeType, nil
}

// marshal writes pbResp into resp. The mime can either be JSON or ProtoBuf.
Expand Down

0 comments on commit bbf0d20

Please sign in to comment.