- 数据库 *** 作
- mysql
- 增删改查
- redis
- string的get和set
- string的批量MGet和MSet *** 作
- list *** 作
- Hash表
- *** 作kafka
- gorm
- 常用标准库
- time
- 格式化时间 time.Format()
- 时间戳
- 时间戳转时间
- log
- 普通log
- 配置logger
- 反射reflect
- 框架
增加数据add
package main import ( "fmt" _ "github.com/go-sql-driver/mysql" "github.com/jmoiron/sqlx" ) type Person1 struct { UserId int `db:"user_id"` Username string `db:"username"` Sex string `db:"sex"` Email string `db:"email"` } type Place struct { Country string `db:"country"` City string `db:"city"` TelCode int `db:"telcode"` } var Db *sqlx.DB func init() { database, err := sqlx.Open("mysql", "root:root@tcp(127.0.0.1:3306)/test") if err != nil { fmt.Println("open mysql failed,", err) return } Db = database } func main() { r, err := Db.Exec("insert into person(username, sex, email)values(?, ?, ?)", "弗拉基米尔", "男", "rita@qq.com") if err != nil { fmt.Println("exec failed, ", err) return } id, err := r.LastInsertId() if err != nil { fmt.Println("exec failed, ", err) return } fmt.Println("insert succ:", id) defer Db.Close() // 注意这行代码要写在上面err判断的下面 }
查询select
package main import ( "fmt" _ "github.com/go-sql-driver/mysql" "github.com/jmoiron/sqlx" ) type Person1 struct { UserId int `db:"user_id"` Username string `db:"username"` Sex string `db:"sex"` Email string `db:"email"` } type Place struct { Country string `db:"country"` City string `db:"city"` TelCode int `db:"telcode"` } var Db *sqlx.DB func init() { database, err := sqlx.Open("mysql", "root:root@tcp(127.0.0.1:3306)/test") if err != nil { fmt.Println("open mysql failed,", err) return } Db = database } func main() { var person []Person1 err := Db.Select(&person, "select user_id, username, sex, email from person") if err != nil { fmt.Println("exec failed, ", err) return } fmt.Println("select succ:", person) defer Db.Close() // 注意这行代码要写在上面err判断的下面 }
修改update
package main import ( "fmt" _ "github.com/go-sql-driver/mysql" "github.com/jmoiron/sqlx" ) type Person1 struct { UserId int `db:"user_id"` Username string `db:"username"` Sex string `db:"sex"` Email string `db:"email"` } type Place struct { Country string `db:"country"` City string `db:"city"` TelCode int `db:"telcode"` } var Db *sqlx.DB func init() { database, err := sqlx.Open("mysql", "root:root@tcp(127.0.0.1:3306)/test") if err != nil { fmt.Println("open mysql failed,", err) return } Db = database } func main() { res, err := Db.Exec("update person set username=? where user_id=?", "伊泽瑞尔", 2) if err != nil { fmt.Println("exec failed, ", err) return } row, err := res.RowsAffected() if err != nil{ fmt.Println("update failed..., ", err) } fmt.Println("udpate succ:", row) defer Db.Close() // 注意这行代码要写在上面err判断的下面 }
删除delete
package main import ( "fmt" _ "github.com/go-sql-driver/mysql" "github.com/jmoiron/sqlx" ) type Person1 struct { UserId int `db:"user_id"` Username string `db:"username"` Sex string `db:"sex"` Email string `db:"email"` } type Place struct { Country string `db:"country"` City string `db:"city"` TelCode int `db:"telcode"` } var Db *sqlx.DB func init() { database, err := sqlx.Open("mysql", "root:root@tcp(127.0.0.1:3306)/test") if err != nil { fmt.Println("open mysql failed,", err) return } Db = database } func main() { res, err := Db.Exec("delete from person where user_id=?", 2) if err != nil { fmt.Println("exec failed, ", err) return } row, err := res.RowsAffected() if err != nil{ fmt.Println("delete failed..., ", err) } fmt.Println("delete succ:", row) defer Db.Close() // 注意这行代码要写在上面err判断的下面 }redis string的get和set
package main import ( "fmt" "github.com/garyburd/redigo/redis" ) func main() { r, err := redis.Dial("tcp", "localhost:6379") if err != nil{ fmt.Println("conn redis failed,", err) return } fmt.Println("redis conn success") defer r.Close() _, err = r.Do("Set", "abc", 100) if err != nil{ fmt.Println(err) return } rg, err := redis.Int(r.Do("Get", "abc")) if err != nil{ fmt.Println(err) return } fmt.Println(rg) }string的批量MGet和MSet *** 作
package main import ( "fmt" "github.com/garyburd/redigo/redis" ) func main() { r, err := redis.Dial("tcp", "localhost:6379") if err != nil{ fmt.Println("conn redis failed,", err) return } fmt.Println("redis conn success") defer r.Close() _, err = r.Do("MSet", "杜拉基米尔", 100, "法外狂徒", 200) if err != nil{ fmt.Println(err) return } rg, err := redis.Ints(r.Do("MGet", "杜拉基米尔", "法外狂徒")) if err != nil{ fmt.Println(err) return } fmt.Println(rg) }list *** 作
package main import ( "fmt" "github.com/garyburd/redigo/redis" ) func main() { r, err := redis.Dial("tcp", "localhost:6379") if err != nil{ fmt.Println("conn redis failed,", err) return } fmt.Println("redis conn success") defer r.Close() _, err = r.Do("lpush", "name_list", "死亡宣告", "黑暗收割者", "死神封印") if err != nil{ fmt.Println(err) return } rg, err := redis.String(r.Do("lpop", "name_list")) if err != nil{ fmt.Println("get name_list,", err) return } fmt.Println(rg) }Hash表
package main import ( "fmt" "github.com/garyburd/redigo/redis" ) func main() { r, err := redis.Dial("tcp", "localhost:6379") if err != nil{ fmt.Println("conn redis failed,", err) return } fmt.Println("redis conn success") defer r.Close() _, err = r.Do("HSet", "books", "efg", 200) if err != nil{ fmt.Println(err) return } rg, err := redis.Int(r.Do("HGet", "books", "efg")) if err != nil{ fmt.Println("get name_list,", err) return } fmt.Println(rg) }*** 作kafka
- 生产者
package main import ( "fmt" "github.com/Shopify/sarama" ) func main() { config := sarama.NewConfig() config.Producer.RequiredAcks = sarama.WaitForAll config.Producer.Partitioner = sarama.NewRandomPartitioner config.Producer.Return.Successes = true // 构造一个消息 msg := &sarama.ProducerMessage{} msg.Topic = "test" msg.Value = sarama.StringEncoder(`{"a": 1, "b": 2}`) client, err := sarama.NewSyncProducer([]string{"127.0.0.1:9092"}, config) if err != nil{ fmt.Println("producer closed, err:", err) } defer client.Close() // 发送消息 pid, offset, err := client.SendMessage(msg) if err != nil{ fmt.Println("send msg failed, err:", err) return } fmt.Printf("pid:%v offset:%vn", pid, offset) }
- 消费者
package main import ( "fmt" "github.com/Shopify/sarama" ) func main() { consumer, err := sarama.NewConsumer([]string{"127.0.0.0.1:9092"}, nil) if err != nil{ fmt.Printf("failed to start consumer, err:%vn", err) return } patitionList, err := consumer.Partitions("test") if err != nil { fmt.Printf("failed to get list of patitionList, err:%vn", err) return } fmt.Println(patitionList) for par:= range patitionList{ pc, err := consumer.ConsumePartition("test", int32(par), sarama.OffsetNewest) if err != nil{ fmt.Printf("failed to start consumer partition %d,err:%vn", par, err) return } defer pc.AsyncClose() go func(sarama.PartitionConsumer) { for msg := range pc.Messages(){ fmt.Printf("Partition:%d Offset:%d Key:%v Value:%v", msg.Partition, msg.Offset, msg.Key, msg.Value) } }(pc) } }gorm
package main import ( "fmt" "github.com/jinzhu/gorm" _ "github.com/jinzhu/gorm/dialects/mysql" "time" ) func main() { db, err := gorm.Open("mysql", "root:root@(localhost:3306)/test?charset=utf8&parseTime=True&loc=Local") // 这里的库后面是没有/的 if err != nil { fmt.Println("failed to connect mysql:", err) return } defer db.Close() // 自动迁移数据结构(table schema) //db.AutoMigrate(&User{}) //db.Create(&User{Name: "卡西奥佩娅", Age: 18, Birthday: time.Now(), Email: "ritashenv@qq.com", PassWord: "adcsadsad"}) //db.Create(&User{Name: "诺克萨斯之手", Age: 25, Birthday: time.Now(), Email: "ritanuoke@qq.com", PassWord: "okmjjad"}) var users []User db.Find(&users) fmt.Println(users) } type User struct { gorm.Model Id uint `gorm:"AUTO_INCREMENT"` Name string `gorm:"size:50"` Age int `gorm:"size:3"` Birthday time.Time Email string `gorm:"type:varchar(50);unique_index"` PassWord string `gorm:"type:varchar(25)"` }常用标准库 time 格式化时间 time.Format()
package main import ( "fmt" "time" ) func main() { now := time.Now() fmt.Println(now) // 24小时制 fmt.Println(now.Format("2006-01-02 15:04:05")) fmt.Println(now.Format("2006-01-02 15:04:05.000 Mon Jan")) // 12小时制 fmt.Println(now.Format("2006-01-02 03:04:05.000 PM Mon Jan")) fmt.Println(now.Format("2006/01/02 15:04")) fmt.Println(now.Format("15:04 2006/01/02")) fmt.Println(now.Format("2006/01/02")) }时间戳
package main import ( "fmt" "time" ) func main() { now := time.Now() fmt.Println(now.Format("2006-01-02 15:04:05")) // 时间戳 timestamp := now.Unix() fmt.Println(timestamp) // 秒级时间戳 fmt.Println(timestamp * 1000) // 毫秒级时间戳 nanostamp := now.UnixNano() fmt.Println(nanostamp) // 纳秒级时间戳 }时间戳转时间
package main import ( "fmt" "time" ) func main() { now := time.Now() fmt.Println(now.Format("2006-01-02 15:04:05")) // 时间戳 timestamp := now.Unix() timeFormat := time.Unix(timestamp, 0) // 将时间戳转时间 fmt.Println(timeFormat.Format("2006-01-02 15:04:05")) }log 普通log
package main import "log" func main() { log.Println("这是一个很普通的日志") v := "花姿彩" log.Printf("这是一条%s日志n", v) log.Fatalln("这是一条会触发fatal的日志") }配置logger
log标准库中的Flags函数会返回标准logger的输出配置,而SetFlags函数用来设置标准logger的输出配置。
log标准库提供了如下的flag选项,它们是一系列定义好的常量。
const ( // 控制输出日志信息的细节,不能控制输出的顺序和格式。 // 输出的日志在每一项后会有一个冒号分隔:例如2009/01/23 01:23:23.123123 /a/b/c/d.go:23: message Ldate = 1 << iota // 日期:2009/01/23 Ltime // 时间:01:23:23 Lmicroseconds // 微秒级别的时间:01:23:23.123123(用于增强Ltime位) Llongfile // 文件全路径名+行号: /a/b/c/d.go:23 Lshortfile // 文件名+行号:d.go:23(会覆盖掉Llongfile) LUTC // 使用UTC时间 LstdFlags = Ldate | Ltime // 标准logger的初始值 )
package main import ( "log" ) func main() { log.SetFlags(log.Llongfile|log.Lmicroseconds|log.Ldate) log.Println("这是一个很普通的日志") // 配置日志前缀 log.SetPrefix("[INFO] ") log.Println("这是一个很普通的日志") }反射reflect
package main import ( "fmt" "reflect" ) func main() { x := 3.4 t := reflect.TypeOf(x) // 查看类型 fmt.Println(t) k := t.Kind() // kind可以获取具体类型 fmt.Println(k) }框架
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)