Linux Go开发笔记
20190924添加:
Go语言实战.pdf
李兆海译
2007年开始开发,2009年11月正式公开发布
main函数保存在名为main的包(package)里。
按照惯例,包和文件夹、子文件夹同名。每段代码都描述包的一部分。
使用包来封装不同语义单元的功能。
Go中,命令(command)指代可执行程序。
获取包的文档:godoc fmt
一个包定义一组编译过的代码,包的名字类似于命名空间,可以用来间接访问包内声明的标识符。
import关键字声明了所有的导入项。
GOROOT、GOPATH环境变量
导入路径前面的下划线标识符的作用:对包做初始化操作。
公开的标识符以大写字母开头,以小写字母开头的标识符不是公开的,不能被其他包中的代码直接访问。
映射(map)是Go里的一个引用类型,需要使用make来构造。map变量默认的零值是nil。
切片(slice)是一种实现了一个动态数组的引用类型。
用关键字func声明函数。
匿名函数是指没有明确声明名字的函数。
Go支持闭包。
关键字interface
空结构在创建实例时不会分配任何内存。
关键字var
简化变量声明符:=
关键字for range可以用于迭代数组、字符串、切片、映射和通道。
const声明常量的时候不需要指定类型。
关键字defer会安排随后的函数调用在函数返回时才执行。
关键字go启动一个goroutine,并对这个goroutine做并发调度。
标准库中的包:
fmt包格式化输出的功能
strconv包数据类型转换
log包
os包访问操作系统的功能,如读文件
sync包提供同步goroutine的功能
encoding/json包提供编解码json的功能
encoding/csv包
encoding/xml包
net/http包
errors包
regexp包
io.Reader.Read方法允许同时返回数据和错误。
经典GO语言程序100例(51-60),翻译自C语言的例子
【程序51】
题目:学习使用按位与 & 。
1.程序分析:0&0=0; 0&1=0; 1&0=0; 1&1=1
2.程序源代码:
package main
import (
"fmt"
)
func main() {
var a,b int
a=077
b=a&3
fmt.Printf("The a & b(decimal) is %d \n",b)
b&=7
fmt.Printf("The a & b(decimal) is %d \n",b)
}
运行结果:
D:\go\src\test51>go build
[0x7FEF9703C50] ANOMALY: meaningless REX prefix used
# test51
[0x7FEF9703C50] ANOMALY: meaningless REX prefix used
D:\go\src\test51>test51
[0x7FEF9703C50] ANOMALY: meaningless REX prefix used
The a & b(decimal) is 3
The a & b(decimal) is 3
==============================================================
【程序52】
题目:学习使用按位或 | 。
1.程序分析:0|0=0; 0|1=1; 1|0=1; 1|1=1
2.程序源代码:
package main
import (
"fmt"
)
func main() {
var a,b int
a=077
b=a|3
fmt.Printf("The a & b(decimal) is %d \n",b)
b|=7
fmt.Printf("The a & b(decimal) is %d \n",b)
}
运行结果:
D:\go\src\test52>test52
[0x7FEF9703C50] ANOMALY: meaningless REX prefix used
The a | b(decimal) is 63
The a | b(decimal) is 63
==============================================================
【程序53】
题目:学习使用按位异或 ^ 。
1.程序分析:0^0=0; 0^1=1; 1^0=1; 1^1=0
2.程序源代码:
package main
import (
"fmt"
)
func main() {
var a,b int
a=077
b=a^3
fmt.Printf("The a ^ b(decimal) is %d \n",b)
b^=7
fmt.Printf("The a ^ b(decimal) is %d \n",b)
}
运行结果:
D:\go\src\test53>test53
[0x7FEF9703C50] ANOMALY: meaningless REX prefix used
The a ^ b(decimal) is 60
The a ^ b(decimal) is 59
==============================================================
==============================================================
【程序55】
题目:学习使用按位取反~。
1.程序分析:~0=1; ~1=0;
2.程序源代码:
package main
import (
"fmt"
)
func main() {
var a,b int
a=234
b=^a
fmt.Printf("The a\'s 1 complement(decimal) is %d \n",b)
a=^a
fmt.Printf("The a\'s 1 complement(decimal) is %d \n",a)
}
运行结果:
D:\go\src\test55>test55
[0x7FEF9703C50] ANOMALY: meaningless REX prefix used
The a\'s 1 complement(decimal) is -235
The a\'s 1 complement(decimal) is -235
==============================================================
【程序61】
题目:打印出杨辉三角形(要求打印出10行如下图)
1.程序分析:
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
2.程序源代码:
package main
import (
"fmt"
)
func main() {
//var i,j int
var a [10][10]int
fmt.Printf("\n")
for i := 0; i < 10; i++ {
a[i][0]=1
a[i][i]=1
}
for i := 2; i < 10; i++ {
for j := 1; j < i; j++ {
a[i][j]=a[i-1][j-1]+a[i-1][j]
}
}
for i := 0; i < 10; i++ {
for j := 0; j <= i; j++ {
fmt.Printf("%5d",a[i][j])
}
fmt.Printf("\n")
}
}
运行结果:
D:\go\src\test61>test61
[0x7FEF9703C50] ANOMALY: meaningless REX prefix used
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
1 6 15 20 15 6 1
1 7 21 35 35 21 7 1
1 8 28 56 70 56 28 8 1
1 9 36 84 126 126 84 36 9 1
==============================================================
【程序63】
求平均数
运行结果:
D:\go\src\test63>go run test63
[0x7FEF9B63C50] ANOMALY: meaningless REX prefix used
# test63
[0x7FEF9B63C50] ANOMALY: meaningless REX prefix used
[0x7FEF9B63C50] ANOMALY: meaningless REX prefix used
The average is 3.000000
程序源代码:
package main
import (
"fmt"
)
// 计算由num个浮点数组成的数组的平均值
func mean(array *[]float64,n int) float64{
var m float64=0.0
for i := 0; i < n; i++ {
m += (*array)[i]
}
m/=float64(n)
return m
//return m/float64(n)
}
func main() {
a := []float64{1,2,3,4,5}
avg := mean(&a,len(a))
fmt.Printf("The average is %f", avg)
}
==============================================================
【程序66】
题目:输入3个数a,b,c,按大小顺序输出。
1.程序分析:利用指针方法。
2.程序源代码:
package main
import (
"fmt"
)
func main() {
var n1,n2,n3 int
var pointer1,pointer2,pointer3 *int
fmt.Printf("please input 3 number:n1,n2,n3:")
fmt.Scanf("%d,%d,%d",&n1,&n2,&n3)
pointer1=&n1
pointer2=&n2
pointer3=&n3
if(true){
if(n1>n2){swapi(pointer1,pointer2)}
if(n1>n3){swapi(pointer1,pointer3)}
if(n2>n3){swapi(pointer2,pointer3)}
}else{
if(n1>n2){n1,n2=swap(n1,n2)}
if(n1>n3){n1,n3=swap(n1,n3)}
if(n2>n3){n2,n3=swap(n2,n3)}
}
fmt.Printf("the sorted numbers are:%d,%d,%d\n",n1,n2,n3)
}
func swapi(x *int, y *int) {
*x, *y = *y, *x
//var temp int
//temp = *x /* 保存 x 地址的值 */
//*x = *y /* 将 y 赋值给 x */
//*y = temp /* 将 temp 赋值给 y */
}
// 互换两个变量的值
// 不需要使用第三个变量做中间变量
func swap(a, b int) (int, int) {
a ^= b // 异或等于运算
b ^= a
a ^= b
return a, b
}
运行结果:
D:\go\src\test66>test66
[0x7FEF9703C50] ANOMALY: meaningless REX prefix used
please input 3 number:n1,n2,n3:4,2,3
the sorted numbers are:2,3,4
==============================================================
【程序91】
题目:时间函数举例1
1.程序分析:
2.程序源代码:
package main
import (
"fmt"
"time"
)
func main() {
var lt time.Time
lt=time.Now()
fmt.Println("Now: ", lt)
lt0:=lt.UTC()
fmt.Println("Now0: ", lt0)
var start int64
start=lt.Unix()
fmt.Println("timestamp: ", start)
start0:=lt0.Unix()
fmt.Println("timestamp0: ", start0)
}
运行结果:
D:\go\src\test91>test91
[0x7FEFA273C50] ANOMALY: meaningless REX prefix used
Now: 2019-09-25 13:06:48.2732107 +0800 CST m=+0.000000001
Now0: 2019-09-25 05:06:48.2732107 +0000 UTC
timestamp: 1569388008
timestamp0: 1569388008
==============================================================
【程序101】
输出置换群S_4的所有元素:
程序源代码:
package main
import (
"fmt"
)
func main() {
n:=4
var i,j,k,p int
for i = 1; i <=n; i++ {
for j = 1; j <=n; j++ {
if(i!=j){
for k = 1; k <=n; k++ {
if((k!=i)&&(k!=j)){
for p = 1; p <=n; p++ {
if((p!=i)&&(p!=j)&&(p!=k)){
fmt.Println(i,j,k,p)
}
}
}
}
}
}
}
}
输出结果:
D:\go\src\test101>test101
[0x7FEFA273C50] ANOMALY: meaningless REX prefix used
1 2 3 4
1 2 4 3
1 3 2 4
1 3 4 2
1 4 2 3
1 4 3 2
2 1 3 4
2 1 4 3
2 3 1 4
2 3 4 1
2 4 1 3
2 4 3 1
3 1 2 4
3 1 4 2
3 2 1 4
3 2 4 1
3 4 1 2
3 4 2 1
4 1 2 3
4 1 3 2
4 2 1 3
4 2 3 1
4 3 1 2
4 3 2 1
==============================================================
【程序102】
整数划分问题:
对于正整数n,输出其和等于n且满足以下限制条件的所有正整数的形式。例n=4,程序输出为
4=4
4=3+1
4=2+2
4=2+1+1
4=1+1+1+1
程序源代码:
package main
import (
"fmt"
)
//type float float64
type float float32
func Abc(a,b,c float)float{
return a+b+b*c+(a+b-c)/(a+b)+4
}
func idiv(n,m uint64)uint64{
if ( n < 1 || m < 1 ) {
return 0
}
if ( n == 1 || m == 1 ) {
return 1
}
if ( n == m ) {
return 1 + idiv( n, m - 1 )
}
if ( n < m ) {
return idiv( n, n )
}
return idiv( n, m - 1 ) + idiv( n - m, m )
}
func main() {
var a uint64
a=4
fmt.Println(Abc(2,3,4),a,"总共有",idiv(a,a),"种划分方法")
}
==============================================================
【程序103】
计算定积分
程序源代码:
package main
import (
"fmt"
"math"
)
/*要进行计算的被积函数*/
func fsimpf(x float64)float64{
var y float64
y=math.Log(1.0+x)/(1.0+x*x)
return y
}
//辛普森算法:a为积分下限,b为积分上限,eps是希望达到的精度
func fsimp(a,b,eps float64)float64{
var n,k int
var h,t1,t2,s1,s2,ep,p,x float64
n=1
h=b-a
t1=h*(fsimpf(a)+fsimpf(b))/2.0//用梯形公式求出一个大概的估值
s1=t1
ep=eps+1.0
for {
if (ep<eps) {
break
}
//用梯形法则计算
p=0.0
for k=0;k<=n-1;k++ {
x=a+(float64(k)+0.5)*h
p=p+fsimpf(x)
}
t2=(t1+h*p)/2.0
//用辛普森公式求精
s2=(4.0*t2-t1)/3.0
ep=math.Abs(s2-s1)
t1=t2
s1=s2
n=n+n
h=h/2.0
}
return s2
}
func main() {
var a,b,eps,t float64
a=0.0
b=1.0
eps=0.0000001
fmt.Println("**********************************************************")
fmt.Println("* This program is to calculat the Value of a definite integral by Simpson Method. *")
fmt.Println("**********************************************************")
t=fsimp(a,b,eps)
fmt.Println("----------------------------------------------------------")
fmt.Println(" >> The result of definite integral is : ")
fmt.Printf(" >> SIGMA(0,1)ln(1+x)/(1+x^2)dx = %e\n",t)
fmt.Println("----------------------------------------------------------")
fmt.Println("Press any key to quit...")
}
运行结果:
D:\go\src\test103>test103
[0x7FEF95B3C50] ANOMALY: meaningless REX prefix used
**********************************************************
* This program is to calculat the Value of a definite integral by Simpson Method. *
**********************************************************
----------------------------------------------------------
>> The result of definite integral is :
>> SIGMA(0,1)ln(1+x)/(1+x^2)dx = 2.721983e-01
----------------------------------------------------------
Press any key to quit...
==============================================================
go调用Windows api
D:\go\src\testwin1>go build
[0x7FEF95B3C50] ANOMALY: meaningless REX prefix used
# testwin1
[0x7FEF95B3C50] ANOMALY: meaningless REX prefix used
D:\go\src\testwin1>testwin1
[0x7FEF95B3C50] ANOMALY: meaningless REX prefix used
Starting Up
Retern: 6【是】
D:\go\src\testwin1>testwin1
[0x7FEF95B3C50] ANOMALY: meaningless REX prefix used
Starting Up
Retern: 7【否】
D:\go\src\testwin1>testwin1
[0x7FEF95B3C50] ANOMALY: meaningless REX prefix used
Starting Up
Retern: 2【取消、关闭】
20191013添加:
经典GO语言程序100例
【程序56】
学习结构体的用法
运行结果:
D:\go\src\struct1>go run struct1
[0x7FEFA1A3C50] ANOMALY: meaningless REX prefix used
# struct1
[0x7FEFA1A3C50] ANOMALY: meaningless REX prefix used
[0x7FEFA1A3C50] ANOMALY: meaningless REX prefix used
husband is John1 Anderson
wife is Mary1 Anderson
son is Joey1 Anderson
daughter is Marla1 Anderson
程序源代码:
package main
import (
"fmt"
)
type family struct {
husband string
wife string
son string
daughter string
}
func main() {
var Anderson family
Anderson=family{"John Anderson","Mary Anderson","Joey Anderson","Marla Anderson"}
Anderson.husband="John1 Anderson"
Anderson.wife="Mary1 Anderson"
Anderson.son="Joey1 Anderson"
Anderson.daughter="Marla1 Anderson"
var ptr = &Anderson
fmt.Println("husband is",Anderson.husband)
fmt.Println("wife is",(*ptr).wife)
fmt.Println("son is",ptr.son)//Go语言自带隐式解引用
fmt.Println("daughter is",(*ptr).daughter)
}
==============================================================
【程序57】
学习复数包的用法,计算复数加法、复正弦、复余弦
x=(1,2.1)
y=(2,2.1)
sin(1,2.1)= (3.48732,2.17302)
cos(1,2.1)= (2.23918,-3.38428)
exp(1,2.1)= (-1.37231,2.34645)
exp(1,2.1)= -1.37231+2.34645i
norm(1,2.1)= 5.41
arg(1,2.1)= 1.12638
conj(1,2.1)= (1,-2.1)
abs(1,2.1)= 2.32594
tan(1,2.1)= 0.0276093+1.01218i
运行结果:
D:\go\src\cmplx0>go run cmplx0
[0x7FEFA1A3C50] ANOMALY: meaningless REX prefix used
# cmplx0
[0x7FEFA1A3C50] ANOMALY: meaningless REX prefix used
[0x7FEFA1A3C50] ANOMALY: meaningless REX prefix used
x= (1+2.1i)
y= (2+2.1i)
sin(1,2.1)=(3.487319284857504+2.1730184716589322i)
cos(1,2.1)=(2.2391819622123945-3.3842757535794106i)
exp(1,2.1)=(-1.3723139923021268+2.3464463355172747i)
arg(1,2.1)=1.1263771168937977
conj(1,2.1)=(1-2.1i)
abs(1,2.1)=2.3259406699226015
tan(1,2.1)=(0.027609253883831848+1.0121802686875254i)
程序源代码:
package main
import (
"fmt"
"math/cmplx"
)
func main() {
var x complex128 = complex(1, 2.1) // 1+2.1i
var y complex128
a:=real(x)
b:=imag(x)
y=complex(1.0,0)
y=x+y
fmt.Println("x=",x)
fmt.Println("y=",y)
fmt.Printf("sin(%v,%v)=%v\n",a,b,cmplx.Sin(x))
fmt.Printf("cos(%v,%v)=%v\n",a,b,cmplx.Cos(x))
fmt.Printf("exp(%v,%v)=%v\n",a,b,cmplx.Exp(x))
fmt.Printf("arg(%v,%v)=%v\n",a,b,cmplx.Phase(x))
fmt.Printf("conj(%v,%v)=%v\n",a,b,cmplx.Conj(x)) //Conj 返回 x 的复共轭
fmt.Printf("abs(%v,%v)=%v\n",a,b,cmplx.Abs(x))
fmt.Printf("tan(%v,%v)=%v\n",a,b,cmplx.Tan(x))
}
==============================================================
【程序58】
运行结果:
D:\go\src\test58>go run test58
[0x7FEFA1A3C50] ANOMALY: meaningless REX prefix used
# test58
[0x7FEFA1A3C50] ANOMALY: meaningless REX prefix used
[0x7FEFA1A3C50] ANOMALY: meaningless REX prefix used
a=3232235884
a1=1812048064
b1=1879156928
[root@localhost cpptest]# g++ -o test58 test58.cpp
[root@localhost cpptest]# ./test58
3232235884
1812048064
1879156928
1812048064(WHSIX反值)=192.168.1.108
1812048064(WHSIX反值)=192.168.1.108
1879156928(WHSIX反值)=192.168.1.112
3232235884(WHSIX反值)=108.1.168.192
程序源代码:
package main
import (
"fmt"
)
func getUint(H,A,B,L uint8) uint32 {
var ret uint32
ret=0
ret+=uint32(L)
ret+=uint32(B)*256
ret+=uint32(A)*65536
ret+=uint32(H)*16777216
return ret
}
func getUintWH(H,A,B,L uint8) uint32 {
return getUint(L,B,A,H)
}
func main() {
a:=getUint(192,168,1,108)//3232235884
a1:=getUintWH(192,168,1,108)//1812048064
//inet_addr
b1:=getUintWH(192,168,1,112)//1879156928
fmt.Printf("a=%d\n", a)
fmt.Printf("a1=%d\n", a1)
fmt.Printf("b1=%d\n", b1)
}
==============================================================
【程序59】
排列、组合、穷举搜索法
运行结果:
D:\go\src\test59>go run test59
[0x7FEF83B3C50] ANOMALY: meaningless REX prefix used
# test59
[0x7FEF83B3C50] ANOMALY: meaningless REX prefix used
[0x7FEF83B3C50] ANOMALY: meaningless REX prefix used
apailie(5,3)=60
apailie(5,2)=20
czuhe(5,3)=10
czuhe(5,2)=10
nSize=120
1,2,3,4,5
1,2,3,5,4
1,2,4,3,5
1,2,4,5,3
1,2,5,3,4
1,2,5,4,3
1,3,2,4,5
1,3,2,5,4
1,3,4,2,5
1,3,4,5,2
1,3,5,2,4
1,3,5,4,2
1,4,2,3,5
1,4,2,5,3
1,4,3,2,5
1,4,3,5,2
1,4,5,2,3
1,4,5,3,2
1,5,2,3,4
1,5,2,4,3
1,5,3,2,4
1,5,3,4,2
1,5,4,2,3
1,5,4,3,2
2,1,3,4,5
2,1,3,5,4
2,1,4,3,5
2,1,4,5,3
2,1,5,3,4
2,1,5,4,3
2,3,1,4,5
2,3,1,5,4
2,3,4,1,5
2,3,4,5,1
2,3,5,1,4
2,3,5,4,1
2,4,1,3,5
2,4,1,5,3
2,4,3,1,5
2,4,3,5,1
2,4,5,1,3
2,4,5,3,1
2,5,1,3,4
2,5,1,4,3
2,5,3,1,4
2,5,3,4,1
2,5,4,1,3
2,5,4,3,1
3,1,2,4,5
3,1,2,5,4
3,1,4,2,5
3,1,4,5,2
3,1,5,2,4
3,1,5,4,2
3,2,1,4,5
3,2,1,5,4
3,2,4,1,5
3,2,4,5,1
3,2,5,1,4
3,2,5,4,1
3,4,1,2,5
3,4,1,5,2
3,4,2,1,5
3,4,2,5,1
3,4,5,1,2
3,4,5,2,1
3,5,1,2,4
3,5,1,4,2
3,5,2,1,4
3,5,2,4,1
3,5,4,1,2
3,5,4,2,1
程序源代码:
package main
import (
"fmt"
)
/*
012:中间的牌
3:最大的牌
4:最小的牌
置换群S_5总共120个置换,最多只需要穷举72个置换就可以了
*/
var g_S5 [][5]int=[][5]int{
{0,1,2,3,4},
{0,1,2,4,3},
{0,1,3,2,4},
{0,1,3,4,2},
{0,1,4,2,3},
{0,1,4,3,2},
{0,2,1,3,4},
{0,2,1,4,3},
{0,2,3,1,4},
{0,2,3,4,1},
{0,2,4,1,3},
{0,2,4,3,1},
{0,3,1,2,4},
{0,3,1,4,2},
{0,3,2,1,4},
{0,3,2,4,1},
{0,3,4,1,2},
{0,3,4,2,1},
{0,4,1,2,3},
{0,4,1,3,2},
{0,4,2,1,3},
{0,4,2,3,1},
{0,4,3,1,2},
{0,4,3,2,1},
{1,0,2,3,4},
{1,0,2,4,3},
{1,0,3,2,4},
{1,0,3,4,2},
{1,0,4,2,3},
{1,0,4,3,2},
{1,2,0,3,4},
{1,2,0,4,3},
{1,2,3,0,4},
{1,2,3,4,0},
{1,2,4,0,3},
{1,2,4,3,0},
{1,3,0,2,4},
{1,3,0,4,2},
{1,3,2,0,4},
{1,3,2,4,0},
{1,3,4,0,2},
{1,3,4,2,0},
{1,4,0,2,3},
{1,4,0,3,2},
{1,4,2,0,3},
{1,4,2,3,0},
{1,4,3,0,2},
{1,4,3,2,0},
{2,0,1,3,4},
{2,0,1,4,3},
{2,0,3,1,4},
{2,0,3,4,1},
{2,0,4,1,3},
{2,0,4,3,1},
{2,1,0,3,4},
{2,1,0,4,3},
{2,1,3,0,4},
{2,1,3,4,0},
{2,1,4,0,3},
{2,1,4,3,0},
{2,3,0,1,4},
{2,3,0,4,1},
{2,3,1,0,4},
{2,3,1,4,0},
{2,3,4,0,1},
{2,3,4,1,0},
{2,4,0,1,3},
{2,4,0,3,1},
{2,4,1,0,3},
{2,4,1,3,0},
{2,4,3,0,1},
{2,4,3,1,0},
{3,0,1,2,4},
{3,0,1,4,2},
{3,0,2,1,4},
{3,0,2,4,1},
{3,0,4,1,2},
{3,0,4,2,1},
{3,1,0,2,4},
{3,1,0,4,2},
{3,1,2,0,4},
{3,1,2,4,0},
{3,1,4,0,2},
{3,1,4,2,0},
{3,2,0,1,4},
{3,2,0,4,1},
{3,2,1,0,4},
{3,2,1,4,0},
{3,2,4,0,1},
{3,2,4,1,0},
{3,4,0,1,2},
{3,4,0,2,1},
{3,4,1,0,2},
{3,4,1,2,0},
{3,4,2,0,1},
{3,4,2,1,0},
{4,0,1,2,3},
{4,0,1,3,2},
{4,0,2,1,3},
{4,0,2,3,1},
{4,0,3,1,2},
{4,0,3,2,1},
{4,1,0,2,3},
{4,1,0,3,2},
{4,1,2,0,3},
{4,1,2,3,0},
{4,1,3,0,2},
{4,1,3,2,0},
{4,2,0,1,3},
{4,2,0,3,1},
{4,2,1,0,3},
{4,2,1,3,0},
{4,2,3,0,1},
{4,2,3,1,0},
{4,3,0,1,2},
{4,3,0,2,1},
{4,3,1,0,2},
{4,3,1,2,0},
{4,3,2,0,1},
{4,3,2,1,0}}
var g_ObjArr [5]int=[5]int{1,2,3,4,5}
var g_ObjPtrArr [5]*int=[5]*int{&g_ObjArr[0],&g_ObjArr[1],&g_ObjArr[2],&g_ObjArr[3],&g_ObjArr[4]}
// n中取m的排列数P(m上,n下)
func apailie(n,m int) int {
if(m==0){
return 1
}else{
return (n-m+1)*apailie(n,m-1)
}
}
// n中取m的组合数C(m上,n下)
func czuhe(n,m int) int {
return apailie(n,m)/apailie(m,m)
}
func main() {
fmt.Printf("apailie(5,3)=%d\n",apailie(5,3))
fmt.Printf("apailie(5,2)=%d\n",apailie(5,2))
fmt.Printf("czuhe(5,3)=%d\n",czuhe(5,3))
fmt.Printf("czuhe(5,2)=%d\n",czuhe(5,2))
var nSize int=len(g_S5)
fmt.Printf("nSize=%d\n",nSize)
for i := 0; i < 72; i++ {
var ObjPtrArr [5]*int=[5]*int{g_ObjPtrArr[g_S5[i][0]],g_ObjPtrArr[g_S5[i][1]],g_ObjPtrArr[g_S5[i][2]],g_ObjPtrArr[g_S5[i][3]],g_ObjPtrArr[g_S5[i][4]]}
var ObjArr [5]int=[5]int{*ObjPtrArr[0],*ObjPtrArr[1],*ObjPtrArr[2],*ObjPtrArr[3],*ObjPtrArr[4]}
fmt.Printf("%d,%d,%d,%d,%d\n",ObjArr[0],ObjArr[1],ObjArr[2],ObjArr[3],ObjArr[4])
}
}
==============================================================
【程序60】
package main
import (
"fmt"
"math"
)
const(
PI=3.1415926535897932
EARTH_RADIUS=(6378.14 * 1000)
)
// 球面距离
func G_Distance(lng1, lat1, lng2, lat2 float64) float64 {
var r_lat1, r_lat2,a, b, result float64
r_lat1 = lat1 * PI / 180
r_lat2 = lat2 * PI / 180
a = r_lat2 - r_lat1
b = (lng1 - lng2) * PI / 180
result = 2 * math.Asin(math.Sqrt(math.Pow(math.Sin(a / 2),2) + math.Cos(r_lat1) * math.Cos(r_lat2) * math.Pow(math.Sin(b / 2),2))) * EARTH_RADIUS
return result
}
//Distance: (120.000000,38.000000) - (121.000000,39.000000) = 141354.976177m
//Distance: (123.028000,41.195400) - (123.032000,41.203700) = 982.820922m
func main() {
{
var x1 float64= 120
var y1 float64= 38
var x2 float64= 121
var y2 float64= 39
fmt.Printf("Distance: (%f,%f) - (%f,%f) = %fm\n", x1, y1, x2, y2, G_Distance(x1, y1, x2, y2))
}
{
var x1 float64= 123.028
var y1 float64= 41.1954
var x2 float64= 123.032
var y2 float64= 41.2037
fmt.Printf("Distance: (%f,%f) - (%f,%f) = %fm\n", x1, y1, x2, y2, G_Distance(x1, y1, x2, y2))
}
}
==============================================================
【程序62】
运行结果:
d:\go\src\test62>go run test62
[0x7FEF7EC3C50] ANOMALY: meaningless REX prefix used
# test62
[0x7FEF7EC3C50] ANOMALY: meaningless REX prefix used
[0x7FEF7EC3C50] ANOMALY: meaningless REX prefix used
ABCDADCDEFDDE!@234
ABCDADCDEFDDE!@234
程序源代码:
package main
import (
"fmt"
"strings"
)
// 将字符变成小写
func tolower(s byte) byte{
if \'A\' <= s && s <= \'Z\' {
s = s - \'A\' + \'a\'
}
return s
}
// 将字符变成大写
func toupper(s byte) byte{
if \'a\' <= s && s <= \'z\' {
s = s + \'A\' - \'a\'
}
return s
}
// 将字符串变成大写
func ToUpper(str string) string{
b := make([]byte, len(str))
for i, _:= range str{
s := str[i]
b[i] = toupper(s)
}
var str1 string = string(b[:])
return str1
}
func main() {
str:="abcdadcdefdde!@234"
fmt.Println(strings.ToUpper(str))
fmt.Println(ToUpper(str))
}
==============================================================
Golang Mongo操作
//mongo1.go
package main
import (
"fmt"
"gopkg.in/mgo.v2"
"gopkg.in/mgo.v2/bson"
)
type DBOper struct {
// Go 里没有类,创建类使用结构体代替
Dbname string
Collection string
}
type User_bean struct {
User_name string
Pwd string
// 结构体内部添加映射字段
}
func connect(DBOper *DBOper) (*mgo.Session, *mgo.Collection) {
session, err := mgo.Dial("mongodb://192.168.31.232:27017") //用户名密码连接方式: mongodb://user:pwd@xxxxxx:27017
if err != nil {
panic(err)
}
session.SetMode(mgo.Monotonic, true)
return session, session.DB(DBOper.Dbname).C(DBOper.Collection)
}
func find_one(dbname string, collection string, query bson.M) (bean interface{}) {
dboper := new(DBOper)
dboper.Dbname = dbname
dboper.Collection = collection
se, db := connect(dboper)
err := db.Find(query).One(&bean)
if err != nil {
panic(err)
}
defer se.Close()
return bean
}
func find_all(dbname string, collection string, query bson.M) (bean []interface{}) {
dboper := new(DBOper)
dboper.Dbname = dbname
dboper.Collection = collection
se, db := connect(dboper)
err := db.Find(query).All(&bean)
if err != nil {
panic(err)
}
defer se.Close()
return bean
}
func insert_one(dbname string, collection string, doc interface{}) {
dboper := new(DBOper)
dboper.Dbname = dbname
dboper.Collection = collection
se, db := connect(dboper)
err := db.Insert(&doc)
if err != nil {
panic(err)
}
defer se.Close()
return
}
func update(dbname string, collection string, query bson.M, updater interface{}) {
dboper := new(DBOper)
dboper.Dbname = dbname
dboper.Collection = collection
se, db := connect(dboper)
err := db.Update(query, updater)
if err != nil {
panic(err)
}
defer se.Close()
return
}
func upsert(dbname string, collection string, query bson.M, updater interface{}) {
dboper := new(DBOper)
dboper.Dbname = dbname
dboper.Collection = collection
se, db := connect(dboper)
_, err := db.Upsert(query, updater)
if err != nil {
panic(err)
}
defer se.Close()
return
}
func update_all(dbname string, collection string, query bson.M, updater interface{}) {
dboper := new(DBOper)
dboper.Dbname = dbname
dboper.Collection = collection
se, db := connect(dboper)
_, err := db.UpdateAll(query, updater)
if err != nil {
panic(err)
}
defer se.Close()
return
}
func delete_one(dbname string, collection string, query bson.M) {
dboper := new(DBOper)
dboper.Dbname = dbname
dboper.Collection = collection
se, db := connect(dboper)
err := db.Remove(query)
if err != nil {
panic(err)
}
defer se.Close()
return
}
func delete_all(dbname string, collection string, query bson.M) {
dboper := new(DBOper)
dboper.Dbname = dbname
dboper.Collection = collection
se, db := connect(dboper)
_, err := db.RemoveAll(query)
if err != nil {
panic(err)
}
defer se.Close()
return
}
func main() {
r := find_one("config_new", "keda3", bson.M{})
fmt.Println(r)
/*
user1 := User_bean{
User_name: "test1",
}
insert_one("config_new", "tab_user", user1)
user2 := User_bean{
User_name: "test2",
}
//只更新一个
update("config_new", "tab_user", bson.M{"user_name": "test1"}, user2)
*/
delete_one("config_new", "tab_user", bson.M{"user_name":"test1"})
}
输出mysql指定数据库和表中的字段名和每条记录:
D:\xkc\go20190906\src\test_mysql>go get github.com/Go-SQL-Driver/MySQL
go: missing Git command. See https://golang.org/s/gogetcmd
package github.com/Go-SQL-Driver/MySQL: exec: "git": executable file not found in %PATH%
处理办法:把git的bin路径加入环境变量Path中,然后重新打开cmd窗口。
我的路径是:C:\Users\1\AppData\Local\Atlassian\SourceTree\git_local\bin
D:\xkc\go20190906\src\test_mysql>git --version
git version 2.15.1.windows.2
D:\xkc\pkg\windows_amd64\github.com\Go-SQL-Driver
MySQL.a
D:\xkc\go20190906\src\test_mysql>go build
D:\xkc\go20190906\src\test_mysql>test_mysql
id name outaddr inneraddr chatsvraddr
0 11.7524ms
package main
import (
"database/sql"
"fmt"
_ "github.com/go-sql-driver/mysql"
"time"
)
func CheckErr(err error) {
if err != nil {
fmt.Println(err.Error())
panic(err)
}
}
func main() {
db, err := sql.Open("mysql", "root:123456@tcp(192.168.31.69:3306)/db_gamesvrs?timeout=30s")
//db, err := sql.Open("mysql", "root:123456@tcp(192.168.31.6:3306)/db_gamesvrs?timeout=30s")
CheckErr(err)
defer db.Close()
t := time.Now()
rows, err := db.Query("select * from gamesvrlist")
CheckErr(err)
cols, _ := rows.Columns()
for i := range cols {
fmt.Printf("%v \t", cols[i])
}
fmt.Printf("\n")
values := make([]sql.RawBytes, len(cols))
scans := make([]interface{}, len(cols))
for i := range values {
scans[i] = &values[i]
}
results := make(map[int]map[string]string)
n := 0
i := 0
for rows.Next() {
if err := rows.Scan(scans...); err != nil {
fmt.Println("错误")
}
row := make(map[string]string)
for j, v := range values {
key := cols[j]
row[key] = string(v)
}
results[i] = row
i++
n++
}
for _, j := range results {
fmt.Println(j)
}
fmt.Println()
fmt.Println(n, time.Now().Sub(t))
}
20190917添加:
csv2go.bat
copy csv\type_svr_merge.csv csvdata\type_svr_merge.csv
sed -i "1 a\a1,a2\nb1,b2" csvdata\type_svr_merge.csv
generator -csvpath csvdata
pause
在第一行下面或上面插入指定文本
linux下:
root@yiyouserver:/home/yiyou# cat 1.txt
col1,col2,col3
123,han,xh
124,wang,xy
root@yiyouserver:/home/yiyou# sed "1 a\a1,a2,a3\nb1,b2,b3" 1.txt
col1,col2,col3
a1,a2,a3
b1,b2,b3
123,han,xh
124,wang,xy
root@yiyouserver:/home/yiyou# sed "1 i\c1,c2,c3\nd1,d2,d3" 1.txt
c1,c2,c3
d1,d2,d3
col1,col2,col3
123,han,xh
124,wang,xy
window下:
环境变量PATH添加:C:\Users\1\AppData\Local\Atlassian\SourceTree\git_local\usr\bin
d:\xkc\src>sed -i "1 a\a1,a2,a3\nb1,b2,b3" csvdata\type_svr_merge.csv
d:\xkc\src>sed "1 a\a1,a2,a3\nb1,b2,b3" csvdata\type_svr_merge.csv
o_svrid,t_svrid
a1,a2,a3
b1,b2,b3
2,1
3,1
https://github.com/gocarina/gocsv
根据csv配置文件生成go中的结构体https://github.com/foolin/gocsv/blob/master/tools/generator/csvgenc.go
D:\>echo %GOPATH%
d:\go
D:\>echo %GOROOT%
C:\Go\
D:\go\src\gocsv>go get -u github.com/gocarina/gocsv
[0x7FEF95F3C50] ANOMALY: meaningless REX prefix used
go get: warning: modules disabled by GO111MODULE=auto in GOPATH/src;
ignoring go.mod;
see \'go help modules\'
# github.com/gocarina/gocsv
[0x7FEF95F3C50] ANOMALY: meaningless REX prefix used
D:\go\src\csv2>go build
[0x7FEF95F3C50] ANOMALY: meaningless REX prefix used
# csv2
[0x7FEF95F3C50] ANOMALY: meaningless REX prefix used
D:\go\src\csv2>csv2
[0x7FEF95F3C50] ANOMALY: meaningless REX prefix used
1 Jose 42
2 Daniel 26
3 Vincent 32
client_id,client_name,client_age
1,Jose,42
2,Daniel,26
3,Vincent,32
12,John,21
13,Fred,
14,James,32
15,Danny,
//csv2.go
package csv2
import (
"fmt"
"os"
"github.com/gocarina/gocsv"
)
//执行generator -csvpath .自动生成这个struct
/*type Client struct { // Our example struct, you can use "-" to ignore a field
Id string `csv:"client_id"`
Name string `csv:"client_name"`
Age string `csv:"client_age"`
NotUsed string `csv:"-"`
}*/
func main() {
clientsFile, err := os.OpenFile("clients.csv", os.O_RDWR|os.O_CREATE, os.ModePerm)
if err != nil {
panic(err)
}
defer clientsFile.Close()
clients := []*Client{}
if err := gocsv.UnmarshalFile(clientsFile, &clients); err != nil { // Load clients from file
panic(err)
}
for _, client := range clients {
fmt.Println(client.Id, client.Name, client.Age)
}
if _, err := clientsFile.Seek(0, 0); err != nil { // Go to the start of the file
panic(err)
}
/*
clients = append(clients, &Client{Id: "12", Name: "John", Age: "21"}) // Add clients
clients = append(clients, &Client{Id: "13", Name: "Fred"})
clients = append(clients, &Client{Id: "14", Name: "James", Age: "32"})
clients = append(clients, &Client{Id: "15", Name: "Danny"})
*/
csvContent, err := gocsv.MarshalString(&clients) // Get all clients as CSV string
//err = gocsv.MarshalFile(&clients, clientsFile) // Use this to save the CSV back to the file
if err != nil {
panic(err)
}
fmt.Println(csvContent) // Display all clients as CSV string
}
凄夜
Golang解析CSV
https://www.cnblogs.com/zengyg/p/11020654.html
https://github.com/usthooz
https://www.cnblogs.com/demodashi/p/10486794.html
csv2json.py
import csv
import json
file_path = "type_svr_merge.csv"
csvfile = open(file_path, \'r\')
jsonfile = open(\'type_svr_merge.json\', \'w\')
fieldnames = ("o_svrid", "t_svrid")
reader = csv.DictReader( csvfile, fieldnames)
out = json.dumps( [ row for row in reader ] )
jsonfile.write(out)
//json1.go
package main
import (
"io/ioutil"
"encoding/json"
"fmt"
//"reflect"
)
//定义配置文件解析后的结构
type type_svr_mgr struct {
o_svrid int `json:"o_svrid"`
t_svrid int `json:"t_svrid"`
}
func main() {
//ReadFile函数会读取文件的全部内容,并将结果以[]byte类型返回
data, err := ioutil.ReadFile("D:/xkc/src0/gamesvr/csv/type_svr_merge.json")
if err != nil {
fmt.Println(err)
return
}
//var m []map[string]interface{}
var m []interface{}
//读取的数据为json格式,需要进行解码
err = json.Unmarshal(data, &m)
if err != nil {
fmt.Println(err)
return
}
fmt.Println(m)
for k, v := range m {
fmt.Println("k", k, "v", v)
//.(type)必须与switch case联合使用
switch vv := v.(type) {
case map[string]interface{}:
//for i, _ := range vv{
for _, j := range vv{
//fmt.Println(i,": ",j)
//fmt.Println(i)
fmt.Println(j)
}
default:
}
}
}
//csv1.go
package main
import (
"encoding/csv"
"fmt"
"io/ioutil"
"log"
"strings"
"io"
)
func main() {
var array = []string{"type_third_acc", "type_svr_merge", "type_buff_client", "type_skill", "type_award", "type_new_idle_level",
"type_activity_config_open"}
for i:=0;i<len(array);i++{
str := "D:\\xkc\\src0\\gamesvr\\csv\\"
str += array[i]
str += ".csv"
dat, err := ioutil.ReadFile(str)
if err != nil {
log.Fatal(err)
}
fmt.Println(array[i])
r := csv.NewReader(strings.NewReader(string(dat[:])))
for {
record, err := r.Read()
if err == io.EOF {
break
}
if err != nil {
log.Fatal(err)
}
fmt.Println(record)
}
}
}
https://gocn.vip/question/3247
D:\xkc\go20190906\src\io1>io1 D:\xkc\src0\gamesvr\csv\type_third_acc.csv
]8,http://api.weiyinggame.com/api/cp/user/check,d30f20be5a54509c9535fa3308d174a0
0->app_id,acc_check_url,app_key
1->22,http://api.weiyinggame.com/api/cp/user/check,26190651fb8250e593addb082738fe27
2->28,http://api.weiyinggame.com/api/cp/user/check,d30f20be5a54509c9535fa3308d174a0
3->
4
1 app_id,acc_check_url,app_key
1 22,http://api.weiyinggame.com/api/cp/user/check,26190651fb8250e593addb082738fe27
1 28,http://api.weiyinggame.com/api/cp/user/check,d30f20be5a54509c9535fa3308d174a0
1
D:\xkc\go20190906\src\io1>io1 D:\xkc\src0\gamesvr\csv\type_svr_merge.csv
],1vrid,t_svrid
0->o_svrid,t_svrid
1->2,1
2->3,1
3->
4
1 o_svrid,t_svrid
1 2,1
1 3,1
1
https://www.ogeek.net/article/74002.htm
D:\xkc\go20190906\src\io3>io3 D:\xkc\src0\gamesvr\csv\type_third_acc.csv
app_id,acc_check_url,app_key
22,http://api.weiyinggame.com/api/cp/user/check,26190651fb8250e593addb082738fe27
28,http://api.weiyinggame.com/api/cp/user/check,d30f20be5a54509c9535fa3308d174a0
D:\xkc\go20190906\src\io3>io3 D:\xkc\src0\gamesvr\csv\type_svr_merge.csv
o_svrid,t_svrid
2,1
3,1
20190916添加:
商业公链之区块链技术使用的常见库(六)------Go语言文档数据库"gopkg.in/mgo.v2"
https://blog.csdn.net/Rcvisual/article/details/88962664
Go语言的标准net库使用
简单的TCP服务器
简单的HTTP服务
https://www.cnblogs.com/zzr-stdio/p/9874759.html
Go1.9安全的限制net.Listener接入连接数
https://blog.csdn.net/fyxichen/article/details/78655199
Go语言net/http 解读
https://blog.csdn.net/fyxichen/article/details/47749179
go语言之行--网络编程、http处理流程详情
https://www.cnblogs.com/wdliu/p/9284459.html
编程语言中的 DUCK TYPING
https://segmentfault.com/a/1190000019607240
Go语言开发(五)、Go语言面向接口
https://blog.51cto.com/9291927/2130244
golang中实现RSA(PKCS#1)加密解密
https://blog.csdn.net/yue7603835/article/details/73433617
[root@pfchang https]# openssl genrsa -out server.key 2048
[root@pfchang https]# openssl req -new -x509 -key server.key -out server.crt -days 365
如何使用openssl生成证书及签名
https://www.jianshu.com/p/7d940d7a07d9
openssl生成证书+安装+使用实例
https://blog.csdn.net/g1531997389/article/details/80048313
[root@pfchang hxh2]# ls
ca-cert.pem ca-cert.srl ca-key.pem ca.p12 ca-req.csr client-cert.pem client-key.pem client.p12 client-req.csr server-cert.pem
server-key.pem server.p12 server-req.csr
如何用Golang在本地开启Https服务
https://blog.csdn.net/puss0/article/details/89282309
RSA非对称加密从私钥中获取公钥Get the public key from the private key
http://tool.chacuo.net/cryptgetpubkey
Go和HTTPS
https://studygolang.com/articles/2946
Microsoft EdgeHTML vs Google Chrome结果:
https://localhost:8080
NET::ERR_CERT_AUTHORITY_INVALID
你的电脑不信任此网站的安全证书。
错误代码: DLG_FLAGS_INVALID_CA
https://192.168.31.69:8081/
此网站的安全证书不安全。
错误代码: 0
NET::ERR_CERT_INVALID
D:\xkc\go20190906\src\https1>curl -k https://localhost:8081
curl: (7) Failed to connect to localhost port 8081: Connection refused
D:\xkc\go20190906\src\https1>curl -k https://localhost:8080
404 page not found
D:\xkc\go20190906\src\https1>curl -k https://localhost:8080/hello
<h1>hello world!</h1>
D:\xkc\go20190906\src\https1>
D:\xkc\go20190906\src\https1>curl -k https://192.168.31.69:8081
404 page not found
D:\xkc\go20190906\src\https2>taskkill /f /pid 19464
成功: 已终止 PID 为 19464 的进程。
D:\xkc\go20190906\src\https2>netstat -ano|findstr "8082"
D:\xkc\go20190906\src\https2>go build
D:\xkc\go20190906\src\https2>https2
HTTP/2.0
//https2.go
package main
import (
"fmt"
"net/http"
)
var certPath = "D:\\xkc\\go20190906\\src\\https1\\server.crt"
var keyPath = "D:\\xkc\\go20190906\\src\\https1\\server.key"
func hello(w http.ResponseWriter, r *http.Request) {
fmt.Println(r.Proto) //打印http协议版本
w.Write([]byte("<h1>hello https!</h1>"))
}
func main() {
http.HandleFunc("/hello", hello)
http.ListenAndServeTLS(":8082", certPath, keyPath, nil)
var i int
fmt.Println("请输入内容:")
fmt.Scan(&i)
}
服务端私钥与证书
[root@pfchang https]# file server.key
server.key: PEM RSA private key
[root@pfchang https]# file server.crt
server.crt: PEM certificate
[root@pfchang https]# cat server.key
-----BEGIN RSA PRIVATE KEY-----
MIIEpQIBAAKCAQEAztDOTNVsHhUnJTIumyHp+DRWSMhSovRM+wSVgr/EQDKwXmNo
fAaAPUYdPzrwohPOajXus3WwvGh0tW2lLfoARutFa6RVW6b0q7tnLSJXq260/QX5
OV8pwqu+ZAzUUMXsVONNPFFmW5OV67xgxv6lrIQ9rQDD/3j4MkJe0hglHlYyvdH0
hwgM2uI35AF+GSI7aVpi8eXfUkqih1Eo6qJ0uDSZWkCvldLVyjGyWk65SsTdt/5N
TuzGXAL5MODUGhnKnIiWstN6WZ9J6AO2MbropWtnwITzPKmjfePBDAJUmE2xDPqA
zIwQ05ViiIaW0zuSV0hDFg0FG+/B5ljr3C7WiQIDAQABAoIBAQCd+/XLzbDEniYE
DPx7NwHyv5A2EwjFQFfZ3NuVQIZbAB2oTMnRDGpD5F6NIaoWNYkVq1NHtZynoCef
PD3VDEfP5QNnweYOmFAJK6QaX0SXSX9qVXjXcbGF6woKhZ5egYMSKXyjmg7V37zD
kmhfOsE2MuKmWJJggnkec4LZfOZF7/Ux+o9tv7NURJxUJeSO7vBWv1TcLYSny+hj
/aoOoSgBl+WskoqPYGUjUQKnG5Ok2mFIGIjIjzuNq4LFP5gwb8qAR6Comm1A/bMV
XycVUS0i0GGsy3NZ9wkC+mB+StDESUFaumynqFVi9rBAQ9ZaXjqXaXeqzp9e8vo/
Ivd7pO8BAoGBAOxPu4tmBfgmlD72cax5ohmu7Uq2nBswdCDSnkY12bX3TPoCVW7F
PPk4yCeldRYV2Opm7WYH4o/Y5AHAbSw+AOfzMBRmTJ2tbhJMInDtKfAvQy2yqU2p
7RMo+fWc4xUU6AMlcEHKSXyIorwIBVfXvYnCJBHNXKI0gakaTWUmbPLpAoGBAOAL
9aqd3swD6FpL4/QlQ3U/4vWDV2JnxzyTgaL8Ejf00r4O5CJqRLouSlLe9DljwwFp
jPlqML42DeFCBNEup9sMDAVNTbqdPD8tNg5fFCliDEinBhK9ikmUmHNuc1sHX3Pt
UckPIYZnH4fu8SCjMtv9NQK2n7cZ1nVcsO0YekKhAoGAHMrGLgDbP1XsABPk27/i
KUDv9odzU7i+nXUsBZ/wC8S640c/g4SSnkb11CbLskotKLoruJ/DUgV6GmCIrLhN
QfWWaRXhxeBopeAS3jF3R6VqiPnYuPa4RPpcIjngTSRD9IYuPEXaWEsJkOFlTUOi
+1LlNCoSXE0Lc0AaJ/XblmkCgYEAy1/P1tqLfaImbqDpAZw5ydr+SGK7FeaiYoh7
atlqKEUib8fQqrTQQjj22pbsFpRKVaPchiMwr9kdbFajTMcPM7WRy9ZKMpW8NJTz
tsPz50TLZb/HsYdAWl56rH2cVQsySGcqkFod0oUViC0L0NaTukH0tsvT2z+m/s3v
BKntgUECgYEAnR4xPaE3ED9Kbce6ldNES1n1B4JHbuPy477nrK9MLZVMErgHDcGo
mZKme1Ec36L8fEsgUl/j1G5HlDUij1r/ATEEJXe+tsy1OPy/9R8JIwrMt47r0/HM
Cdvuq5ygFM9qAjUFfdckqThJTmWNheHUcDOKMjPxQMjx/vQJgEZoj18=
-----END RSA PRIVATE KEY-----
[root@pfchang https]# cat server.crt
-----BEGIN CERTIFICATE-----
MIIDfzCCAmegAwIBAgIJAL5qUDTXrsHTMA0GCSqGSIb3DQEBCwUAMFYxCzAJBgNV
BAYTAlhYMRUwEwYDVQQHDAxEZWZhdWx0IENpdHkxHDAaBgNVBAoME0RlZmF1bHQg
Q29tcGFueSBMdGQxEjAQBgNVBAMMCWxvY2FsaG9zdDAeFw0xOTA5MTYwMjUwMjda
Fw0yMDA5MTUwMjUwMjdaMFYxCzAJBgNVBAYTAlhYMRUwEwYDVQQHDAxEZWZhdWx0
IENpdHkxHDAaBgNVBAoME0RlZmF1bHQgQ29tcGFueSBMdGQxEjAQBgNVBAMMCWxv
Y2FsaG9zdDCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAM7QzkzVbB4V
JyUyLpsh6fg0VkjIUqL0TPsElYK/xEAysF5jaHwGgD1GHT868KITzmo17rN1sLxo
dLVtpS36AEbrRWukVVum9Ku7Zy0iV6tutP0F+TlfKcKrvmQM1FDF7FTjTTxRZluT
leu8YMb+payEPa0Aw/94+DJCXtIYJR5WMr3R9IcIDNriN+QBfhkiO2laYvHl31JK
oodRKOqidLg0mVpAr5XS1coxslpOuUrE3bf+TU7sxlwC+TDg1BoZypyIlrLTelmf
SegDtjG66KVrZ8CE8zypo33jwQwCVJhNsQz6gMyMENOVYoiGltM7kldIQxYNBRvv
weZY69wu1okCAwEAAaNQME4wHQYDVR0OBBYEFHx0Ci/1F7kdNat1bGZfMxA2v/g8
MB8GA1UdIwQYMBaAFHx0Ci/1F7kdNat1bGZfMxA2v/g8MAwGA1UdEwQFMAMBAf8w
DQYJKoZIhvcNAQELBQADggEBAIs7D2gYHKZezAw3HUUIeAKADYTJPtoghEO7ilQm
wHhJfL6nhwkDkgXi9v0TReGv6A6lmbeEVFUoQiwwVtXDFHjxquthD6/h9ODQJTp6
ckrfwegvijfsTbcFve/mb7D7nxo1EiE84ycbfVp1CyQ51XmZGyY7iJw7qtL3cG47
IqJIyN+ImwVEgOYIKM2xljXWjQr0sF/PicpqS0eOnqKV53wCBCqbRoUQ1xLQbDkB
iusw355EyZzXWyUDVUhSiV7GAZ2vGHBnnYOnBxKdvlrgrqOkYBMW9FC88WdvCh+w
aL+Pef7RfK0m7umt/GHJlHzJQ+CtEsjoASWCW/kZGE1k3H0=
-----END CERTIFICATE-----
[root@pfchang https]#
20190915添加:
root@dthero_cn:/home/yiyou/gopath/src# go version
go version go1.12.1 linux/amd64
root@dthero_cn:/home/yiyou/gopath/src# git --version
git version 2.17.1
root@dthero_cn:/home/yiyou/gopath/src# svn --version
svn, version 1.9.7 (r1800392)
compiled Mar 28 2018, 08:49:13 on x86_64-pc-linux-gnu
git clone https://gitee.com/hanshouqing85/YIYOUGAME.git src
mv src/src0/* src/
git config --global user.email [email protected]
git config --global user.name hanshouqing85
root@dthero_cn:/home/yiyou/gopath# cp -r /home/yiyou/gopath/src/gamesvr/config ./config
root@dthero_cn:/home/yiyou/gopath# cp -r /home/yiyou/gopath/src/gamesvr/csv ./csv
root@dthero_cn:/home/yiyou/gopath# go build gamesvr1
root@dthero_cn:/home/yiyou/gopath# ./gamesvr1
root@yiyouserver:/home/yiyou/DTHero/oversea# go version
go version go1.12.5 linux/amd64
root@yiyouserver:/home/yiyou/DTHero/oversea# echo $GOPATH
/home/yiyou/gopath:/home/yiyou/DTHero/oversea
root@yiyouserver:/home/yiyou/DTHero/oversea# echo $GOROOT
/home/yiyou/tools/go
root@yiyouserver:/home/yiyou/DTHero/oversea# svn --version
svn, version 1.9.7 (r1800392)
compiled Mar 28 2018, 08:49:13 on x86_64-pc-linux-gnu
root@yiyouserver:/home/yiyou/DTHero/oversea# cd /home/yiyou/DTHero/oversea
root@yiyouserver:/home/yiyou/DTHero/oversea# svn checkout http://192.168.31.20:80/svn/DTHero/BC_Server src --username hxh
root@yiyouserver:/home/yiyou/DTHero/oversea# go build accountsvr
root@yiyouserver:/home/yiyou/DTHero/oversea# go build gamesvr
root@yiyouserver:/home/yiyou/DTHero/oversea# go build crosssvr
root@yiyouserver:/home/yiyou/DTHero/oversea# go build dirtysvr
root@yiyouserver:/home/yiyou/DTHero/oversea# go build sdksvr
root@yiyouserver:/home/yiyou/DTHero/oversea# go build logsvr
root@yiyouserver:/home/yiyou/DTHero/oversea# go build chatsvr
关闭指定端口的进程
#!/bin/sh
netstat -ntlp | grep svr | grep -E "8081|8095|8200" | awk \'{print $7}\' |awk -F"/" \'{print $1}\' | xargs kill -9
#!/bin/sh
netstat -ntlp | grep svr | grep -E "8110" | awk \'{print $7}\' |awk -F"/" \'{print $1}\' | xargs kill -9
开启指定进程
root@yiyouserver:/home/yiyou/yiyougamesvr/sdkserver# cat ./start.sh
#!/bin/bash
dateStr=`date +%Y%m%d_%H%M%S`
#./sdksvr > /home/dt_game/commserver/sdksvr.${dateStr}.log
nohup ./sdksvr > sdksvr.${dateStr}.log &
在Linux终端运行命令的时候,在命令末尾加上 & 符号,就可以让程序在后台运行
root@yiyouserver:/home/yiyou/yiyougamesvr/common# nohup ./accountsvr > account.nohup &
查看当前有多少在后台运行的命令
root@yiyouserver:/home/yiyou/yiyougamesvr/common# jobs -l
[1]+ 11231 Running nohup ./accountsvr > account.nohup &
将后台中的命令调至前台继续运行
root@yiyouserver:/home/yiyou/yiyougamesvr/common# fg %1
nohup ./accountsvr > account.nohup
前台进程的终止:Ctrl+c
Ubuntu 18.04.2 LTS无法使用root用户ssh远程登录的问题:
vim /etc/ssh/sshd_config
PermitRootLogin yes
:wq
service sshd restart
root@yiyouserver:/# ps -au|grep sshd
root 1780 0.0 0.0 13136 1008 pts/0 S+ 13:56 0:00 grep --color=auto sshd
2090729添加:
Linux localhost 3.4.67 #1 SMP PREEMPT Sat Dec 9 12:45:58 CST 2017 armv7l
Debian GNU/Linux 9 (stretch) [running via Linux Deploy]
root@localhost:~# apt-get update
root@localhost:~# sudo apt-get install golang
root@localhost:~# go version
go version go1.7.4 linux/arm
root@localhost:/home/hxh/go# go run hello.go
Hello World!
root@localhost:/home/hxh/go# go build hello.go
root@localhost:/home/hxh/go# ls
hello hello.go
root@localhost:/home/hxh/go# ./hello
Hello World!
20190804添加:
并发Concurrency
并行Parallel
如果某个系统支持两个或多个动作同时存在,就是并发系统。
如果某个系统支持两个或多个动作同时执行,就是并行系统。
并发的应用场景
一方面我们需要灵敏响应的GUI,一方面程序还需要执行大量的运算或者IO密集操作,而我们需要让界面响应与运算同
时执行。
当我们的Web服务器面对大量用户请求时,需要有更多的Web服务器工作单元来分别响应用户。
Golang应用领域:
区块链,主流开发语言,去中心化
Go服务器,设计者,处理日志,文件打包,数据处理(排序、推荐、搜索)和大并发很厉害,例如美团后台流量支撑
分布式云计算,例如盛大云CDN
并发的实现机制
多进程:是内核调度的,进程间通过文件、管道、消息队列等通信
多线程:是内核调度的,线程间通过共享内存通信,启动快、开销低、很难管理、不能在分布式系统下运行
基于回调的非阻塞/异步IO
协程:是用户调度的
主goroutine相当于main函数
不要通过共享内存来通信,而应该通过通信来共享内存
通道提供了两个协程联系的桥梁,允许他们进行通信。
一个线程被detach后就不能被join了,joinable()成员函数返回值为false
20190906添加:
C:\Users\Administrator.HEMEI-20180102W>go version
[0x7FEF98C3C50] ANOMALY: meaningless REX prefix used
go version go1.12.5 windows/amd64
C:\Users\1>go version
C:\Users\1>echo %GOROOT%
D:\Go
C:\Users\1>echo %GOPATH%
D:\xkc\
go version go1.9.1 windows/amd64
[root@MiWiFi-R4CM-srv hxh]# go version
go version go1.10.3 linux/amd64
[root@MiWiFi-R4CM-srv hxh]# echo $GOROOT
/usr/local/go
[root@MiWiFi-R4CM-srv hxh]# echo $GOPATH
[root@MiWiFi-R4CM-srv hxh]#
请发表评论