分类 编程 下的文章

方案一:

package main

import (
    "fmt"
    "runtime"
    "sync"
    "time"
)

// 定义一个同步等待的组
var wg sync.WaitGroup

// 定义一个Printer函数用于并发
func Printer(a int) {
    time.Sleep(2000 * time.Millisecond)
    fmt.Printf("i am %d\n", a)
    defer wg.Done()
}

func main() {
    // 获取cpu个数
    maxProcs := runtime.NumCPU()
    // 限制同时运行的goroutines数量
    runtime.GOMAXPROCS(maxProcs)
    for i := 0; i < 10; i++ {
        //为同步等待组增加一个成员
        wg.Add(1)
        //并发一个goroutine
        go Printer(i)
    }
    // 阻塞等待所有组内成员都执行完毕退栈
    wg.Wait()
    fmt.Println("WE DONE!!!")
}

- 阅读剩余部分 -

引入包

import (
    "net/http"
)

具体实现

// HTTPGet compatible http & https
func HTTPGet(reqURL string) []byte {
    tr := &http.Transport{
        TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
    }
    c := &http.Client{
        Transport: tr,
        Timeout:   30 * time.Second,
    }
    res, err := c.Get(reqURL)
    if err != nil {
        fmt.Println(err)
    }
    body, _ := ioutil.ReadAll(res.Body)
    res.Body.Close()
    responeDate := make(map[string]interface{})
    json.Unmarshal([]byte(string(body)), &responeDate)
    return responeDate
}

// HTTPPost is post func
func HTTPPost(reqURL, reqData string) map[string]interface{} {
    req, _ := http.NewRequest("POST", reqURL, strings.NewReader(reqData))
    req.Header.Set("Content-Type", "application/json")
    c := &http.Client{
        Timeout: 9 * time.Second,
    }
    res, err := c.Do(req)
    if err != nil {
        fmt.Println(err)
        return nil
    }
    body, _ := ioutil.ReadAll(res.Body)
    res.Body.Close()
    responeDate := make(map[string]interface{})
    json.Unmarshal([]byte(string(body)), &responeDate)
    return responeDate
}

// HTTPPut is post func
func HTTPPut(reqURL, reqData string) map[string]interface{} {
    req, _ := http.NewRequest("PUT", reqURL, strings.NewReader(reqData))
    req.Header.Set("Content-Type", "application/json")
    c := &http.Client{
        Timeout: 9 * time.Second,
    }
    res, err := c.Do(req)
    if err != nil {
        fmt.Println(err)
        return nil
    }
    body, _ := ioutil.ReadAll(res.Body)
    res.Body.Close()
    responeDate := make(map[string]interface{})
    json.Unmarshal([]byte(string(body)), &responeDate)
    return responeDate
}

// HTTPDelete is delete func
func HTTPDelete(reqURL, reqData string) map[string]interface{} {
    req, _ := http.NewRequest("DELETE", reqURL, strings.NewReader(reqData))
    req.Header.Set("Content-Type", "application/json")
    c := &http.Client{
        Timeout: 9 * time.Second,
    }
    res, err := c.Do(req)
    if err != nil {
        fmt.Println(err)
        return nil
    }
    body, _ := ioutil.ReadAll(res.Body)
    res.Body.Close()
    responeDate := make(map[string]interface{})
    json.Unmarshal([]byte(string(body)), &responeDate)
    return responeDate
}

https://github.com/garyburd/redigo/

引入库

import (
    "github.com/garyburd/redigo/redis"
)

查询数据

cli, cerr := redis.Dial("tcp", ip:port, redis.DialPassword(redisPasswd), redis.DialDatabase(1))
if cerr != nil {
    fmt.Println(cerr)
}
defer cli.Close()
// 查询 key
val, err := redis.String(cli.Do("GET", key))
if err != nil {
    fmt.Println(err)
}
return val

写入数据

cli, cerr := redis.Dial("tcp", ip:port, redis.DialPassword(redisPasswd), redis.DialDatabase(1))
if cerr != nil {
    fmt.Println(cerr)
}
defer cli.Close()
_, err := cli.Do("SET", key, value)
if err != nil {
    fmt.Println(err)
}

