func()

in image/resources/knfsd-agent/routes.go [69:110]


func (handler JSONHandlerFunc[T]) Execute(r *http.Request) (statusCode int, body []byte, err error) {
	statusCode = http.StatusOK

	if r.Method == http.MethodHead {
		// In case a client relies on sending a HEAD request (e.g. for CORS
		// support) just send a basic empty response.
		// We're not going to try and generate any other headers such as
		// Content-Length as many of the handlers scrape live details on
		// request, and HEAD is supposed to be cheap to call.
		return http.StatusOK, []byte{}, nil
	}

	// Endpoints only support GET requests.
	if r.Method != http.MethodGet && r.Method != http.MethodHead {
		statusCode = http.StatusMethodNotAllowed
		body = []byte("{\"message\": \"method not allowed\"}")
		err = errors.New("method not allowed")
		return statusCode, body, err
	}

	result, err := handler(r)
	if err == nil {
		if result == nil {
			// The status endpoints only deal with queries, so there's no valid
			// reason for an endpoint to return 204 No Content. Thus if a handler
			// method returns (nil, nil) then something has gone wrong.
			err = errors.New("handler did not return any content")
		} else {
			// Convert the result to json if there was no error.
			body, err = json.MarshalIndent(result, "", "  ")
		}
	}

	// If there was an error from either the handler, or JSON conversion return
	// a generic error message to the client and log the real error message.
	if err != nil {
		statusCode = http.StatusInternalServerError
		body = []byte("{\"message\": \"An unknown error occurred\"}")
	}

	return statusCode, body, err
}