func handleRequest(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/json") w.WriteHeader(http.StatusOK) response := make(map[string]string) response["message"] = "Hello, world!" json.NewEncoder(w).Encode(response) }
func handleStreamRequest(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "text/html; charset=utf-8") w.WriteHeader(http.StatusOK) for i := 0; i < 100000; i++ { fmt.Fprintf(w, "Count: %dIn this example, we use ResponseWriter to stream a large response to the client. We first set the response header and status code. Then, we loop 100,000 times and write a line of HTML to the ResponseWriter each time. To ensure the client receives each line as it's written, we call the Flush method on the ResponseWriter. Finally, we write some text to indicate that the stream has ended. In conclusion, the Go HTTP ResponseWriter interface is a core component of the net/http package. It allows developers to write HTTP response data in a flexible and efficient manner, whether that's a simple JSON response or a stream of data.
\n", i) w.(http.Flusher).Flush() time.Sleep(time.Millisecond * 100) } fmt.Fprint(w, "Stream ended.") }