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


Golang textproto.NewReader函数代码示例

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


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

示例1: EvaluateEmail

func EvaluateEmail(t *Templater, baseName string, context interface{}) (*Email, error) {
	email := &Email{}

	headerBytes, err := t.Evaluate(baseName+".hdr", context)
	if err != nil {
		return nil, fmt.Errorf("%s.hdr: %s", baseName, err)
	}

	r := textproto.NewReader(bufio.NewReader(bytes.NewReader(headerBytes)))
	email.Header, err = r.ReadMIMEHeader()
	if err != nil {
		return nil, fmt.Errorf("%s.hdr: %s", baseName, err)
	}

	if email.Text, err = t.Evaluate(baseName+".txt", context); err != nil {
		return nil, fmt.Errorf("%s.txt: %s", baseName, err)
	}

	if email.HTML, err = t.Evaluate(baseName+".html", context); err != nil {
		return nil, fmt.Errorf("%s.html: %s", baseName, err)
	}

	if sf, ok := context.(staticFiles); ok {
		attachments := sf.Attachments()
		email.Attachments = make([]Attachment, 0, len(attachments))
		for _, attachment := range attachments {
			email.Attachments = append(email.Attachments, attachment)
		}
		sort.Sort(attachmentList(email.Attachments))
	}

	return email, nil
}
开发者ID:logan,项目名称:heim,代码行数:33,代码来源:email.go

示例2: downloadDict

func downloadDict(url string) {
	log.Println("Getting dict", path.Base(url))
	resp, err := http.Get(url)
	if err != nil {
		log.Println("Error getting dict:", err)
		return
	}
	f, err := os.Create(path.Join("dicts", path.Base(url)))
	if err != nil {
		log.Println(err)
		return
	}
	defer f.Close()

	buffered := bufio.NewReader(resp.Body)
	tr := textproto.NewReader(buffered)
	sdchHeader, err := tr.ReadMIMEHeader()
	if err != nil {
		log.Println(err)
		return
	}
	pretty.Println("Decoded sdch header:", sdchHeader)

	_, err = io.Copy(f, buffered)
	if err != nil {
		log.Println(err)
		return
	}
	dictName = path.Base(url)
	log.Println("Got dict", dictName)
}
开发者ID:rakoo,项目名称:MMAS,代码行数:31,代码来源:main.go

示例3: ProcessResponse

// ProcessResponse adds any returned header data to the response header and sends the rest
// to the response body.
func ProcessResponse(stdout io.Reader, w http.ResponseWriter, r *http.Request) error {
	bufReader := bufio.NewReader(stdout)
	mimeReader := textproto.NewReader(bufReader)
	hdr, err := mimeReader.ReadMIMEHeader()
	if err != nil {
		// We got nothing! Assume there is an error. Should be more robust.
		return err
	}
	if err == nil {
		for k, vals := range hdr {
			for _, v := range vals {
				w.Header().Add(k, v)
			}
		}
	}
	statusCode := http.StatusOK
	if status := hdr.Get("Status"); status != "" {
		delete(w.Header(), "Status")
		// Parse the status code
		var code int
		if n, _ := fmt.Sscanf(status, "%d", &code); n == 1 {
			statusCode = int(code)
		}
	}
	// Are there other fields we need to rewrite? Probably!
	w.WriteHeader(statusCode)
	io.Copy(w, bufReader)
	return nil
}
开发者ID:sh1nu11bi,项目名称:gofcgisrv,代码行数:31,代码来源:http.go

示例4: ReadLeds

func (b *Board) ReadLeds() (colors []color.Color, err error) {
	err = b.Write(0x3, make([]byte, 0))
	if err != nil {
		return
	}
	reader := textproto.NewReader(bufio.NewReader(b.ser))
	line, err := reader.ReadLineBytes()
	if err != nil {
		return
	}

	type LedsMessage struct {
		Leds []string
	}
	var ret LedsMessage
	err = json.Unmarshal(line, &ret)
	if err != nil {
		return
	}

	colors = make([]color.Color, len(ret.Leds))
	for i, c := range ret.Leds {
		r, g, b := hex.HexToRGB(hex.Hex(c))
		colors[i] = color.RGBA{r, g, b, 0}
	}

	return colors, nil
}
开发者ID:drewp,项目名称:homeauto,代码行数:28,代码来源:pilight.go

