go 文件服务器(标准库) 添加关机,睡眠,退出功能

package main

import (
	"errors"
	"fmt"
	"github.com/atotto/clipboard"
	"github.com/lxn/walk"
	. "github.com/lxn/walk/declarative"
	"net"
	"net/http"
	"os"
	"os/exec"
	"strings"
)

type MyMainWindow struct {
	*walk.MainWindow
	edit *walk.TextEdit
}

var mw = &MyMainWindow{}

func main() {
	err := MainWindow{
		AssignTo: &mw.MainWindow,   
		Title:    "选择文件夹",           
		MinSize:  Size{Width: 150, Height: 200},
		Size:     Size{300, 400},
		Layout:   VBox{}, 
		Children: []Widget{ 
			TextEdit{
				AssignTo: &mw.edit,
			},
			PushButton{
				Text:      "打开",
				OnClicked: mw.selectFolder,
			},
		},
	}.Create()

	if err != nil {
		fmt.Fprintln(os.Stderr, err)
		os.Exit(1)
	}

	mw.Run()
}

func (mw *MyMainWindow) selectFolder() {
	dlg := new(walk.FileDialog)

	mw.edit.SetText("")
	if ok, err := dlg.ShowBrowseFolder(mw); err != nil {
		mw.edit.AppendText("Error : Folder Open\n")
		return
	} else if !ok {
		mw.edit.AppendText("Cancel\n")
		return
	}

	s := fmt.Sprintf("Select : %s\n", dlg.FilePath)
	mw.edit.AppendText(s)

	ip, _:=GetInternalIP()
	walk.MsgBox(nil, "URL", fmt.Sprintf("%s:9999 copied", ip), walk.MsgBoxIconInformation)
	clipboard.WriteAll(fmt.Sprintf("%s:9999", ip))

	mw.Close()

	http.Handle("/", MyHandle(dlg))
	err := http.ListenAndServe(":9999", nil)
	if err != nil {
		panic(err)
	}
}

func sleep() {
	exec.Command("cmd", "/K", "rundll32.exe powrprof.dll,SetSuspendState 0,1,0").Run()
	os.Exit(0)
}

func shutdown() {
	exec.Command("shutdown", "-s", "-t","10").Run()
	os.Exit(0)
}

func MyHandle(dlg *walk.FileDialog) http.HandlerFunc {

	return func(w http.ResponseWriter, r *http.Request) {
		if strings.Contains(r.URL.Path, "sleep") {
			sleep()
		} else if strings.Contains(r.URL.Path, "exit") {
			os.Exit(0)
		}else if strings.Contains(r.URL.Path, "shutdown") {
			shutdown()
		}

		http.FileServer(http.Dir(dlg.FilePath)).ServeHTTP(w, r)
	}
}

func GetInternalIP() (string, error) {
	conn, err := net.Dial("udp", "8.8.8.8:80")
	if err != nil {
		return "", errors.New("internal IP fetch failed, detail:" + err.Error())
	}
	defer conn.Close()

	res := conn.LocalAddr().String()
	res = strings.Split(res, ":")[0]
	return res, nil
}

  系统:win10 64位 打包的exe https://files-cdn.cnblogs.com/files/ligaofeng/awesomeGo.zip

  使用:打开exe(自行编译或下载),选择文件夹,ip:port 复制到剪贴板,确定,界面关闭,访问web(url带exit退出,shutdown关机5s,sleep睡眠)例:localhost:9999/exit

  页面美化:无,其他功能:待添加,说明:凑合着用

posted @ 2020-09-12 21:32  lgf133  阅读(175)  评论(0编辑  收藏  举报