Golang Register示例

说明

golang register示例是从最受好评的开源项目中提取的实现代码,你可以参考下面示例的使用方式。

编程语言: Golang

命名空间/包名称: encoding/gob

示例#1
文件: coordinate.go 项目: dmaze/goordinate

// NewWithClock creates a new coordinate.Coordinate connection object,
// using an explicit time source.  See New() for further details.
// Most application code should call New(), and use the default (real)
// time source; this entry point is intended for tests that need to
// inject a mock time source.
func NewWithClock(connectionString string, clk clock.Clock) (coordinate.Coordinate, error) {
	// If the connection string is a destructured URL, turn it
	// back into a proper URL
	if len(connectionString) >= 2 && connectionString[0] == '/' && connectionString[1] == '/' {
		connectionString = "postgres:" + connectionString
	}
	db, err := sql.Open("postgres", connectionString)
	if err != nil {
		return nil, err
	}
	// TODO(dmaze): shouldn't unconditionally do this force-upgrade here
	err = Upgrade(db)
	if err != nil {
		return nil, err
	}
	// Make sure the gob library understands our data maps
	gob.Register(map[string]interface{}{})
	gob.Register(map[interface{}]interface{}{})
	gob.Register([]interface{}{})
	gob.Register(cborrpc.PythonTuple{})
	gob.Register(uuid.UUID{})

	return &pgCoordinate{
		db:    db,
		clock: clk,
	}, nil
}

示例#2
文件: dump_trace.go 项目: philips/earthquake

func dumpTrace(args []string) {
	dumpTraceFlagset.Parse(args)

	if _dumpTraceFlags.TracePath == "" {
		fmt.Printf("specify path of trace data file\n")
		os.Exit(1)
	}

	file, err := os.Open(_dumpTraceFlags.TracePath)
	if err != nil {
		fmt.Printf("failed to open trace data file(%s): %s\n", _dumpTraceFlags.TracePath, err)
		os.Exit(1)
	}
	gob.Register(map[string]interface{}{})
	gob.Register([]map[string]interface{}{})
	dec := gob.NewDecoder(file)
	var trace SingleTrace
	derr := dec.Decode(&trace)
	if derr != nil {
		fmt.Printf("failed to decode trace file(%s): %s\n", _dumpTraceFlags.TracePath, err)
		os.Exit(1)
	}

	doDumpTrace(&trace)
}

示例#3
文件: auth.go 项目: thansau239/gophish

//init registers the necessary models to be saved in the session later
func init() {
	gob.Register(&models.User{})
	gob.Register(&models.Flash{})
	Store.Options.HttpOnly = true
	// This sets the maxAge to 5 days for all cookies
	Store.MaxAge(86400 * 5)
}

示例#4
文件: googlevoxels.go 项目: tartavull/dvid

func init() {
	datastore.Register(NewType())

	// Need to register types that will be used to fulfill interfaces.
	gob.Register(&Type{})
	gob.Register(&Data{})
}

示例#5
文件: vm_cli.go 项目: summits/minimega

func init() {
	registerHandlers("vm", vmCLIHandlers)

	// for vm info
	gob.Register(VMs{})
	gob.Register(&vmKVM{})
}

示例#6
文件: actor_test.go 项目: theckman/goiardi

func TestActorClient(t *testing.T) {
	config.Config.UseAuth = true
	indexer.Initialize(config.Config)
	c, _ := client.New("fooclient")
	gob.Register(c)
	c.Save()
	c1, err := GetReqUser("fooclient")
	if err != nil {
		t.Errorf(err.Error())
	}
	y := c1.IsSelf(c)
	if y == false {
		t.Errorf("self not equal to self")
	}
	c2, _ := client.New("foo2client")
	y = c1.IsSelf(c2)
	if y != false {
		t.Errorf("client %s was equal to client %s, but should not have been", c1.GetName(), c2.Name)
	}

	u, _ := user.New("foouser")
	gob.Register(u)
	u.Save()

	y = c1.IsSelf(u)
	if y != false {
		t.Errorf("client %s was equal to user %s, but should not have been", c1.GetName(), u.Username)
	}

	c.Delete()
	c2.Delete()
	u.Delete()
}

示例#7
文件: serialization_test.go 项目: darciopacifico/enablecache

func init() {
	gob.Register(Car{})
	gob.Register(Attribute{})

	cacheStorageRedis_test.SetValues(GetRegs(qtdChaves)...)

}

示例#8
文件: client.go 项目: alect/TaskSprint

