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


Golang ResponseWriter.Close方法代码示例

本文整理汇总了Golang中net/http.ResponseWriter.Close方法的典型用法代码示例。如果您正苦于以下问题:Golang ResponseWriter.Close方法的具体用法?Golang ResponseWriter.Close怎么用?Golang ResponseWriter.Close使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在net/http.ResponseWriter的用法示例。


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

示例1: ServeHTTP

func (rc *RevelController) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	// Dirty hacks, do NOT copy!
	revel.MainRouter = rc.router

	upgrade := r.Header.Get("Upgrade")
	if upgrade == "websocket" || upgrade == "Websocket" {
		panic("Not implemented")
	} else {
		var (
			req  = revel.NewRequest(r)
			resp = revel.NewResponse(w)
			c    = revel.NewController(req, resp)
		)
		req.Websocket = nil
		revel.Filters[0](c, revel.Filters[1:])
		if c.Result != nil {
			c.Result.Apply(req, resp)
		} else if c.Response.Status != 0 {
			panic("Not implemented")
		}
		// Close the Writer if we can
		if w, ok := resp.Out.(io.Closer); ok {
			w.Close()
		}
	}
}
开发者ID:kosuda,项目名称:go-http-routing-benchmark,代码行数:26,代码来源:routers.go

示例2: echoReadAll

// echoReadAll echoes messages from the client by reading the entire message
// with ioutil.ReadAll.
func echoReadAll(w http.ResponseWriter, r *http.Request, writeMessage bool) {
	conn, err := websocket.Upgrade(w, r.Header, nil, 4096, 4096)
	if err != nil {
		log.Println("Upgrade:", err)
		http.Error(w, "Bad request", 400)
		return
	}
	defer conn.Close()
	for {
		op, r, err := conn.NextReader()
		if err != nil {
			if err != io.EOF {
				log.Println("NextReader:", err)
			}
			return
		}
		if op == websocket.OpPong {
			continue
		}
		if op == websocket.OpText {
			r = &validator{r: r}
		}
		b, err := ioutil.ReadAll(r)
		if err != nil {
			if err == errInvalidUTF8 {
				conn.WriteControl(websocket.OpClose,
					websocket.FormatCloseMessage(websocket.CloseInvalidFramePayloadData, ""),
					time.Time{})
			}
			log.Println("ReadAll:", err)
			return
		}
		if writeMessage {
			err = conn.WriteMessage(op, b)
			if err != nil {
				log.Println("WriteMessage:", err)
			}
		} else {
			w, err := conn.NextWriter(op)
			if err != nil {
				log.Println("NextWriter:", err)
				return
			}
			if _, err := w.Write(b); err != nil {
				log.Println("Writer:", err)
				return
			}
			if err := w.Close(); err != nil {
				log.Println("Close:", err)
				return
			}
		}
	}
}
开发者ID:rif,项目名称:golang-stuff,代码行数:56,代码来源:server.go

示例3: echoCopy

// echoCopy echoes messages from the client using io.Copy.
func echoCopy(w http.ResponseWriter, r *http.Request, writerOnly bool) {
	conn, err := websocket.Upgrade(w, r.Header, nil, 4096, 4096)
	if err != nil {
		log.Println("Upgrade:", err)
		http.Error(w, "Bad request", 400)
		return
	}
	defer conn.Close()
	for {
		op, r, err := conn.NextReader()
		if err != nil {
			if err != io.EOF {
				log.Println("NextReader:", err)
			}
			return
		}
		if op == websocket.OpPong {
			continue
		}
		if op == websocket.OpText {
			r = &validator{r: r}
		}
		w, err := conn.NextWriter(op)
		if err != nil {
			log.Println("NextWriter:", err)
			return
		}
		if op == websocket.OpText {
			r = &validator{r: r}
		}
		if writerOnly {
			_, err = io.Copy(struct{ io.Writer }{w}, r)
		} else {
			_, err = io.Copy(w, r)
		}
		if err != nil {
			if err == errInvalidUTF8 {
				conn.WriteControl(websocket.OpClose,
					websocket.FormatCloseMessage(websocket.CloseInvalidFramePayloadData, ""),
					time.Time{})
			}
			log.Println("Copy:", err)
			return
		}
		err = w.Close()
		if err != nil {
			log.Println("Close:", err)
			return
		}
	}
}
开发者ID:jaekwon,项目名称:go-websocket,代码行数:52,代码来源:server.go

