Ultimate Guide to GUI Development Frameworks in Programming Languages (Open-Source Libraries)

Introduction to GUI Development in Popular Programming Languages

Graphical User Interface (GUI) development is essential for creating interactive and user-friendly applications across various platforms. Whether you’re developing desktop, mobile, or web applications, the choice of a programming language and its corresponding GUI framework can significantly impact your project’s success. This article provides a detailed overview of 80 GUI frameworks across multiple programming languages, highlighting their key features and providing official links for further exploration.

A Detailed Guide to Cross-Platform GUI Frameworks in Popular Programming Languages

1. Python

Python is widely known for its simplicity and readability, making it a popular choice for beginners and experienced developers alike. Here are some of the most popular GUI frameworks in Python:

GUI FrameworkKey FeaturesOfficial Link
TkinterBuilt-in, easy to use, lightweight, cross-platformTkinter
PyQtComprehensive, cross-platform, supports Qt Designer, commercial license availablePyQt
KivyOpen-source, cross-platform, multitouch, GPU acceleratedKivy
wxPythonNative look and feel, cross-platform, supports older versions of PythonwxPython
PyGTKGNOME-based, cross-platform, supports native Linux themesPyGTK
PySideOfficial Qt for Python, LGPL licensed, powerful, cross-platformPySide
PySimpleGUISimple to use, wraps around other GUI frameworks, cross-platformPySimpleGUI
Dear PyGuiImmediate Mode GUI, GPU accelerated, cross-platformDear PyGui
PygameSpecifically for game development, easy to use, cross-platformPygame
TogaPart of the BeeWare project, native GUI toolkit, cross-platformToga

2. C++

C++ is a powerful programming language commonly used for system/software development, game development, and performance-critical applications. Below are some of the most popular C++ GUI frameworks:

GUI FrameworkKey FeaturesOfficial Link
QtExtensive, cross-platform, commercial support, rich UI toolsQt
wxWidgetsCross-platform, native look and feel, free and open-sourcewxWidgets
GTK+Open-source, used by GNOME, cross-platformGTK+
FLTKLightweight, cross-platform, minimal dependenciesFLTK
ImGuiImmediate Mode GUI, optimized for performance, lightweight, cross-platformImGui
JUCEDesigned for audio applications, cross-platform, modern UIJUCE
CEGUICustomizable, cross-platform, designed for gamesCEGUI
NanaModern C++11 style, cross-platform, lightweightNana
Ultimate++Modern C++ GUI framework, rich features, cross-platformUltimate++
AntTweakBarLightweight, for small GUI applications, easy integrationAntTweakBar

3. Java

Java is a versatile and widely-used programming language, especially known for its portability across platforms. Here are some popular Java GUI frameworks:

GUI FrameworkKey FeaturesOfficial Link
SwingPart of Java Standard Library, lightweight, cross-platformSwing
JavaFXRich set of UI controls, 3D graphics, web view, cross-platformJavaFX
SWTNative look and feel, developed by IBM, cross-platformSWT
AWTBasic UI components, part of Java Standard Library, lightweightAWT
JFoenixMaterial Design components for JavaFXJFoenix
VaadinWeb framework, Java-based, cross-platformVaadin
Apache PivotOpen-source, rich set of components, cross-platformApache Pivot
ThinletLightweight, XML-based, designed for small GUIsThinlet
LanternaText-based UI, terminal applications, cross-platformLanterna
JFreeChartCharting library, extensive, easy to useJFreeChart

4. C#

C# is a popular language for Windows applications, particularly within the .NET ecosystem. Below are some widely-used C# GUI frameworks:

GUI FrameworkKey FeaturesOfficial Link
Windows FormsEasy to use, part of .NET, Windows-onlyWindows Forms
WPFAdvanced graphics, data binding, part of .NET, Windows-onlyWPF
AvaloniaCross-platform, XAML-based, modern UI frameworkAvalonia
Uno PlatformCross-platform, single codebase, based on UWPUno Platform
Eto.FormsCross-platform, shared code, multiple backendsEto.Forms
MAUICross-platform, next-gen Xamarin.Forms, built on .NETMAUI
Xamarin.FormsCross-platform, mobile-first, part of XamarinXamarin.Forms
CefSharpEmbedded browser, based on Chromium, supports WPF and Windows FormsCefSharp
WinUIModern native UI, Windows 10+, scalableWinUI
OpenTKAdvanced graphics, game development, cross-platformOpenTK