func (c *Client) startServer(socket string) {
	rpcs := rpc.NewServer()
	rpcs.Register(c)
	gob.Register([]interface{}{})
	gob.Register(map[string]interface{}{})

	if c.options.socktype == "unix" {
		os.Remove(socket)
	}
	if c.options.socktype == "tcp" {
		sepIndex := strings.Index(socket, ":")
		port := socket[sepIndex:]
		socket = "0.0.0.0" + port
	}
	l, e := net.Listen(c.options.socktype, socket)
	if e != nil {
		log.Fatal("listen error: ", e)
	}
	c.l = l

	for !c.dead {
		conn, err := c.l.Accept()
		if err != nil {
			fmt.Printf("RPC Error: %v\n", err.Error())
			c.l.Close()
		} else if !c.dead {
			go rpcs.ServeConn(conn)
		} else {
			return
		}
	}
}

示例#9
文件: gob.go 项目: keep94/Dominator

func init() {
	gob.Register(&filesystem.RegularInode{})
	gob.Register(&filesystem.ComputedRegularInode{})
	gob.Register(&filesystem.SymlinkInode{})
	gob.Register(&filesystem.SpecialInode{})
	gob.Register(&filesystem.DirectoryInode{})
}

示例#10
文件: vm_cli.go 项目: npe9/minimega

func init() {
	registerHandlers("vm", vmCLIHandlers)

	// Register these so we can serialize the VMs
	gob.Register(VMs{})
	gob.Register(&KvmVM{})
}

示例#11
文件: test_test.go 项目: jeffchan/pushydb

func TestBasic(t *testing.T) {

	Delete()
	pdb := Make()
	point := Data{1, 2, "hello"}
	gob.Register(Data{})
	gob.Register("ok")
	vals := []interface{}{"A", int(21), int64(22), true, point}
	for i, val := range vals {
		pdb.Put("paxos", i, "blah", val)
	}
	// Amazingly, go doesn't let you write a for loop for this. Amazing.
	val := ""
	true_val := "A"
	ok := pdb.Get("paxos", 0, "blah", &val)
	chk(t, ok, val, true_val)
	// XX A couple missing assertions(Blame go.)
	val4 := Data{}
	true_val4 := point
	ok = pdb.Get("paxos", 4, "blah", &val4)
	chk(t, ok, val4, true_val4)
	if pdb.Get("paxos", -1, "blah", Data{}) != false {
		t.Fatalf("Expected key to not be found!")
	}
	fmt.Println("Passed!")
	Delete()
}

示例#12
文件: net.go 项目: alytvynov/lachesis

func netInit() {
	gob.Register(message{})
	gob.Register(node{})
	gob.Register(make(map[string]node))
	gob.Register(exec.Error{})
	gob.Register(errors.New(""))
}

示例#13
文件: coords.go 项目: Niriel/daggor

func init() {
	// For Gob to be able to deal with interfaces, we must
	// teach it the concrete types that implement these
	// interfaces.
	gob.Register(absoluteDirection{0})
	gob.Register(relativeDirection{0})
}

示例#14
文件: raft_node.go 项目: salmanpatel/cs733

func New(rnConfig RaftNodeConfig, jsonFile string) RaftNode {
	var rn RaftNode
	rn.eventCh = make(chan interface{}, 100)
	//rn.timeoutCh = make(chan bool)
	rn.shutdownSig = make(chan bool)
	rn.commitCh = make(chan CommitInfo, 100)
	// rn.parTOs = 0
	rn.logDir = rnConfig.logDir

	rn.initializeStateMachine(rnConfig)

	var err error
	rn.nwHandler, err = cluster.New(int(rnConfig.id), jsonFile)
	assert(err == nil)

	// Register various types to be send on outbox and receive in inbox
	gob.Register(VoteReqEv{})
	gob.Register(VoteResEv{})
	gob.Register(AppendEntriesReqEv{})
	gob.Register(AppendEntriesResEv{})

	// Set initial election timeout
	/*go func() {
		time.Sleep(time.Millisecond * time.Duration(RandInt(rn.sm.electionTO)))
		rn.timeoutCh <- true
	}()*/
	rn.timer = time.NewTimer(time.Duration(RandInt(rnConfig.electionTO)) * time.Millisecond)

	return rn
}

示例#15
文件: context.go 项目: yonglehou/gopark

func init() {
	log.SetFlags(log.LstdFlags)
	runtime.GOMAXPROCS(runtime.NumCPU())

	gob.Register(new(KeyValue))
	gob.Register(new(KeyGroups))
}

示例#16
文件: boltdb_storage.go 项目: nullboundary/pesand

//StoreMsg
func (b *BoltStorage) StoreMsg(clientid string, m *proto.Publish) (string, error) {

	storedMsgId := createStoredMsgId(clientid, m)
	s := &StoredMsg{
		lastupdated: time.Now(),
		clientid:    clientid,
		Message:     m,
		status:      StoredMsgSending,
	}

	w := new(bytes.Buffer)
	gob.Register(&proto.Publish{})
	gob.Register(&proto.BytesPayload{})
	encoder := gob.NewEncoder(w)
	err := encoder.Encode(s)
	if err != nil {
		return "", err
	}

	err = b.set(b.StoredMsgBucket, clientid, w.Bytes())
	if err != nil {
		return "", err
	}

	return storedMsgId, nil

}

