[Golang]關於 Channels 的控制一些要注意的事項(一)

前言 學習Golang 讓人最興奮的大概就是它內建的 Concurrency 的支援,並且相當的容易使用. 但是最近在學習與使用的時候,發現發現 Goroutine 可以讓本來需要用到 40 秒的 Request 減少到1/3 左右的時間.進而可以進步到 5 秒左右.平常的應用上,幾乎已經離不開 Goroutine 與Channel。 但是最近遇到幾個例子,一開始覺得很不能理解,也不容易解決.也是讓我找了一些解決方式. 一般用法 Go Channel一般有兩種用法(當然有更多的使用方式可以用),一個是把channel當成資料來傳遞,另外的方式只是單純把channel當成是signal來等待或是啟動新的thread // 同時要處理多個可以同步運行的運算,利用channel來回傳結果 c := make(chan int) // Allocate a channel. go func() { result : = do_some_cal() c <- result }() c2 := make(chan int) // Allocate a channel. go func() { result : = do_some_cal2() c2 <- result }() totalResult := <-c2 + <-c fmt.Printf("result is %d"), totalResult) // 傳送訊號(signal)的方式 c := make(chan int) // Allocate a channel. go func() { list.Sort() c <- 1 // Send a signal; value does not matter. }() doSomethingForAWhile() <-c // Wait for sort to finish; discard sent value. 陷阱出現了 以上兩個方式相當的簡單,也相當直覺來使用.但是如果要跑goroutine的條件不是必要呢?也就是說不一定要透過go routine來同步執行很多的結果呢? c := make(chan int) //並不一定會進入go routine來計算,也就是說channel會是為空的. if needRoutine == true { go func() { result : = do_some_cal() c <- result }() } else { c <- 0 //note this kind will not work, because channels need input value in...
繼續閱讀

[Golang][程式設計週記].. 2015第五週

##雜七雜八感言: 令人開心的事情,總算在工作上把某些專案推坑Golang… 可以更專心的學習跟使用Golang… ##筆記: ###[Golang] 一些有趣的package 跟 網站 [Golang][Gala] Final list of Gala 最後進入final 名單的Gala 2015競爭者,Docket竟然被踢掉了… [Golang][Gala] http://gophergala.com/blog/gopher/gala/2015/02/03/winners/ 最後的獲勝者出線了…. [Golang]Go Report Card: A report card for your Go application 根據你github上面的go project給予一些分數,評分依據根據gofmt, go vet, go lint與 gocyclo. 挺有趣的,很多時候issue越多並不代表分數不高喔… [Golang] Beego 的教學(tutorial) First,Second, Third, Git 這是之前又介紹過MVC架構的Web Framework Beego的教學.Beego被許多大公司所使用(Weibo, Taobao, Tudou….),算是很棒的架構,有機會可以好好學習. [Golang]Moving from Node.js to Go at Bowery Bowery這家公司把他們平台從Node.js換到Go的經歷.裡面有提到以下的優點: Easy to write cross-platform code, Faster deployment, Concurrency primitives, Integrated testing framework, Standard library and Developer workflow tools are more powerful. [Golang] Go HTTP request router benchmark and comparison 有各種Go Webframework的效能比較,幾個值得注意的事情是net/http 的ServerMux並不會有最好的效能.而martini雖然效能最差,但是擴展性是最高的. 也可以順便知道有多少web framework…. (Beego, go-json-rest, Denco, Gocraft Web, Goji, Gorilla Mux, http.ServeMux, HttpRouter, HttpTreeMux, Kocha-urlrouter, Martini, Pat, TigerTonic, Traffic) [Livehouse.in] 關於c9s的slideshare “Get Merge!” Get Merge [Golang] Sample Email Sender using SocketLabs 不錯的寄信範例程式使用Go [Golang] 關於Session的學習 要開始弄martini關於authorication的部分,首先最簡單的除了SSL之外,就使用session了. Martini session 提供了一個相當簡單的方式來使用. 首先可以參考這段教學影片,其實相當的簡單易用,也可以設定哪些網址才需要透過session. [Golang] 關於Go與CGI的搭配 本來的討論是希望讓Go可以取代PHP在Apache中的地位,主要可以達成以下的結果: 可以多個process,彼此獨立 一個process 出事情不會影響到全部的系統. 是開始尋找有沒有類似的結果,如下: Deploying Go web services behind Nginx under Debian or Ubuntu 讓你架起來nginx之後,每一個CGI去執行Go Apache - mod_go 恩… 就是Apache 裡面可以直接跑Go….....
繼續閱讀

