(ctx context.Context)
| 425 | } |
| 426 | |
| 427 | func startCallbackServerWithContext(ctx context.Context) (int, <-chan AuthResponse, <-chan error, func(), error) { |
| 428 | listener, err := net.Listen("tcp", "127.0.0.1:0") |
| 429 | if err != nil { |
| 430 | return 0, nil, nil, nil, err |
| 431 | } |
| 432 | |
| 433 | port := listener.Addr().(*net.TCPAddr).Port |
| 434 | |
| 435 | authChan := make(chan AuthResponse, 1) |
| 436 | errChan := make(chan error, 1) |
| 437 | |
| 438 | mux := http.NewServeMux() |
| 439 | server := &http.Server{ |
| 440 | Handler: mux, |
| 441 | } |
| 442 | |
| 443 | mux.HandleFunc("/callback", func(w http.ResponseWriter, r *http.Request) { |
| 444 | token := r.URL.Query().Get("token") |
| 445 | refreshToken := r.URL.Query().Get("refresh_token") |
| 446 | errorParam := r.URL.Query().Get("error") |
| 447 | |
| 448 | if errorParam != "" { |
| 449 | errChan <- fmt.Errorf("authentication error: %s", errorParam) |
| 450 | w.Header().Set("Content-Type", "text/html") |
| 451 | w.WriteHeader(http.StatusUnauthorized) |
| 452 | _ = authFailedTemplate.Execute(w, map[string]string{"Error": errorParam}) //nolint:errcheck // template execution error is non-fatal |
| 453 | return |
| 454 | } |
| 455 | |
| 456 | if token == "" { |
| 457 | errChan <- fmt.Errorf("no token received") |
| 458 | w.WriteHeader(http.StatusBadRequest) |
| 459 | fmt.Fprintf(w, "No token received") |
| 460 | return |
| 461 | } |
| 462 | |
| 463 | authResp := AuthResponse{ |
| 464 | Token: token, |
| 465 | RefreshToken: refreshToken, |
| 466 | } |
| 467 | |
| 468 | authChan <- authResp |
| 469 | |
| 470 | w.Header().Set("Content-Type", "text/html") |
| 471 | _ = authSuccessTemplate.Execute(w, nil) //nolint:errcheck // template execution error is non-fatal |
| 472 | }) |
| 473 | |
| 474 | go func() { |
| 475 | if err := server.Serve(listener); err != nil && err != http.ErrServerClosed { |
| 476 | errChan <- err |
| 477 | } |
| 478 | }() |
| 479 | |
| 480 | cleanup := func() { |
| 481 | shutdownCtx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond) |
| 482 | defer cancel() |
| 483 | _ = server.Shutdown(shutdownCtx) //nolint:errcheck // shutdown error is non-fatal |
| 484 | } |
no test coverage detected