Exemplo n.º 1
0
func (p *httpProtocol) Read(reader io.Reader, buffer *link.InBuffer) error {
	// head
	p.writePos = 0

	header_buf := make([]byte, 1)
	for {
		if p.writePos == p.MaxPacketSize {
			return link.PacketTooLargeError
		}

		if _, err := io.ReadFull(reader, header_buf); err != nil {
			return err
		}
		p.header_data[p.writePos] = header_buf[0]
		p.writePos++
		if header_buf[0] == '\n' && p.writePos > 4 && string(p.header_data[p.writePos-4:p.writePos]) == "\r\n\r\n" {
			break
		}
	}
	header_buf = p.header_data[:p.writePos]
	content_length := 0
	if !(string(header_buf[:3]) == "GET") {
		for _, m := range bytes.Split(header_buf, []byte("\r\n")) {
			if bytes.Index(m, []byte("HTTP/1.1")) > 0 || bytes.Index(m, []byte(":")) < 0 {
				continue
			}
			header_split := bytes.SplitN(m, []byte(":"), 2)
			//headerKey := strings.TrimSpace(string(header_split[0]))
			headerValue := strings.TrimSpace(string(header_split[1]))

			if string(header_split[0]) == "CONTENT-LENGTH" {
				content_length, _ = strconv.Atoi(string(headerValue))
			}
		}
	}

	body_buf := make([]byte, content_length)
	if _, err := io.ReadFull(reader, body_buf); err != nil {
		return err
	}

	buffer.Prepare(p.writePos + 1 + content_length)
	for i := 0; i < p.writePos; i++ {
		buffer.Data[i] = p.header_data[i]
	}
	for i := 0; i < content_length; i++ {
		buffer.Data[p.writePos+i] = body_buf[i]
	}

	return nil
}
Exemplo n.º 2
0
func (p *tcProtocol) Read(reader io.Reader, buffer *link.InBuffer) error {
	// head
	lenBuf := bytes.Buffer{}

	tmpByte := make([]byte, 1)
	writePos := 0
	for {
		///包最大长度不能大于9999
		if writePos > 4 {
			return link.PacketTooLargeError
		}

		if _, err := io.ReadFull(reader, tmpByte); err != nil {
			return err
		}

		//fmt.Print(string(tmpByte))
		if tmpByte[0] == '\r' {
			if _, err := io.ReadFull(reader, tmpByte); tmpByte[0] != '\n' || err != nil {
				return errors.New("bad request")
			}
			len, err := strconv.Atoi(lenBuf.String())
			if err != nil {
				return errors.New("bad request,len is incorrect")
			}
			buffer.Prepare(len)
			if _, err := io.ReadFull(reader, buffer.Data); err != nil {
				return err
			} else {
				return nil
			}
		}
		lenBuf.WriteByte(tmpByte[0])
		writePos++
	}
	return nil
}