当前位置: 首页>>代码示例>>Golang>>正文


Golang os.NewError函数代码示例

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


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

示例1: UnmarshalNbt

func (inv *Inventory) UnmarshalNbt(tag *nbt.Compound) (err os.Error) {
	itemList, ok := tag.Lookup("Items").(*nbt.List)
	if !ok {
		return os.NewError("bad inventory - not a list")
	}

	for _, slotTagITag := range itemList.Value {
		slotTag, ok := slotTagITag.(*nbt.Compound)
		if !ok {
			return os.NewError("inventory slot not a compound")
		}

		var slotIdTag *nbt.Byte
		if slotIdTag, ok = slotTag.Lookup("Slot").(*nbt.Byte); !ok {
			return os.NewError("Slot ID not a byte")
		}
		slotId := types.SlotId(slotIdTag.Value)

		if err = inv.SlotUnmarshalNbt(slotTag, slotId); err != nil {
			return
		}
	}

	return nil
}
开发者ID:valtyr,项目名称:chunkymonkey,代码行数:25,代码来源:inventory.go

示例2: passwordfromfile

func passwordfromfile(hostname string, port int, dbname string, username string) (string, os.Error) {
	var sport string
	var lhostname string
	if dbname == "" {
		return "", nil
	}
	if username == "" {
		return "", nil
	}
	if hostname == "" {
		lhostname = "localhost"
	} else {
		lhostname = hostname
	}
	if port == 0 {
		sport = "5432"
	} else {
		sport = fmt.Sprintf("%d", port)
	}
	pgfile := getpgpassfilename()
	fileinfo, err := os.Stat(pgfile)
	if err != nil {
		err := os.NewError(fmt.Sprintf("WARNING: password file \"%s\" is not a plain file\n", pgfile))
		return "", err
	}
	if (fileinfo.Mode & 077) != 0 {
		err := os.NewError(fmt.Sprintf("WARNING: password file \"%s\" has group or world access; permissions should be u=rw (0600) or less", pgfile))
		return "", err
	}
	fp, err := os.Open(pgfile)
	if err != nil {
		err := os.NewError(fmt.Sprintf("Problem opening pgpass file \"%s\"", pgfile))
		return "", err
	}
	br := bufio.NewReader(fp)
	for {
		line, ok := br.ReadString('\n')
		if ok == os.EOF {
			return "", nil
		}
		// Now, split the line into pieces
		// hostname:port:database:username:password
		// and * matches anything
		pieces := strings.Split(line, ":")
		phost := pieces[0]
		pport := pieces[1]
		pdb := pieces[2]
		puser := pieces[3]
		ppass := pieces[4]

		if (phost == lhostname || phost == "*") &&
			(pport == "*" || pport == sport) &&
			(pdb == "*" || pdb == dbname) &&
			(puser == "*" || puser == username) {

			return ppass, nil
		}
	}
	return "", nil
}
开发者ID:samuel,项目名称:go-pgsql,代码行数:60,代码来源:conn.go

示例3: decodeSecureCookie

func decodeSecureCookie(value string) (user string, session string, err os.Error) {
	parts := strings.Split(value, "|", 3)
	if len(parts) != 3 {
		err = os.NewError("Malformed cookie value")
		return
	}
	val := parts[0]
	timestamp := parts[1]
	sig := parts[2]
	// Check signature
	if getCookieSig([]byte(val), timestamp) != sig {
		return "", "", os.NewError("Signature error, cookie is invalid")
	}
	// Check time stamp
	ts, _ := strconv.Atoi64(timestamp)
	if ts+maxAge < time.UTC().Seconds() {
		return "", "", os.NewError("Cookie is outdated")
	}

	buf := bytes.NewBufferString(val)
	encoder := base64.NewDecoder(base64.StdEncoding, buf)
	res, _ := ioutil.ReadAll(encoder)
	str := string(res)
	lst := strings.Split(str, "!", -1)
	if len(lst) != 2 {
		return "", "", os.NewError("Missing !")
	}
	return lst[0], lst[1], nil
}
开发者ID:AaronO,项目名称:lightwave,代码行数:29,代码来源:server.go

示例4: LoadBlockDefs

