func Handler()

in kernelspecs/kernelspecs.go [115:163]


func Handler(localBackend *backends.Backend, remoteBackend *backends.Backend) http.Handler {
	bs := []*backends.Backend{localBackend, remoteBackend}
	resourcePath := "/kernelspecs/"
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		if r.Method != http.MethodGet {
			errorMsg := fmt.Sprintf("unsupported method %v", r.Method)
			http.Error(w, errorMsg, http.StatusBadRequest)
			util.Log(r, errorMsg)
			return
		}
		if strings.HasPrefix(r.URL.Path, resourcePath) {
			subpath := strings.TrimPrefix(r.URL.Path, resourcePath)
			unifiedID := strings.Split(subpath, "/")[0]
			backend, localID, err := backends.ParseUnifiedID(unifiedID, bs)
			if err != nil {
				errorMsg := fmt.Sprintf("invalid kernelspec ID: %q", unifiedID)
				http.Error(w, errorMsg, http.StatusBadRequest)
				util.Log(r, fmt.Sprintf("Failure parsing a kernelspecs resource path: %q", errorMsg))
				return
			}
			localPath := strings.Replace(r.URL.Path, unifiedID, localID, 1)
			util.Log(r, fmt.Sprintf("Translated unified path %q into local path %q", r.URL.Path, localPath))
			r.URL.Path = localPath
			backend.ServeHTTP(w, r)
			return
		}
		if r.URL.Path != APIPath {
			errorMsg := fmt.Sprintf("unsupported kernelspecs API endpoint: %q", r.URL.Path)
			http.Error(w, errorMsg, http.StatusBadRequest)
			util.Log(r, fmt.Sprintf("Failed kernelspecs API call: %q\n", errorMsg))
			return
		}
		unifiedKernelSpecs, err := CombinedKernelSpecs(localBackend, remoteBackend)
		if err != nil {
			errorMsg := fmt.Sprintf("failure fetching the kernelspecs: %v", err)
			http.Error(w, errorMsg, util.HTTPStatusCode(err))
			util.Log(r, fmt.Sprintf("Failed kernelspecs API call: %q", errorMsg))
			return
		}
		respBytes, err := unifiedKernelSpecs.MarshalJSON()
		if err != nil {
			errorMsg := fmt.Sprintf("failure marshalling the kernelspecs collection: %v", err)
			http.Error(w, errorMsg, util.HTTPStatusCode(err))
			util.Log(r, fmt.Sprintf("Failed kernelspecs API call: %q", errorMsg))
			return
		}
		w.Write(respBytes)
	})
}