5. JavaScript

JavaScript is the language of the web, and many frameworks are available for building web-based GUIs and even desktop applications through hybrid frameworks:

GUI FrameworkKey FeaturesOfficial Link
ElectronCross-platform, web-based, uses Chromium and Node.jsElectron
NW.jsCross-platform, uses Node.js and WebKit, deep Node.js integrationNW.js
React NativeCross-platform, mobile-first, declarative UI, backed by FacebookReact Native
Vue.js with ElectronLightweight, reactive components, combined with Electron for desktop appsVue.js
Angular ElectronFramework for building Electron apps with AngularAngular Electron
NodeGUINative desktop apps with JavaScript, uses QtNodeGUI
BootstrapHTML/CSS/JS framework, responsive design, cross-platformBootstrap
FoundationResponsive front-end framework, mobile-first, cross-platformFoundation
QuasarHigh-performance, cross-platform, Vue-basedQuasar
Ext JSRich UI components, enterprise-level, responsiveExt JS

6. Swift

Swift is Apple’s language for developing macOS, iOS, watchOS, and tvOS applications. Below are some key GUI frameworks in Swift:

GUI FrameworkKey FeaturesOfficial Link
SwiftUIDeclarative syntax, seamless integration with Apple ecosystems, modern and responsive UI frameworkSwiftUI
CocoaNative macOS and iOS framework, extensive integration with Apple servicesCocoa
AppKitFoundation of Cocoa for macOS, used for building native macOS appsAppKit
UIKitUI framework for iOS, tvOS, watchOS, part of Apple’s Cocoa Touch frameworkUIKit
VaporServer-side Swift framework, good for web applications with SwiftVapor
PerfectServer-side Swift framework, flexible routing, web-based GUIsPerfect
KituraLightweight, IBM-supported, cross-platform web frameworkKitura
SwiftWebUIBrings SwiftUI’s declarative syntax to the webSwiftWebUI
TonicTiny, reactive UI library for SwiftUI on iOS/macOSTonic
SwiftPlotData visualization and plotting for SwiftSwiftPlot

7. Dart

Dart is a language optimized for building fast, cross-platform applications. It’s best known for its use in Flutter, but there are other GUI frameworks available as well:

GUI FrameworkKey FeaturesOfficial Link
FlutterCross-platform, mobile-first, modern UI, built on DartFlutter
AngularDartWeb framework, built on Dart, Google-supportedAngularDart
OverReactReact-like framework for building UIs in DartOverReact
HummingbirdEarly-stage, experimental project to run Flutter on the webHummingbird
StageXL2D game framework, focused on web, based on DartStageXL
Druid (Dart)Lightweight, cross-platform, inspired by FlutterDruid (Dart)
ReactiveX (RxDart)Library for composing asynchronous and event-based programs using Dart and reactive programmingReactiveX
FlintSmall UI library for Dart, component-basedFlint
DashWeb-based framework, designed for building analytical applications in DartDash
AqueductWeb server framework, ORM, based on DartAqueduct

8. Ruby

Ruby is a dynamic, reflective, object-oriented programming language known for its simplicity and productivity. Below are some GUI frameworks used in Ruby:

GUI FrameworkKey FeaturesOfficial Link
Ruby GTKGNOME-based, cross-platform, Ruby bindings for GTKRuby GTK
ShoesSimple and intuitive, ideal for beginners, cross-platformShoes
FXRubyRuby bindings for FOX Toolkit, native look and feel, cross-platformFXRuby
Tk (Ruby bindings)Simple, built-in with Ruby, cross-platformRuby Tk
QtRubyRuby bindings for Qt, powerful and flexible, cross-platformQtRuby
GosuSimple 2D game development, fast and easy to useGosu
GlimmerDSL for writing GUI apps, Ruby bindings for SWT, cross-platformGlimmer
RuGUILightweight, Ruby GUI toolkit, easy to useRuGUI
Green ShoesUpdated version of Shoes, better documentation, cross-platformGreen Shoes
VedeuTerminal-based, text user interfaces, cross-platformVedeu

9. Go

Go, or Golang, is a statically typed, compiled language known for its simplicity and performance. Below are some GUI frameworks available for Go:

GUI FrameworkKey FeaturesOfficial Link
FyneCross-platform, mobile and desktop, simple APIFyne
GioImmediate Mode GUI, based on Go, lightweight and fastGio
GoQtGo bindings for Qt, extensive features, cross-platformGoQt
WalkWindows GUI toolkit for Go, easy to use, native Windows look and feelWalk
LorcaSimple API, lightweight, uses HTML/CSS/JS for UI, cross-platformLorca
EbitenSimple game library for Go, 2D graphics, cross-platformEbiten
GopherJSCompiler, translates Go code to JavaScript, useful for web-based GUIsGopherJS
QtGoGo bindings for Qt, supports modern Qt features, cross-platformQtGo
gotk3GTK3 bindings for Go, native look and feel, cross-platformgotk3
WailsLightweight framework for creating web-based GUIs for desktop applications in GoWails

10. Rust

Rust is known for its memory safety and performance, making it an excellent choice for systems programming. Here are some GUI frameworks available for Rust:

GUI FrameworkKey FeaturesOfficial Link
DruidCross-platform, data-oriented, Rust-first GUI frameworkDruid
GTK-rsRust bindings for GTK, cross-platform, mature and stableGTK-rs
IcedCross-platform, reactive UI framework, inspired by ElmIced
ConrodImmediate Mode GUI, cross-platform, easy to integrateConrod
AzulDesktop GUI framework, focuses on performance, uses WebRenderAzul
SlintUI toolkit for Rust, modern declarative UI designSlint
TauriLightweight, desktop applications with web technologies, security-focusedTauri
OrbTkLightweight, modular, cross-platformOrbTk
ServoModern web engine written in Rust, great for web-based GUIsServo
SmithayWayland compositor framework for building Rust-based GUIsSmithay

11. C

C is a powerful language that is widely used in systems programming, embedded systems, and applications requiring high performance. Below are some popular GUI frameworks available in C:

GUI FrameworkKey FeaturesOfficial Link
GTK+Open-source, used by GNOME, cross-platformGTK+
NuklearImmediate Mode GUI, minimal dependencies, cross-platformNuklear
FLTKLightweight, cross-platform, C-firstFLTK
CursesText-based UI, simple and lightweight, cross-platformCurses
XFormsLightweight, open-source, used for X11 on UNIX, cross-platformXForms
WinAPINative Windows GUI, extensive, high performanceWinAPI
AllegroGame programming library, supports basic GUI functionalityAllegro
SDLLow-level access to audio, keyboard, mouse, 3D hardware via OpenGLSDL
EFL (Enlightenment Foundation Libraries)Lightweight, performance-oriented, used by the Enlightenment desktop environmentEFL
XlibLow-level C language interface to the X Window System protocolXlib

12. Haskell

Haskell is a statically typed, purely functional programming language. Below are some GUI frameworks available for Haskell:

GUI FrameworkKey FeaturesOfficial Link
Gtk2HsHaskell bindings for GTK, cross-platformGtk2Hs
wxHaskellHaskell bindings for wxWidgets, native look and feelwxHaskell
Threepenny-GUILightweight, functional, uses web browser as GUIThreepenny-GUI
ReflexFunctional Reactive Programming (FRP) library for GUIs, web-basedReflex
BrickTerminal-based, declarative, cross-platformBrick
GlossEasy to use, focuses on 2D graphics, cross-platformGloss
GI-GTKModern, based on GObject Introspection, cross-platformGI-GTK
VtyTerminal user interfaces, pure HaskellVty
fltkhsHaskell bindings for FLTK, lightweight, cross-platformfltkhs
HsQMLHaskell binding to the Qt Quick GUI library, cross-platformHsQML

13. Lua

Lua is a lightweight, high-level scripting language often used for embedded applications and games. Here are some GUI frameworks available for Lua:

