beta.blog

Golang: Create WiFi Connect QR Code

by on Apr.01, 2024, under News

Here’s the code:

package main

import (
	"bufio"
	"fmt"
	"os"
	"strings"

	"github.com/skip2/go-qrcode"
)

var reader = bufio.NewReader(os.Stdin)

func askUserToEnterData(message string) string {
	fmt.Print(message + ": ")
	userInput, _ := reader.ReadString('\n')
	userInput = strings.TrimSpace(userInput)

	if len(userInput) == 0 {
		fmt.Println("Received no user input, exiting!")
		os.Exit(0)
	}

	return userInput
}

func main() {
	ssid := askUserToEnterData("Enter WiFi name (SSID)")
	password := askUserToEnterData("Enter WiFi password")
	networkType := askUserToEnterData("Enter WiFi type (WPA, WEP, nopass)")

	// Encode the string using the WIFI scheme
	// WIFI:T:<NetworkType>;S:<SSID>;P:<Password>;;
	wifiString := fmt.Sprintf("WIFI:T:%s;S:%s;P:%s;;", networkType, ssid, password)

	// Generate and save the QR code
	err := qrcode.WriteFile(wifiString, qrcode.Medium, 256, "wifi-qr.png")
	if err != nil {
		fmt.Println("Failed to generate QR code:", err)
		return
	}

	fmt.Println("QR code generated successfully: wifi-qr.png")
}

Leave a Reply

*

Looking for something?

Use the form below to search the site:

Still not finding what you're looking for? Drop a comment on a post or contact us so we can take care of it!