我的第一个go程序
package main
import (
"fmt"
"github.com/go-redis/redis"
"github.com/golang/protobuf/proto"
"github.com/user/appcpi/game/protobuf/game_data"
"os"
"log"
//"unsafe"
"encoding/json"
)
func checkFile(filename string) {
_, err := os.Stat(filename)
if err == nil {
os.Remove(filename)
}
}
func createFileAndWrite(filename string, data []byte) {
checkFile(filename)
file, err := os.Create(filename)
if err != nil {
log.Fatal("create %s err:%s \n", filename, err)
}
file.Write(data)
/*if err != nil {
log.Fatal("write len(data)=%d err:%s \n", data, err)
}*/
file.Close()
}
func parseGameProto(data string) []byte{
game_data := &APPCPI_GAME.GameData{}
err := proto.Unmarshal([]byte(data), game_data)
if err != nil {
log.Fatal("GameData Unmarshal err: %s\n", err)
}
result, err := json.MarshalIndent(game_data, "", " ")
if err != nil {
log.Fatal("GameData arshalIndent err: %s\n", err)
}
return result
}
func parseTicketProto(data string) []byte{
ticket := &APPCPI_GAME.TicketInfo{}
err := proto.Unmarshal([]byte(data), ticket)
if err != nil {
log.Fatal("ticket Unmarshal err: %s\n", err)
}
result, err := json.MarshalIndent(ticket, "", " ")
if err != nil {
log.Fatal("ticket arshalIndent err: %s\n", err)
}
return result
}
func getRecord(client *redis.Client, id string) {
data, err := client.HGetAll(id).Result()
if err != nil {
log.Fatal("HGetAll(%s) err: %s\n", id, err)
}
for k,v := range(data) {
fmt.Printf("k:%s len(v):%d\n", k, len(v))
if k == "game" {
createFileAndWrite(id + "_game.txt", parseGameProto(v))
} else if k == "ticket" {
createFileAndWrite(id + "_ticket.txt", parseTicketProto(v))
}
}
}
func main() {
argv := os.Args[1:]
if len(argv) < 1 {
fmt.Printf("Usage:%s [user_id] {IP} {PORT}\n", os.Args[0])
os.Exit(0)
}
var Addr string
if len(argv) >= 3 {
Addr += argv[1]
Addr += ":"
Addr += argv[2]
} else {
Addr = "127.0.0.1:7003"
}
client := redis.NewClient(&redis.Options{
Addr: Addr,
Password: "", // no password set
DB: 0, // use default DB
})
//fmt.Printf("type:%s\n", unsafe.Sizeof(client))
_, err := client.Ping().Result()
if err != nil {
log.Fatal("redis ping err:%s \n", err)
}
//fmt.Println(pong, err)
getRecord(client, argv[0])
}
解释
- 从输入获取要查找的键值及Redis的IP和Port
- 连接Redis
- 从Redis获取Hash数据
- 将Hash数据根据Key,处理相应的value,将其转换成Proto格式
- 将Proto格式以转换成可阅读的格式输出到文件
技术点
- Redis操作
- Protobuf操作
- 文件操作
- 其他基本操作
go新手,有疑问的可以评论共同学习。。
网友评论