robert-min / handson-go

Go-lang hands on guide
0 stars 0 forks source link

Chapter7. Service HTTP Server - Stop request handling #20

Open robert-min opened 1 year ago

robert-min commented 1 year ago

요청 핸들링 중단

robert-min commented 1 year ago

http.TimeoutHandler를 활용한 요청 핸들링 중단


func handleUserApi(w http.ResponseWriter, r *http.Request) {
    log.Println("I started processing the request")
    time.Sleep(15 * time.Second)
    fmt.Fprintf(w, "Hello world!")
    log.Println("I finished processing the request")
}

func main() {
    listenAddr := os.Getenv("LINSTEN_ADDR")
    if len(listenAddr) == 0 {
        listenAddr = ":8080"
    }

    timeoutDuration := 14 * time.Second

    userhandler := http.HandlerFunc(handleUserApi)
    hTimeout := http.TimeoutHandler(userhandler, timeoutDuration, "I ran out of time.")
    mux := http.NewServeMux()
    mux.Handle("/api/users", hTimeout)

    log.Fatal(http.ListenAndServe(listenAddr, mux))
}
robert-min commented 1 year ago

요청 중단 후 서버에서 처리

robert-min commented 1 year ago

요청 중단 후 서버에서 컨텍스트 처리 코드

func handlePing(w http.ResponseWriter, r *http.Request) { log.Println("ping: Got a request") fmt.Fprintf(w, "ping") }

func doSomeWork() { time.Sleep(2 * time.Second) }

func handleUserApi(w http.ResponseWriter, r *http.Request) { log.Println("I started processing the request")

doSomeWork()

req, err := http.NewRequestWithContext(
    r.Context(),
    "GET",
    "http://localhost:8080/ping", nil,
)
if err != nil {
    http.Error(w, err.Error(), http.StatusInternalServerError)
    return
}

client := &http.Client{}
log.Println("Outgoing HTTP request")

// Check context valid
resp, err := client.Do(req)
if err != nil {
    log.Printf("Error making request: %v\n", err)
    http.Error(w, err.Error(), http.StatusInternalServerError)
    return
}
defer resp.Body.Close()
data, _ := io.ReadAll(resp.Body)

fmt.Fprintf(w, string(data))
log.Println("I finished processing the request.")

}

func main() { listenAddr := os.Getenv("LISTEN_ADDR") if len(listenAddr) == 0 { listenAddr = ":8080" }

timeoutDuration := 5 * time.Second

userHandler := http.HandlerFunc(handleUserApi)
hTimeout := http.TimeoutHandler(
    userHandler,
    timeoutDuration,
    "I ran out of time",
)

mux := http.NewServeMux()
mux.Handle("/api/users", hTimeout)
mux.HandleFunc("/ping", handlePing)
log.Fatal(http.ListenAndServe(listenAddr, mux))

}