GUI FrameworkKey FeaturesOfficial Link
Love2DSimple API, easy to learn, 2D-focused, game developmentLove2D
IUPPortable, easy to use, cross-platform GUI toolkitIUP
LÖVRVR-focused, easy to use, lightweightLÖVR
MoonshineLightweight, 2D-focused, game developmentMoonshine
Nuklear (via Lua bindings)Immediate Mode GUI, minimal dependencies, cross-platformNuklear-Lua
Torch7Scientific computing framework, neural networks, cross-platformTorch7
FengariLua interpreter, runs in the browser, JavaScript interopFengari
DefoldCross-platform game engine with Lua scripting, lightweightDefold
Pico-8Fantasy console for making, sharing, and playing tiny games and other computer programsPico-8
Corona SDKMobile app development framework with Lua, easy to useCorona SDK

14. PHP

PHP is widely used for web development, and it has some frameworks that allow for the creation of web-based GUI applications:

GUI FrameworkKey FeaturesOfficial Link
LaravelElegant syntax, MVC architecture, extensive ecosystemLaravel
SymfonyReusable PHP components, modular, enterprise-levelSymfony
CodeIgniterLightweight, simple to use, small footprintCodeIgniter
Yii FrameworkHigh-performance, component-based PHP frameworkYii Framework
PhalconHigh-performance, low-level, written in C, very fastPhalcon
Zend FrameworkEnterprise-grade, object-oriented, comprehensive set of featuresZend Framework
CakePHPRapid development framework, scaffolding, easy to useCakePHP
Slim FrameworkMicro framework, simple yet powerful, very flexibleSlim Framework
LaminasEnterprise-level, continuation of Zend Framework, modularLaminas
FuelPHPFull-featured PHP framework, modular, security-focusedFuelPHP

15. Perl

Perl, known for its strengths in text processing and scripting, also has GUI frameworks for building desktop and web applications:

GUI FrameworkKey FeaturesOfficial Link
Perl/TkPerl bindings for Tk, easy to use, cross-platformPerl/Tk
Gtk2-PerlPerl bindings for GTK, cross-platform, native look and feelGtk2-Perl
PrimaGUI toolkit for Perl, custom widgets, cross-platformPrima
wxPerlPerl bindings for wxWidgets, cross-platform, native look and feelwxPerl
CamelBonesCocoa framework for MacOS, specifically for PerlCamelBones
MojoReal-time web framework, non-blocking, event-drivenMojolicious
MasonWeb application framework, integrates with ApacheMason
DancerLightweight web application framework, simple DSLDancer
CatalystMVC web framework, highly flexible and modularCatalyst
PadreIDE for Perl, includes Perl/Tk, cross-platformPadre
GUI development frameworks in popular programming languages

Conclusion

This table provides a comprehensive overview of 80 GUI frameworks across multiple programming languages, offering developers a broad range of options for creating user interfaces. Whether you’re a beginner looking for an easy-to-learn framework or an experienced developer seeking a powerful tool for complex applications, this guide should help you find the right framework for your needs.

By exploring the official links provided, you can delve deeper into each framework’s features and capabilities, ensuring you choose the best option for your next project.


Tags: GUI development, programming languages, cross-platform frameworks, desktop applications, open-source libraries

Go Programming: Build a Simple BMI Calculator GUI with Fyne (In 5 Easy Steps)

Building a Simple BMI Calculator GUI with Go and Fyne

Introduction to Go Programming: Building a Simple BMI Calculator GUI

Go Programming (also known as Golang) is a powerful and efficient programming language that has gained popularity for its simplicity and performance. While Go is often used for backend and systems programming, it is also capable of creating desktop GUI applications. In this Go Programming tutorial, we will guide you through setting up Go, creating a simple BMI (Body Mass Index) calculator using the Fyne GUI library, and understanding the basics of GUI development in Go. This Go programming tutorial is perfect for beginners with no prior experience in Go or GUI development.

What We Will Build

We will build a simple BMI calculator that allows users to input their weight in kilograms and height in meters. The application will then calculate the BMI and provide a health category (e.g., Underweight, Normal weight, etc.) along with a helpful tip based on the BMI result. Additionally, the application will feature a light/dark theme toggle for user preference.

Prerequisites