示例4: ServeHTTP

func (t wsHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	t.Log("HELLOOO")
	if r.Method != "GET" {
		http.Error(w, "Method not allowed", 405)
		t.Logf("bad method: %s", r.Method)
		return
	}
	if r.Header.Get("Origin") != "http://"+r.Host {
		http.Error(w, "Origin not allowed", 403)
		t.Logf("bad origin: %s", r.Header.Get("Origin"))
		return
	}
	ws, err := websocket.Upgrade(w, r.Header, "", 1024, 1024)
	if _, ok := err.(websocket.HandshakeError); ok {
		t.Logf("bad handshake: %v", err)
		http.Error(w, "Not a websocket handshake", 400)
		return
	} else if err != nil {
		t.Logf("upgrade error: %v", err)
		return
	}
	defer ws.Close()
	for {
		op, r, err := ws.NextReader()
		if err != nil {
			if err != io.EOF {
				t.Logf("NextReader: %v", err)
			}
			return
		}
		if op == websocket.OpPong {
			continue
		}
		w, err := ws.NextWriter(op)
		if err != nil {
			t.Logf("NextWriter: %v", err)
			return
		}
		if _, err = io.Copy(w, r); err != nil {
			t.Logf("Copy: %v", err)
			return
		}
		if err := w.Close(); err != nil {
			t.Logf("Close: %v", err)
			return
		}
	}
}
开发者ID:nchern,项目名称:go-websocket,代码行数:48,代码来源:client_server_test.go

示例5: echoCopy

// echoCopy echoes messages from the client using io.Copy.
func echoCopy(w http.ResponseWriter, r *http.Request, writerOnly bool) {
	conn, err := upgrader.Upgrade(w, r, nil)
	if err != nil {
		log.Println("Upgrade:", err)
		return
	}
	defer conn.Close()
	for {
		mt, r, err := conn.NextReader()
		if err != nil {
			if err != io.EOF {
				log.Println("NextReader:", err)
			}
			return
		}
		if mt == websocket.TextMessage {
			r = &validator{r: r}
		}
		w, err := conn.NextWriter(mt)
		if err != nil {
			log.Println("NextWriter:", err)
			return
		}
		if mt == websocket.TextMessage {
			r = &validator{r: r}
		}
		if writerOnly {
			_, err = io.Copy(struct{ io.Writer }{w}, r)
		} else {
			_, err = io.Copy(w, r)
		}
		if err != nil {
			if err == errInvalidUTF8 {
				conn.WriteControl(websocket.CloseMessage,
					websocket.FormatCloseMessage(websocket.CloseInvalidFramePayloadData, ""),
					time.Time{})
			}
			log.Println("Copy:", err)
			return
		}
		err = w.Close()
		if err != nil {
			log.Println("Close:", err)
			return
		}
	}
}
开发者ID:hartct,项目名称:toadserver,代码行数:48,代码来源:server.go

示例6: HandleWebSocket

