golang Mongo Mgo备忘单

Mongo Mgo备忘单

query_find.go
sess := mgoSession()

sess.DB("db").C("collection").
		Find(bson.M{"items": bson.M{"$elemMatch": bson.M{"name": item}}}).
		All(&oL)
insert.go
sess := mgoSession()

collection := sess.DB("db").C("collection")
collection.Insert(&offer)
conn.go
func mgoSession() *mgo.Session {
	uri := "127.0.0.1"
	if uri == "" {
		fmt.Println("no connection string provided")
		os.Exit(1)
	}

	sess, err := mgo.Dial(uri)
	if err != nil {
		fmt.Printf("Can't connect to mongo, go error %v\n", err)
		os.Exit(1)
	}
	// defer sess.Close()

	return sess
}

golang gorp_for_postgres.go

gorp_for_postgres.go

gistfile1.go
package main

import (
	"database/sql"
	_ "github.com/lib/pq"
	"gopkg.in/gorp.v1"
	"log"
	"time"
)

func main() {
	// initialize the DbMap
	dbmap := initDb()
	defer dbmap.Db.Close()

	// delete any existing rows
	err := dbmap.TruncateTables()
	checkErr(err, "TruncateTables failed")

	// create two posts
	p1 := newPost("Go 1.1 released!", "Lorem ipsum lorem ipsum")
	p2 := newPost("Go 1.2 released!", "Lorem ipsum lorem ipsum")

	// insert rows - auto increment PKs will be set properly after the insert
	err = dbmap.Insert(&p1, &p2)
	checkErr(err, "Insert failed")

	// use convenience SelectInt
	count, err := dbmap.SelectInt("select count(*) from posts")
	checkErr(err, "select count(*) failed")
	log.Println("Rows after inserting:", count)

	// update a row
	p2.Title = "Go 1.2 is better than ever"
	count, err = dbmap.Update(&p2)
	checkErr(err, "Update failed")
	log.Println("Rows updated:", count)

	// fetch one row - note use of "post_id" instead of "Id" since column is aliased
	//
	// Postgres users should use $1 instead of ? placeholders
	// See 'Known Issues' below
	//
	err = dbmap.SelectOne(&p2, "select * from posts where post_id=$1", p2.Id)
	checkErr(err, "SelectOne failed")
	log.Println("p2 row:", p2)

	// fetch all rows
	var posts []Post
	_, err = dbmap.Select(&posts, "select * from posts order by post_id")
	checkErr(err, "Select failed")
	log.Println("All rows:")
	for x, p := range posts {
		log.Printf("    %d: %v\n", x, p)
	}

	// delete row by PK
	count, err = dbmap.Delete(&p1)
	checkErr(err, "Delete failed")
	log.Println("Rows deleted:", count)

	// delete row manually via Exec
	_, err = dbmap.Exec("delete from posts where post_id=$1", p2.Id)
	checkErr(err, "Exec failed")

	// confirm count is zero
	count, err = dbmap.SelectInt("select count(*) from posts")
	checkErr(err, "select count(*) failed")
	log.Println("Row count - should be zero:", count)

	log.Println("Done!")
}

type Post struct {
	// db tag lets you specify the column name if it differs from the struct field
	Id      int64 `db:"post_id"`
	Created int64
	Title   string
	Body    string
}

func newPost(title, body string) Post {
	return Post{
		Created: time.Now().UnixNano(),
		Title:   title,
		Body:    body,
	}
}

func initDb() *gorp.DbMap {
	// connect to db using standard Go database/sql API
	// use whatever database/sql driver you wish
	db, err := sql.Open("postgres", "user=test1 dbname=cName sslmode=disable")
	checkErr(err, "sql.Open failed")

	// construct a gorp DbMap
	dbmap := &gorp.DbMap{Db: db, Dialect: gorp.PostgresDialect{}}

	// add a table, setting the table name to 'posts' and
	// specifying that the Id property is an auto incrementing PK
	dbmap.AddTableWithName(Post{}, "posts").SetKeys(true, "Id")

	// create the table. in a production system you'd generally
	// use a migration tool, or create the tables via scripts
	err = dbmap.CreateTablesIfNotExists()
	checkErr(err, "Create tables failed")

	return dbmap
}

