DEV Community

Cover image for Exploring Unicode with Go and Vue.js
Maicon Gavino
Maicon Gavino

Posted on

Exploring Unicode with Go and Vue.js

Unicode is a fundamental standard in modern computing, ensuring consistent representation and manipulation of text in any language, style, or even emojis. In this article, we’ll explore the Unicode standard to develop a project that converts text into bold, italic, bold/italic, and underlined styles using Golang and Vue.js, providing a practical and efficient approach to text manipulation with Unicode.

Image description

Project Structure
Backend in Golang

  • Processes requests sent from the frontend, applying transformations to the text based on Unicode table offsets.

Frontend in Vue.js

  • Provides a simple interface where users can input text, send it to the backend, and view the styled results.

File Structure

TextConvert/

├── main.go          # Código do servidor em Golang
├── go.mod           # Gerenciador de dependências do Go
└── template/
    ├── index.html   # Interface do usuário
Enter fullscreen mode Exit fullscreen mode

Backend Implementation

On the backend, we use Golang to implement a REST API that processes text. The core is the stringFormat function, which takes the input text as a string along with two integer offsets representing the Unicode shifts for uppercase and lowercase letters. The function iterates through each character in the text, applies the appropriate shifts to style alphabetic characters, and leaves other characters unchanged.

func stringFormat(input string, upperOffset, lowerOffset int) string {
 var result strings.Builder
 for _, r := range input {
  if r >= 'A' && r <= 'Z' {
   result.WriteRune(rune(int(r) - 'A' + upperOffset))
  } else if r >= 'a' && r <= 'z' {
   result.WriteRune(rune(int(r) - 'a' + lowerOffset))
  } else {
   result.WriteRune(r)
  }
 }
 return result.String()
}
Enter fullscreen mode Exit fullscreen mode

This function uses Unicode table offsets to transform alphabetic characters into their stylized equivalents.

CORS Configuration

To allow the frontend to send requests to the backend, we configure the CORS middleware on the Go server using the enableCORS function. This configuration is crucial in web applications, where the frontend and backend often operate on different domains.

func enableCORS(next http.Handler) http.Handler {
 return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  w.Header().Set("Access-Control-Allow-Origin", "*") // Permite todas as origens
  w.Header().Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE")
  w.Header().Set("Access-Control-Allow-Headers", "Content-Type")
  if r.Method == http.MethodOptions {
   w.WriteHeader(http.StatusOK)
   return
  }
  next.ServeHTTP(w, r)
 })
}
Enter fullscreen mode Exit fullscreen mode

This ensures that the browser does not block requests due to security policies (CORS).

Frontend with Vue.js

The frontend is implemented in a single index.html file, leveraging Vue.js for reactivity. It allows the user to input text, send it to the API, and view the styled results. Here’s an example of the Vue component:

 <!-- Resultado em Negrito -->
            <div class="mb-4 border rounded-lg p-4">
                <p><strong>Negrito:</strong> <span>{{ results.bold }}</span></p>
                <button @click="copyText(results.bold)" class="bg-blue-500 text-white py-1 px-4 rounded mt-2">
                    Copiar
                </button>
            </div>
Enter fullscreen mode Exit fullscreen mode

And the Vue.js method for making the request:

try {
    const response = await fetch("https://convert-1tqr.onrender.com/convert", {
        method: "POST",
        headers: {
            "Content-Type": "application/json",
        },
        body: JSON.stringify({ text: this.inputText }),
    });

    if (!response.ok) {
        throw new Error("Erro ao processar o texto.");
    }

    this.results = await response.json();
} catch (error) {
    console.error("Erro:", error);
    alert("Erro ao converter texto. Tente novamente.");
} finally {
    this.isLoading = false;
}
Enter fullscreen mode Exit fullscreen mode

This project demonstrates how to manipulate text with Unicode using Golang and Vue.js, create REST APIs, and configure integrations following best practices, such as implementing CORS.

Access the complete project via the links below:

Live Demo: Click here to test

GitHub Repository: MaiconGavino/TextConvert

If you enjoyed this article, feel free to share it or leave your feedback in the comments.

Top comments (0)