• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Golang json.RawMessage类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Golang中encoding/json.RawMessage的典型用法代码示例。如果您正苦于以下问题:Golang RawMessage类的具体用法?Golang RawMessage怎么用?Golang RawMessage使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



在下文中一共展示了RawMessage类的10个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Golang代码示例。

示例1: Update

func (c RecentCacheUpdater) Update(db *DB) *json.RawMessage {
	users, err := db.RecentlyUpdatedUsers(12)
	if err != nil {
		return nil
	}
	items := make([]recentItem, len(users))
	for index, user := range users {
		logs, err := db.ClimbingLogs(user.ID)
		if err != nil {
			continue
		}
		routeIDs := make([]bson.ObjectId, 0)
		for _, log := range logs {
			if !log.Pending {
				routeIDs = append(routeIDs, log.Route)
			}
		}
		items[index] = recentItem{UserID: user.ID, RouteIDs: routeIDs}
	}
	ret, err := json.Marshal(items)
	if err != nil {
		fmt.Println(err)
		return nil
	}
	j := new(json.RawMessage)
	j.UnmarshalJSON(ret)
	return j
}
开发者ID:songgao,项目名称:HalfDomeChallenge,代码行数:28,代码来源:cacheUpdaters.go


示例2: MockSession

// MockSession creates a new mocked API session returning the JSON message stored in message.
func MockSession(message []byte) (*Session, error) {
	rm := json.RawMessage{}
	err := rm.UnmarshalJSON(message)
	if err != nil {
		return nil, err
	}
	return &Session{
		requester: &mockRequester{message: &rm},
	}, nil
}
开发者ID:UniversityRadioYork,项目名称:myradio-go,代码行数:11,代码来源:api.go


示例3: unmarshalRawJson

func unmarshalRawJson(input *json.RawMessage, output interface{}) (err error) {
	raw, err := input.MarshalJSON()
	if err != nil {
		return
	}

	err = json.Unmarshal(raw, &output)
	if err != nil {
		return
	}

	return
}
开发者ID:untergrundbiber,项目名称:torture,代码行数:13,代码来源:search.go


示例4: ToSigned

func (ts SignedTimestamp) ToSigned() (*Signed, error) {
	s, err := cjson.Marshal(ts.Signed)
	if err != nil {
		return nil, err
	}
	signed := json.RawMessage{}
	err = signed.UnmarshalJSON(s)
	if err != nil {
		return nil, err
	}
	sigs := make([]Signature, len(ts.Signatures))
	copy(sigs, ts.Signatures)
	return &Signed{
		Signatures: sigs,
		Signed:     signed,
	}, nil
}
开发者ID:progrium,项目名称:notary,代码行数:17,代码来源:timestamp.go


示例5: ToSigned

func (sp SignedSnapshot) ToSigned() (*Signed, error) {
	s, err := cjson.Marshal(sp.Signed)
	if err != nil {
		return nil, err
	}
	signed := json.RawMessage{}
	err = signed.UnmarshalJSON(s)
	if err != nil {
		return nil, err
	}
	sigs := make([]Signature, len(sp.Signatures))
	copy(sigs, sp.Signatures)
	return &Signed{
		Signatures: sigs,
		Signed:     signed,
	}, nil
}
开发者ID:aaronlehmann,项目名称:notary,代码行数:17,代码来源:snapshot.go


示例6: PayloadOptions

func (h *H) PayloadOptions(w http.ResponseWriter, req *http.Request) {
	p := req.URL.Query().Get("payload")
	if p == "" {
		h.JSON400(w, errors.New("payload query parameter missing"))
		return
	}
	var options [][]string
	var thing json.RawMessage
	err := h.C.Call("payload_options", []string{p}, &thing)
	if err != nil {
		h.JSON400(w, err)
		return
	}
	d, err := thing.MarshalJSON()
	if err != nil {
		h.JSON400(w, err)
	}
	if err := json.Unmarshal(d, &options); err != nil {
		h.JSON400(w, err)
		return
	}
	opts := []PayloadOption{}
	for _, o := range options {
		if len(o) < 3 {
			continue
		}
		opts = append(opts, PayloadOption{Key: o[0], DefaultValue: o[1], Value: o[2]})
	}
	opts = append(opts, PayloadOption{
		Key:          "pwnstaller",
		DefaultValue: "N",
		Value:        "Use pwnstaller",
	})
	opts = append(opts, PayloadOption{
		Key:          "outputbase",
		DefaultValue: "",
		Value:        "Output base for generated payloads",
	})
	opts = append(opts, PayloadOption{
		Key:          "overwrite",
		DefaultValue: "true",
		Value:        "Overwrite existing files",
	})
	h.JSON(w, opts)
}
开发者ID:johnjohnsp1,项目名称:veil-evasion-api,代码行数:45,代码来源:handlers.go


示例7: PostData

func (esi *MockIndex) PostData(typeName string, id string, obj interface{}) (*IndexResponse, error) {
	ok, err := esi.IndexExists()
	if err != nil {
		return nil, err
	}
	if !ok {
		return nil, fmt.Errorf("Index does not exist")
	}
	ok, err = esi.TypeExists(typeName)
	if err != nil {
		return nil, err
	}

	var typ *MockIndexType
	if !ok {
		typ = &MockIndexType{}
		typ.items = make(map[string]*json.RawMessage)
		esi.types[typeName] = typ
	} else {
		typ = esi.types[typeName]
	}

	byts, err := json.Marshal(obj)
	if err != nil {
		return nil, err
	}

	var raw json.RawMessage
	err = raw.UnmarshalJSON(byts)
	if err != nil {
		return nil, err
	}
	typ.items[id] = &raw

	r := &IndexResponse{Created: true, ID: id, Index: esi.name, Type: typeName}
	return r, nil
}
开发者ID:venicegeo,项目名称:pz-logger,代码行数:37,代码来源:mock_index.go


示例8: RPC

// RPC Handler passes on a JSON or form encoded RPC request to
// a service.
func RPC(w http.ResponseWriter, r *http.Request) {
	if r.Method != "POST" {
		http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
		return
	}
	defer r.Body.Close()

	badRequest := func(description string) {
		e := errors.BadRequest("go.micro.rpc", description)
		w.WriteHeader(400)
		w.Write([]byte(e.Error()))
	}

	var service, method, address string
	var request interface{}

	// response content type
	w.Header().Set("Content-Type", "application/json")

	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":
		var rpcReq rpcRequest

		d := json.NewDecoder(r.Body)
		d.UseNumber()

		if err := d.Decode(&rpcReq); err != nil {
			badRequest(err.Error())
			return
		}

		service = rpcReq.Service
		method = rpcReq.Method
		address = rpcReq.Address
		request = rpcReq.Request

		// JSON as string
		if req, ok := rpcReq.Request.(string); ok {
			d := json.NewDecoder(strings.NewReader(req))
			d.UseNumber()

			if err := d.Decode(&request); err != nil {
				badRequest("error decoding request string: " + err.Error())
				return
			}
		}
	default:
		r.ParseForm()
		service = r.Form.Get("service")
		method = r.Form.Get("method")
		address = r.Form.Get("address")

		d := json.NewDecoder(strings.NewReader(r.Form.Get("request")))
		d.UseNumber()

		if err := d.Decode(&request); err != nil {
			badRequest("error decoding request string: " + err.Error())
			return
		}
	}

	if len(service) == 0 {
		badRequest("invalid service")
		return
	}

	if len(method) == 0 {
		badRequest("invalid method")
		return
	}

	// create request/response
	var response json.RawMessage
	var err error
	req := (*cmd.DefaultOptions().Client).NewJsonRequest(service, method, request)

	// create context
	ctx := helper.RequestToContext(r)

	// remote call
	if len(address) > 0 {
		err = (*cmd.DefaultOptions().Client).CallRemote(ctx, address, req, &response)
	} else {
		err = (*cmd.DefaultOptions().Client).Call(ctx, req, &response)
	}
	if err != nil {
		ce := errors.Parse(err.Error())
		switch ce.Code {
		case 0:
			// assuming it's totally screwed
			ce.Code = 500
//.........这里部分代码省略.........
开发者ID:micro,项目名称:micro,代码行数:101,代码来源:rpc.go


示例9: 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
		}

//.........这里部分代码省略.........
开发者ID:micro,项目名称:micro,代码行数:101,代码来源:rpcx.go


示例10: processOverview


//.........这里部分代码省略.........
	for _, region := range regions.Regions {
		fmt.Println("-", *region.RegionName)
	}

	ec2client = ec2.New(session.New(), &aws.Config{Region: aws.String(config.General.DefaultRegion)})

	instances, err := ec2client.DescribeInstances(nil)
	if err != nil {
		panic(err)
	}

	fmt.Println("Instances:")
	instanceCount := 0
	instanceMap := make(map[string]ec2.Instance)
	for _, reservation := range instances.Reservations {
		for _, instance := range reservation.Instances {
			fmt.Println("-", *instance.InstanceId)
			instanceMap[*instance.InstanceId] = *instance
			if *instance.State.Name == "running" {
				instanceCount++
			}
		}
	}
	attachment.Fields = append(attachment.Fields, Field{Title: "Running instances", Value: fmt.Sprintf("%d", instanceCount), Short: true})

	volumes, err := ec2client.DescribeVolumes(nil)
	if err != nil {
		panic(err)
	}
	attachment.Fields = append(attachment.Fields, Field{Title: "Volumes", Value: fmt.Sprintf("%d", len(volumes.Volumes)), Short: true})

	securityGroups, err := ec2client.DescribeSecurityGroups(nil)
	if err != nil {
		panic(err)
	}

	securityGroupMap := make(map[string]ec2.SecurityGroup)
	for _, securityGroup := range securityGroups.SecurityGroups {
		securityGroupMap[*securityGroup.GroupId] = *securityGroup
	}

	vpcs, err := ec2client.DescribeVpcs(nil)
	if err != nil {
		panic(err)
	}

	subnets, err := ec2client.DescribeSubnets(nil)
	if err != nil {
		panic(err)
	}

	routeTables, err := ec2client.DescribeRouteTables(nil)
	if err != nil {
		panic(err)
	}

	vpcPeeringConnections, err := ec2client.DescribeVpcPeeringConnections(nil)
	if err != nil {
		panic(err)
	}

	s3client := s3.New(session.New(), &aws.Config{Region: aws.String(config.General.DefaultRegion)})

	buckets, err := s3client.ListBuckets(nil)
	if err != nil {
		panic(err)
	}
	attachment.Fields = append(attachment.Fields, Field{Title: "S3 buckets", Value: fmt.Sprintf("%d", len(buckets.Buckets)), Short: true})

	rdsclient := rds.New(session.New(), &aws.Config{Region: aws.String(config.General.DefaultRegion)})

	dbInstances, err := rdsclient.DescribeDBInstances(nil)
	if err != nil {
		panic(err)
	}
	attachment.Fields = append(attachment.Fields, Field{Title: "DB instances", Value: fmt.Sprintf("%d", len(dbInstances.DBInstances)), Short: true})

	overview := Overview{Instances: instances, SecurityGroups: securityGroups, Vpcs: vpcs, Subnets: subnets, RouteTables: routeTables, VpcPeeringConnections: vpcPeeringConnections, Buckets: buckets, DBInstances: dbInstances}
	jsonData, err := json.MarshalIndent(overview, "", "  ")
	if err != nil {
		panic(err)
	}

	const outputDir = "/tmp"
	err = os.MkdirAll(outputDir, os.ModeDir)
	if err != nil {
		panic(err)
	}

	err = ioutil.WriteFile(outputDir+"/aws.json", jsonData, 0777)
	if err != nil {
		panic(err)
	}

	var m json.RawMessage
	err = m.UnmarshalJSON(jsonData)
	if err != nil {
		panic(err)
	}
}
开发者ID:ngyewch,项目名称:aws-dashboard,代码行数:101,代码来源:overview.go



注:本文中的encoding/json.RawMessage类示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Golang json.Unmarshaler类代码示例发布时间:2022-05-24
下一篇:
Golang json.Number类代码示例发布时间:2022-05-24
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap