package actions import ( "context" "encoding/json" "fmt" "net/http" "time" "git.t-juice.club/microfilm/users" "github.com/urfave/cli/v2" ) func UserCreate(c *cli.Context) error { token, err := LoadToken() if err != nil { return fmt.Errorf("Unable to load token: %w", err) } username, password, err := getCreds() if err != nil { return err } ctx, cancel := context.WithTimeout(c.Context, 5*time.Second) defer cancel() body := jsonToReader(&users.CreateUserRequest{ Username: username, Password: password, }) url := "http://localhost:8085/user/" req, err := http.NewRequestWithContext(ctx, http.MethodPost, url, body) if err != nil { return err } req.Header.Add("Authorization", fmt.Sprintf("Bearer %s", token)) resp, err := http.DefaultClient.Do(req) if err != nil { return err } defer resp.Body.Close() if resp.StatusCode != http.StatusOK { var errData users.ErrorResponse decoder := json.NewDecoder(resp.Body) if err := decoder.Decode(&errData); err != nil { return fmt.Errorf("unable to decode error: %w", err) } return fmt.Errorf("error %d when authenticating: %s", errData.Status, errData.Message) } var responseData users.CreateUserResponse decoder := json.NewDecoder(resp.Body) if err := decoder.Decode(&responseData); err != nil { return err } fmt.Printf("Created user with id %s", responseData.User.ID) return nil }