示例5: MuxConnection

// muxConnection takes an inbound connection reads MIME headers from it and
// then attempts to set up a connection to the service specified by the
// Zen-Service header. If the Zen-Service header is missing or the requested
// service is not running (listening) on the local host and error message
// is sent to the requestor and its connection is closed. Otherwise data is
// proxied between the requestor and the local service.
func (mux TCPMux) MuxConnection(conn net.Conn) {
	rdr := textproto.NewReader(bufio.NewReader(conn))
	hdr, err := rdr.ReadMIMEHeader()
	if err != nil {
		sendMuxError(conn, "MuxConnection", "textproto.ReadMIMEHeader", "bad request (no headers)", err)
		conn.Close()
		return
	}

	zs, ok := hdr["Zen-Service"]
	if ok == false {
		sendMuxError(conn, "MuxConnection", "MIMEHeader", "bad request (no Zen-Service header)", err)
		conn.Close()
		return
	}

	port, err := strconv.Atoi(strings.Split(zs[0], "/")[1])
	if err != nil {
		sendMuxError(conn, "MuxConnection", "Zen-Service Header", "bad Zen-Service spec", err)
		conn.Close()
		return
	}

	svc, err := net.Dial("tcp4", fmt.Sprintf("172.17.42.1:%d", port))
	if err != nil {
		sendMuxError(conn, "MuxConnection", "net.Dial", "cannot connect to service", err)
		conn.Close()
		return
	}

	go io.Copy(conn, svc)
	go io.Copy(svc, conn)
}
开发者ID:jhuie-zenoss,项目名称:serviced,代码行数:39,代码来源:mux.go

示例6: main

func main() {
	mcon := CreateConnection()
	sock, err := mcon.Connect()

	if err != nil {
		fmt.Printf("Error connecting to the server")
	}

	mcon.Start(sock)

	reader := bufio.NewReader(sock)
	tp := textproto.NewReader(reader)
	// The input system is really ugly and cumbersome
	// I use holder as fix, but should be rewritten
	input := ""
	holder := ""
	for input != "/quit" {
		line, err := tp.ReadLine()
		if err != nil {
			break // break loop on errors
		}
		fmt.Printf("%s\n", line)

		fmt.Scanf("%s", &input)
		if input != "" && input != holder {
			mcon.SendMessage(sock, input)
			holder = input
		}
	}

	return
}
开发者ID:dysoco,项目名称:gossip,代码行数:32,代码来源:main.go

示例7: main

func main() {
	conn, err := net.Dial("tcp", os.Args[1])
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Println("connect ok")

	reader := textproto.NewReader(bufio.NewReader(conn))
	for _, s := range os.Args[2:] {
		fmt.Println("send", s)
		_, e := conn.Write([]byte(s + "\r\n"))
		if nil != e {
			fmt.Println(e)
			break
		}

		if "exit" == s {
			break
		}
		ln, e := reader.ReadLine()
		if nil != e {
			fmt.Println(e)
			break
		}
		fmt.Println("recv", ln)
	}
	fmt.Println("disconnect")
}
开发者ID:runner-mei,项目名称:daemontools,代码行数:29,代码来源:client.go

示例8: QueryForFilePattern

