Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

format whatsapp number for brazilian rules #201

Open
wants to merge 1 commit into
base: main
Choose a base branch
from

Conversation

iagocotta
Copy link

Context

  • Adicionado variáveis para controle da sincronização de Mídias e Histórico (IgnoreExtractMedia e IgnoreExtractHistory) na pasta storages (útil quando não se deseja receber as mídias do telefone, utilizando apenas o envio da ferramenta);

  • Adicionado variavel "NumberFormatLocale" para definição do formato do número do whatsapp (Criado tratamento para a regra númerica do Brazil com e sem o digito 9

  • Criada função NumberFormatLocale (\src\views\components\funcoes.js) e NumberFormatLocale (\src\pkg\utils\general.go) para validar o formato por região. Adicionado tratamento apenas para o Brazil, mas basta adicionar outras localidades de acordo com as regras do número whatsapp da região.

Se informado no arquivo "\src\config\settings.go" para a variavel NumberFormatLocale = "" não interfere em nada no fluxo atual para outras regiões, se utilizado NumberFormatLocale = "Brazil" o tratamento para o Brazil é aplicado tanto no front quando via requisições na API

Copy link
Contributor

coderabbitai bot commented Oct 10, 2024

Walkthrough

The changes in this pull request introduce several enhancements across multiple files. Notably, new global variables and functions are added to manage configuration settings related to media synchronization and number formatting. The NumberFormatLocale function is implemented to format phone numbers based on locale settings, affecting various components and methods that handle phone numbers. Additionally, HTTP request handling is established through new endpoints, allowing for better integration and response management.

Changes

File Change Summary
src/config/settings.go Added import statements, new global variables (IgnoreExtractMedia, IgnoreExtractHistory, NumberFormatLocale), and two functions (envHandler, config).
src/internal/rest/send.go Enhanced phone number handling in methods (SendText, SendImage, SendFile, SendVideo, SendContact, SendLink, SendLocation, SendAudio, SendPoll) by adding formatting step using utils.NumberFormatLocale.
src/pkg/utils/general.go Introduced NumberFormatLocale function for locale-based phone number formatting and added import for config.
src/pkg/whatsapp/whatsapp.go Added conditional checks for config.IgnoreExtractMedia and config.IgnoreExtractHistory in relevant functions.
src/views/components/*.js Updated phone_id computed property in multiple components (AccountAvatar, AccountUserInfo, MessageDelete, MessageReact, MessageRevoke, MessageUpdate, SendAudio, SendContact, SendFile, SendImage, SendLocation, SendMessage, SendPoll, SendVideo) to use NumberFormatLocale for formatting phone numbers before concatenation.
src/views/components/funcoes.js Introduced getNumberFormatLocale function for fetching locale configuration and logging, and exported NumberFormatLocale function for phone number formatting.

Possibly related PRs

  • feat: login with pair code #171: The changes in src/config/settings.go regarding the new global variable NumberFormatLocale are related to the modifications in src/pkg/utils/general.go, where the NumberFormatLocale function is defined to format phone numbers based on the locale.

🐰 In the land of code, where rabbits hop,
New functions and variables, we can't stop!
Formatting numbers with care and delight,
Media and history, all set just right.
With each little change, our code grows bright! 🌟


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 7

🧹 Outside diff range and nitpick comments (19)
src/views/components/MessageRevoke.js (1)

15-15: LGTM: phone_id computed property updated correctly.

The phone_id computed property has been successfully updated to use the NumberFormatLocale function, which aligns with the PR objectives to enhance handling of WhatsApp numbers for specific formatting rules.

Consider improving readability by breaking the long line into multiple lines:

phone_id() {
    const formattedPhone = NumberFormatLocale(this.phone);
    return this.type === 'user' 
        ? `${formattedPhone}@${window.TYPEUSER}` 
        : `${formattedPhone}@${window.TYPEGROUP}`;
}
src/views/components/AccountUserInfo.js (1)

20-20: Approve change with suggestion for error handling

The modification to the phone_id computed property correctly implements the NumberFormatLocale function, aligning with the PR objectives. The existing logic for differentiating between user and group types is preserved.

However, consider adding error handling for potential exceptions that NumberFormatLocale might throw:

Consider wrapping the NumberFormatLocale call in a try-catch block to handle potential formatting errors gracefully. Here's a suggested implementation:

phone_id() {
    try {
        const formattedPhone = NumberFormatLocale(this.phone);
        return this.type === 'user' ? `${formattedPhone}@${window.TYPEUSER}` : `${formattedPhone}@${window.TYPEGROUP}`;
    } catch (error) {
        console.error('Error formatting phone number:', error);
        return this.type === 'user' ? `${this.phone}@${window.TYPEUSER}` : `${this.phone}@${window.TYPEGROUP}`;
    }
}

This approach ensures that even if NumberFormatLocale fails, the component will still function using the unformatted phone number.

src/views/components/SendAudio.js (1)

14-14: LGTM with a minor suggestion: phone_id computed property

The modification correctly applies the NumberFormatLocale function to this.phone, which aligns with the PR objectives. The conditional logic for user vs. group type is preserved.

For improved readability, consider splitting the line:

phone_id() {
    const formattedPhone = NumberFormatLocale(this.phone);
    return this.type === 'user' 
        ? `${formattedPhone}@${window.TYPEUSER}` 
        : `${formattedPhone}@${window.TYPEGROUP}`;
}

This change is optional and doesn't affect functionality.

src/views/components/MessageReact.js (1)

16-16: LGTM with suggestion: phone_id computed property update

The use of NumberFormatLocale to format the phone number in the phone_id computed property is correct and aligns with the PR objectives. However, consider adding a conditional check to apply this formatting only when the NumberFormatLocale is set to "Brazil" in the configuration. This would ensure that the formatting is applied selectively based on the locale settings.

Example:

phone_id() {
    const formattedPhone = window.NumberFormatLocale === 'Brazil' ? NumberFormatLocale(this.phone) : this.phone;
    return this.type === 'user' ? `${formattedPhone}@${window.TYPEUSER}` : `${formattedPhone}@${window.TYPEGROUP}`;
}
src/views/components/AccountAvatar.js (1)

17-17: Approve with suggestion: Ensure robust string concatenation in phone_id computed property

The modification correctly applies the NumberFormatLocale function to format the phone number before constructing the phone_id. This aligns with the PR objectives of enhancing WhatsApp number handling for Brazilian formatting rules.

However, to improve robustness, consider ensuring that the result of NumberFormatLocale is always a string before concatenation.

Consider modifying the line as follows:

return this.type === 'user' ? `${String(NumberFormatLocale(this.phone))}@${window.TYPEUSER}` : `${String(NumberFormatLocale(this.phone))}@${window.TYPEGROUP}`

This change ensures that even if NumberFormatLocale returns a non-string value (e.g., undefined or null), it will be converted to a string before concatenation, preventing potential runtime errors.

src/views/components/SendContact.js (1)

16-16: LGTM: phone_id computed property updated with NumberFormatLocale

The phone_id computed property has been correctly updated to use the NumberFormatLocale function for formatting phone numbers. This change aligns with the PR objectives and should enhance WhatsApp number handling for Brazilian formatting rules.

For improved readability, consider extracting the formatted phone number to a separate variable:

phone_id() {
    const formattedPhone = NumberFormatLocale(this.phone);
    return this.type === 'user' ? `${formattedPhone}@${window.TYPEUSER}` : `${formattedPhone}@${window.TYPEGROUP}`;
}

This change would make the code more readable and reduce repetition.

src/views/components/SendMessage.js (1)

16-16: LGTM: phone_id computed property updated with NumberFormatLocale

The phone_id computed property has been correctly updated to use the NumberFormatLocale function, which aligns with the PR objectives of formatting WhatsApp numbers according to specific rules (e.g., Brazilian format).

For improved readability, consider extracting the formatted phone number to a separate variable:

phone_id() {
    const formattedPhone = NumberFormatLocale(this.phone);
    return this.type === 'user' ? `${formattedPhone}@${window.TYPEUSER}` : `${formattedPhone}@${window.TYPEGROUP}`;
}

This change would make the code more readable and reduce repetition.

src/views/components/SendFile.js (1)

Line range hint 1-21: Summary: Changes align with PR objectives, consider additional locale-specific enhancements

The changes in this file successfully implement the use of NumberFormatLocale for formatting WhatsApp numbers, which aligns with the PR objectives. The implementation is correct and enhances the handling of both user and group phone numbers.

To further improve the implementation:

  1. Consider adding a check for the 'Brazil' locale in the phone_id computed property to ensure the formatting is only applied when necessary.
  2. It might be beneficial to add unit tests for the phone_id computed property to verify its behavior with different locales and phone number formats.

These enhancements would ensure that the implementation fully meets the PR objectives and maintains flexibility for future locale-specific requirements.

src/views/components/SendPoll.js (1)

18-18: LGTM: phone_id computed property updated with NumberFormatLocale

The modification to apply NumberFormatLocale to this.phone in the phone_id computed property is correct and aligns with the PR objectives. This change ensures that phone numbers are formatted according to the specified locale rules before being used.

For improved readability, consider extracting the formatted phone number to a separate variable:

phone_id() {
    const formattedPhone = NumberFormatLocale(this.phone);
    return this.type === 'user' ? `${formattedPhone}@${window.TYPEUSER}` : `${formattedPhone}@${window.TYPEGROUP}`;
}

This suggestion is optional and aims to enhance code clarity.

src/views/components/SendImage.js (1)

18-18: LGTM: Phone number formatting is correctly implemented.

The use of NumberFormatLocale function to format the phone number aligns with the PR objectives and should improve number handling for Brazilian users without affecting other locales.

Consider improving readability by breaking the line into multiple lines:

phone_id() {
  const formattedPhone = NumberFormatLocale(this.phone);
  const suffix = this.type === 'user' ? window.TYPEUSER : window.TYPEGROUP;
  return `${formattedPhone}@${suffix}`;
}

This change would make the code easier to read and maintain.

src/views/components/SendVideo.js (1)

24-24: LGTM: phone_id computed property updated with NumberFormatLocale

The phone_id computed property has been correctly updated to use the NumberFormatLocale function for formatting the phone number. This change aligns with the PR objectives to implement number formatting based on locale settings.

For improved readability, consider extracting the formatted phone number to a separate variable:

phone_id() {
    const formattedPhone = NumberFormatLocale(this.phone);
    return this.type === 'user' ? `${formattedPhone}@${window.TYPEUSER}` : `${formattedPhone}@${window.TYPEGROUP}`;
}

This minor refactoring would make the code slightly more readable and easier to maintain.

src/internal/rest/send.go (2)

33-34: LGTM! Consider adding error handling for NumberFormatLocale.

The addition of utils.NumberFormatLocale aligns with the PR objectives for formatting WhatsApp numbers. The order of operations (format then sanitize) is logical.

Consider adding error handling for NumberFormatLocale if it can return an error:

formattedPhone, err := utils.NumberFormatLocale(request.Phone)
if err != nil {
    return c.Status(fiber.StatusBadRequest).JSON(utils.ResponseData{
        Status:  400,
        Code:    "BAD_REQUEST",
        Message: "Invalid phone number format",
    })
}
request.Phone = formattedPhone

Line range hint 1-215: Consider refactoring to reduce code duplication.

The phone number formatting and sanitization logic is repeated across all methods. Consider extracting this logic into a separate function to reduce code duplication and improve maintainability.

Here's a suggested refactoring:

  1. Create a new function in the Send struct:
func (controller *Send) formatAndSanitizePhone(phone string) (string, error) {
    formattedPhone, err := utils.NumberFormatLocale(phone)
    if err != nil {
        return "", err
    }
    whatsapp.SanitizePhone(&formattedPhone)
    return formattedPhone, nil
}
  1. Replace the repeated logic in each method with a call to this new function:
formattedPhone, err := controller.formatAndSanitizePhone(request.Phone)
if err != nil {
    return c.Status(fiber.StatusBadRequest).JSON(utils.ResponseData{
        Status:  400,
        Code:    "BAD_REQUEST",
        Message: "Invalid phone number format",
    })
}
request.Phone = formattedPhone

This refactoring will centralize the phone number processing logic, making it easier to maintain and update in the future.

src/pkg/whatsapp/whatsapp.go (3)

285-301: LGTM with a minor style suggestion.

The addition of the IgnoreExtractHistory flag is a good improvement, allowing more control over the history sync process. This aligns well with the PR objectives.

Consider adjusting the brace placement for consistency with Go style guidelines:

-if !config.IgnoreExtractHistory{
+if !config.IgnoreExtractHistory {

459-498: LGTM with a minor indentation suggestion.

The addition of the IgnoreExtractMedia flag is a valuable improvement, providing more control over the media extraction process. This aligns well with the PR objectives.

Consider adjusting the indentation of the entire block inside the new condition for better readability:

 if !config.IgnoreExtractMedia {
-		if mediaFile == nil {
-			logrus.Info("Skip download because data is nil")
-			return extractedMedia, nil
-		}
+	if mediaFile == nil {
+		logrus.Info("Skip download because data is nil")
+		return extractedMedia, nil
+	}
 	
-		data, err := cli.Download(mediaFile)
-		if err != nil {
-			return extractedMedia, err
-		}
+	data, err := cli.Download(mediaFile)
+	if err != nil {
+		return extractedMedia, err
+	}
 	
-		switch media := mediaFile.(type) {
-		case *waE2E.ImageMessage:
-			extractedMedia.MimeType = media.GetMimetype()
-			extractedMedia.Caption = media.GetCaption()
-		case *waE2E.AudioMessage:
-			extractedMedia.MimeType = media.GetMimetype()
-		case *waE2E.VideoMessage:
-			extractedMedia.MimeType = media.GetMimetype()
-			extractedMedia.Caption = media.GetCaption()
-		case *waE2E.StickerMessage:
-			extractedMedia.MimeType = media.GetMimetype()
-		case *waE2E.DocumentMessage:
-			extractedMedia.MimeType = media.GetMimetype()
-			extractedMedia.Caption = media.GetCaption()
-		}
+	switch media := mediaFile.(type) {
+	case *waE2E.ImageMessage:
+		extractedMedia.MimeType = media.GetMimetype()
+		extractedMedia.Caption = media.GetCaption()
+	case *waE2E.AudioMessage:
+		extractedMedia.MimeType = media.GetMimetype()
+	case *waE2E.VideoMessage:
+		extractedMedia.MimeType = media.GetMimetype()
+		extractedMedia.Caption = media.GetCaption()
+	case *waE2E.StickerMessage:
+		extractedMedia.MimeType = media.GetMimetype()
+	case *waE2E.DocumentMessage:
+		extractedMedia.MimeType = media.GetMimetype()
+		extractedMedia.Caption = media.GetCaption()
+	}
 	
-		var extension string
-		if ext, err := mime.ExtensionsByType(extractedMedia.MimeType); err != nil && len(ext) > 0 {
-			extension = ext[0]
-		} else if parts := strings.Split(extractedMedia.MimeType, "/"); len(parts) > 1 {
-			extension = "." + parts[len(parts)-1]
-		}
+	var extension string
+	if ext, err := mime.ExtensionsByType(extractedMedia.MimeType); err != nil && len(ext) > 0 {
+		extension = ext[0]
+	} else if parts := strings.Split(extractedMedia.MimeType, "/"); len(parts) > 1 {
+		extension = "." + parts[len(parts)-1]
+	}
 	
-		extractedMedia.MediaPath = fmt.Sprintf("%s/%d-%s%s", storageLocation, time.Now().Unix(), uuid.NewString(), extension)
-		err = os.WriteFile(extractedMedia.MediaPath, data, 0600)
-		if err != nil {
-			return extractedMedia, err
-		}
-	}		
+	extractedMedia.MediaPath = fmt.Sprintf("%s/%d-%s%s", storageLocation, time.Now().Unix(), uuid.NewString(), extension)
+	err = os.WriteFile(extractedMedia.MediaPath, data, 0600)
+	if err != nil {
+		return extractedMedia, err
+	}
+ }		

Line range hint 1-498: Overall, the changes look good and align well with the PR objectives.

The implementation of IgnoreExtractHistory and IgnoreExtractMedia flags provides the desired control over media and history synchronization. These additions allow the tool to function solely for sending messages when media extraction from the phone is not desired, as mentioned in the PR objectives.

The changes are implemented correctly and don't introduce any logical errors. Only minor style and indentation issues were noted in the previous comments.

Consider adding logging statements when media or history extraction is skipped due to the new configuration flags. This would improve debugging and provide better visibility into the application's behavior based on these settings.

src/views/components/funcoes.js (1)

6-6: Remove unnecessary console log

The console.log(config.NumberFormatLocale); statement is primarily for debugging purposes. It may not be necessary in production code.

Consider removing or commenting out the console log:

-        console.log(config.NumberFormatLocale); 
src/config/settings.go (2)

33-35: Enhance clarity of comments for configuration variables

The comments for IgnoreExtractMedia, IgnoreExtractHistory, and NumberFormatLocale can be improved for better readability and understanding.

Apply this diff to improve the comments:

-IgnoreExtractMedia                = false // Skip sync media to storages folder (jpg ...)
-IgnoreExtractHistory              = false // Skip sync history to storages folder
-NumberFormatLocale                = "" // Empty to maintain the current process or "Brazil" to use the WhatsApp number pattern for the country
+IgnoreExtractMedia                = false // Set to true to skip syncing media files (e.g., JPG) to the storages folder
+IgnoreExtractHistory              = false // Set to true to skip syncing chat history to the storages folder
+NumberFormatLocale                = ""    // Leave empty to maintain current behavior or set to "Brazil" to apply Brazilian WhatsApp number formatting rules

38-38: Correct the typo in the comment

The comment refers to NumberFormatLocal, but the variable is NumberFormatLocale.

Apply this diff to fix the typo:

-func envHandler(w http.ResponseWriter, r *http.Request) { // exposes the NumberFormatLocal variable for use in JS functions 
+func envHandler(w http.ResponseWriter, r *http.Request) { // exposes the NumberFormatLocale variable for use in JS functions 
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 661a7ce and 4a6d4d7.

📒 Files selected for processing (19)
  • src/config/settings.go (2 hunks)
  • src/internal/rest/send.go (9 hunks)
  • src/pkg/utils/general.go (2 hunks)
  • src/pkg/whatsapp/whatsapp.go (2 hunks)
  • src/views/components/AccountAvatar.js (2 hunks)
  • src/views/components/AccountUserInfo.js (2 hunks)
  • src/views/components/MessageDelete.js (2 hunks)
  • src/views/components/MessageReact.js (2 hunks)
  • src/views/components/MessageRevoke.js (2 hunks)
  • src/views/components/MessageUpdate.js (2 hunks)
  • src/views/components/SendAudio.js (2 hunks)
  • src/views/components/SendContact.js (2 hunks)
  • src/views/components/SendFile.js (2 hunks)
  • src/views/components/SendImage.js (2 hunks)
  • src/views/components/SendLocation.js (2 hunks)
  • src/views/components/SendMessage.js (2 hunks)
  • src/views/components/SendPoll.js (2 hunks)
  • src/views/components/SendVideo.js (2 hunks)
  • src/views/components/funcoes.js (1 hunks)
🧰 Additional context used
🔇 Additional comments (38)
src/pkg/utils/general.go (1)

5-5: LGTM: New import added correctly.

The import for the config package is correctly added and is necessary for accessing the NumberFormatLocale variable used in the new function.

src/views/components/MessageRevoke.js (2)

1-1: LGTM: Import statement for NumberFormatLocale is correct.

The import statement for NumberFormatLocale from './funcoes.js' is correctly placed and aligns with the PR objectives to introduce number formatting for different locales.


Line range hint 1-15: Verify the impact of NumberFormatLocale on application behavior.

The introduction of NumberFormatLocale in this component is a good step towards consistent phone number formatting. However, it's important to ensure that this change doesn't negatively impact the existing functionality of the application.

Please run the following script to check for any inconsistencies in phone number formatting across the application:

This script will help identify any areas where the new NumberFormatLocale function should be used but might have been overlooked, ensuring consistency across the application.

src/views/components/AccountUserInfo.js (1)

1-1: LGTM: Import statement for NumberFormatLocale

The import statement for NumberFormatLocale from './funcoes.js' is correctly implemented and aligns with the PR objectives of introducing number formatting functionality.

src/views/components/MessageDelete.js (2)

1-1: LGTM: Import statement for NumberFormatLocale

The import statement correctly introduces the NumberFormatLocale function from the local 'funcoes.js' file. This aligns with the PR objectives and is necessary for the subsequent use in the component.


15-15: LGTM: Phone number formatting applied

The modification correctly applies the NumberFormatLocale function to format the phone number before constructing the phone_id. This change aligns with the PR objectives for handling Brazilian number formats.

Please ensure that the NumberFormatLocale function in funcoes.js handles non-Brazilian numbers appropriately, maintaining the existing behavior for other locales when NumberFormatLocale in the configuration is not set to "Brazil".

To verify this, you can run the following script:

This script will help ensure that the NumberFormatLocale function is implemented correctly and handles non-Brazilian numbers appropriately.

✅ Verification successful
<!-- [monologue]
[task verification/1]
Review the output of the shell scripts regarding the NumberFormatLocale function.
[observations]
- The `NumberFormatLocale` function is defined in `src/views/components/funcoes.js` starting at line 12.
- The function checks if the locale is "Brazil" and applies specific formatting; otherwise, it returns the number unchanged.
- The shell script confirmed that there is a condition handling the "Brazil" locale and an else case that returns the number as is.
[analysis]
- The modification introduced the `NumberFormatLocale` function to format phone numbers for Brazilian locale.
- For non-Brazilian locales, the function maintains the original behavior by returning the number without formatting.
- This ensures that existing functionality is preserved for all other locales, addressing the reviewer's concern.
[actions]
- Since the `NumberFormatLocale` function correctly handles both Brazilian and non-Brazilian numbers, the verification is successful.
- No further scripts are necessary.
-->

Verified: NumberFormatLocale handles non-Brazilian numbers correctly

The NumberFormatLocale function effectively formats Brazilian phone numbers while maintaining the original behavior for non-Brazilian numbers. This ensures consistency across different locales as intended.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the implementation of NumberFormatLocale function

# Test: Check the implementation of NumberFormatLocale in funcoes.js
echo "Checking NumberFormatLocale implementation in funcoes.js:"
ast-grep --lang javascript --pattern 'function NumberFormatLocale($_) { $$$ }'

# Test: Check if there's a condition for handling non-Brazilian numbers
echo "Checking for non-Brazilian number handling:"
rg --type js 'NumberFormatLocale.*Brazil' src/views/components/funcoes.js

Length of output: 1237

src/views/components/SendAudio.js (2)

1-1: LGTM: Import statement for NumberFormatLocale

The import statement for NumberFormatLocale from './funcoes.js' is correctly placed and aligns with the PR objectives of introducing number formatting functionality.


Line range hint 1-14: Verify NumberFormatLocale implementation

The changes introduce number formatting for WhatsApp numbers, which aligns with the PR objectives. However, to ensure full compliance with the stated goals:

  1. Verify that the NumberFormatLocale function in './funcoes.js' correctly implements the Brazilian formatting rules.
  2. Confirm that it handles both formats with and without the digit '9' for Brazilian numbers.
  3. Ensure that it doesn't affect number formatting for other regions when not set to "Brazil".

To assist with this verification, you can run the following script:

This script will help verify the implementation details of NumberFormatLocale and ensure it meets the requirements specified in the PR objectives.

✅ Verification successful

NumberFormatLocale Implementation Verified

The NumberFormatLocale function in ./funcoes.js correctly implements the Brazilian formatting rules as intended:

  1. Brazil-Specific Logic: The function checks for the "Brazil" locale and prefixes numbers with '55' if necessary.
  2. Handling Digit '9': It properly handles cases where the fifth digit is '9' for numbers with a length of 13, ensuring accurate formatting.
  3. Non-Impact on Other Regions: The implementation ensures that number formatting for other regions remains unaffected when the locale is not set to "Brazil".
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the implementation of NumberFormatLocale

# Test: Check the implementation of NumberFormatLocale in funcoes.js
echo "Checking NumberFormatLocale implementation:"
ast-grep --lang javascript --pattern $'export function NumberFormatLocale($_) {
  $$$
}'

# Test: Check for Brazil-specific logic
echo "Checking for Brazil-specific logic:"
rg --type js "Brazil" ./src/views/components/funcoes.js

# Test: Check for handling of digit '9'
echo "Checking for handling of digit '9':"
rg --type js "9" ./src/views/components/funcoes.js

Length of output: 1377

src/views/components/MessageReact.js (2)

1-1: LGTM: Import statement for NumberFormatLocale

The import of NumberFormatLocale from './funcoes.js' is correctly placed and aligns with the PR objectives to enhance WhatsApp number formatting.


Line range hint 1-138: Overall impact assessment and suggestion for additional features

The changes to this component effectively implement the number formatting feature for WhatsApp numbers, aligning with the PR objectives. The modifications are minimal and focused, which is good for maintainability and reduces the risk of unintended side effects.

However, I noticed that the new configuration variables mentioned in the PR objectives (IgnoreExtractMedia and IgnoreExtractHistory) are not utilized in this component. Consider if these variables should be incorporated into this component's logic, especially if they affect message reactions or the display of messages.

To ensure that these configuration variables are properly implemented elsewhere in the codebase, you may want to run the following verification script:

This will help confirm that these new configuration variables are being used appropriately in the codebase.

src/views/components/AccountAvatar.js (2)

1-1: LGTM: Import statement for NumberFormatLocale

The import statement for NumberFormatLocale from ./funcoes.js is correctly added. This aligns with the PR objectives of introducing number formatting based on locale.


Line range hint 1-17: Overall impact: Consider updating related tests

The changes to import NumberFormatLocale and use it in the phone_id computed property align well with the PR objectives. They enhance the handling of WhatsApp numbers for Brazilian formatting rules without significantly altering the component's structure or behavior.

However, these changes may impact how phone numbers are displayed and used in API calls.

To ensure the changes don't introduce any regressions:

  1. Please verify that any existing unit tests for this component are updated to reflect the new number formatting behavior.
  2. Consider adding new test cases that specifically check the formatting for Brazilian phone numbers.

Run the following script to check for existing tests related to this component:

If test files are found, please review and update them accordingly.

src/views/components/SendLocation.js (3)

1-1: LGTM: Import statement is correct and necessary.

The import of NumberFormatLocale from './funcoes.js' is correctly formatted and is required for the changes in the phone_id computed property.


Line range hint 1-16: Overall impact: Enhanced locale-specific phone number handling.

The changes to this component improve its ability to handle phone number formatting based on locale settings, specifically addressing the PR objective for Brazilian number formatting. The modifications are well-contained and don't affect other parts of the component.

To ensure the changes don't negatively impact existing functionality:

  1. Test the component with Brazilian phone numbers to confirm correct formatting.
  2. Verify that the component still works correctly for non-Brazilian locales.
  3. Check that the NumberFormatLocale function in funcoes.js gracefully handles undefined or empty locale settings.

Consider adding unit tests for the phone_id computed property to cover various locale scenarios.


16-16: LGTM: Phone number formatting enhanced, but verify non-Brazilian locales.

The modification to apply NumberFormatLocale to this.phone aligns with the PR objective of enhancing WhatsApp number handling for Brazilian formatting rules. This change improves the flexibility of phone number formatting based on locale settings.

Please ensure that the NumberFormatLocale function in funcoes.js handles non-Brazilian locales correctly, maintaining existing functionality for other regions. Run the following script to verify the implementation:

src/views/components/MessageUpdate.js (2)

1-1: LGTM: Import statement correctly added.

The import of NumberFormatLocale from ./funcoes.js is correctly placed and will be used in the phone_id computed property.


16-16: Approve change with a suggestion for verification.

The modification to use NumberFormatLocale for formatting phone numbers aligns with the PR objectives. However, it's important to ensure that this change doesn't negatively impact non-Brazilian locales.

Please verify that the NumberFormatLocale function in funcoes.js handles non-Brazilian locales appropriately, possibly by returning the original number format when the locale is not set to Brazil.

✅ Verification successful

Approve change.

The NumberFormatLocale function correctly returns the original number format for non-Brazilian locales, ensuring consistency across different regions.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the implementation of NumberFormatLocale function

# Test: Check the implementation of NumberFormatLocale
ast-grep --lang javascript --pattern $'export function NumberFormatLocale($_) {
  $$$
}'

Length of output: 901

src/views/components/SendContact.js (2)

1-1: LGTM: Import statement for NumberFormatLocale

The import statement for NumberFormatLocale is correctly placed and aligns with the PR objectives of introducing number formatting for Brazilian rules.


Line range hint 1-16: Verify NumberFormatLocale implementation and its impact on other locales

The changes look good and align with the PR objectives. However, it's important to verify a few things:

  1. The implementation of NumberFormatLocale in funcoes.js to ensure it correctly handles Brazilian number formatting.
  2. The impact of these changes on other locales, ensuring that non-Brazilian numbers are not affected.

To assist with this verification, you can run the following script:

This script will help verify the implementation of NumberFormatLocale and its usage across the codebase, ensuring that it's correctly handling Brazilian numbers without affecting other locales.

✅ Verification successful

NumberFormatLocale implementation verified and correctly handles other locales

The implementation of NumberFormatLocale in funcoes.js appropriately formats Brazilian numbers without affecting other locales. All usages across the codebase are consistent and adhere to the intended locale-specific logic.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify NumberFormatLocale implementation and its usage

# Test 1: Check the implementation of NumberFormatLocale in funcoes.js
echo "Checking NumberFormatLocale implementation:"
ast-grep --lang javascript --pattern $'export function NumberFormatLocale($_) {
  $$$
}'

# Test 2: Check for any conditional logic related to locales in NumberFormatLocale
echo "Checking for locale-specific logic in NumberFormatLocale:"
rg --type js "NumberFormatLocale.*Brazil" ./src

# Test 3: Check for any other usages of NumberFormatLocale in the codebase
echo "Checking for other usages of NumberFormatLocale:"
rg --type js "NumberFormatLocale" ./src

Length of output: 5657

src/views/components/SendMessage.js (2)

1-1: LGTM: Import statement for NumberFormatLocale

The import statement for NumberFormatLocale from './funcoes.js' is correctly placed and aligns with the PR objectives of introducing number formatting functionality.


Line range hint 1-16: Verify consistency of number formatting across the application

The changes to introduce NumberFormatLocale in this component are well-implemented. However, it's important to ensure that this formatting is consistently applied across the entire application wherever phone numbers are used.

Please run the following script to check for other occurrences of phone number handling that might need similar updates:

Review the results to ensure that all relevant places are updated with the new NumberFormatLocale function for consistency.

✅ Verification successful

Consistency of phone number formatting is verified across the application.

All relevant components utilize NumberFormatLocale for handling phone numbers, ensuring consistent formatting throughout the codebase.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Search for potential phone number handling in other components and files

# Test: Search for phone number-related variables or methods
echo "Searching for phone number-related code:"
rg --type js --type vue 'phone|number|telefone|número' src/

# Test: Search for potential formatting of phone numbers
echo "\nSearching for potential phone number formatting:"
rg --type js --type vue 'format.*phone|phone.*format' src/

Length of output: 380


Script:

#!/bin/bash
# Description: Search for potential phone number handling in .js and .vue files

# Test: Search for phone number-related variables or methods
echo "Searching for phone number-related code in .js and .vue files:"
rg -g '*.js' -g '*.vue' 'phone|number|telefone|número' src/

# Test: Search for potential formatting of phone numbers
echo "\nSearching for potential phone number formatting in .js and .vue files:"
rg -g '*.js' -g '*.vue' 'format.*phone|phone.*format' src/

Length of output: 13371

src/views/components/SendFile.js (2)

1-1: LGTM: Import statement for NumberFormatLocale

The import statement for NumberFormatLocale from './funcoes.js' is correctly added. This aligns with the PR objectives to implement number formatting based on locale.


21-21: Approve with suggestion: Verify locale-specific behavior in phone_id computed property

The implementation of NumberFormatLocale in the phone_id computed property is correct and aligns with the PR objectives. It enhances WhatsApp number handling for both user and group types.

However, consider adding a check for the 'Brazil' locale to ensure the formatting is only applied when necessary. This would align more closely with the PR objective of specifically handling Brazilian formatting rules.

To verify the implementation of NumberFormatLocale and its usage, please run the following script:

This script will help us understand how NumberFormatLocale is implemented and used across the codebase, and whether there's any Brazil-specific logic that we might need to consider.

✅ Verification successful

Verification Successful: Locale-specific behavior is correctly implemented

The implementation of NumberFormatLocale in the phone_id computed property correctly handles the 'Brazil' locale as intended. The function ensures proper formatting for Brazilian phone numbers, and its usage across various components is consistent.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the implementation and usage of NumberFormatLocale

# Test 1: Check the implementation of NumberFormatLocale in funcoes.js
echo "Checking NumberFormatLocale implementation:"
ast-grep --lang javascript --pattern 'function NumberFormatLocale($_) { $$$ }' src/views/components/funcoes.js

# Test 2: Verify the usage of NumberFormatLocale in other components
echo "Checking NumberFormatLocale usage in other components:"
rg --type js 'NumberFormatLocale\(' src/views/components/

# Test 3: Check for any locale-specific logic in the codebase
echo "Checking for locale-specific logic:"
rg --type js 'NumberFormatLocale.*Brazil' src/

Length of output: 4314

src/views/components/SendPoll.js (2)

1-1: LGTM: Import statement for NumberFormatLocale

The import statement for NumberFormatLocale from ./funcoes.js is correctly implemented and aligns with the PR objectives to introduce number formatting for Brazilian rules.


Line range hint 1-18: Summary: Successfully implemented NumberFormatLocale for phone number formatting

The changes in this file successfully introduce the NumberFormatLocale function for formatting phone numbers, which aligns with the PR objectives to enhance handling of WhatsApp numbers for Brazilian formatting rules. The implementation is correct and maintains the existing functionality while adding the new formatting feature.

Key points:

  1. The NumberFormatLocale function is properly imported.
  2. The phone_id computed property now applies the formatting function to the phone number.
  3. The changes are non-breaking and integrate well with the existing code structure.

These modifications improve the flexibility of the component to handle different number formats based on locale settings.

src/views/components/SendImage.js (2)

1-1: LGTM: Import statement is correctly added.

The import of NumberFormatLocale from ./funcoes.js is properly placed and necessary for the changes in the phone_id computed property.


Line range hint 1-18: Consider updating tests and documentation.

The changes to the phone_id computed property improve number formatting without affecting the overall functionality of the component. However, it's important to ensure that these changes are reflected in any existing tests and documentation.

Please run the following script to check for any existing tests related to this component:

If tests exist, please update them to account for the new number formatting logic. Also, consider updating any relevant documentation to reflect these changes.

src/views/components/SendVideo.js (2)

1-1: LGTM: Import statement for NumberFormatLocale

The import of NumberFormatLocale from './funcoes.js' is correctly added and aligns with the PR objectives to implement number formatting based on locale.


Line range hint 1-24: Summary: Successful implementation of number formatting in SendVideo component

The changes in this file successfully implement the number formatting feature for WhatsApp numbers as described in the PR objectives. The NumberFormatLocale function is imported and correctly applied in the phone_id computed property, ensuring that phone numbers are formatted according to the specified locale before being used.

These changes enhance the flexibility of the component, allowing it to handle different number formats based on locale settings. The implementation is non-intrusive and maintains compatibility with existing functionality for other regions when no specific locale is set.

Overall, the modifications align well with the PR's goals and improve the component's ability to handle region-specific number formatting requirements.

src/internal/rest/send.go (8)

58-59: Consistent implementation of phone number formatting.

The changes in this method are consistent with those in SendText.

Please refer to the comment on SendText regarding error handling for NumberFormatLocale.


81-82: Consistent implementation of phone number formatting.

The changes in this method are consistent with those in previous methods.

Please refer to the comment on SendText regarding error handling for NumberFormatLocale.


104-105: Consistent implementation of phone number formatting.

The changes in this method are consistent with those in previous methods.

Please refer to the comment on SendText regarding error handling for NumberFormatLocale.


123-124: Consistent implementation of phone number formatting.

The changes in this method are consistent with those in previous methods.

Please refer to the comment on SendText regarding error handling for NumberFormatLocale.


142-143: Consistent implementation of phone number formatting.

The changes in this method are consistent with those in previous methods.

Please refer to the comment on SendText regarding error handling for NumberFormatLocale.


161-162: Consistent implementation of phone number formatting.

The changes in this method are consistent with those in previous methods.

Please refer to the comment on SendText regarding error handling for NumberFormatLocale.


184-185: Consistent implementation of phone number formatting.

The changes in this method are consistent with those in previous methods.

Please refer to the comment on SendText regarding error handling for NumberFormatLocale.


203-204: Consistent implementation of phone number formatting.

The changes in this method are consistent with those in previous methods.

Please refer to the comment on SendText regarding error handling for NumberFormatLocale.

src/views/components/funcoes.js (1)

14-16: Ensure proper handling of international prefixes

When adding the country code prefix '55', make sure the number does not already include a '+' sign or other international prefixes. This prevents potential duplication or formatting issues.

Consider enhancing the validation to handle different number formats and prefixes. Let me know if you'd like assistance in implementing this.

Comment on lines +114 to +132
func NumberFormatLocale(number string) string {

if config.NumberFormatLocale == "Brazil" {
if strings.HasSuffix(number, "@s.whatsapp.net") {
number = strings.TrimSuffix(number, "@s.whatsapp.net")
}

if !strings.HasPrefix(number, "55") {
number = "55" + number
}

if len(number) == 13 && number[4] == '9' {
return number[:4] + number[5:]
}
return number
}else{
return number
}
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

⚠️ Potential issue

Improve number formatting logic and add input validation.

The NumberFormatLocale function has a good start, but there are some areas for improvement:

  1. Input validation is missing. Consider adding checks for the input number format.
  2. The function assumes all Brazilian numbers should start with "55". This might not always be the case for local calls.
  3. The removal of '9' might not be applicable to all Brazilian number formats. This logic needs verification.
  4. The else clause on line 129 is not properly indented.

Consider refactoring the function as follows:

func NumberFormatLocale(number string) (string, error) {
    // Remove "@s.whatsapp.net" suffix if present
    number = strings.TrimSuffix(number, "@s.whatsapp.net")

    if config.NumberFormatLocale == "Brazil" {
        // Validate input
        if !strings.HasPrefix(number, "55") && !strings.HasPrefix(number, "+55") {
            return "", fmt.Errorf("invalid Brazilian number format: %s", number)
        }

        // Remove '+' if present
        number = strings.TrimPrefix(number, "+")

        // Handle different Brazilian number formats
        switch len(number) {
        case 12: // DDD + 8 digits
            return number, nil
        case 13: // DDD + 9 digits
            if number[4] != '9' {
                return "", fmt.Errorf("invalid Brazilian mobile number format: %s", number)
            }
            return number[:4] + number[5:], nil
        default:
            return "", fmt.Errorf("invalid number length for Brazilian format: %s", number)
        }
    }

    return number, nil
}

This refactored version:

  • Adds input validation
  • Handles different Brazilian number formats
  • Returns an error for invalid inputs
  • Properly formats the number based on Brazilian rules

Don't forget to update the function calls to handle the returned error.

@@ -11,7 +13,7 @@ export default {
},
computed: {
phone_id() {
return this.type === 'user' ? `${this.phone}@${window.TYPEUSER}` : `${this.phone}@${window.TYPEGROUP}`
return this.type === 'user' ? `${NumberFormatLocale(this.phone)}@${window.TYPEUSER}` : `${NumberFormatLocale(this.phone)}@${window.TYPEGROUP}`
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Consider adding error handling and input validation.

While the changes implement the required functionality, consider adding error handling and input validation for the phone property. This could prevent potential issues with invalid phone numbers or unexpected input.

Here's a suggested implementation:

phone_id() {
  if (!this.phone || typeof this.phone !== 'string') {
    console.warn('Invalid phone number');
    return '';
  }
  const formattedPhone = NumberFormatLocale(this.phone);
  return this.type === 'user' 
    ? `${formattedPhone}@${window.TYPEUSER}` 
    : `${formattedPhone}@${window.TYPEGROUP}`;
}

Comment on lines +1 to +10
async function getNumberFormatLocale() {
try {
const response = await fetch('/api/config');
const config = await response.json();

console.log(config.NumberFormatLocale);
} catch (error) {
console.error('Error fetching the config:', error);
}
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Consider caching the locale value to improve performance

Fetching the configuration from the server every time NumberFormatLocale is called can be inefficient, especially if this function is called frequently. Consider storing the locale value after the first fetch and reusing it in subsequent calls.

Example implementation:

let cachedLocale = null;

async function getNumberFormatLocale() {
    if (cachedLocale !== null) {
        return cachedLocale;
    }
    try {
        const response = await fetch('/api/config'); 
        const config = await response.json();
        cachedLocale = config.NumberFormatLocale;
        return cachedLocale;
    } catch (error) {
        console.error('Error fetching the config:', error);
        return null;
    }
}

⚠️ Potential issue

Function getNumberFormatLocale should return the locale value

Currently, getNumberFormatLocale fetches the locale configuration but does not return it. As a result, when it's used in NumberFormatLocale(number), it does not provide the required locale value.

Apply this diff to return the locale from getNumberFormatLocale:

 async function getNumberFormatLocale() {
     try {
         const response = await fetch('/api/config'); 
         const config = await response.json();
         
+        return config.NumberFormatLocale;
     } catch (error) {
         console.error('Error fetching the config:', error);
+        return null;
     }
 }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
async function getNumberFormatLocale() {
try {
const response = await fetch('/api/config');
const config = await response.json();
console.log(config.NumberFormatLocale);
} catch (error) {
console.error('Error fetching the config:', error);
}
}
async function getNumberFormatLocale() {
try {
const response = await fetch('/api/config');
const config = await response.json();
return config.NumberFormatLocale;
} catch (error) {
console.error('Error fetching the config:', error);
return null;
}
}

Comment on lines +12 to +24
export function NumberFormatLocale(number) {
if (getNumberFormatLocale() == "Brazil") {
if (!number.startsWith('55')) {
number = '55' + number;
}

if (number.length === 13 && number[4] === '9') {
return number.slice(0, 4) + number.slice(5);
}
return number;
}
return number;
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Handle asynchronous behavior when calling getNumberFormatLocale()

getNumberFormatLocale is an asynchronous function that returns a promise. In NumberFormatLocale(number), it is being used without awaiting its result. This can lead to incorrect behavior because the comparison with "Brazil" will not work as intended.

Modify NumberFormatLocale to be an asynchronous function and await the result of getNumberFormatLocale():

-export function NumberFormatLocale(number) {
+export async function NumberFormatLocale(number) {
+    const locale = await getNumberFormatLocale();
     if (locale == "Brazil") {
         if (!number.startsWith('55')) {
             number = '55' + number;
         }
         
         if (number.length === 13 && number[4] === '9') {
             return number.slice(0, 4) + number.slice(5);
         }
         return number;
     }
     return number;
 }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
export function NumberFormatLocale(number) {
if (getNumberFormatLocale() == "Brazil") {
if (!number.startsWith('55')) {
number = '55' + number;
}
if (number.length === 13 && number[4] === '9') {
return number.slice(0, 4) + number.slice(5);
}
return number;
}
return number;
}
export async function NumberFormatLocale(number) {
const locale = await getNumberFormatLocale();
if (locale == "Brazil") {
if (!number.startsWith('55')) {
number = '55' + number;
}
if (number.length === 13 && number[4] === '9') {
return number.slice(0, 4) + number.slice(5);
}
return number;
}
return number;
}

Comment on lines +38 to +45
func envHandler(w http.ResponseWriter, r *http.Request) { // exposes the NumberFormatLocal variable for use in JS functions
response := map[string]string{
"NumberFormatLocale": NumberFormatLocale,
}

w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(response)
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Assess security implications of exposing configuration via HTTP

The envHandler function exposes configuration settings over an unauthenticated HTTP endpoint. This could lead to security vulnerabilities if sensitive information is exposed.

Consider implementing authentication for the /api/config endpoint or restricting access to trusted origins.

Comment on lines +47 to +50
func config() {
http.HandleFunc("/api/config", envHandler)
http.ListenAndServe(":"+AppPort, nil)
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Avoid starting a new HTTP server within the config() function

Starting a new HTTP server inside the config() function with http.ListenAndServe may lead to conflicts if the application already has an existing server running. It could also cause issues with port allocation and application flow.

Consider integrating the /api/config endpoint into the main application's HTTP server instead of starting a new one.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant