use client for login action
This commit is contained in:
		| @@ -52,49 +52,15 @@ func ActionLogin(c *cli.Context) error { | ||||
| 		return fmt.Errorf("error reading password: %w", err) | ||||
| 	} | ||||
|  | ||||
| 	url := fmt.Sprintf("%s/api/login", c.String("url")) | ||||
| 	client := &http.Client{} | ||||
| 	// TODO: Change timeout | ||||
| 	ctx, cancel := context.WithTimeout(c.Context, 10*time.Second) | ||||
| 	defer cancel() | ||||
|  | ||||
| 	body := new(bytes.Buffer) | ||||
| 	requestData := struct { | ||||
| 		Username string `json:"username"` | ||||
| 		Password string `json:"password"` | ||||
| 	}{ | ||||
| 		Username: username, | ||||
| 		Password: password, | ||||
| 	clnt := client.Client{ | ||||
| 		BaseURL: c.String("url"), | ||||
| 	} | ||||
| 	encoder := json.NewEncoder(body) | ||||
| 	if err := encoder.Encode(&requestData); err != nil { | ||||
| 		return fmt.Errorf("error encoding response: %w", err) | ||||
| 	if err := clnt.Login(c.Context, username, password); err != nil { | ||||
| 		errmsg := fmt.Sprintf("Error logging in: %s", err) | ||||
| 		return cli.Exit(errmsg, 1) | ||||
| 	} | ||||
| 	req, err := http.NewRequestWithContext(ctx, http.MethodPost, url, body) | ||||
| 	if err != nil { | ||||
| 		return fmt.Errorf("error creating request: %w", err) | ||||
| 	} | ||||
|  | ||||
| 	resp, err := client.Do(req) | ||||
| 	if err != nil { | ||||
| 		return fmt.Errorf("unable to perform request: %s", err) | ||||
| 	} | ||||
| 	defer resp.Body.Close() | ||||
|  | ||||
| 	if resp.StatusCode != http.StatusOK { | ||||
| 		return cli.Exit("got non-ok response from server", 0) | ||||
| 	} | ||||
|  | ||||
| 	responseData := struct { | ||||
| 		Token string `json:"token"` | ||||
| 	}{} | ||||
|  | ||||
| 	decoder := json.NewDecoder(resp.Body) | ||||
| 	if err := decoder.Decode(&responseData); err != nil { | ||||
| 		return fmt.Errorf("unable to parse response: %s", err) | ||||
| 	} | ||||
|  | ||||
| 	fmt.Printf("Token: %s", responseData.Token) | ||||
| 	// TODO: Store this somewhere, so we don't need to log in each time | ||||
| 	fmt.Println("Successfully logged in.") | ||||
|  | ||||
| 	return nil | ||||
| } | ||||
|   | ||||
		Reference in New Issue
	
	Block a user