當第一次看到go程式在windows平台生成可執行的exe檔案,就宣告了windows應用也一定是go語言的戰場。go不是腳本語言,但卻有着腳本語言的輕便簡單的特性。相較于php和python之類以伺服器控制台為主要戰場的腳本語言來說,go語言是真正的圓了“動态語言的應用開發夢”。
windows桌面應用依賴于win api,畫出各種應用界面和控件本質上就是調用windows提供的api。go開發windows app要做的第一件事情就是封裝這些windows api。
<a href="https://github.com/lxn/go-winapi">https://github.com/lxn/go-winapi</a>
這個項目已經實作了對winapi的封裝。比如你會在go-winapi/user32.go中找到createwindowex的封裝:

這裡是使用了syscall包。這裡要說明一下,golang的官方文檔沒有對syscall.syscall12的說明,需要檢視代碼,這裡的syscall12代表了createwindowex傳入的參數有12個,已經實作的syscall方法還有
syscall, syscall6, syscall9, syscall12, syscall15。
下一步,有基本的winapi之後,需要的是各個控件的使用接口。官方并沒有提供标準庫,但是有許多開源項目已經完成了這個封裝,下面就是幾個開源項目:
這裡推薦和使用的是lxn的walk項目(windows application library kit),walk封裝的控件應該是這幾個裡面最全的了,并且也在不斷的完善中。
比如bitmap, radiobutton, checkbox, pushbutton等。在walk/example中能看到幾個例子提供參考
好了,有了go-winapi和walk兩個開源項目,就可以開始做一個windows app了
界面如下:
這個是一個簡易的socket im, 在一台機子上開啟兩個端口,8000和8001,兩個端口互相監聽和發送消息。
go版本的socket im 源碼:
<a href="https://github.com/jianfengye/myworks/tree/master/go_socketim">https://github.com/jianfengye/myworks/tree/master/go_socketim</a>
實作總是簡單的,說幾個代碼片段:
1 walk.initialize(walk.initparams{paniconerror: true})
2 defer walk.shutdown()
3
4 mainwnd, err := walk.newmainwindow()
5 if err != nil {
6 return
7 }
8
9 mw := &mainwindow{mainwindow: mainwnd}
10
11 mw.setsize(walk.size{120, 150})
12 mw.show()
13 mw.run()
button1, _ := walk.newpushbutton(mw)
button1.settext("start port 8000")
button1.setx(10)
button1.sety(10)
button1.setwidth(100)
button1.setheight(30)
button1.clicked().attach(func() {
go newtalkwindow(mw, 8000, 8001)
button1.setenabled(false)
})
建立ui基本就靠這兩步就行了,當然walk還有更為複雜的控件使用方法,這裡沒有使用。
func (this *talkwindow)send() error {
txt := this.sendtext.text()
conn, err := net.dial("tcp", "localhost:" + strconv.itoa(this.sendport))
if err != nil {
return err
}
lenth := len([]byte(txt))
pre := int32tostream(int32(lenth),bigendian)
fmt.fprintf(conn, string(pre) + txt)
this.sendtext.settext("")
return nil
}
func (this *talkwindow)listen() error {
ln, err := net.listen("tcp", ":" + strconv.itoa(this.listenport))
for {
conn, err := ln.accept()
if err != nil {
continue
}
go func(){
buffer := make([]byte, 4)
conn.read(buffer)
lenth := streamtoint32(buffer, bigendian)
contentbuf := make([]byte, lenth)
conn.read(contentbuf)
text := strings.trimspace(string(contentbuf))
fmt.println(text)
this.showtext.settext(this.showtext.text() + time.now().format("2006-01-02 10:13:40") + breakchars + strconv.itoa(this.sendport) + ":" + text + "\r\n")
}()
}
ui建立完成後就是具體的業務邏輯了,這裡的業務邏輯比較簡單,主要使用了net包建立和監聽tcp端口。
使用go相較于c#獲益更多的是在邏輯實作方面,比如在c#中開啟多程序,一個程序監聽消息一個程序收取消息,這樣的實作是比較麻煩和繁瑣的,需要使用thread庫。但是在go中是使用goroutine實作的,直接開一個goroutine來監聽消息,主程序發送消息,很符合思維邏輯的程式設計方式。
go相較于c#不足的應該說是ide方面了,go還沒有能可視化程式設計應用ide。但是walk庫使用熟練了,我想這應該不是問題,而且也有理由相信在不久會出現類似的ide。
go在将來有沒有可能支援移動終端應用的開發呢?android,ios?據說能使用go開發android應用的要求已經提上議程了,畢竟都是google的孩子嘛。至于ios可能還有很長的路要走。
ps: 截止至2012/11/6,walk的更新版本已經把 walk.initialize去掉了,換成其他函數了,故本文中的例子請做相應修改
具體可以看這個comment