Before we start, make sure you have the following installed on your machine:

  • Go: If you haven’t installed Go yet, you can download it from the official Go website. Follow the instructions for your operating system.
  • Fyne: Fyne is a cross-platform GUI library for Go that makes it easy to create beautiful and responsive desktop applications. We will install it as part of this tutorial.

Step 1: Setting Up Your Go Environment

  1. Install Go:
  • Download the Go installer from the official site.
  • Run the installer and follow the prompts.
  • Once installed, you can verify the installation by opening a terminal and typing: go version
  • You should see something like go version go1.16.3 (or whichever version you installed).
  1. Set Up Your Workspace:
  • Go uses a workspace structure where all your projects reside. By default, your workspace should be located in ~/go (on Unix systems) or C:\Users\YourName\go (on Windows).
  • Create a directory for your new project: mkdir -p ~/go/src/github.com/yourusername/bmi-calculator cd ~/go/src/github.com/yourusername/bmi-calculator

Step 2: Installing the Fyne Library

Now that your Go environment is set up, let’s install the Fyne library.

  1. Install Fyne:
  • In your project directory, run the following command to install Fyne: go get fyne.io/fyne/v2
  • This will download and install Fyne and its dependencies.
  1. Create Your Main Go File:
  • In your project directory, create a new file named main.go: touch main.go
  • Open main.go in your preferred text editor or IDE.

Step 3: Writing the BMI Calculator Code

Let’s dive into writing the code for our BMI calculator. The code is designed to be simple and easy to understand, even for those new to Go.

The Code

package main

import (
    "fmt"
    "fyne.io/fyne/v2"
    "fyne.io/fyne/v2/app"
    "fyne.io/fyne/v2/container"
    "fyne.io/fyne/v2/theme"
    "fyne.io/fyne/v2/widget"
    "strconv"
)

func calculateBMI(weightKg, heightM float64) (float64, string, string) {
    bmi := weightKg / (heightM * heightM)
    fmt.Println(bmi)
    var category, tip string

    switch {
    case bmi < 18.5:
        category = "Underweight"
        tip = "Consider increasing your calorie intake with nutrient-rich foods 
 and consult with a healthcare provider for a plan to reach a healthy weight."
    case bmi >= 18.5 && bmi <= 24.9:
        category = "Normal weight"
        tip = "Maintain your healthy lifestyle with a balanced diet and regular physical activity."
    case bmi >= 25 && bmi <= 29.9:
        category = "Overweight"
        tip = "Incorporate more physical activity into your 
 routine and watch your portion sizes to manage your weight effectively."
    case bmi >= 30 && bmi <= 34.9:
        category = "Obesity (Class 1)"
        tip = "Focus on a healthier diet and regular exercise.
 It’s advisable to consult with a healthcare provider for personalized advice."
    case bmi >= 35 && bmi <= 39.9:
        category = "Obesity (Class 2)"
        tip = "Medical advice is recommended to develop a weight loss plan,
 as well as to monitor any related health conditions."
    default:
        category = "Severe Obesity (Class 3)"
        tip = "Seek professional medical assistance to address potential 
 health risks and to develop a comprehensive weight management plan."
    }

    return bmi, category, tip
}

func main() {
    app := app.New()
    w := app.NewWindow("BMI Buddy")
    w.SetFixedSize(true)
    w.Resize(fyne.NewSize(700, 500))

    weight := widget.NewEntry()
    height := widget.NewEntry()
    bmiText := widget.NewLabel("")
    categoryText := widget.NewLabel("")
    tipText := widget.NewLabel("")

    themeStyle := widget.NewRadioGroup([]string{"Light", "Dark"}, func(value string) {
        if value == "Light" {
            app.Settings().SetTheme(theme.LightTheme())
        } else {
            app.Settings().SetTheme(theme.DarkTheme())
        }
    })

    themeStyle.SetSelected("Light")

    w.SetContent(container.NewVBox(
        widget.NewLabel("Weight (kg):"),
        weight,
        widget.NewLabel("Height (m):"),
        height,

        widget.NewButton("Calculate", func() {
            weightValue, err1 := strconv.ParseFloat(weight.Text, 64)
            if err1 != nil {
                fmt.Println("Error converting weight:", err1)
                bmiText.SetText("Invalid weight input")
                fmt.Println(err1)
                return
            }
            heightValue, err := strconv.ParseFloat(height.Text, 64)
            if err != nil {
                fmt.Println("Error converting height:", err)
                bmiText.SetText("Invalid height input")
                fmt.Println(err)
                return
            }
            bmi, category, tip := calculateBMI(weightValue, heightValue)
            bmiText.SetText(fmt.Sprintf("Your BMI is: %.2f", bmi))
            categoryText.SetText("Category: " + category)
            tipText.SetText("Tip: " + tip)

            // Update the UI
            fmt.Println("Done!")

        }),
        bmiText,
        categoryText,
        tipText,
        themeStyle,
    ))
    w.ShowAndRun()
}