func checkErr(err error, msg string) {
	if err != nil {
		log.Fatalln(msg, err)
	}
}

golang 滤波

滤波

filter.go
package main

import (
	"fmt"
	"sync"
)

type FilterFunc func(int) bool

func notTwo(value int) bool {
	return value == 2
}

func notFive(value int) bool {
	return value == 5
}

func main() {

	a := []int{1, 2, 3, 4, 5, 6, 7, 8}
	b := filter(a, notTwo, notFive)
	fmt.Println(a)
	fmt.Println(b)
}

//=======================================================================
/**
filter function
 */
func filter(a []int, filters ...FilterFunc) []int {
	var wg sync.WaitGroup
	resChan := make(chan int, len(a))
	for _, value := range a {
		wg.Add(1)
		go filtering(value, &wg, resChan, filters...)
	}
	wg.Wait()
	close(resChan)

	res := make([]int, 0)
	for val := range resChan {
		res = append(res, val)
	}
	return res
}

/**
do filtering for value
 */
func filtering(value int, wg *sync.WaitGroup, resChan chan int, filters... FilterFunc) {
	defer wg.Done()
	println("value: ", value)
	for _, filter := range filters {
		if filter(value) {
			return
		}
	}
	resChan<-value
}

golang 以脚本运行Go程序

以脚本运行Go程序

script.go
//usr/bin/env go run $0 "$@"; exit
package main

import (
	"fmt"
	"os"
)

func main() {
	fmt.Println("Hello world!")
	cwd, _ := os.Getwd()
	fmt.Println("cwd:", cwd)
	fmt.Println("args:", os.Args[1:])
}

golang 以脚本运行Go程序

以脚本运行Go程序

script.go
//usr/bin/env go run $0 "$@"; exit
package main

import (
	"fmt"
	"os"
)

func main() {
	fmt.Println("Hello world!")
	cwd, _ := os.Getwd()
	fmt.Println("cwd:", cwd)
	fmt.Println("args:", os.Args[1:])
}

golang 将元素添加到切片中

将元素添加到切片中

prepend.go
func prepend(arr []string, item string) {
  return append([]string{item}, arr...)
}

golang hello.go

start_go.sh
#!/bin/bash

echo Stop Apache2

sudo service apache2 stop

echo Format Source Code...
go fmt hello.go
echo Build go package
go build hello.go
echo run go server
sudo ./hello
hello.go
package main

import (
	"fmt"
	"log"
	"net/http"
)

func helloworld(w http.ResponseWriter, r *http.Request) {
	fmt.Fprintf(w, "Hello Go World!")
}

func main() {
    port := 80
	fmt.Println("Start Listen port ", port)
	http.HandleFunc("/", helloworld)
	err := http.ListenAndServe(fmt.Sprintf(":%d", port), nil)
	if err != nil {
		log.Fatal("Error in ListenAndServe: ", err)
	}
}

golang grace.go

grace.go
package main

import (
	"log"
	"net"
	"os"
	"os/signal"
	"sync"
	"syscall"
	"time"
)

// An uninteresting service.
type Service struct {
	ch        chan bool
	waitGroup *sync.WaitGroup
}

// Make a new Service.
func NewService() *Service {
	s := &Service{
		ch:        make(chan bool),
		waitGroup: &sync.WaitGroup{},
	}
	s.waitGroup.Add(1)
	return s
}

// Accept connections and spawn a goroutine to serve each one.  Stop listening
// if anything is received on the service's channel.
func (s *Service) Serve(listener *net.TCPListener) {
	defer s.waitGroup.Done()
	for {
		select {
		case <-s.ch:
			log.Println("stopping listening on", listener.Addr())
			listener.Close()
			return
		default:
		}
		listener.SetDeadline(time.Now().Add(1e9))
		conn, err := listener.AcceptTCP()
		if nil != err {
			if opErr, ok := err.(*net.OpError); ok && opErr.Timeout() {
				continue
			}
			log.Println(err)
		}
		log.Println(conn.RemoteAddr(), "connected")
		s.waitGroup.Add(1)
		go s.serve(conn)
	}
}

// Stop the service by closing the service's channel.  Block until the service
// is really stopped.
func (s *Service) Stop() {
	close(s.ch)
	s.waitGroup.Wait()
}