[Golang][程式設計週記].. 2015第四週

##雜七雜八感言: 啊… 我覺得我blog樣板好醜啊….應該要改成Patrick類似的… 本來想加回廣告的… 後來看到每天流量沒有破百…. 算了…. ##筆記: 以下是關於本週的學習筆記… ###[Golang] 一些有趣的package 跟 網站 goth: Package goth provides a simple, clean, and idiomatic way to write authentication packages for Go web applications. 可以很快速地使用OAuth跟OAuth2的工具. switcher: Run SSH and HTTP(S) on the same port 可以同一個communication port 同時接受http跟https 或是ssh,透過protocol 不同, 比如說原本跑http的port 80,可以透過switcher把https的request導到另外一個process $ switcher –listen :80 –ssh 127.0.0.1:22 –default 127.0.0.1:8080 總覺得會是很有用的東西…. deck: Slide Decks 可以透過markup language來做投影片,挺有趣的. Docket - Custom docker registry that allows for deploys through bittorrent 有神人在Gopher Gala Golang 48 hour hackathon的作品.. 很特別的點子是.. 透過bittorrent來deploy go iOS.App() 一個關於如何用Go在iOS上面寫App的討論串,有不少成果可以看. goIosHelloWorld: a go ios hello world project Using Go in mobile apps: How I learned Go while integrating it into my iOS and Android app 記錄了如何用Go寫Android/iOS的App,一開始有先介紹如何使用cgo接下來就是如何寫出App. Gopher Gala 2015 hackathon 第一屆的Gopher hackathon,優勝者會在02/03揭曉,挺多有趣的專案說… ImgurGo: An open source image uploader by the Imgur team 這次Gala參賽作品.. imgur 團隊用go寫了圖片上傳網站… 還支援AWS… cool freegeoip: IP geolocation web server http://freegeoip.net 一個工具可以讓你用ip找到位址,只有第一次使用的時候會把資料庫下載下來.其他查詢都很快. Excellent Open Source Go Projects Go open source project 大排名,第一名竟然是Go-github.docker落到第十名…. : Hound: Lightning...
繼續閱讀

[Golang] Enable HTTPS in martini using martini-contrib/secure

實在有點懶得用中文來寫了… 讓我用英文寫這篇吧… Before this.. I am learning about golang on server backend side programming via martini. I want to write a RESTful server communicate via JSON. Currently my framework as follow: Host on: Heroku DB: MongoDB Web framework: maritini Here is the note about how I add martini-secure HTTPS in martini. Working step with martini-secure 1. Create a SSL key using generate_cert.go You need create your localhost SSL key (or purchase one from CA) using generate_cert.go. I am not sure how to get this package, so I just download this source code and run it locally. go run generate_cert.go --host="localhost" You will get file “key.pem” and “cert.pem”, just put in your web side source code. 2. Apply martini-secure in martini program. It is very easy to add SSL as a plugin in martini, here is some code. At first I would like to host two services as follow: HTTP: port...
繼續閱讀

[Golang][程式設計週記].. 2015第3週.. 20150123