func (s *LiveServer) HandleWebSocket(w http.ResponseWriter, r *http.Request) {
	conn, err, closed := websocket.Upgrade(w, r, s.websocketOrigin, "")
	if err != nil {
		log.StandardError(err)
		if !closed {
			serve400(w, r)
		}
		return
	}
	logRequest(HTTP_WEBSOCKET, http.StatusOK, r)
	conn.SetReadMaxSize(1 << 20)
	reads := make(chan []byte, 1)
	quit := make(chan bool, 1)
	writes := make(chan []byte, 1)
	tick := time.NewTicker(pingInterval)
	go readWebSocket(conn, reads, quit)
	defer func() {
		tick.Stop()
		conn.Close()
	}()
	for {
		select {
		case <-tick.C:
			err = conn.WriteControl(websocket.OpPing, pingData, time.Now().Add(pingInterval))
			if err != nil {
				log.Error("websocket: failed on ping: %s", err)
				return
			}
		case read := <-reads:
			writes <- read
		case write := <-writes:
			w, err := conn.NextWriter(websocket.OpText)
			if err != nil {
				log.Error("websocket: failed on NextWriter: %s", err)
				return
			}
			n, err := w.Write(write)
			w.Close()
			if n != len(write) || err != nil {
				log.Error("websocket: failed on write: %s", err)
				return
			}
		case <-quit:
			return
		}
	}
}
开发者ID:tav,项目名称:oldproto,代码行数:47,代码来源:main.go

示例7: ServeHTTP

func (t handshakeHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	if r.Method != "GET" {
		http.Error(w, "Method not allowed", 405)
		t.Logf("method = %s, want GET", r.Method)
		return
	}
	subprotos := Subprotocols(r)
	if !reflect.DeepEqual(subprotos, handshakeDialer.Subprotocols) {
		http.Error(w, "bad protocol", 400)
		t.Logf("Subprotocols = %v, want %v", subprotos, handshakeDialer.Subprotocols)
		return
	}
	ws, err := handshakeUpgrader.Upgrade(w, r, http.Header{"Set-Cookie": {"sessionID=1234"}})
	if err != nil {
		t.Logf("upgrade error: %v", err)
		return
	}
	defer ws.Close()

	if ws.Subprotocol() != "p1" {
		t.Logf("ws.Subprotocol() = %s, want p1", ws.Subprotocol())
		return
	}

	for {
		op, r, err := ws.NextReader()
		if err != nil {
			if err != io.EOF {
				t.Logf("NextReader: %v", err)
			}
			return
		}
		w, err := ws.NextWriter(op)
		if err != nil {
			t.Logf("NextWriter: %v", err)
			return
		}
		if _, err = io.Copy(w, r); err != nil {
			t.Logf("Copy: %v", err)
			return
		}
		if err := w.Close(); err != nil {
			t.Logf("Close: %v", err)
			return
		}
	}
}
开发者ID:GABONIA,项目名称:cli,代码行数:47,代码来源:client_server_test.go

示例8: echoReadAll

// echoReadAll echoes messages from the client by reading the entire message
// with ioutil.ReadAll.
func echoReadAll(w http.ResponseWriter, r *http.Request, writeMessage bool) {
	conn, err := websocket.Upgrade(w, r, nil, 4096, 4096)
	if err != nil {
		log.Println("Upgrade:", err)
		http.Error(w, "Bad request", 400)
		return
	}
	defer conn.Close()
	for {
		mt, b, err := conn.ReadMessage()
		if err != nil {
			if err != io.EOF {
				log.Println("NextReader:", err)
			}
			return
		}
		if mt == websocket.TextMessage {
			if !utf8.Valid(b) {
				conn.WriteControl(websocket.CloseMessage,
					websocket.FormatCloseMessage(websocket.CloseInvalidFramePayloadData, ""),
					time.Time{})
				log.Println("ReadAll: invalid utf8")
			}
		}
		if writeMessage {
			err = conn.WriteMessage(mt, b)
			if err != nil {
				log.Println("WriteMessage:", err)
			}
		} else {
			w, err := conn.NextWriter(mt)
			if err != nil {
				log.Println("NextWriter:", err)
				return
			}
			if _, err := w.Write(b); err != nil {
				log.Println("Writer:", err)
				return
			}
			if err := w.Close(); err != nil {
				log.Println("Close:", err)
				return
			}
		}
	}
}
开发者ID:bhawdeadlydan,项目名称:thebot,代码行数:48,代码来源:server.go

