golang mod开发模式

2020-10-04  本文已影响0人  hehehehe
用变量 GO111MODULE 开启或关闭模块支持,它有三个可选值:off、on、auto,默认值是 auto。
GO111MODULE=off 无模块支持,go 会从 GOPATH 和 vendor 文件夹寻找包。
GO111MODULE=on 模块支持,go 会忽略 GOPATH 和 vendor 文件夹,只根据 go.mod 下载依赖。
GO111MODULE=auto 在 $GOPATH/src 外面且根目录有 go.mod 文件时,开启模块支持。
在使用模块的时候,GOPATH 是无意义的,不过它还是会把下载的依赖储存在 $GOPATH/src/mod 中,
也会把 go install 的结果放在 $GOPATH/bin 中。
golang版本为1.14。设置方式为  go env -w GO111MODULE=on

goland中开启go module,设置 https://goproxy.cn,direct
差点忘了go断言的类型转换

https://github.com/radi2015/GolangTraining

包的导入与使用

assertion
interface type

func main() {
    var val interface{} = 7
    fmt.Println(val.(int) + 6)
}

func main() {
    name := "Sydney"
    str, ok := name.(string)
    if ok {
        fmt.Printf("%q\n", str)
    } else {
        fmt.Printf("value is not a string\n")
    }
}

func main() {
    var name interface{} = "Sydney"
    str, ok := name.(string)
    if ok {
        fmt.Printf("%T\n", str)
    } else {
        fmt.Printf("value is not a string\n")
    }
}

import (
    "fmt"
    "geom/util"
)

func main() {
    // import的是文件夹 用的是包名
    geomFromWkt := geoutil.GeomFromWkt("POLYGON ((0 0, 1 0, 1 1, 0 2, 0 0))")
}

变量覆盖

func max(x int) int {
    return 42 + x
}
func main() {
    max := max(7)
    fmt.Println(max) // max is now the result, not the function
}

return 的骚操作

func greet(fname string, lname string) (s string) {
    s = fmt.Sprint(fname, lname)
    return
}

callback

func visit(numbers []int, callback func(int)) {
    for _, n := range numbers {
        callback(n)
    }
}
func main() {
    visit([]int{1, 2, 3, 4}, func(n int) {
        fmt.Println(n)
    })
}

匿名函数并自动调用

func main() {
    func() {
        fmt.Println("I'm driving!")
    }()
}

切片 and 数组

slice
student := []string{}  0,0
var student []string nil
greeting := make([]string, 3, 5) 大于初始容量需要append


arr
var array1 = [5]int{1, 2, 3}
var array1 = [...]int{1, 2, 3}

实现了 ServerHTTP()就是子类

package main
import (
    "io"
    "net/http"
)
// MyHandler 实现了 ServerHTTP()就是子类
type MyHandler int
func (h MyHandler) ServeHTTP(res http.ResponseWriter, req *http.Request) {
    io.WriteString(res, "Hello World")
}
func main() {
    var h MyHandler
    http.ListenAndServe(":9000", h)
}

os

func main() {
    src, err := os.Open("src.txt")
    if err != nil {
        panic(err)
    }
    defer src.Close()

    dst, err := os.Create("dst.txt")
    if err != nil {
        panic(err)
    }
    defer dst.Close()

    bs := make([]byte, 5)
    src.Read(bs)
    dst.Write(bs)
}

// io.Copy
File 实现了read方法
type Reader interface {
    Read(p []byte) (n int, err error)
}
func (f *File) read(b []byte) (n int, err error) {
    n, e := fixCount(syscall.Read(f.fd, b))
    if n == 0 && len(b) > 0 && e == nil {
        return 0, io.EOF
    }
    return n, e
}
func main() {
    f, err := os.Open(os.Args[1:])
    if err != nil {
        log.Fatalln("my program broke: ", err.Error())
    }
    defer f.Close()
    //dd File 
    io.Copy(os.Stdout, f)
}

func main() {
    rdr := strings.NewReader("test")
    io.Copy(os.Stdout, rdr)
}

func main() {
    src, err := os.Open("src.txt")
    if err != nil {
        panic(err)
    }
    defer src.Close()

    dst, err := os.Create("dst.txt")
    if err != nil {
        panic(err)
    }
    defer dst.Close()

    bs := make([]byte, 5)
    io.ReadFull(src, bs)
    //rdr := io.LimitReader(src, 5)
    dst.Write(bs)
}

//write str

func main() {

    f, err := os.Create("hello.txt")
    if err != nil {
        log.Fatalln("my program broke", err.Error())
    }
    defer f.Close()

    str := "Put some phrase here."
    bs := []byte(str)

    _, err = f.Write(bs)
    //_, err = io.WriteString(f, str)
    if err != nil {
        log.Fatalln("error writing to file: ", err.Error())
    }
}

//ioutil

bs, err := ioutil.ReadAll(rdr)
err := ioutil.WriteFile("hello.txt", []byte("Hello world"), 0777)