func LoadBlockDefs(reader io.Reader) (blocks BlockTypeList, err os.Error) {
	blocksStr := make(map[string]blockDef)
	decoder := json.NewDecoder(reader)
	err = decoder.Decode(&blocksStr)

	// Find the max block ID so we allocate the correct amount of memory. Also
	// range check the IDs.
	maxId := 0
	for idStr := range blocksStr {
		var id int
		id, err = strconv.Atoi(idStr)
		if err != nil {
			return
		}
		if id < BlockIdMin || id > BlockIdMax {
			err = os.NewError(fmt.Sprintf(
				"Encountered block type with ID %d which is outside the range"+
					"%d <= N <= %d", id, BlockIdMin, BlockIdMax))
			return
		}
		if id > maxId {
			maxId = id
		}
	}

	// Convert map string keys to ints.
	blocks = make(BlockTypeList, maxId+1)
	for idStr, blockDef := range blocksStr {
		var id int
		id, _ = strconv.Atoi(idStr)

		if blocks[id].defined {
			err = os.NewError(fmt.Sprintf(
				"Block ID %d defined more than once.", id))
		}

		var block *BlockType
		block, err = blockDef.LoadBlockType()
		if err != nil {
			return
		}
		block.id = BlockId(id)
		block.defined = true
		blocks[id] = *block
	}

	// Put VoidAspect in any undefined blocks rather than leave it nil, and also
	// set id on each block type.
	for id := range blocks {
		block := &blocks[id]
		block.id = BlockId(id)
		if !block.defined {
			void := makeVoidAspect()
			block.Aspect = void
			void.setAttrs(&block.BlockAttrs)
		}
	}

	return
}
开发者ID:nictuku,项目名称:chunkymonkey,代码行数:60,代码来源:block_loader.go

示例5: readRequestHeader

func (server *Server) readRequestHeader(codec ServerCodec) (service *service, mtype *methodType, req *Request, err os.Error) {
	// Grab the request header.
	req = server.getRequest()
	err = codec.ReadRequestHeader(req)
	if err != nil {
		req = nil
		if err == os.EOF || err == io.ErrUnexpectedEOF {
			return
		}
		err = os.NewError("rpc: server cannot decode request: " + err.String())
		return
	}

	serviceMethod := strings.Split(req.ServiceMethod, ".")
	if len(serviceMethod) != 2 {
		err = os.NewError("rpc: service/method request ill-formed: " + req.ServiceMethod)
		return
	}
	// Look up the request.
	server.mu.Lock()
	service = server.serviceMap[serviceMethod[0]]
	server.mu.Unlock()
	if service == nil {
		err = os.NewError("rpc: can't find service " + req.ServiceMethod)
		return
	}
	mtype = service.method[serviceMethod[1]]
	if mtype == nil {
		err = os.NewError("rpc: can't find method " + req.ServiceMethod)
	}
	return
}
开发者ID:Quantumboost,项目名称:gcc,代码行数:32,代码来源:server.go

示例6: Expand

// Expand expands a shortened url to long url.
// It returns the orgin url and nil if success, or empty string
// and an os.Error when failed.
func (req *Googl) Expand(url string) (string, os.Error) {
	res, err := req.get(url)
	if err != nil {
		return "", err
	}

	var temp map[string]string
	if err = json.Unmarshal([]byte(res), &temp); err != nil {
		return "", os.Error(err)
	}

	if _, ok := temp["code"]; ok {
		return "", os.NewError(temp["message"])
	}

	if status, _ := temp["status"]; "OK" != status {
		return "", os.NewError(status)
	}

	url, ok := temp["longUrl"]
	if !ok {
		return "", os.NewError("Invalid response")
	}

	return url, nil
}
开发者ID:mcspring,项目名称:googl.go,代码行数:29,代码来源:googl.go

示例7: writeToContainer

func writeToContainer(data [][]byte, val reflect.Value) os.Error {
	switch v := val; v.Kind() {
	case reflect.Ptr:
		return writeToContainer(data, reflect.Indirect(v))
	case reflect.Interface:
		return writeToContainer(data, v.Elem())
	case reflect.Map:
		if v.Type().Key().Kind() != reflect.String {
			return os.NewError("Invalid map type")
		}
		elemtype := v.Type().Elem()
		for i := 0; i < len(data)/2; i++ {
			mk := reflect.ValueOf(string(data[i*2]))
			mv := reflect.New(elemtype).Elem()
			writeTo(data[i*2+1], mv)
			v.SetMapIndex(mk, mv)
		}
	case reflect.Struct:
		for i := 0; i < len(data)/2; i++ {
			name := string(data[i*2])
			field := v.FieldByName(name)
			if !field.IsValid() {
				continue
			}
			writeTo(data[i*2+1], field)
		}
	default:
		return os.NewError("Invalid container type")
	}
	return nil
}
开发者ID:alangenfeld,项目名称:flock,代码行数:31,代码来源:redis.go