示例9: handleInternal

func handleInternal(w http.ResponseWriter, r *http.Request, ws *websocket.Conn) {
	var (
		req  = NewRequest(r)
		resp = NewResponse(w)
		c    = NewController(req, resp)
	)
	req.Websocket = ws

	Filters[0](c, Filters[1:])
	if c.Result != nil {
		c.Result.Apply(req, resp)
	} else if c.Response.Status != 0 {
		c.Response.Out.WriteHeader(c.Response.Status)
	}
	// Close the Writer if we can
	if w, ok := resp.Out.(io.Closer); ok {
		w.Close()
	}
}
开发者ID:roblillack,项目名称:mars,代码行数:19,代码来源:server.go

示例10: echo

func echo(w http.ResponseWriter, r *http.Request) {
	conn, err := websocket.Upgrade(w, r.Header, nil, 1024, 1024)
	if err != nil {
		http.Error(w, err.Error(), 400)
		return
	}
	defer conn.Close()
	for {
		op, r, err := conn.NextReader()
		if err != nil {
			return
		}
		if op != websocket.OpBinary && op != websocket.OpText {
			continue
		}
		w, err := conn.NextWriter(op)
		if err != nil {
			return
		}
		io.Copy(w, r)
		w.Close()
	}
}
开发者ID:rif,项目名称:golang-stuff,代码行数:23,代码来源:main.go

示例11: handleInternal

func handleInternal(w http.ResponseWriter, r *http.Request, ws *websocket.Conn) {
	// TODO For now this okay to put logger here for all the requests
	// However, it's best to have logging handler at server entry level
	start := time.Now()

	var (
		req  = NewRequest(r)
		resp = NewResponse(w)
		c    = NewController(req, resp)
	)
	req.Websocket = ws

	Filters[0](c, Filters[1:])
	if c.Result != nil {
		c.Result.Apply(req, resp)
	} else if c.Response.Status != 0 {
		c.Response.Out.WriteHeader(c.Response.Status)
	}
	// Close the Writer if we can
	if w, ok := resp.Out.(io.Closer); ok {
		w.Close()
	}

	// Revel request access log format
	// RequestStartTime ClientIP ResponseStatus RequestLatency HTTPMethod URLPath
	// Sample format:
	// 2016/05/25 17:46:37.112 127.0.0.1 200  270.157µs GET /
	requestLog.Printf("%v %v %v %10v %v %v",
		start.Format(requestLogTimeFormat),
		ClientIP(r),
		c.Response.Status,
		time.Since(start),
		r.Method,
		r.URL.Path,
	)
}
开发者ID:revel,项目名称:revel,代码行数:36,代码来源:server.go

示例12: ServeHTTP