前言: 看起來每個禮拜一篇的紀錄會有點繁雜,應該要把所有文章拆開來一篇一篇儲存.但是很多部分沒辦法一次寫完又很痛苦. 再觀察看看要怎麼寫好了. 筆記: [Golang] 相關網頁與資源 EBOOK: Learn how to build and deploy web applications with Go. Golang Microsoft Version Info and Icon Resource Generato 在Windows上面可以幫你寫好版本資訊,對於之後要sign code或是其他build process會比較方便. Golang适合高并发场景的原因分析 這篇主要是講解一些Go的優點,以及Go是不是合作為大型伺服器的開發.裡面也提到所謂的C10K甚至到C10M也就是開發同時客戶超過一萬個與一百萬個的伺服器,是可以使用Go作為開發語言的.個人覺得這一篇相當適合詳細閱讀. 如何处理10000 TCP连接 千万级并发实现的秘密:内核不是解决方案,而是问题所在! Time parsing utility for Go http://godoc.org/github.com/dataence/timex Learning HTTP caching in Go 有寫Http Cache的部分滿值得看的, The Most Powerful Feature of Go Is The Least Sexy 提到很多Go的優點跟缺點,其實透過一般人所認為Go的缺點,反而會是Go最重要的優點… 比如說Go不支援 generics,可以讓速度更快.更不容易出問題. 不支援exception,但是支援multiple return卻可以讓program更容易控制,更不容易在意想不到的地方跳出去. 是不是很威? :) Provide basic charts in go Golang繪圖與畫圖工具,雖然說是basic charts但是裡面其實不論是長條圖,直方圖,條狀圖,折線圖,圓餅圖其實都有支援.看起來很實用 A compiler from Go (golang.org) to JavaScript for running Go code in a browser 把Golang一些邏輯可以完全轉到JS,也有出playground Sync MySQL data into elasticsearch 把MySql裡面的資料sync到ElasticSearch,很酷喔…. Go London User Group London的Go Group裡面有相當多的影片可以看. Mooc: Essential Go Go的線上課程,雖然一定要收費而且內容比較適合初學者. [Golang]關於JSON,如何處理敏感的資料: JSON Encoding in Go: Dealing with Sensitive Fields 這篇解決了我最近對於JSON struct tag的疑問. // 隱藏AuthToken ,在JSON中完全不會出現. type SafePerson struct { FirstName string LastName string AuthToken string `json:"-"` } // 如果沒有值,就不會出現在JSON裡面. type PrettySafePerson struct { FirstName string LastName string AuthToken string `json:",omitempty"` } [Go Boston] 2015-01 Meetup講稿 Go/Gorilla for MEAN Stack...
繼續閱讀

[Golang] 相當好用但又要注意的defer

經常在處理檔案的開關必須要注意到file open就一定要有搭配的 file close.但是如果有很多的case,搭配著很多的return.那是不是就得在每個地方寫上fclose? func FileProcess() error { //開啟檔案 f, err := os.Create("/tmp/dat2") check(err) //在這裡呼叫 defer f.Close(),如果有參數會這時候讀入 defer f.Close() if CASE1 { Do something //這時候會執行 f.Close() return errors.New("Error Case2") } else if CASE2 { Do something //這時候會執行 f.Close() return errors.New("Error Case2") } // 就算之後要增加新的case,也不用擔心要補 f.Close() //這時候會執行 f.Close() return nil } Golang裡面有個很方便的function 叫做defer,他執行的時間點會是在你離開目前的function. 不過這裡需要注意的是有兩個地方: 變數的傳遞,會在呼叫defer的時候傳入.所以他並不是很簡單的直接移到最後呼叫 根據GoDoc Defer: The arguments to the deferred function (which include the receiver if the function is a method) are evaluated when the defer executes. 呼叫與執行defer採取的是LIFO. 參考這篇文章 結論: defer最好還是使用在fopen與fclose比較不會有問題. 如果有參數要帶,千萬要想清楚當時參數的順序與是否有其他問題會發生. package main import ( "errors" "fmt" ) func useAClosure() error { var err error defer func() { fmt.Printf("useAClosure: err has value %v\n", err) }() err = errors.New("Error 1") fmt.Println("Finish func useAClosure") return err } func deferPrintf() error { var err error //呼叫的時候會把參數帶過去,所以err是nil defer fmt.Printf("deferPrintf: err has value %v\n", err) err = errors.New("Error 2") //注意這裡是LIFO,所以呼叫會是43210 for i := 0; i < 5; i++ { defer fmt.Printf("%d ", i)...
繼續閱讀