// QueryForFilePattern searches through all installed files, matching them against
// pattern and returns the list of package names containing a file matching patterns.
//
// Returns an error if globbing /var/lib/dpkg/info/*.list fails.
func (self Dpkg) QueryForFilePattern(pattern string) ([]string, error) {
	result := []string{}

	info := filepath.Join(self.runtimeDir, "info")

	entries, err := filepath.Glob(filepath.Join(info, "*.list"))
	if err != nil {
		return nil, errors.New(fmt.Sprintf("Failed to glob *.list from %s [%s]", info, err))
	}

	for _, entry := range entries {
		if f, err := os.Open(entry); err != nil {
			continue
		} else {
			tpr := textproto.NewReader(bufio.NewReader(f))

			for line, err := tpr.ReadLine(); err == nil; line, err = tpr.ReadLine() {
				if matched, _ := filepath.Match(pattern, line); matched {
					if matches := extractPnRegexp.FindStringSubmatch(entry); len(matches) > 0 {
						result = append(result, matches[smIdxPn])
						// We have to break the inner loop as we want to avoid
						// adding the same package over and over again.
						break
					}
				}
			}
		}
	}

	return result, nil
}
开发者ID:vosst,项目名称:csi,代码行数:35,代码来源:dpkg.go

示例9: ParseMIME

// ParseMIME reads a MIME document from the provided reader and parses it into
// tree of MIMEPart objects.
func ParseMIME(reader *bufio.Reader) (MIMEPart, error) {
	tr := textproto.NewReader(reader)
	header, err := tr.ReadMIMEHeader()
	if err != nil {
		return nil, err
	}
	ctype := header.Get("Content-Type")
	mediatype, params, err := mime.ParseMediaType(ctype)
	if err != nil {
		return nil, err
	}
	root := &memMIMEPart{header: header, contentType: mediatype}

	if strings.HasPrefix(mediatype, "multipart/") {
		boundary := params["boundary"]
		err = parseParts(root, reader, boundary)
		if err != nil {
			return nil, err
		}
	} else {
		// Content is text or data, decode it
		content, err := decodeSection(header.Get("Content-Transfer-Encoding"), ctype, mediatype, reader)
		if err != nil {
			return nil, err
		}
		root.content = content
	}

	return root, nil
}
开发者ID:revapost,项目名称:go.enmime,代码行数:32,代码来源:part.go

示例10: Serve

func (c *client) Serve() {
	go func() {
		reader := textproto.NewReader(bufio.NewReader(c.conn))
		for {
			m, err := reader.ReadLineBytes()
			if err != nil {
				c.stopChan <- err
				return
			}
			c.notifyChan <- append(m, '\n')
		}
	}()

	for {
		select {
		case <-c.stopChan:
			c.exitChan <- c
			c.conn.Close()
			return
		case m := <-c.broadcastChan:
			if _, err := c.conn.Write(m); err != nil {
				c.exitChan <- c
			}
		}
	}
}
开发者ID:migsbeast,项目名称:homework,代码行数:26,代码来源:server_impl.go

示例11: main

func main() {
	if len(os.Args) < 2 {
		fmt.Printf("Usage: %s <script file>\n", os.Args[0])
		return
	}
	namehash_hash := md5.New()
	io.WriteString(namehash_hash, os.Args[1])
	namehash := hex.EncodeToString(namehash_hash.Sum())
	tempfile := temp_dir() + "/" + namehash

	readpipe, writepipe, _ := os.Pipe()
	stdfiles := [](*os.File){readpipe, os.Stdout, os.Stderr}

	syscall.Umask(0077)
	srcfile, err := os.Open(os.Args[1], os.O_RDONLY, 0)
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}
	srcinfo, _ := srcfile.Stat()
	outfile, err := os.Open(tempfile+".ld", os.O_RDONLY, 0)
	var outinfo (*os.FileInfo)
	if err == nil {
		outinfo, _ = outfile.Stat()
		outfile.Close()
	}

	if err != nil || outinfo.Mtime_ns < srcinfo.Mtime_ns {
		//fmt.Printf("Compiling...")
		cpid, cerr := os.ForkExec(GOBIN+"8g", []string{GOBIN + "8g", "-o", tempfile + ".cd", "/dev/stdin"}, nil, "", stdfiles)

		src := textproto.NewReader(bufio.NewReader(srcfile))
		firstline := true
		for {
			s, err := src.ReadLine()
			if err != nil {
				break
			}
			if (len(s) > 0) && (s[0] == '#') && firstline {
				continue
			}
			firstline = false
			writepipe.WriteString(s + "\n")
		}
		writepipe.Close()
		srcfile.Close()

		stage_check(cpid, cerr, "compile")

		lpid, err := os.ForkExec(GOBIN+"8l", []string{GOBIN + "8l", "-o", tempfile + ".ld", tempfile + ".cd"}, nil, "", stdfiles)
		stage_check(lpid, err, "link")
		os.Chmod(tempfile+".ld", 0700)
		//fmt.Println("done.")
	} else {
		//fmt.Println("Running cached.")
	}
	err = os.Exec(tempfile+".ld", os.Args[1:], nil)
	fmt.Println(err)
	os.Exit(1)
}
开发者ID:stiletto,项目名称:goscript,代码行数:60,代码来源:goscript.go