func (h *KagomeDemoHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	type record struct {
		Surface        string
		Pos            string
		Baseform       string
		Reading        string
		Pronounciation string
	}
	sen := r.FormValue("s")
	opt := r.FormValue("r")
	var records []record
	var tokens []kagome.Token
	var svg string
	var cmdErr string
	const cmdTimeout = 30 * time.Second
	switch opt {
	case "1": // normal
		tokens = h.tokenizer.Tokenize(sen)
	case "2": // search
		tokens = h.tokenizer.SearchModeTokenize(sen)
	case "3": // extended
		tokens = h.tokenizer.ExtendedModeTokenize(sen)
	case "4": // lattice
		if _, e := exec.LookPath("dot"); e != nil {
			log.Print("graphviz is not in your future\n")
			break
		}
		var buf bytes.Buffer
		cmd := exec.Command("dot", "-Tsvg")
		r, w := io.Pipe()
		cmd.Stdin = r
		cmd.Stdout = &buf
		cmd.Stderr = os.Stderr
		cmd.Start()
		h.tokenizer.Dot(sen, w)
		w.Close()

		done := make(chan error, 1) //XXX
		go func() {
			done <- cmd.Wait()
		}()
		select {
		case <-time.After(cmdTimeout):
			if err := cmd.Process.Kill(); err != nil {
				log.Fatal("failed to kill: ", err)
			}
			cmdErr = "Time out"
			<-done
		case err := <-done:
			if err != nil {
				cmdErr = "Error"
				log.Printf("process done with error = %v", err)
			}
		}
		svg = buf.String()
		if pos := strings.Index(svg, "<svg"); pos > 0 {
			svg = svg[pos:]
		}
	}
	for _, tok := range tokens {
		if tok.Id == kagome.BosEosId {
			continue
		}
		m := record{Surface: tok.Surface}
		fs := tok.Features()
		switch len(fs) {
		case 9:
			m.Pos = strings.Join(fs[0:5], ",")
			m.Baseform = fs[6]
			m.Reading = fs[7]
			m.Pronounciation = fs[8]
		case 7:
			m.Pos = strings.Join(fs[0:5], ",")
			m.Baseform = fs[6]
			m.Reading = "*"
			m.Pronounciation = "*"
		case 3:
			m.Pos = fs[0]
			m.Baseform = fs[1]
			m.Reading = fs[2]
			m.Pronounciation = "*"
		}
		records = append(records, m)
	}
	d := struct {
		Sentence string
		Tokens   []record
		CmdErr   string
		GraphSvg template.HTML
		RadioOpt string
	}{Sentence: sen, Tokens: records, CmdErr: cmdErr, GraphSvg: template.HTML(svg), RadioOpt: opt}
	t := template.Must(template.New("top").Parse(demo_html))
	t.Execute(w, d)
}
开发者ID:postfix,项目名称:kagome,代码行数:94,代码来源:kagome.go

示例13: xhrHandlerBase

// The handlers
func xhrHandlerBase(opts xhrOptions, r *Router, w http.ResponseWriter, req *http.Request) {
	if xhrProlog(w, req) {
		return
	}
	xhrJsessionid(r, w, req)
	w.Header().Set("Content-type", opts.contentType())
	// For CORS, if the server sent Access-Control-Request-Headers, we
	// echo it back.
	acrh := req.Header.Get("Access-Control-Request-Headers")
	if acrh != "" {
		w.Header().Set("Access-Control-Allow-Headers", acrh)
	}
	sessionId := mux.Vars(req)["sessionid"]

	w.WriteHeader(http.StatusOK)
	opts.writePrelude(w)
	hijackAndContinue(w, func(w io.WriteCloser, done chan struct{}) {
		defer w.Close()
		var trans *xhrTransport
		// Find the session
		s, _ := r.getOrCreateSession(sessionId)
		s.sessionLock.Lock()
		// TODO: encapsulate this logic
		var sessionUnlocked bool
		defer func() {
			if !sessionUnlocked {
				s.sessionLock.Unlock()
			}
		}()
		if s.trans != nil {
			if s.closed {
				s.trans.writeFrame(w, closeFrame(3000, "Go away!"))
				return
			}
			var ok bool
			trans, ok = s.trans.(*xhrTransport)
			if !ok {
				s.trans.writeFrame(w, closeFrame(1001, "Another kind of connection is using this session"))
				return
			}
		} else {
			trans = new(xhrTransport)
			trans.opts = opts
			s.trans = trans
			trans.s = s
			trans.writeFrame(w, openFrame())
			conn := &Conn{s}
			go r.handler(conn)
			if !opts.streaming() {
				w.Close()
				return
			}
		}
		s.sessionLock.Unlock()
		sessionUnlocked = true
		var leavingVoluntarily bool
		loopDone := make(chan bool)
		recvDone := make(chan bool)
		go func() {
			defer close(loopDone)
			defer w.Close()
			select {
			case <-recvDone:
				leavingVoluntarily = true
				return
			case <-done:
				return
			}
		}()
		err := trans.setReceiver(&xhrReceiver{t: trans, w: w, opts: opts, closed: recvDone})
		if err != nil {
			return
		}
		defer trans.clearReceiver()
		// The session may already have closed from underneath us!
		// If so, die now
		if s.closed {
			return
		}
		<-loopDone
		// If the session isn't closed, and we're not closing voluntarily, then
		// assume the client closed us and close the session.
		if !leavingVoluntarily && !s.closed {
			trans.clearReceiver()
			s.Close()
			r.removeSession(sessionId, s)
		}
	})
}
开发者ID:mrlauer,项目名称:gosockjs,代码行数:90,代码来源:xhr.go