示例8: MapChunkToFile

func (m *Master) MapChunkToFile(args *sfs.MapChunkToFileArgs, ret *sfs.MapChunkToFileReturn) os.Error {
	file, ok := QueryFile(args.Name)

	if !ok {
		log.Printf("master: MapChunkToFile: File %s does not exist\n", args.Name)
		return os.NewError("File does not exist! Herp derp")
	}

	log.Printf("master: MapChunkToFile: ChunkID: %d  Offset %d  nservers: %d\n", args.Chunk.ChunkID, args.Offset, len(args.Chunk.Servers))
	var newChunk chunk

	newChunk.chunkID = args.Chunk.ChunkID
	newChunk.servers = new(vector.Vector)
	for i := 0; i < len(args.Chunk.Servers); i++ {
		newChunk.servers.Push(addrToServerMap[args.Chunk.Servers[i].String()])
	}

	_, err := file.MapChunk(args.Offset, &newChunk)

	if err != nil {
		return os.NewError("Could not add chunk! Ruh roh")
	}

	return nil
}
开发者ID:lalkaka,项目名称:stealthFS,代码行数:25,代码来源:master.go

示例9: SetLinkState

func (self *LinkHandler) SetLinkState(flag link.Flags) (err os.Error) {
	var qry *netlink.Message
	if hdr, ok := self.cache.Header.(*link.Header); ok {
		// While rtnetlink(7) says changes should always be IFF_QUERY, it has some
		// behaviours that are undocumented - like limiting actions on SETLINK's to
		// specific FLAGs.
		hdr = link.NewHeader(hdr.InterfaceFamily(), hdr.InterfaceType(), hdr.InterfaceIndex(), flag&link.IFF_UP, link.IFF_UP)
		msg := rtnetlink.Message{Header: hdr}
		qry, err = netlink.NewMessage(rtnetlink.RTM_SETLINK, netlink.NLM_F_ACK|netlink.NLM_F_REQUEST, msg, 4)
	} else {
		err = os.NewError("Cant set link flags (invalid cache)")
	}
	if err != nil {
		return
	}
	mch, err := self.h.Query(*qry, 1, 4)
	if err == nil {
		for m := range mch {
			switch m.Header.MessageType() {
			case netlink.NLMSG_ERROR:
				emsg := &netlink.Error{}
				err = emsg.UnmarshalNetlink(m.Body, 4)
				if err == nil && emsg.Code() != 0 {
					err = emsg
				}
			default:
				err = os.NewError("Unexpected netlink message")
				log.Printf("NetlinkError: %v", err)
			}
		}
		close(mch)
	}
	return
}
开发者ID:abneptis,项目名称:GoNetlink,代码行数:34,代码来源:links.go

示例10: pkgConfig

// pkgConfig runs pkg-config and extracts --libs and --cflags information
// for packages.
func pkgConfig(packages []string) (cflags, ldflags []string, err os.Error) {
	for _, name := range packages {
		if len(name) == 0 || name[0] == '-' {
			return nil, nil, os.NewError(fmt.Sprintf("invalid name: %q", name))
		}
	}

	args := append([]string{"pkg-config", "--cflags"}, packages...)
	stdout, stderr, ok := run(nil, args)
	if !ok {
		os.Stderr.Write(stderr)
		return nil, nil, os.NewError("pkg-config failed")
	}
	cflags, err = splitQuoted(string(stdout))
	if err != nil {
		return
	}

	args = append([]string{"pkg-config", "--libs"}, packages...)
	stdout, stderr, ok = run(nil, args)
	if !ok {
		os.Stderr.Write(stderr)
		return nil, nil, os.NewError("pkg-config failed")
	}
	ldflags, err = splitQuoted(string(stdout))
	return
}
开发者ID:WXB506,项目名称:golang,代码行数:29,代码来源:gcc.go

示例11: write

// Write Bind Response PDU
func (pdu *PDUBindResp) write(w *bufio.Writer) (err os.Error) {
	// Write Header
	err = pdu.Header.write(w)
	if err != nil {
		err = os.NewError("Bind Response: Error writing Header")
		return
	}
	// Create byte array the size of the PDU
	p := make([]byte, pdu.Header.CmdLength-pdu.OptionalLen-16)
	pos := 0
	// Copy system id
	if len(pdu.SystemId) > 0 {
		copy(p[pos:len(pdu.SystemId)], []byte(pdu.SystemId))
		pos += len(pdu.SystemId)
	}
	pos++ // Null terminator
	// Write to buffer
	_, err = w.Write(p)
	if err != nil {
		err = os.NewError("Bind Response: Error writing to buffer")
		return
	}
	// Flush write buffer
	err = w.Flush()
	if err != nil {
		err = os.NewError("Bind Response: Error flushing write buffer")
	}
	// Optional params
	err = pdu.writeOptional(w)
	if err != nil {
		err = os.NewError("Bind Response: Error writing optional params")
	}
	return
}
开发者ID:Philio,项目名称:GoSMPP,代码行数:35,代码来源:smpp_pdu.go

