Skip to content

missing chap7/client-slow-write #7

@openjny

Description

@openjny

In chapter 7, we are instructed to use a custom client to make sure our server programs work as expected.

You can find the client code in the chap7/client-slow-write directory of the source code repository.

However, the source code available here and on the support page does not include such a directory.

FYI: until the official code is released, I'd like to share my code for those who want to know a workaround.

// chapter7/client-slow-write/main.go
package main

import (
	"fmt"
	"io"
	"log"
	"net/http"
	"os"
	"time"
)

func longRunningProcess(w *io.PipeWriter) {
	for i := 0; i <= 10; i++ {
		fmt.Fprintf(w, "hello")
		time.Sleep(1 * time.Second)
	}
	w.Close()
}

func main() {
	logger := log.New(os.Stdout, "", log.Ldate|log.Ltime)

	pipeReader, pipeWriter := io.Pipe()
	go longRunningProcess(pipeWriter)

	client := &http.Client{}
	url := "http://localhost:8080/api/users/"

	logger.Println("Starting client request")
	resp, err := client.Post(url, "text/plain", pipeReader)
	if err != nil {
		logger.Fatalf("Error when sending the request: %v\n", err)
	}
	defer resp.Body.Close()

	bytes, err := io.ReadAll(resp.Body)
	if err != nil {
		logger.Fatalf("Error when reading the body: %v\n", err)
	}

	logger.Printf("Response body: %s\n", string(bytes))
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions