本文整理汇总了Golang中encoding/json.RawMessage.Marshal方法的典型用法代码示例。如果您正苦于以下问题:Golang RawMessage.Marshal方法的具体用法?Golang RawMessage.Marshal怎么用?Golang RawMessage.Marshal使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类encoding/json.RawMessage
的用法示例。
在下文中一共展示了RawMessage.Marshal方法的1个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: ServeHTTP
// RPCX Handler is an alternative handler which passes through an RPC request without modification
func (h *rpcxHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
if r.Method != "POST" {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
return
}
defer r.Body.Close()
// get service/method
service, method := pathToReceiver(h.Namespace, r.URL.Path)
ct := r.Header.Get("Content-Type")
// Strip charset from Content-Type (like `application/json; charset=UTF-8`)
if idx := strings.IndexRune(ct, ';'); idx >= 0 {
ct = ct[:idx]
}
switch ct {
case "application/json":
// response content type
w.Header().Set("Content-Type", "application/json")
// get request
br, err := ioutil.ReadAll(r.Body)
if err != nil {
e := errors.InternalServerError("go.micro.api", err.Error())
http.Error(w, e.Error(), 500)
return
}
// use as raw json
request := json.RawMessage(br)
// create request/response
var response json.RawMessage
req := (*cmd.DefaultOptions().Client).NewJsonRequest(service, method, &request)
// create context
ctx := helper.RequestToContext(r)
// make the call
if err := (*cmd.DefaultOptions().Client).Call(ctx, req, &response); err != nil {
ce := errors.Parse(err.Error())
switch ce.Code {
case 0:
// assuming it's totally screwed
ce.Code = 500
ce.Id = "go.micro.api"
ce.Status = http.StatusText(500)
ce.Detail = "error during request: " + ce.Detail
w.WriteHeader(500)
default:
w.WriteHeader(int(ce.Code))
}
w.Write([]byte(ce.Error()))
return
}
b, _ := response.MarshalJSON()
w.Header().Set("Content-Length", strconv.Itoa(len(b)))
w.Write(b)
case "application/proto", "application/protobuf":
// get request
br, err := ioutil.ReadAll(r.Body)
if err != nil {
e := errors.InternalServerError("go.micro.api", err.Error())
http.Error(w, e.Error(), 500)
return
}
// use as raw proto
request := proto.NewMessage(br)
// create request/response
response := &proto.Message{}
req := (*cmd.DefaultOptions().Client).NewProtoRequest(service, method, request)
// create context
ctx := helper.RequestToContext(r)
// make the call
if err := (*cmd.DefaultOptions().Client).Call(ctx, req, response); err != nil {
ce := errors.Parse(err.Error())
switch ce.Code {
case 0:
// assuming it's totally screwed
ce.Code = 500
ce.Id = "go.micro.api"
ce.Status = http.StatusText(500)
ce.Detail = "error during request: " + ce.Detail
w.WriteHeader(500)
default:
w.WriteHeader(int(ce.Code))
}
// response content type
w.Header().Set("Content-Type", "application/json")
w.Write([]byte(ce.Error()))
return
}
//.........这里部分代码省略.........