1 package main
2
3 import(
4 "encoding/json"
5 "fmt"
6 "log"
7 "labix.org/v2/mgo"
8 "labix.org/v2/mgo/bson"
9 "net/http"
10 "strconv"
11 )
12
13 type Room struct {
14 Id bson.ObjectId `bson:"_id"`
15 Name string `bson:"name"`
16 Type string `bson:"type"`
17 Status int `bson:"status"`
18 Price string `bson:"price"`
19 Area string `bson:"area"`
20 BuildId int `bson:"buildId"`
21 }
22
23 //查询售楼信息
24 func rooms(rw http.ResponseWriter, req *http.Request){
25 req.ParseForm() //解析参数,默认是不会解析的
26 sess, err := mgo.Dial("127.0.0.1")
27 if err != nil {
28 fmt.Printf("连接数据库失败");
29 }
30 defer sess.Close()
31 log.Println("id的值:", req.FormValue("id"))
32 sess.SetSafe(&mgo.Safe{})
33 col := sess.DB("estates").C("room")
34 rooms := []Room{}
35 buildId, err := strconv.Atoi(req.FormValue("id"))
36 err = col.Find(bson.M{"buildId":buildId}).All(&rooms)
37 result,_ := json.Marshal(rooms)
38 fmt.Fprintf(rw, string(result));
39 }
40
41 //更新售房信息
42 func updateRoom(rw http.ResponseWriter, req *http.Request) {
43 req.ParseForm();
44
45 sess, err := mgo.Dial("127.0.0.1")
46 if err != nil {
47 fmt.Fprintf(rw, "连接数据库失败");
48 }
49 defer sess.Close()
50 sess.SetSafe(&mgo.Safe{})
51 status,err := strconv.Atoi(req.FormValue("status"))
52 _id := req.FormValue("id")
53 log.Println(_id,status)
54 col := sess.DB("estates").C("room")
55 err = col.Update(bson.M{"_id":bson.ObjectIdHex(_id)}, bson.M{"$set":bson.M{"status":status}})
56 if err != nil {
57 log.Println(err)
58 fmt.Fprintf(rw, "false")
59 } else {
60 fmt.Fprintf(rw, "true")
61 }
62 }
63
64 func main() {
65 http.HandleFunc("/build", rooms)
66 http.HandleFunc("/updateRoom", updateRoom)
67 log.Fatal(http.ListenAndServe(":8002", nil))
68 }
复制代码
mgo的安装 请参见 http://labix.org/mgo
另由于最近的工作一直需要2台电脑。一台mac本,另一台win。所以经常2台电脑间要copy文件。很蛋疼。用go写了个简单的文件服务器。用上之后,周大爷@kklldog
再也不用担心我的文件分享了
package main
import (
"net/http"
"flag"
"os"
"fmt"
"log"
)
func main() {
flag.Parse()
arg := flag.Arg(0);
if(arg == "") {
fmt.Println("请输入服务地址")
os.Exit(1)
}
port := flag.Arg(1)
if port == "" {
port = "88"
}
http.Handle("/", http.FileServer(http.Dir(arg)));
log.Fatal(http.ListenAndServe(fmt.Sprintf(":%d",port), nil))
}