// csv reader

func main() {
    // #1 open a file
    f, err := os.Open("../state_table.csv")
    if err != nil {
        log.Fatalln(err)
    }
    defer f.Close()

    // #2 parse a csv file
    csvReader := csv.NewReader(f)
    for {
        record, err := csvReader.Read()
        if err == io.EOF {
            break
        } else if err != nil {
            log.Fatalln(err)
        }
        fmt.Println(record)
    }
}

Anything

func SwitchOnType(x interface{}) {
    switch x.(type) { // this is an assert; asserting, "x is of this type"
    case int:
        fmt.Println("int")
    case string:
        fmt.Println("string")
    case contact:
        fmt.Println("contact")
    default:
        fmt.Println("unknown")

    }
}

mkdir

err := os.Mkdir("/somefolderthatdoesntexist", 0x777)
fpath := "/data/" + uploadID + "/" + chunkIndex
os.MkdirAll(path.Dir(fpath), 0744)

response

package util

import (
    "encoding/json"
    "fmt"
    "log"
)

// RespMsg : http响应数据的通用结构
type RespMsg struct {
    Code int         `json:"code"`
    Msg  string      `json:"msg"`
    Data interface{} `json:"data"`
}

// NewRespMsg : 生成response对象
func NewRespMsg(code int, msg string, data interface{}) *RespMsg {
    return &RespMsg{
        Code: code,
        Msg:  msg,
        Data: data,
    }
}

// JSONBytes : 对象转json格式的二进制数组
func (resp *RespMsg) JSONBytes() []byte {
    r, err := json.Marshal(resp)
    if err != nil {
        log.Println(err)
    }
    return r
}

// JSONString : 对象转json格式的string
func (resp *RespMsg) JSONString() string {
    r, err := json.Marshal(resp)
    if err != nil {
        log.Println(err)
    }
    return string(r)
}

// GenSimpleRespStream : 只包含code和message的响应体([]byte)
func GenSimpleRespStream(code int, msg string) []byte {
    return []byte(fmt.Sprintf(`{"code":%d,"msg":"%s"}`, code, msg))
}

// GenSimpleRespString : 只包含code和message的响应体(string)
func GenSimpleRespString(code int, msg string) string {
    return fmt.Sprintf(`{"code":%d,"msg":"%s"}`, code, msg)
}

redis

package redis

import (
    "fmt"
    "time"
    "github.com/garyburd/redigo/redis"
)
var (
    pool      *redis.Pool
    redisHost = "127.0.0.1:6379"
    redisPass = "testupload"
)

// newRedisPool : 创建redis连接池
func newRedisPool() *redis.Pool {
    return &redis.Pool{
        MaxIdle:     50,
        MaxActive:   30,
        IdleTimeout: 300 * time.Second,
        Dial: func() (redis.Conn, error) {
            // 1. 打开连接
            c, err := redis.Dial("tcp", redisHost)
            if err != nil {
                fmt.Println(err)
                return nil, err
            }

            // 2. 访问认证
            if _, err = c.Do("AUTH", redisPass); err != nil {
                c.Close()
                return nil, err
            }
            return c, nil
        },
        TestOnBorrow: func(conn redis.Conn, t time.Time) error {
            if time.Since(t) < time.Minute {
                return nil
            }
            _, err := conn.Do("PING")
            return err
        },
    }
}

func init() {
    pool = newRedisPool()
}

func RedisPool() *redis.Pool {
    return pool
}

pgsql

package main

import (
    "database/sql"
    "fmt"
    _ "github.com/lib/pq"
)

const (
    host     = "10.43.75.11"
    port     = 5432
    user     = "postgres"
    password = "postgres"
    dbname   = "checkdb_common"
)

func connectDB() *sql.DB {
    psqlInfo := fmt.Sprintf("host=%s port=%d user=%s "+
        "password=%s dbname=%s sslmode=disable",
        host, port, user, password, dbname)

    db, err := sql.Open("postgres", psqlInfo)
    if err != nil {
        panic(err)
    }

    err = db.Ping()
    if err != nil {
        panic(err)
    }
    return db
}

func query(db *sql.DB) {

    var pkg_id, process_name string

    stmt, err := db.Prepare(
        "select pkg_id,process_name from ics_check_pkg  where process_id = $1")
    if err != nil {
        fmt.Println(err.Error())
        return
    }
    defer stmt.Close()

    rows, err := stmt.Query(2)
    if err != nil {
        fmt.Println(err.Error())
        return
    }

    for rows.Next() {
        err := rows.Scan(&pkg_id, &process_name)
        if err != nil {
            fmt.Println(err)
        }
        fmt.Println(pkg_id, process_name)
    }

    //err = rows.Err()
    //if err != nil {
    //  fmt.Println(err)
    //}
    //fmt.Println(pkg_id, process_name)
    
}

func main() {
    db := connectDB()
    query(db)

}

``
上一篇 下一篇

猜你喜欢

热点阅读