When to use hijacking in a golang?

I don’t understand why we use capture, since I can write something directly into the body of the answer, can anyone explain this?

func writeSome(w http.ResponseWriter, r *http.Request) { fmt.Fprintf(w, "write some thing") } 

he is the same:

 func hijack(w http.ResponseWriter, r *http.Request) { hj, _ := w.(http.Hijacker) _, buf, _ := hj.Hijack() buf.WriteString("write some thing") buf.Flush() } 

I'm confused

+6
source share
2 answers

Use Hijack if you do not want to use the built-in implementation of the HTTP protocol server. Perhaps this is due to the fact that you want to switch protocols (for example, to WebSocket) or the built-in server bothers you.

The two code snippets above do not produce the same output on the wire. The result of the first fragment will include the response header:

 HTTP/1.1 200 OK Date: Wed, 26 Nov 2014 03:37:57 GMT Content-Length: 16 Content-Type: text/plain; charset=utf-8 write some thing 

The second fragment bypasses the built-in server code and writes

 write some thing 

directly to the exit.

+13
source

You can see one library ( martini ) that introduced hijack : question 45
(Note: I do not recommend Martini, which is not idiomatic , but is mentioned here for illustration only hijack )

Is it possible for your type of responseWriter to implement http.Hijack?
This will allow libraries like websockets one to work with martinis.

This issue applies to the next thread thread , where one tried to implement the http.ResponseWriter interface to record statistics such as bytes and request durations.

Someone later pointed out some other interesting features of the http library, such as the CloseNotifier interface, and I understood the above code might not be such a good idea.
Since I am implementing the interface, I cannot automatically inherit *http.Response implementations of CloseNotifier and Flusher .

So, if you want to take on ResponseWriter to:

  • write more information (status, size, ..., hijack call, probably a buster here),
  • implement another protocol (for example, websocket, which Upgrade "connection to the HTTP server, call w.(http.Hijacker) )

Then you can consider using hijacking.
But as documented , after calling Hijack() the HTTP server library will do nothing with the connection.
Responsibility for managing and closing the connection becomes the responsibility of the caller.

If not, as shown in this other question , then the capture is not interesting.

+3
source

Source: https://habr.com/ru/post/978539/


All Articles