// Serve a connection by reading and writing what was read.  That's right, this
// is an echo service.  Stop reading and writing if anything is received on the
// service's channel but only after writing what was read.
func (s *Service) serve(conn *net.TCPConn) {
	defer conn.Close()
	defer s.waitGroup.Done()
	for {
		select {
		case <-s.ch:
			log.Println("disconnecting", conn.RemoteAddr())
			return
		default:
		}
		conn.SetDeadline(time.Now().Add(1e9))
		buf := make([]byte, 4096)
		if _, err := conn.Read(buf); nil != err {
			if opErr, ok := err.(*net.OpError); ok && opErr.Timeout() {
				continue
			}
			log.Println(err)
			return
		}
		if _, err := conn.Write(buf); nil != err {
			log.Println(err)
			return
		}
	}
}

func main() {

	// Listen on 127.0.0.1:48879.  That's my favorite port number because in
	// hex 48879 is 0xBEEF.
	laddr, err := net.ResolveTCPAddr("tcp", "127.0.0.1:48879")
	if nil != err {
		log.Fatalln(err)
	}
	listener, err := net.ListenTCP("tcp", laddr)
	if nil != err {
		log.Fatalln(err)
	}
	log.Println("listening on", listener.Addr())

	// Make a new service and send it into the background.
	service := NewService()
	go service.Serve(listener)

	// Handle SIGINT and SIGTERM.
	ch := make(chan os.Signal)
	signal.Notify(ch, syscall.SIGINT, syscall.SIGTERM)
	log.Println(<-ch)

	// Stop the service gracefully.
	service.Stop()

}

golang 用Go编写的IRC bot,在RethinkDB集群遇到问题时提供通知

用Go编写的IRC bot,在RethinkDB集群遇到问题时提供通知

main.go
package main

import (
	"code.google.com/p/gcfg"
	"fmt"
	r "github.com/dancannon/gorethink"
	irc "github.com/fluffle/goirc/client"
	"log"
	"strings"
)

type Config struct {
	IRC struct{ Host, Channel, Nickname string }
	DB  struct{ Host string }
}

type Issue struct {
	Description, Type string
}

type Server struct {
	Name, Status string
}

func main() {
	quit := make(chan bool, 1)

	var config Config
	if err := gcfg.ReadFileInto(&config, "config.gcfg"); err != nil {
		log.Fatal("Couldn't read configuration")
	}

	db, err := r.Connect(r.ConnectOpts{Address: config.DB.Host})
	if err != nil {
		log.Fatal("Database connection failed:", err)
	}

	ircConf := irc.NewConfig(config.IRC.Nickname)
	ircConf.Server = config.IRC.Host
	bot := irc.Client(ircConf)

	bot.HandleFunc("connected", func(conn *irc.Conn, line *irc.Line) {
		log.Println("Connected to IRC server", config.IRC.Host)
		conn.Join(config.IRC.Channel)
	})

	bot.HandleFunc("privmsg", func(conn *irc.Conn, line *irc.Line) {
		log.Println("Received:", line.Nick, line.Text())
		if strings.HasPrefix(line.Text(), config.IRC.Nickname) {
			command := strings.Split(line.Text(), " ")[1]
			switch command {
			case "quit":
				log.Println("Received command to quit")
				quit <- true
			}
		}
	})

	log.Println("Connecting to IRC server", config.IRC.Host)
	if err := bot.Connect(); err != nil {
		log.Fatal("IRC connection failed:", err)
	}

	issues, _ := r.Db("rethinkdb").Table("current_issues").Filter(
		r.Row.Field("critical").Eq(true)).Changes().Field("new_val").Run(db)

	go func() {
		var issue Issue
		for issues.Next(&issue) {
			if issue.Type != "" {
				text := strings.Split(issue.Description, "\n")[0]
				message := fmt.Sprintf("(%s) %s ...", issue.Type, text)
				bot.Privmsg(config.IRC.Channel, message)
			}
		}
	}()

	<-quit
}

golang 去实用工具

去实用工具

request_json_to_object.go
package goUtils

import (
	"encoding/json"
	"io/ioutil"
	"net/http"
)

func reqJsonToObject(resp *http.Response, v interface{}) error {
	defer resp.Body.Close()

	content, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return err
	} else {
		json.Unmarshal(content, &v)
		return nil
	}
}