示例#17
文件: dicts.go 项目: 1995parham/FlyNest

func init() {
	gob.Register(driverInfo{})
	gob.Register(flow{})
	gob.Register(nodeDrivers{})
	gob.Register(nodeFlows{})
	gob.Register(nodeTriggers{})
}

示例#18
文件: gob.go 项目: hanjin8307/circuit

// Register some common types. Repeated registration is ok.
func init() {
	gob.Register(make(map[string]interface{}))
	gob.Register(make(map[string]string))
	gob.Register(make(map[string]int))
	gob.Register(make([]interface{}, 0))
	gob.Register(time.Duration(0))
}

示例#19
文件: messages.go 项目: frazy/babou

func init() {
	gob.Register(Message{})
	gob.Register(DeleteUserMessage{})
	gob.Register(DeleteTorrentMessage{})
	gob.Register(TorrentStatMessage{})

}

示例#20
文件: utils.go 项目: vChrysanthemum/iron

func Encode(data interface{}) ([]byte, error) {
	var err error
	buf := bytes.NewBuffer(nil)
	enc := gob.NewEncoder(buf)

	switch data.(type) {
	case map[string]interface{}:
		nd := map[string]interface{}(data.(map[string]interface{}))
		for _, v := range nd {
			gob.Register(v)
		}
		err = enc.Encode(nd)
	case map[interface{}]interface{}:
		nd := map[string]interface{}(data.(map[string]interface{}))
		for _, v := range nd {
			gob.Register(v)
		}
		err = enc.Encode(nd)
	case []interface{}:
		nd := []interface{}(data.([]interface{}))
		for _, v := range nd {
			gob.Register(v)
		}
		err = enc.Encode(nd)
	default:
	}
	err = enc.Encode(data)

	if err != nil {
		return []byte(""), err
	}
	return buf.Bytes(), nil
}

示例#21
文件: executor_plugin.go 项目: nak3/nomad

// Registering these types since we have to serialize and de-serialize the Task
// structs over the wire between drivers and the executor.
func init() {
	gob.Register([]interface{}{})
	gob.Register(map[string]interface{}{})
	gob.Register([]map[string]string{})
	gob.Register([]map[string]int{})
	gob.Register(syscall.Signal(0x1))
}

示例#22
文件: register_handlers.go 项目: aarzilli/tools

func InitHandlers() {

	initCodeBaseDir()

	// Register datatypes such that it can be saved in the session.
	gob.Register(SessionUserKey(0))
	gob.Register(&User{})

	// Initialize XSRF token key.
	xsrfKey = "My personal very secure XSRF token key"

	sessKey := []byte("secure-key-234002395432-wsasjasfsfsfsaa-234002395432-wsasjasfsfsfsaa-234002395432-wsasjasfsfsfsaa")

	// Create a session cookie store.
	cookieStore = sessions.NewCookieStore(
		sessKey[:64],
		sessKey[:32],
	)

	cookieStore.Options = &sessions.Options{
		MaxAge:   maxSessionIDAge, // Session valid for 30 Minutes.
		HttpOnly: true,
	}

	// Create identity toolkit client.
	c := &gitkit.Config{
		ServerAPIKey: getConfig(siteName, "serverAPIKey"),
		ClientID:     getConfig(siteName, "clientID"),
		WidgetURL:    WidgetSigninAuthorizedRedirectURL,
	}
	// Service account and private key are not required in GAE Prod.
	// GAE App Identity API is used to identify the app.
	if appengine.IsDevAppServer() {
		c.ServiceAccount = getConfig(siteName, "serviceAccount")
		c.PEMKeyPath = privateKeyPath
	}
	var err error
	gitkitClient, err = gitkit.New(c)
	if err != nil {
		log.Fatal(err)
	}

	// The gorilla sessions use gorilla request context
	ClearHandler := func(fc http.HandlerFunc) http.Handler {
		return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
			defer gorillaContext.Clear(r)
			fc(w, r)
		})
	}

	http.Handle(homeURL, ClearHandler(handleHome))

	http.Handle(WidgetSigninAuthorizedRedirectURL, ClearHandler(handleWidget))
	http.Handle(signOutURL, ClearHandler(handleSignOut))

	http.Handle(signinLandingDefaultURL, ClearHandler(handleSigninSuccessLanding))
	http.Handle(signoutLandingDefaultURL, ClearHandler(handleSignOutLanding))

	http.HandleFunc(accountChooserBrandingURL, accountChooserBranding)
}

