Json 解析
package main
import (
"encoding/json"
"fmt"
"os"
)
type MongoConfig struct {
MongoAddr string
MongoPoolLimit int
MongoDb string
MongoCollection string
}
type Config struct {
Port string
Mongo MongoConfig
}
func main() {
JsonParse := NewJsonStruct()
v := Config{}
if err := JsonParse.Load("json_parse.json", &v); err != nil {
fmt.Println("Error loading configuration:", err)
return
}
fmt.Println("Port:", v.Port)
fmt.Println("MongoDb:", v.Mongo.MongoDb)
}
type JsonStruct struct{}
func NewJsonStruct() *JsonStruct {
return &JsonStruct{}
}
func (js *JsonStruct) Load(filename string, v interface{}) error {
data, err := os.ReadFile(filename)
if err != nil {
return err
}
if err = json.Unmarshal(data, v); err != nil {
return err
}
return nil
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
生成 Json
package main
import (
"encoding/json"
"fmt"
"os"
)
type User struct {
UserName string
NickName string `bson:"nickName"`
Email string
}
func main() {
user := &User{
UserName: "Jack",
NickName: "Ma",
Email: "xxxxx@qq.com",
}
data, err := json.Marshal(user)
if err != nil {
fmt.Printf("json.Marshal failed,err:", err)
return
}
fmt.Printf("%s\n", string(data))
file, _ := os.Create("json_write.json")
defer file.Close()
file.Write(data)
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
Regexp 包应用示例
匹配电话号码
package main
import (
"fmt"
"regexp"
)
func findPhoneNumber(str string) bool {
reg := regexp.MustCompile("^1[1-9]{10}")
res := reg.FindAllString(str, -1)
if res == nil {
return false
}
return true
}
func main() {
res2 := findPhoneNumber("13688888888")
fmt.Println(res2)
res2 = findPhoneNumber("02888888888")
fmt.Println(res2)
res2 = findPhoneNumber("123456789")
fmt.Println(res2)
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
匹配 Email
package main
import (
"fmt"
"regexp"
)
func findEmail(str string) bool {
reg := regexp.MustCompile("^[a-zA-Z0-9_]+@[a-zA-Z0-9]+\\.[a-zA-Z0-9]+")
res := reg.FindAllString(str, -1)
if res == nil {
return false
}
return true
}
func main() {
res2 := findEmail("8888@qq.com")
fmt.Println(res2)
res2 = findEmail("shir?don@qq.com")
fmt.Println(res2)
res2 = findEmail("8888@qqcom")
fmt.Println(res2)
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
从数据库导出 CSV 文件
Mysql
CREATE DATABASE UserManager;
USE UserManager;
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
`uid` int(10) NOT NULL AUTO_INCREMENT,
`name` varchar(30) DEFAULT '',
`phone` varchar(20) DEFAULT '',
`email` varchar(30) DEFAULT '',
`password` varchar(100) DEFAULT '',
PRIMARY KEY (`uid`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8 COMMENT='用户表';
BEGIN;
INSERT INTO `user` VALUES (1, 'shirdon', '1888888888', 'shirdonliao@gmail.com', '');
INSERT INTO `user` VALUES (2, 'barry', '18788888888', 'barry@163.com', '');
COMMIT;
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
Go
package main
import (
"database/sql"
"encoding/csv"
"fmt"
_ "github.com/go-sql-driver/mysql"
"log"
"os"
"strconv"
)
var db *sql.DB
type User struct {
Uid int
Name string
Phone string
Email string
Password string
}
var u User
func init() {
db, _ = sql.Open("mysql",
"account:password@tcp(127.0.0.1:3306)/UserManager?"+
"charset=utf8mb4&parseTime=True&loc=Local")
}
func main() {
filename := "./exportUsers.csv"
users := queryMultiRow()
column := [][]string{{"手机号", "用户UID", "Email", "用户名"}}
for _, u := range users {
str := []string{}
str = append(str, u.Phone)
str = append(str, strconv.Itoa(u.Uid))
str = append(str, u.Email)
str = append(str, u.Name)
column = append(column, str)
}
ExportCsv(filename, column)
}
func ExportCsv(filePath string, data [][]string) {
fp, err := os.Create(filePath)
if err != nil {
log.Fatalf("创建文件["+filePath+"]句柄失败,%v", err)
return
}
defer fp.Close()
fp.WriteString("\xEF\xBB\xBF")
w := csv.NewWriter(fp)
w.WriteAll(data)
w.Flush()
}
func queryMultiRow() []User {
rows, err := db.Query("select uid,name,phone,email from `user` where uid > ?", 0)
if err != nil {
fmt.Printf("query failed, err:%v\n", err)
return nil
}
defer rows.Close()
users := []User{}
for rows.Next() {
err := rows.Scan(&u.Uid, &u.Name, &u.Phone, &u.Email)
users = append(users, u)
if err != nil {
fmt.Printf("scan failed, err:%v\n", err)
return nil
}
}
return users
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 56
- 57
- 58
- 59
- 60
- 61
- 62
- 63
- 64
- 65
- 66
- 67
- 68
- 69
- 70
- 71
- 72
- 73
- 74
- 75
- 76
- 77
- 78
- 79
- 80
- 81
- 82
- 83
- 84
- 85
- 86
- 87
- 88
处理日志文件
Print 一般日志
package main
import (
"log"
)
func main() {
no := []int{6, 8}
log.Print("Print NO. ", no, "\n")
log.Println("Println NO.", no)
log.Printf("Printf NO. with item [%d,%d]\n", no[0], no[1])
}
Panic 意外日志
package main
import (
"log"
)
func main() {
no := []int{6, 8}
log.Panicln("Println NO.", no)
}
Fatal 致命日志
package main
import (
"log"
)
func main() {
no := []int{6, 8}
log.Fatalln("Println NO.", no)
}
自定义日志
package main
import (
"log"
"os"
)
func main() {
fileName := "New.log"
logFile, err := os.Create(fileName)
defer logFile.Close()
if err != nil {
log.Fatalln("open file error")
}
debugLog := log.New(logFile, "[Info]", log.Llongfile)
debugLog.Println("Info Level Message")
debugLog.SetPrefix("[Debug]")
debugLog.Println("Debug Level Message")
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19