package main

import (
    "fmt"
    "time"
)

func timeCost(start time.Time) {
    terminal := time.Since(start)
    fmt.Println(terminal)
}

func main() {
    defer timeCost(time.Now())
    fmt.Println("start program")
    time.Sleep(5 * time.Second)
    fmt.Println("finish program")
}

https://github.com/go-sql-driver/mysql

引入库

import (
    "database/sql"

    _ "github.com/go-sql-driver/mysql"
)

查询数据

// 建立 MySQL 链接
db, err := sql.Open("mysql", "user:passwd@tcp(ip:port)/db")
if err != nil {
    fmt.Println(err)
}
defer db.Close()
// 执行 SQL
rows, rerr := db.Query(sqlInfo)
if rerr != nil {
    fmt.Println(rerr)
}
defer rows.Close()
// 获取 SQL 数据
for rows.Next() {
    var returnData string
    err := rows.Scan(&returnData)
    if err != nil {
        fmt.Println(err)
    }
    return returnData
}
return returnData

写入/更新数据

// 建立 MySQL 链接
db, err := sql.Open("mysql", "user:passwd@tcp(ip:port)/db")
if err != nil {
    fmt.Println(err)
}
defer db.Close()
// 执行 SQL
db.Exec(sqlInfo)

new 和 make 都可以用来分配空间,初始化类型,但是它们确有不同。
new(T)返回的是 T 的指针
new(T)为一个 T 类型新值分配空间并将此空间初始化为 T 的零值,返回的是新值的地址,也就是 T 类型的指针 *T,该指针指向 T 的新分配的零值。

package main

import "fmt"

func main() {
    p1 := new(int)
    fmt.Printf("p1 --> %#v \n ", p1)
    fmt.Printf("p1 point to --> %#v \n ", *p1)

    var p2 *int
    i := 0
    p2 = &i
    fmt.Printf("p2 --> %#v \n ", p2)
    fmt.Printf("p2 point to --> %#v \n ", *p2)
}

- 阅读剩余部分 -

读 excel

package main
    
import (
    "fmt"
    
    "github.com/tealeg/xlsx"
)
    
func main() {
    excelFileName := "test.xls"
    xlFile, _ := xlsx.OpenFile(excelFileName)
    for _, sheet := range xlFile.Sheets {
        for _, row := range sheet.Rows {
            for _, cell := range row.Cells {
                fmt.Println(cell.String())
            }
        }
    }
}

写 excel

package main
    
import (
    "encoding/csv"
    "os"
)
    
func main() {
    f, err := os.Create("test.xls")
    if err != nil {
        panic(err)
    }
    defer f.Close()
    // 写入 utf-8 编码
    f.WriteString("\xEF\xBB\xBF")
    w := csv.NewWriter(f)
    w.Write([]string{"编号", "姓名", "年龄"})
    w.Write([]string{"1", "张三", "23"})
    w.Write([]string{"2", "李四", "24"})
    w.Write([]string{"3", "王五", "25"})
    w.Write([]string{"4", "赵六", "26"})
    w.Flush()
}

package main

import (
    "fmt"
"strconv"
    "time"
)

// TimeUnix is time for unix
func TimeUnix() string {
naiveTime := time.Now().Unix()
naiveTimeString := strconv.FormatInt(naiveTime, 10)
return naiveTimeString
}

func main() {
    timeNow := time.Now()
    fmt.Println("tNow(time format): ", timeNow)
    
    // 时间转化为 string layout 必须为 "2006-01-02 15:04:05"
    timeNowStr := timeNow.Format("2006-01-02 15:04:05")
    fmt.Println("tNow(string format): ", timeNowStr)

    timeNowUnixInt := timeNow.Unix()
    fmt.Println(timeNowUnixInt)

    // string 转化为时间 layout 必须为 "2006-01-02 15:04:05"
    t1, _ := time.Parse("2006-01-02 15:04:05", "2014-06-15 08:37:18")
    fmt.Println("t(time format): ", t1)
    t2 := time.Unix(1389058332, 0).Format("2006-01-02 15:04:05")
    fmt.Println("t(time format): ", t2)
}