Explanation

  1. Imports: We import necessary packages including Fyne for the GUI components, strconv for converting string inputs to float, and fmt for printing to the console.
  2. calculateBMI Function: This function takes in the weight and height, calculates the BMI, and determines the health category and a tip based on the BMI. The function returns the BMI value, the category, and the tip.
  3. Main Function:
    • We create a new Fyne app and window.
    • The window size is set to 700×500 pixels.
    • We define the input fields for weight and height, as well as labels to display the BMI, category, and tip.
    • We also add a theme toggle that allows users to switch between light and dark modes.
    • The “Calculate” button triggers the calculation when clicked, updating the labels with the results.
    • Finally, we use w.ShowAndRun() to start the application.

Step 4: Running Your Application

Once you’ve written the code, it’s time to run your application.

  1. Run the Application:
  • In your terminal, make sure you’re in your project directory and simply type: go run main.go
  • This will compile and run your BMI calculator.
  1. Interact with the Application:
  • Enter your weight in kilograms and height in meters, then click “Calculate”.
  • The application will display your BMI, the health category, and a helpful tip.
  • You can also switch between light and dark themes using the radio buttons.
Go Programming, Fyne GUI, BMI Calculator, Go GUI Development, Golang Applications

Conclusion

Congratulations! You’ve successfully created a simple BMI calculator with a GUI in Go using the Fyne library. Through this tutorial, you’ve learned the basics of setting up a Go environment, installing and using the Fyne library, and creating a functional desktop application with user interaction.

While this project is simple, it introduces you to the fundamentals of Go programming and GUI development, providing a foundation for more complex projects in the future. You can expand on this project by adding more features, such as saving user data, allowing for more input options, or even extending it to track BMI over time.

Go and Fyne together offer a powerful platform for building cross-platform desktop applications with ease. Keep experimenting and exploring the possibilities!

Happy coding!

References

Go Programming, Fyne GUI, BMI Calculator, Go GUI Development, Golang Applications

Go Programming: How to Build a Low-Memory, Efficient MySQL Monitor Service

Intro

In this tutorial, we will guide you through the process of creating a simple, low-memory, and efficient service using Go. This service monitors your MySQL server and automatically restarts it if it goes down. We’ll also cover how to deploy this service on a VPS, run it in the background, and ensure it starts automatically with your system.

Prerequisites

Before we start, make sure you have the following:

  • A VPS running Ubuntu or any Linux distribution. If you don’t have one, you can get a VPS from DigitalOcean, AWS, or Azure.
  • Go installed on your local development environment (preferably using WSL if you are on Windows). You can download Go from the official website.
  • Basic understanding of the Linux command line and Go programming.

Step 1: Setting Up the Project

First, let’s set up a new Go project with a go.mod file:

  1. Open your terminal and create a new directory for your project: mkdir mysql_monitor cd mysql_monitor
  2. Initialize the Go module: go mod init mysql_monitor
  3. Install the necessary dependencies, such as the Gomail package for sending email notifications: go get gopkg.in/mail.v2

Step 2: Writing the Go Code

Here’s the Go code that monitors MySQL, attempts to restart it if it’s down, and sends email notifications about its status:

package main

import (
    "fmt"
    "log"
    "os/exec"
    "time"

    "gopkg.in/mail.v2"
)