示例#23
文件: ipc.go 项目: Cepave/lvs-metrics

func init() {
	gob.Register(&healthcheck.DNSChecker{})
	gob.Register(&healthcheck.HTTPChecker{})
	gob.Register(&healthcheck.PingChecker{})
	gob.Register(&healthcheck.TCPChecker{})
	gob.Register(&healthcheck.UDPChecker{})
}

示例#24
文件: meshage.go 项目: cdshann/minimega

func init() {
	gob.Register(meshageCommand{})
	gob.Register(meshageResponse{})
	gob.Register(meshageVMLaunch{})
	gob.Register(meshageVMResponse{})
	gob.Register(iomeshage.IOMMessage{})
}

示例#25
文件: sessions.go 项目: scyth/gorilla-sessions-filestore

func init() {
	// gob encoding/decoding: register types for sessions and flashes.
	gob.Register(SessionData{})
	gob.Register([]interface{}{})
	// Register the default session store.
	DefaultSessionFactory.SetStore("cookie", new(CookieSessionStore))
}

示例#26
文件: user.go 项目: BRONSOLO/ahipbot

func init() {
	gob.Register(&GoogleUserProfile{})

	// Backwards compatibility
	type UserProfile GoogleUserProfile
	gob.Register(&UserProfile{})
}

示例#27
文件: main.go 项目: dnesting/alife

func main() {
	if len(os.Args) < 2 {
		fmt.Printf("Usage: %s /path/to/census-file\n", path.Base(os.Args[0]))
	}
	f, err := os.Open(os.Args[1])
	if err != nil {
		fmt.Printf("%s: %v\n", os.Args[1], err)
		return
	}
	fmt.Printf("reading from %#v\n", *f)
	dec := gob.NewDecoder(f)
	gob.Register(time.Time{})
	gob.Register(&cpu1.Cpu{})

	var pop census.Population
	if err := dec.Decode(&pop); err != nil {
		fmt.Printf("error: %v\n", err)
		return
	}
	fmt.Printf("%+v\n", pop)
	fmt.Printf("%#v\n", pop)

	if c, ok := pop.Key.(*cpu1.Cpu); ok {
		slist, err := cpu1.Ops.Decompile(c.Code)
		if err != nil {
			fmt.Printf("error decompiling: %v\n", err)
		}
		for _, s := range slist {
			fmt.Println(s)
		}
	}
}

示例#28
文件: imageblk.go 项目: hanslovsky/dvid

func init() {
	// Need to register types that will be used to fulfill interfaces.
	gob.Register(&Type{})
	gob.Register(&Data{})
	gob.Register(binary.LittleEndian)
	gob.Register(binary.BigEndian)
}

示例#29
文件: nds.go 项目: jongillham/nds

func init() {
	gob.Register(time.Time{})
	gob.Register(datastore.ByteString{})
	gob.Register(&datastore.Key{})
	gob.Register(appengine.BlobKey(""))
	gob.Register(appengine.GeoPoint{})
}

示例#30
文件: server.go 项目: heyihong/MIT-OpenCourseWare

//
// servers[] contains the ports of the set of
// servers that will cooperate via Raft to
// form the fault-tolerant key/value service.
// me is the index of the current server in servers[].
// the k/v server should store snapshots with persister.SaveSnapshot(),
// and Raft should save its state (including log) with persister.SaveRaftState().
// the k/v server should snapshot when Raft's saved state exceeds maxraftstate bytes,
// in order to allow Raft to garbage-collect its log. if maxraftstate is -1,
// you don't need to snapshot.
// StartKVServer() must return quickly, so it should start goroutines
// for any long-running work.
//
func StartKVServer(servers []*labrpc.ClientEnd, me int, persister *raft.Persister, maxraftstate int) *RaftKV {
	// call gob.Register on structures you want
	// Go's RPC library to marshall/unmarshall.
	gob.Register(Op{})
	gob.Register(PutAppendArgs{})
	gob.Register(GetArgs{})

	kv := new(RaftKV)
	kv.me = me
	kv.persister = persister
	kv.maxraftstate = maxraftstate
	// Your initialization code here.
	kv.appliedIndex = 0
	kv.clientIdToSeq = make(map[int64]int)
	kv.kv = make(map[string]string)

	kv.applyCh = make(chan raft.ApplyMsg)
	kv.rf = raft.Make(servers, me, persister, kv.applyCh)

	kv.readSnapshot(persister.ReadSnapshot())
	kv.rf.Snapshot(kv.appliedIndex)
	DPrintf("Server %d recovered from a snapshot (index = %d, snapshot size = %d, raft state size = %d)\n", kv.me, kv.appliedIndex, len(persister.ReadSnapshot()), len(persister.ReadRaftState()))

	go kv.apply()

	return kv
}

展开阅读全文