示例14: postContainersAttach

func (s *MonitorServer) postContainersAttach(version version.Version, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
	if err := parseForm(r); err != nil {
		return err
	}
	if vars == nil {
		return fmt.Errorf("Missing parameter")
	}

	inStream, outStream, err := hijackServer(w)
	if err != nil {
		return err
	}
	defer func() {
		if tcpc, ok := inStream.(*net.TCPConn); ok {
			tcpc.CloseWrite()
		} else {
			inStream.Close()
		}
	}()
	defer func() {
		if tcpc, ok := outStream.(*net.TCPConn); ok {
			tcpc.CloseWrite()
		} else if closer, ok := outStream.(io.Closer); ok {
			closer.Close()
		}
	}()

	var errStream io.Writer

	fmt.Fprintf(outStream, "HTTP/1.1 200 OK\r\nContent-Type: application/vnd.docker.raw-stream\r\n\r\n")

	/* !tty & api>1.6
	errStream = stdcopy.NewStdWriter(outStream, stdcopy.Stderr)
	outStream = stdcopy.NewStdWriter(outStream, stdcopy.Stdout)
	*/
	errStream = outStream

	var (
		logs   = boolValue(r, "logs")
		stream = boolValue(r, "stream")
		stdin  = boolValue(r, "stdin")
		stdout = boolValue(r, "stdout")
		stderr = boolValue(r, "stderr")
	)

	container := s.monitor.Container()

	//logs
	if logs {
		cLog, err := container.ReadLog("json")
		if err != nil && os.IsNotExist(err) {
			// Legacy logs
			log.Debugf("Old logs format")
			if stdout {
				cLog, err := container.ReadLog("stdout")
				if err != nil {
					log.Errorf("Error reading logs (stdout): %s", err)
				} else if _, err := io.Copy(outStream, cLog); err != nil {
					log.Errorf("Error streaming logs (stdout): %s", err)
				}
			}
			if stderr {
				cLog, err := container.ReadLog("stderr")
				if err != nil {
					log.Errorf("Error reading logs (stderr): %s", err)
				} else if _, err := io.Copy(errStream, cLog); err != nil {
					log.Errorf("Error streaming logs (stderr): %s", err)
				}
			}
		} else if err != nil {
			log.Errorf("Error reading logs (json): %s", err)
		} else {
			dec := json.NewDecoder(cLog)
			for {
				l := &jsonlog.JSONLog{}

				if err := dec.Decode(l); err == io.EOF {
					break
				} else if err != nil {
					log.Errorf("Error streaming logs: %s", err)
					break
				}
				if l.Stream == "stdout" && stdout {
					io.WriteString(outStream, l.Log)
				}
				if l.Stream == "stderr" && stderr {
					io.WriteString(errStream, l.Log)
				}
			}
		}
	}

	//stream
	if stream {
		var (
			cStdin           io.ReadCloser
			cStdout, cStderr io.Writer
			cStdinCloser     io.Closer
		)

//.........这里部分代码省略.........
开发者ID:TencentSA,项目名称:docker-1.3,代码行数:101,代码来源:server_monitor.go


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