// CheckMySQLStatus checks if MySQL is running
func CheckMySQLStatus() bool {
    cmd := exec.Command("systemctl", "is-active", "--quiet", "mysql")
    err := cmd.Run()
    return err == nil
}

// RestartMySQL restarts the MySQL service
func RestartMySQL() {
    log.Println("MySQL is down! Attempting to restart...")
    cmd := exec.Command("systemctl", "restart", "mysql")
    sendMail("MySQL is down! Attempting to restart...", "MySQL is down! Attempting to restart...")
    err := cmd.Run()
    if err != nil {
        log.Printf("Failed to restart MySQL: %v
", err)
        sendMail(fmt.Sprintf("Failed to restart MySQL: %v", err), "MySQL Restart Failure")
    } else {
        log.Println("MySQL restarted successfully.")
        sendMail("MySQL restarted successfully.", "MySQL Restart Success")
    }
}

func main() {
    for {
        if !CheckMySQLStatus() {
            RestartMySQL()
        }
        time.Sleep(1 * time.Minute) // Check every minute
    }
}

func sendMail(body string, subject string) {
    m := mail.NewMessage()
    m.SetHeader("From", "rambod.gh@outlook.com")
    m.SetHeader("To", "rambod.dev@gmail.com")
    m.SetHeader("Subject", subject)
    m.SetBody("text/plain", body)

    d := mail.NewDialer("smtp-mail.outlook.com", 587, "rambod.gh@outlook.com", "password")

    if err := d.DialAndSend(m); err != nil {
        log.Printf("Failed to send email: %v
", err)
    }
}

Explanation of the Code

  • CheckMySQLStatus: This function checks whether the MySQL service is running using the systemctl is-active command.
  • RestartMySQL: If MySQL is down, this function attempts to restart it and sends an email notification about the status.
  • sendMail: This function sends an email using the Gomail package, notifying you of any important events.

Step 3: Building the Binary

Once the code is written, build the Go binary:

go build -o mysql_monitor

This command will create an executable named mysql_monitor in your project directory.

Step 4: Transferring the Binary to Your VPS

Use scp to transfer the binary to your VPS. If you don’t have a VPS, you can get one from DigitalOcean, AWS, or Azure.

scp mysql_monitor username@your-vps-ip:/path/to/destination

Step 5: Setting Up a Non-Root User (Optional but Recommended)

For security reasons, it’s best to run services as a non-root user:

  1. Create a new user: sudo adduser yourusername
  2. Grant sudo privileges to the new user: sudo usermod -aG sudo yourusername
  3. Switch to the new user: su - yourusername

Step 6: Running the Service in the Background

Once logged in as your new user, make the binary executable:

chmod +x /path/to/destination/mysql_monitor

You can run it in the background using nohup:

nohup ./mysql_monitor &

Step 7: Creating a systemd Service

For better management, create a systemd service to run your application automatically on startup:

  1. Create a service file: sudo nano /etc/systemd/system/mysql_monitor.service
  2. Add the following content:
    [Unit]
    Description=MySQL Monitor Service
    After=network.target

    [Service]
    ExecStart=/path/to/destination/mysql_monitor
    Restart=always
    User=yourusername

    [Install]
    WantedBy=multi-user.target
  1. Enable and start the service:
    sudo systemctl daemon-reload
    sudo systemctl enable mysql_monitor.service
    sudo systemctl start mysql_monitor.service
  1. Check the status of the service:
 sudo systemctl status mysql_monitor.service

Step 8: Monitoring Logs

You can monitor the service logs with:

sudo journalctl -u mysql_monitor.service

Conclusion

By following this tutorial, you’ve created a simple, low-memory, and efficient Go service that monitors and automatically restarts MySQL if it goes down. This service will also notify you via email of any issues with your MySQL server, ensuring that you’re always aware of its status.

This setup is ideal for small-scale deployments where resource usage is a concern. Go’s lightweight nature makes it a perfect choice for such tasks. Whether you’re using a VPS from DigitalOcean, AWS, or Azure, this tutorial helps you ensure your MySQL server stays up and running.

External Links:

Tags

  • Go Programming
  • MySQL
  • Linux Server
  • VPS
  • systemd
  • DevOps
  • Low-Memory Usage
  • Server Monitoring