示例12: readDoc

// readDoc reads a single document from the connection.
func (c *connection) readDoc(alloc bool) ([]byte, os.Error) {
	if c.responseLen < 4 {
		return nil, c.fatal(os.NewError("mongo: incomplete document in message"))
	}
	b, err := c.br.Peek(4)
	if err != nil {
		return nil, c.fatal(err)
	}
	n := int(wire.Uint32(b))
	if c.responseLen < n {
		return nil, c.fatal(os.NewError("mongo: incomplete document in message"))
	}
	var p []byte
	if n > len(c.buf) || alloc {
		p = make([]byte, n)
	} else {
		p = c.buf[:n]
	}
	_, err = io.ReadFull(c.br, p)
	if err != nil {
		return nil, c.fatal(err)
	}
	c.responseLen -= n
	c.responseCount -= 1
	if c.responseCount == 0 {
		c.cursor = nil
		if c.responseLen != 0 {
			return nil, c.fatal(os.NewError("mongo: unexpected data in message."))
		}
	}
	return p, nil
}
开发者ID:xuechengbao,项目名称:go-mongo,代码行数:33,代码来源:connection.go

示例13: getMirror

func (me *WorkerDaemon) getMirror(rpcConn, revConn net.Conn, reserveCount int) (*Mirror, os.Error) {
	if reserveCount <= 0 {
		return nil, os.NewError("must ask positive jobcount")
	}
	me.mirrorMapMutex.Lock()
	defer me.mirrorMapMutex.Unlock()
	used := 0
	for _, v := range me.mirrorMap {
		used += v.maxJobCount
	}

	remaining := me.maxJobCount - used
	if remaining <= 0 {
		return nil, os.NewError("no processes available")
	}
	if remaining < reserveCount {
		reserveCount = remaining
	}

	mirror := NewMirror(me, rpcConn, revConn)
	mirror.maxJobCount = reserveCount
	key := fmt.Sprintf("%v", rpcConn.RemoteAddr())
	me.mirrorMap[key] = mirror
	mirror.key = key
	return mirror, nil
}
开发者ID:lht,项目名称:termite,代码行数:26,代码来源:worker.go

示例14: ExecuteOperation

func ExecuteOperation(input interface{}, op Operation) (output interface{}, err os.Error) {
	switch op.Kind {
	case NoOp:
		return input, nil
	case StringOp:
		if input == nil {
			input = NewSimpleText("")
		}
		text, ok := input.(Text)
		if !ok {
			err = os.NewError("Type mismatch: Not a string")
			return
		}
		err = executeString(text, op.Operations)
		output = text
	case ArrayOp:
		// TODO
	case ObjectOp:
		obj, ok := input.(Object)
		if !ok {
			err = os.NewError("Type mismatch: Not an object")
			return
		}
		err = executeObject(obj, op.Operations)
		output = obj
	default:
		err = os.NewError("Operation not allowed in this place")
	}
	return
}
开发者ID:AaronO,项目名称:lightwave,代码行数:30,代码来源:document.go

示例15: RunCommand

func (c *attrCmd) RunCommand(up *Uploader, args []string) os.Error {
	if len(args) != 3 {
		return os.NewError("Attr takes 3 args: <permanode> <attr> <value>")
	}
	permanode, attr, value := args[0], args[1], args[2]

	var err os.Error

	pn := blobref.Parse(permanode)
	if pn == nil {
		return fmt.Errorf("Error parsing blobref %q", permanode)
	}
	m := schema.NewSetAttributeClaim(pn, attr, value)
	if c.add {
		if c.del {
			return os.NewError("Add and del options are exclusive")
		}
		m = schema.NewAddAttributeClaim(pn, attr, value)
	} else {
		// TODO: del, which can make <value> be optional
		if c.del {
			return os.NewError("del not yet implemented")
		}
	}
	put, err := up.UploadAndSignMap(m)
	handleResult(m["claimType"].(string), put, err)
	return nil
}
开发者ID:ipeet,项目名称:camlistore,代码行数:28,代码来源:attr.go


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