第三方库很多在github,加速一下,你懂的

将最新的dns hosts或者 GitHub520 添加到/etc/hosts

刷新一下name service

yum install nscd
nscd

安装golang
手动下载安装包也可以,版本会更新

yum install golang

配置环境变量

# !!!!GOROOT要与安装目录一致
# 否则如果安装过两个不同目录的go,在go get的时候会遇到错误
# compile: version "go1.15.6" does not match go tool version "go1.15.14"
export GOROOT=/usr/lib/golang

# 安装的各种第三方源会放到这里
export GOPATH=$HOME/gocode

export PATH=$PATH:$GOROOT/bin:$GOPATH/bin

下载第三方模块

go get github.com/jackc/pgconn

# 会自动下载到$GOPATH/src/github.com/jackc/pgconn/下面
# 并且会自动下载对应的依赖模块

或者手动下载

# 如上述github.com/jackc/pgconn,下载到
$GOPATH/src/github.com/jackc/pgconn/

有些依赖包来自于golang.org,由于一些你懂的原因,不能下载,例如

package golang.org/x/crypto/pbkdf2: unrecognized import path "golang.org/x/crypto/pbkdf2": https fetch: Get "https://golang.org/x/crypto/pbkdf2?go-get=1": dial tcp 142.251.43.17:443: i/o timeout

解决办法,下载golang.org在github上的同步镜像

mkdir -p $GOPATH/src/golang.org/x
cd $GOPATH/src/golang.org/x
git clone https://github.com/golang/crypto.git
git clone https://github.com/golang/text.git
git clone https://github.com/golang/sync.git

代码中引用第三方包

package main

import (
        "fmt"
        "log"
        "github.com/jackc/pgconn"
        "context"
        "time"
)

func main() {
        connstr := fmt.Sprintf("host=%s port=%d user=%s password=%s dbname=%s sslmode=disable",
                "127.0.0.1", 5432, "postgres", "2121", "postgres")

        log.Println(connstr)

        conn, err := pgconn.Connect(context.Background(), connstr)
        if err != nil {
                log.Fatal(err)
        }

/*
        results, err := conn.Exec(context.Background(), "select 'Hello, world'").ReadAll()
        if err != nil {
                log.Fatal(err)
        }


        fmt.Println(string(string(results[0].CommandTag)))

        fmt.Println(string(results[0].Rows[0][0]))
*/

        ctx, _ := context.WithTimeout(context.Background(), 20*time.Second)

        conn.Close(ctx)
}

运行

go run /root/work/golang/pgsec.go

黑暗森林
12 声望3 粉丝

弱小和无知不是生存的障碍,傲慢才是!


下一篇 »
bs4