##前言 為了要寫一個Web Service但是有可能會發生以下的需求: 不同Server,有不同的設定參數 不同的OS有不同的command set 想要快速的開啟或是關閉debug log 在有以上的需求的時候,一開始都是使用OS偵測或是configuration file來區隔.但是到後其實是希望能透過不同的build config能夠產生不同的binary. 決定研究了一下: go build 有以下兩種方式可以達到部分的效果. ##Go build -ldflags 這可以在go build的時候,先設定一些變數的名稱.通常我自己比較習慣透過OS環境變數來設定,然後程式裡面再去讀取. 在你的主程式裡面,可以先定義一個變數flagString: package main import ( "fmt" ) var flagString string func main() { fmt.Println("This build with ldflag:", flagString) } 透過外在go build來設定這個變數 go build -ldflags '-X main.flagString "test"' 這樣你的結果會是 >> This build with ldflag: test 這個方式可以直接設定參數,讓initialize value透過外部設定來跑. ##Go build -tags 透過go build -tags 可以達到加入不同的檔案在compiling time.由於這樣,你能夠放在這個檔案裡面的東西就有很多.可以是: 不同系列的define (達到ifdef的效果) 不同的function implement (達到同一個function 在不同設定下有不同實現) 以下增加一個簡單的範例,來達到不同的build config可以載入不同的define value. file: debug_config.go //+build debug package main var TestString string = "test debug" var TestString2 string = " and it will run every module with debug tag." func GetConfigString() string { return "it is debug....." } 請注意: //+build debug 前後需要一個空行(除非你在第一行) 另外,我們也有一般的設定檔 release_config.go //+build !debug package main var TestString string = "test release" var TestString2 string = " and it will run every module as no debug tag." func GetConfigString() string { return "it is release....." } 最後在主要的main裡面,可以直接去參考這兩個define value...
Preface When we trying to use MongoDB, the requirement comes more and more complex and diversity. Here is some note during my implement. Multiple condition in MongoDB Query It is very easy to find data in MongoDB, but how about multiple condition such as “AND” and “OR” ? AND OR in MongoDB It is very easy to find “AND” support in MongoDB, but how to apply in mgo (MongoDB driver in Go)? // Find user name is John and Contry is US. var alldb []User UserCollection.Find(bson.M{"$and": []bson.M{bson.M{"name": "John"}, bson.M{"Contry": "US"}}}).All(&alldb) Please note: the $and need combine an array of bson.M. // Find CONDITION_A and CONDITION_B bson.M{"$and": []bson.M{ CONDITION_A, CONDITION_B }} So, it is similar with “OR” ($or), detail doc is here. // Find CONDITION_A or CONDITION_B bson.M{"$or": []bson.M{ CONDITION_A, CONDITION_B }} Make it more clear in code. // Find user name is John or Tom. var alldb []User UserCollection.Find(bson.M{"$or": []bson.M{bson.M{"name":...