示例12: NewConn

// NewConn returns a new Conn using conn for I/O.
func NewConn(conn io.ReadWriteCloser) *Conn {
	return &Conn{
		Reader: Reader{R: textproto.NewReader(bufio.NewReader(conn))},
		Writer: Writer{W: bufio.NewWriter(conn)},
		conn:   conn,
	}
}
开发者ID:huuzkee-foundation,项目名称:go-pop3,代码行数:8,代码来源:pop3proto.go

示例13: NewTextConn

func NewTextConn(conn net.Conn) *TextConn {
	return &TextConn{
		conn:   conn,
		reader: textproto.NewReader(bufio.NewReader(conn)),
		writer: bufio.NewWriter(conn),
	}
}
开发者ID:vchimishuk,项目名称:chub,代码行数:7,代码来源:textconn.go

示例14: ReadRequest

func ReadRequest(b *bufio.Reader) (req *http.Request, err error) {
	tp := textproto.NewReader(b)
	var s string
	if s, err = tp.ReadLine(); err != nil {
		return nil, err
	}
	defer func() {
		if err == io.EOF {
			err = io.ErrUnexpectedEOF
		}
	}()

	var f []string
	// TODO a split that only allows N values?
	if f = strings.SplitN(s, " ", 3); len(f) < 3 {
		return nil, &badStringError{"malformed request line", s}
	}
	if f[1] != "*" {
		return nil, &badStringError{"bad URL request", f[1]}
	}
	req = &http.Request{
		Method: f[0],
	}
	var ok bool
	if req.ProtoMajor, req.ProtoMinor, ok = http.ParseHTTPVersion(strings.TrimSpace(f[2])); !ok {
		return nil, &badStringError{"malformed HTTP version", f[2]}
	}

	mimeHeader, err := tp.ReadMIMEHeader()
	if err != nil {
		return nil, err
	}
	req.Header = http.Header(mimeHeader)
	return
}
开发者ID:ronindev,项目名称:dms,代码行数:35,代码来源:ssdp.go

示例15: Connect

func (bot *Bot) Connect() {
	conn, err := net.Dial("tcp", fmt.Sprintf("%s:%d", bot.server, bot.port))
	if err != nil {
		log.Fatal("Could not connect to server: ", err)
	}
	fmt.Printf("Connected to server %s:%d (%s)\n", bot.server, bot.port, conn.RemoteAddr())
	bot.coutput = make(chan string)
	bot.cinput = make(chan string)
	bot.conn = conn
	reader := bufio.NewReader(bot.conn)
	tp := textproto.NewReader(reader)

	go bot.outputHandler()
	go bot.inputHandler()

	bot.SendCommand("USER " + bot.user + " 8 * :" + bot.nick)
	bot.SendCommand("NICK " + bot.nick)

	for {
		line, err := tp.ReadLine()
		if err != nil {
			log.Fatal(err)
			break
		}
		bot.cinput <- line
	}

}
开发者ID:Nyubis,项目名称:mibot,代码行数:28,代码来源:core.go


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