package main

import (
	"fmt"
	"io"
	"net/http"
	"os"
	"path/filepath"
	"strconv"
	"strings"

	"github.com/go-ini/ini"
	"github.com/lxn/walk"
	. "github.com/lxn/walk/declarative"
)

func main() {
	// 创建窗口
	var inputTE *walk.TextEdit
	var mainWindow *walk.MainWindow
	MainWindow{
		Title:   "下载证书",
		MinSize: Size{Width: 300, Height: 150},
		Layout:  VBox{},
		Children: []Widget{
			Label{
				Text: "请输入编号:",
			},
			TextEdit{
				AssignTo: &inputTE,
			},
			HSpacer{},
			Composite{
				Layout: HBox{},
				Children: []Widget{
					PushButton{
						Text: "确定",
						OnClicked: func() {
							// 获取编辑框中的内容
							input := inputTE.Text()

							// 如果编号为空则提示用户输入编号
							if input == "" {
								walk.MsgBox(mainWindow, "提示", "请输入编号", walk.MsgBoxIconInformation)
								return
							}

							// 下载证书
							downloadURL := "https://example.com/certificates/" + input + ".pem"
							err := downloadFile("https://example.com/certificates/" + input + ".pem", filepath.Join(os.Getenv("USERPROFILE"), "Desktop"))
							if err != nil {
								walk.MsgBox(mainWindow, "错误", "下载证书失败:" + err.Error(), walk.MsgBoxIconError)
								return
							}

							// 写入配置文件
							cfg, err := ini.Load(filepath.Join(os.Getenv("USERPROFILE"), "config.ini"))
							if err != nil {
								cfg = ini.Empty()
							}
							sec, err := cfg.NewSection("certificates")
							if err != nil {
								sec, _ = cfg.Section("certificates")
							}
							sec.Key(input).SetValue(filepath.Join(os.Getenv("USERPROFILE"), "Desktop", input + ".pem"))
							err = cfg.SaveTo(filepath.Join(os.Getenv("USERPROFILE"), "config.ini"))
							if err != nil {
								walk.MsgBox(mainWindow, "错误", "写入配置文件失败:" + err.Error(), walk.MsgBoxIconError)
								return
							}

							// 提示用户设置完成
							walk.MsgBox(mainWindow, "提示", "设置完成", walk.MsgBoxIconInformation)
						},
					},
					PushButton{
						Text: "取消",
						OnClicked: func() {
							walk.App().Exit(0)
						},
					},
				},
			},
		},
		AssignTo: &mainWindow,
		OnSizeChanged: func() {
			// 窗口居中
			mainWindow.SetX((walk.ScreenFromCursor().Size().Width - mainWindow.Width()) / 2)
			mainWindow.SetY((walk.ScreenFromCursor().Size().Height - mainWindow.Height()) / 2)
		},
	}.Run()
}

// 下载文件
func downloadFile(url string, destDir string) error {
	resp, err := http.Get(url)
	if err != nil {
		return err
	}
	defer resp.Body.Close()

	fileName := strings.TrimSuffix(filepath.Base(url), filepath.Ext(url))
	file, err := os.Create(filepath.Join(destDir, fileName + ".pem"))
	if err != nil {
		return err
	}
	defer file.Close()

	_, err = io.Copy(file, resp.Body)
	if err != nil {
		return err
	}

	return nil
}
Go语言实现证书下载、配置文件写入及窗口界面

原文地址: https://www.cveoy.top/t/topic/nRST 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录