http.TimeoutHandler with JSON response body and header

Hi,

Is there a way to return a JSON body with http.TimeoutHandler and application/json; charset=utf-8 content type header?

Thanks

I don’t know with http.TimeoutHandler, but an idea using context:

func handlerWithTimeout(w http.ResponseWriter, r *http.Request) {
	ctx, cancel := context.WithTimeout(context.Background(), 1*time.Second)
	defer cancel()

	result := make(chan string)

	go func() {
		result <- slowOperation()
	}()

	select {
	case r := <-result:
		io.WriteString(w, r+"\n")
	case <-ctx.Done():
		w.Header().Add("content-type", "application/json")
		w.WriteHeader(http.StatusServiceUnavailable)

		d := map[string]string{"error": "timeout"}
		err := json.NewEncoder(w).Encode(d)
		if err != nil {
			w.WriteHeader(http.StatusInternalServerError)
		}
	}
}

func slowOperation() string {
	fmt.Println("Working on it...")

	time.Sleep(2 * time.Second)

	return "data"
}

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.