├── .editorconfig ├── 01_base ├── 01_Values │ └── main.go ├── 02_Variables │ └── main.go ├── 03_Constants │ ├── iota_main.go │ └── main.go ├── 04_Type │ ├── array_main.go │ ├── base_main.go │ ├── interface2_main.go │ ├── interface_main.go │ ├── map_main.go │ ├── slice_main.go │ ├── struct2_main.go │ ├── struct_main.go │ └── type_convert.go ├── 05_Func │ ├── anonymous_func.go │ ├── func_main.go │ ├── method_func.go │ └── recursion.go ├── 06_Control │ ├── defer.go │ ├── for.go │ ├── if.go │ ├── range.go │ └── switch.go ├── 07_Point │ ├── arr_point_main.go │ └── main.go └── 08_Error │ ├── errors.go │ └── panic_recover.go ├── 02_goroutine ├── 01_Go │ ├── go1.go │ ├── go_clock.go │ └── go_netcat.go ├── 02_Channel │ ├── chan1.go │ ├── chan2.go │ ├── chan3.go │ ├── chan4.go │ ├── chan5.go │ └── chan_base1.go ├── 03_Select │ ├── select1.go │ ├── select2.go │ └── select3.go └── 04_Mutex │ └── mutex.go ├── 03_exmaples ├── Files │ ├── dir.go │ ├── file.go │ ├── file_md5.go │ ├── tmp.txt │ └── wallk.go ├── Http │ ├── simple_http.go │ ├── static │ │ └── avatar.jpg │ ├── static_server.go │ └── web_server.go ├── Json │ ├── json_marshal.go │ └── json_unmarshal.go ├── Os │ └── env.go ├── Strings │ ├── string_format.go │ └── strings.go └── Template │ └── .gitkeep ├── 04_framework └── hello_beego │ ├── .gitignore │ ├── README.MD │ ├── conf │ ├── app.conf │ ├── dev.conf │ └── prod.conf │ ├── controllers │ ├── api │ │ └── .gitkeep │ ├── backend │ │ ├── base.go │ │ └── site.go │ ├── base.go │ ├── default.go │ └── user.go │ ├── main.go │ ├── models │ └── user.go │ ├── routers │ └── router.go │ ├── static │ └── js │ │ └── reload.min.js │ ├── tests │ └── default_test.go │ ├── utils │ └── functions.go │ └── views │ ├── frontend │ └── layout │ │ └── main.html │ └── index.tpl ├── LICENSE ├── README.md └── hello.go /.editorconfig: -------------------------------------------------------------------------------- 1 | root = true 2 | 3 | # Unix-style newlines with a newline ending every file 4 | [*] 5 | end_of_line = lf 6 | insert_final_newline = true 7 | 8 | 9 | # Matches multiple files with brace expansion notation 10 | # Set default charset 11 | [*.{js,jsx,html,sass,go}] 12 | charset = utf-8 13 | indent_style = tab 14 | indent_size = 4 15 | trim_trailing_whitespace = true 16 | 17 | [*.md] 18 | trim_trailing_whitespace = false -------------------------------------------------------------------------------- /01_base/01_Values/main.go: -------------------------------------------------------------------------------- 1 | /** 2 | * datetime: 2017-05-21 3 | * Go语言字面量:Go语言中值的表示形式 4 | */ 5 | package main 6 | 7 | import "fmt" 8 | 9 | func main() { 10 | /** 11 | * 1. 基础类型的字面量 12 | */ 13 | //字符串:支持打印所有UTF-8类型字符串 14 | fmt.Println("This is String") 15 | fmt.Println("中国") 16 | fmt.Println("中国" + "心") //两个字符串拼接使用 + 号 17 | //整数值 18 | fmt.Println(100) 19 | //浮点数值 20 | fmt.Println(10.323) 21 | fmt.Println(19E-3) 22 | //布尔值 23 | fmt.Println(true) 24 | fmt.Println(false) 25 | /** 26 | * 2. 符合类型字面量 27 | * 符合类型字面量值后面学到在看:主要包括 struct、array、slice、map 类型的值 28 | */ 29 | 30 | } 31 | 32 | //$ go run main.go 33 | -------------------------------------------------------------------------------- /01_base/02_Variables/main.go: -------------------------------------------------------------------------------- 1 | /** 2 | * datetime: 2017-05-21 3 | * Go语言-变量 4 | * Go语言为静态语言,不能在运行时改变变量类型 5 | */ 6 | package main 7 | 8 | import ( 9 | "fmt" 10 | ) 11 | 12 | /** 13 | * 1. 在函数外部声明的变量是全局变量 14 | * 2. 全局变量未被使用,编译器不会报错 15 | * 16 | */ 17 | var g1 = 10 18 | var v3 = "this is v3" 19 | var v4 int 20 | 21 | func main() { 22 | 23 | //Go语言使用 var 关键字声明变量,并且自动初始化为零值。如果提供初始化值,可省略变量类型,编译器会自动推断变量类型。 24 | //如果声明局部变量未被使用,那么程序会编译不通过。可通过 _ 来回收未使用的局部变量。 25 | //变量名称区分大小写 26 | var v0 int 27 | _ = v0 28 | var v1 int = 100 //这样声明变量,编译器会给予一个这样提示:it will be inferred from the right-hand side。大概意思是变量可通过右侧值推断出变量类型。 29 | _ = v1 30 | 31 | //在函数内部可以使用:=来声明变量。 32 | v3 := "this is v3 plus" 33 | _ = v3 34 | 35 | fmt.Println(v3) 36 | 37 | // 局部变量优先级高于全局变量,也就是说 局部变量会修改全局变量的值 38 | g1 := 100 39 | fmt.Println(g1) 40 | 41 | //可一次定义多个变量 42 | var v4, v5, v6 = "golang", "hello", "world" 43 | var v7, v8 int 44 | 45 | var ( 46 | v9, v10 int 47 | ) 48 | var ( 49 | v11 int 50 | v12 int 51 | ) 52 | _, _, _, _, _, _ = v7, v8, v9, v10, v11, v12 53 | 54 | fmt.Println(v4 + v5 + v6) 55 | 56 | //变量交换 57 | v13, v14 := 10, 20 58 | fmt.Printf("v13 = %d, v14 = %d\n", v13, v14) 59 | v13, v14 = v14, v13 60 | fmt.Printf("v13 = %d, v14 = %d\n", v13, v14) 61 | 62 | // 在Go中,同一个作用域下,不允许定义两个同名变量 63 | var v15 = 10 64 | // var v15 = 100 //或者 v15 := 10000 65 | fmt.Println(v15) 66 | } 67 | 68 | //$ go run main.go 69 | -------------------------------------------------------------------------------- /01_base/03_Constants/iota_main.go: -------------------------------------------------------------------------------- 1 | /** 2 | * datetime: 2017-05-21 3 | * Go语言-枚举类型 4 | * 枚举类型关键字:iota 5 | * 定义在常量组中,从0开始安行计算的自增枚举值。如果枚举值被非 _ 打算,那么需要手动显示恢复。 6 | */ 7 | package main 8 | 9 | import "fmt" 10 | 11 | // 星期 12 | const ( 13 | //星期天 初始化为0,后面为以后每一行为自增量 14 | Sunday = iota 15 | //星期一 16 | Monday 17 | //星期二 18 | Tuesday 19 | //星期三 20 | Wednesday 21 | //星期四 22 | Thurday 23 | //星期五 24 | Friday 25 | //星期六 26 | Saturday 27 | ) 28 | 29 | const ( 30 | c1, c2, c3 = iota, 3, iota // 0,3,0 iota: 0 31 | c4 = 1 //iota被打断,必须显示恢复 iota: 1 32 | c5 = iota // iota: 2 33 | c6 // iota: 3 34 | c7 = 20 // iota: 4 35 | c8 = iota // 显示恢复 iota: 5 36 | c9 // iota: 6 37 | ) 38 | 39 | const ( 40 | c01, c02 = iota, iota // 0, 0 41 | c03 = 10 //1 42 | c04 = iota //2 43 | ) 44 | 45 | // 使用 _ 符号 跳过 iota值 46 | const ( 47 | s1 = iota // iota: 0 48 | s2 // iota: 1 49 | s3 // iota: 2 50 | s4 // iota: 3 51 | _ // iota: 4 52 | _ // iota: 5 53 | s5 // iota: 6 不需要iota显示恢复 54 | s6 // iota: 7 55 | ) 56 | 57 | // Effective go example 58 | 59 | //ByteSize 字节换算 60 | type ByteSize float64 61 | 62 | const ( 63 | _ = iota // ignore first value by assigning to blank identifier 64 | KB ByteSize = 1 << (10 * iota) 65 | MB 66 | GB 67 | TB 68 | PB 69 | EB 70 | ZB 71 | YB 72 | ) 73 | 74 | func main() { 75 | fmt.Println("星期:", Sunday, Monday, Tuesday, Wednesday, Thurday, Friday, Saturday) 76 | fmt.Println(c1, c2, c3, c4, c5, c6, c7, c8, c9) 77 | fmt.Println(c01, c02, c03, c04) 78 | fmt.Println(s1, s2, s3, s4, s5, s6) 79 | fmt.Println(KB, MB, TB, PB, EB, ZB, YB) 80 | 81 | } 82 | 83 | // go run iota_main.go 84 | 85 | /** 86 | 星期: 0 1 2 3 4 5 6 87 | 0 3 0 1 2 3 20 5 6 88 | 0 0 10 2 89 | 0 1 2 3 6 7 90 | 1024 1.048576e+06 1.099511627776e+12 1.125899906842624e+15 1.152921504606847e+18 1.1805916207174113e+21 1.2089258196146292e+24 91 | */ 92 | -------------------------------------------------------------------------------- /01_base/03_Constants/main.go: -------------------------------------------------------------------------------- 1 | /** 2 | * datetime: 2017-05-21 3 | * Go语言-常量 4 | * Go语言的常量值只能包含:字符串值、布尔值、数值类型(int,float,complex等) 5 | * 常量的值还可以使用 len, cap, unsafe.Sizeof 等编译器内可确定结果的函数返回值 6 | * 常量命名规范:官方推荐使用驼峰方式命名(以大写开头的常量为导出常量,小写开头的为包常量) 7 | * 当使用常量组的时候,如果常量不提供类型和初始化值,那么该常量的值和类型视作和上一个常量相同 8 | */ 9 | package main 10 | 11 | import "fmt" 12 | import "unsafe" 13 | 14 | // 声明ip常量 15 | const ip string = "192.168.1.0" 16 | 17 | // 声明ip2常量,并且常量类型通过值推到. 18 | const ip2 = "192.168.1.1" 19 | 20 | const d = 1.3 21 | 22 | //声明一组常量 23 | const ( 24 | c1, c2 = 10, 20 25 | c4 = false 26 | ) 27 | 28 | //声明组常量 29 | const ( 30 | c5 = 100 31 | c6 //c6的值为100。(如果常量不提供类型和初始化值,那么该常量的值和类型视作和上一个常量相同) 32 | c7 = 102 33 | ) 34 | 35 | // 常量的值还可以使用 len, cap, unsafe.Sizeof 等编译器内可确定结果的函数返回值 36 | var arr1 = [3]int{1, 2, 3} //声明一个长度为3的整形数组。(固定长度) 37 | 38 | const ( 39 | c8 = "c8 constant" 40 | c9 = len(c8) 41 | c10 = unsafe.Sizeof(c8) 42 | c11 = cap(arr1) 43 | ) 44 | 45 | func main() { 46 | //声明c5变量,和常量名称有冲突,编译器不会有报错,这时c5的常量值被c5变量值覆盖。 47 | c5 := 10 48 | 49 | //在函数内部声明常量, 其作用域也是在函数内部,不能再其他函数内使用 50 | const c13 = 10000 51 | 52 | fmt.Println(c5) 53 | test() //打印常量c5 54 | 55 | //len cap unsafe.Sizeof 56 | 57 | fmt.Println(c9, c10, c11) 58 | 59 | //常量名称区分大小写 60 | // fmt.Println(C1) 61 | 62 | } 63 | 64 | func test() { 65 | //使用常量c5, 但是不能调用到c13常量 66 | fmt.Println(c5) 67 | } 68 | 69 | //$ go run main.go 70 | /* 71 | 10 72 | 100 73 | 11 16 3 74 | */ 75 | -------------------------------------------------------------------------------- /01_base/04_Type/array_main.go: -------------------------------------------------------------------------------- 1 | /** 2 | * datetime: 2017-05-21 3 | * Go语言-数组 4 | * 1. 数组是一组相同类型元素组成的序列。 5 | * 2. 数组一旦声明,数组类型和长度都不允许改变 6 | * 3. 通过数组下标可以访问数组的元素,数组下标从0开始。 7 | * 4. 切勿越界赋值或者访问数组元素 8 | * 5. 使用len获取数组长度 9 | * 6. 数组赋值操作相当于拷贝,一个数组的改变,不会影响到另一个数组 10 | * 7. 数组长度使用 ... 特殊符号,go编译器可以自动获取数组长度 11 | */ 12 | package main 13 | 14 | import "fmt" 15 | 16 | func main() { 17 | 18 | // 初始化数组 19 | var arr1 [4]int = [4]int{1, 2, 3, 4} // 依据值类型推倒 var arr1 = [4]int{1,2,3,4}, 短声明 arr1 := [4]int{1,2,3,4} 20 | 21 | // 初始化一个字符串数组,数组长度为2 22 | var arr2 = [2]string{"hello", "world"} 23 | 24 | // 数组赋值操作相当于值拷贝, 一个数组值的改变,不会影响到另一个数组的值 25 | arr3 := arr2 26 | //修改第二个元素的值 27 | arr2[1] = "hhhh" 28 | 29 | fmt.Println(arr2, arr3) // [hello hhhh] [hello world] 30 | 31 | //访问数组第二个元素 32 | fmt.Println(arr1[1]) 33 | 34 | //查看数据元素个数- len, 当然使用cap 也可以获取数组长度,但是不推荐。cap 一般使用在获取slice容量上。 35 | fmt.Println(len(arr1)) 36 | 37 | //遍历数组元素 38 | fmt.Println("开始遍历数组:arr1") 39 | for i := 0; i < len(arr1); i++ { 40 | fmt.Println(arr1[i]) 41 | } 42 | fmt.Println("-----") 43 | for index, value := range arr1 { 44 | fmt.Printf("index=%d,value=%d\n", index, value) 45 | } 46 | 47 | fmt.Println("arr1 遍历结束") 48 | 49 | // 数组长度使用 ... 标记, 标识该数组长度由编译器计算获得 50 | var arr4 = [...]int{3, 3, 3, 3, 3} 51 | var arr5 = [...]int{4, 4, 4, 4, 4} 52 | _ = arr5 53 | fmt.Println(arr4) // [3, 3, 3, 3, 3] 54 | } 55 | 56 | //$ go run array_main.go 57 | 58 | /* 59 | hello hhhh] [hello world] 60 | 2 61 | 4 62 | 开始遍历数组:arr1 63 | 1 64 | 2 65 | 3 66 | 4 67 | ----- 68 | index=0,value=1 69 | index=1,value=2 70 | index=2,value=3 71 | index=3,value=4 72 | arr1 遍历结束 73 | [3 3 3 3 3] 74 | 75 | */ 76 | -------------------------------------------------------------------------------- /01_base/04_Type/base_main.go: -------------------------------------------------------------------------------- 1 | /** 2 | * datetime: 2017-05-21 3 | * Go语言-基本数据类型 共有18个基本数据类型 4 | * bool,byte,rune,int/uint, int8/uint8,int16/uint16, int32/uint32, int64/uint64, float32, float64, complex64, complex128, string 5 | * 数值类型支持:8进制,16进制,以及科学计数法 6 | */ 7 | 8 | package main 9 | 10 | import ( 11 | "fmt" 12 | "math" 13 | "reflect" 14 | "strings" 15 | "unsafe" 16 | ) 17 | 18 | func main() { 19 | comment := "" 20 | _ = comment 21 | fmt.Println(unsafe.Sizeof(comment)) // 占用字节:16 22 | fmt.Println(reflect.TypeOf(comment)) // 变量类型:string 23 | /* 24 | * 布尔类型 25 | * 宽度:1字节 26 | * 默认值:false 27 | */ 28 | var isActive bool 29 | fmt.Println(isActive, reflect.TypeOf(isActive)) 30 | 31 | /** 32 | * byte 33 | * 宽度:1字节 34 | * 默认值:0 35 | * 字节类型,uint8别名,可以看作为由8位二进制标示的无符号整数类型 36 | * 范围:0 ~ 255 37 | */ 38 | var firstByte byte 39 | firstByte = 10 // firstByte > 255 or firstByte < 0 is error 40 | fmt.Println(firstByte, reflect.TypeOf(firstByte)) //0, uint8 41 | 42 | /** 43 | * rune 44 | * 宽度:4字节 45 | * 默认值:0 46 | * int32别名, 专注于存储unicode编码的单个字符 47 | * 范围:-21亿 ~ 21亿 48 | */ 49 | var firstRune rune 50 | firstRune = 'a' 51 | firstRune = 29999 52 | fmt.Println(firstRune, unsafe.Sizeof(firstRune)) //占用4个字节 53 | 54 | /** 55 | * int,uint 56 | * 整型:根据当前计算机架构自动判断是32位还是64位 57 | * 宽度:4 / 8个字节 58 | * 默认值:0 59 | */ 60 | var i1 uint 61 | i1 = 10 62 | fmt.Println(unsafe.Sizeof(i1)) // 32位计算机:4字节,64位计算机:8字节 63 | 64 | /** 65 | * int8,uint8 / int16, uint16 / int32,uint32 / int64, uint64 66 | * 整型:表示由8位,16位,32位,64位二进制数的 有符号 / 无符号的整型 67 | * 默认值:0 68 | */ 69 | 70 | // 一般使用int足够了,编译器可以根据操作系统自动初始化32位或者64位的整数 71 | var i2 int 72 | i2 = 2000000000000000000 73 | fmt.Println(reflect.TypeOf(i2), unsafe.Sizeof(i2)) // int 8 74 | 75 | /** 76 | * float32, float64 77 | * 浮点型 78 | * 默认值: 0 79 | * 字节:4字 / 8字节 80 | */ 81 | 82 | var f1 float32 83 | fmt.Println(f1) 84 | var f2 float64 85 | fmt.Println(f2) 86 | 87 | //可以通过标准库math,查看各个数字类型的取值范围 88 | 89 | // math.MaxFloat32 90 | // math.MaxFloat64 91 | // math.MaxInt16 92 | // math.MaxInt32 93 | // math.MaxInt8 94 | // math.MaxUint16 95 | // math.MaxUint32 96 | // math.MaxUint64 97 | // math.MaxUint8 98 | 99 | // 数值类型可用标识:8进制,16进制,科学计数法 100 | a, b, c, d := 071, 0x1F, 1e9, math.MaxUint16 101 | _, _, _, _ = a, b, c, d 102 | 103 | /** 104 | * complex64, complex 128 105 | * 复数类型 106 | * 由float32 / float64 类型的实部和虚部联合表示 107 | * 默认值:0+0i 108 | */ 109 | 110 | var c1 complex64 111 | c1 = 1 + 1i 112 | fmt.Println(c1) 113 | 114 | var c2 complex128 115 | c2 = 1.0 + 3.8i 116 | fmt.Println(c2) 117 | 118 | /** 119 | * 字符串 120 | * string 121 | * 默认值:"" 122 | * 一个字符串类型,表示一个字符串值的集合。字符串实质是字节序列。字符串的值一旦被创建,其内容不可更改 123 | * 标准库:strings 中有大量字符串操作方法 124 | */ 125 | var s = "hello china a daksjdklasjdklasjdlaskjdlasjldasljd" 126 | // 占用字节数 127 | fmt.Println(unsafe.Sizeof(s)) 128 | //查询字符串长度 129 | fmt.Println(len(s)) 130 | fmt.Println(strings.Contains(s, "hello")) 131 | 132 | //字符串原型格式 133 | var strFormat = ` 134 | hello 135 | world 136 | ` 137 | fmt.Println(strFormat) 138 | 139 | } 140 | -------------------------------------------------------------------------------- /01_base/04_Type/interface2_main.go: -------------------------------------------------------------------------------- 1 | // tests 2 | // interface类型为通用类型 3 | // 将一个变量定义为interface类型,那么编译器根据变量的值来推动变量类型。 4 | package main 5 | 6 | import ( 7 | "fmt" 8 | "reflect" 9 | ) 10 | 11 | func main() { 12 | var it interface{} 13 | it = 10 //不会报错 reflect.TypeOf(it) int 14 | it = 10 15 | var it2 int 16 | it2 = 10 17 | _ = it2 18 | fmt.Println("it typeof ", reflect.TypeOf(it)) //int 19 | fmt.Println("it == i2 true or false ? ", it == it2) // true 20 | it = "a" //不会报错 reflect.TypeOf(it) string 21 | it3 := "a" 22 | _ = it3 23 | fmt.Println("it typeof ", reflect.TypeOf(it)) //string 24 | fmt.Println("it == i2 true or false ? ", it == it3) // true 25 | } 26 | 27 | //$ go run interface2_main.go 28 | 29 | //it typeof int 30 | //it == i2 true or false ? true 31 | //it typeof string 32 | //it == i2 true or false ? true 33 | -------------------------------------------------------------------------------- /01_base/04_Type/interface_main.go: -------------------------------------------------------------------------------- 1 | /** 2 | * datetime: 2017-05-24 3 | * Go语言-interface(接口类型) 4 | * 接口类型用于定义一组方法行为, 并且方法只有方法声明,没有方法体。 5 | * 一个接口类型声明,可以嵌套其他接口类型。 6 | */ 7 | package main 8 | 9 | import "fmt" 10 | 11 | // 声明Talk接口类型 - 关键字 type, interface 12 | type Talk interface { 13 | Hello (UserName string) string 14 | Talk(heard string) (saying string, end bool , err error) 15 | } 16 | 17 | 18 | type Chatbot interface { 19 | Name() string 20 | Talk //Talk类型接口 21 | Start() bool 22 | Shutdown() bool 23 | } 24 | 25 | // 自定义mytalk类型 26 | type mytalk string; 27 | 28 | //*mytalk实现Talk接口类型 29 | func (talk *mytalk) Hello (UserName string) string { 30 | return UserName 31 | } 32 | 33 | func (talk *mytalk) Talk(heard string) (saying string, end bool,err error) { 34 | saying = heard 35 | return 36 | } 37 | 38 | func (talk *mytalk) Name () string { 39 | return "name" 40 | } 41 | 42 | 43 | func (talk *mytalk) Start() bool { 44 | isStart := true 45 | return isStart 46 | } 47 | 48 | func (tallk *mytalk) Shutdown() bool { 49 | down := true 50 | return down 51 | } 52 | 53 | 54 | func main () { 55 | 56 | // *myTalk 实现 Talk类型 57 | var talk Talk = new(mytalk) //返回地址 58 | _, ok := talk.(*mytalk) 59 | if ok { 60 | fmt.Println("is ok") 61 | } 62 | 63 | //断言测试 64 | var bot1 Chatbot = new(mytalk) 65 | _, ok2 := bot1.(*mytalk) 66 | if ok2 { 67 | fmt.Println("bot1 is ok") 68 | } 69 | } 70 | 71 | //$ go run interface_main.go 72 | 73 | // 74 | //is ok 75 | //bot1 is ok 76 | // -------------------------------------------------------------------------------- /01_base/04_Type/map_main.go: -------------------------------------------------------------------------------- 1 | /** 2 | * datetime: 2017-05-22 3 | * Go语言-map字典 4 | * Go中字典类型是一个关联数组结构。关联数组是用来保存键值对的无序集合。 5 | * 字典类型属于引用类型, 其长度不是固定的 6 | * 字典类型的零值是nil, 零值的长度是0 7 | * 可以使用len获取字典长度 8 | * 字典类型是非线程安全,在多个线程或者协程存储时,要加锁 9 | */ 10 | package main 11 | 12 | import ( 13 | "fmt" 14 | ) 15 | 16 | func main() { 17 | 18 | //初始化字典类型 map[keyType]ValueType{} 19 | var m1 = map[string]bool{"isGood": true, "isActive": true, "less10": false} 20 | fmt.Println(m1) 21 | //获取字典长度 22 | fmt.Println("len(m1) = ", len(m1)) //len(m1) = 3 23 | //取值 24 | fmt.Println("m1[\"isGood\"] = ", m1["isGood"]) //m1["isGood"] = true 25 | //更改值 26 | m1["isGood"] = false 27 | fmt.Println("m1[\"isGood\"] = ", m1["isGood"]) //m1["isGood"] = false 28 | //增加值 29 | m1["isStart"] = true 30 | fmt.Println("m1=", m1) //map[isGood:false isActive:true less10:false isStart:true] 31 | //删除 32 | delete(m1, "isStart") 33 | fmt.Println("m1=", m1) //m1= map[isGood:false isActive:true less10:false] 34 | 35 | //判断key是否存在 36 | isGood, ok := m1["isGood"] 37 | if ok { 38 | fmt.Println("isGood exists") 39 | } else { 40 | fmt.Println("isGood not exists") 41 | } 42 | _ = isGood 43 | 44 | //遍历map 45 | 46 | // return 47 | // isGood = false 48 | // isActive = true 49 | // less10 = false 50 | 51 | for key, value := range m1 { 52 | fmt.Printf("%v = %v\n", key, value) 53 | } 54 | 55 | //引用类型 - 一个改变,另一个跟着改变 56 | m2 := m1 57 | m2["isGood2"] = true 58 | fmt.Println("m1=", m1) //m1= map[isGood:false isActive:true less10:false isGood2:true] 59 | fmt.Println("m2=", m2) //m2= map[isGood:false isActive:true less10:false isGood2:true] 60 | 61 | // 通过make 创建map - make用于内建类型(map、slice 和channel)的内存分配 62 | var m3 = make(map[string]string) 63 | m3["username"] = "jsser" 64 | m3["domain"] = "jsser.com" 65 | fmt.Println(m3) 66 | 67 | } 68 | -------------------------------------------------------------------------------- /01_base/04_Type/slice_main.go: -------------------------------------------------------------------------------- 1 | /** 2 | * datetime: 2017-05-22 3 | * Go语言-切片 4 | * 切片是针对底层数组中某个连续片段的描述 ^-^ 5 | * 0. 切片属于引用类型, 数组属于值类型 6 | * 1. 切片的长度是可变的 7 | * 2. 只要切片元素类型相同,两个切片的类型就相同. 8 | * 3. 切片的零值是nil, 且长度(len)和容量(cap) 都是0 9 | * 4. 切片的容量和长度理解 10 | * 5. slice几个有用的内置函数:len, cap, append, cpoy 11 | */ 12 | package main 13 | 14 | import ( 15 | "fmt" 16 | ) 17 | 18 | func main() { 19 | 20 | //声明一个切片类型的变量 - 长度为0, 容量为0 21 | var s1 = []int{} //可以声明直接赋值 var s1 = []int{1,2,3,4,5} 22 | //向切片s1追加元素 23 | s1 = append(s1, 10) 24 | s1 = append(s1, 20) 25 | s1 = append(s1, 30) 26 | 27 | _ = s1 28 | 29 | //通过数组来初始化切片 - slice1, slice2 30 | 31 | //slice有一些简便的操作 32 | //slice的默认开始位置是0,ar[:n]等价于ar[0:n] 33 | //slice的第二个序列默认是数组的长度,ar[n:]等价于ar[n:len(ar)] 34 | //如果从一个数组里面直接获取slice,可以这样ar[:],因为默认第一个序列是0,第二个是数组的长度,即等价于ar[0:len(ar)] 35 | 36 | var arr1 = [10]int{} 37 | slice1 := arr1[:] 38 | slice2 := arr1[:] 39 | _, _, _ = arr1, slice1, slice2 40 | 41 | fmt.Println("arr1 = ", arr1) 42 | fmt.Println("slice1 = ", slice1) 43 | fmt.Println("slice2 = ", slice2) 44 | 45 | //关于切片容量和切片长度 46 | var arr01 = [10]int{0, 1, 2, 3, 4, 5} //因为数组的是类型和长度是不可变的,所以它的容量和长度都是相等的。len = cap 47 | //通过数组初始化切片 48 | //https://github.com/astaxie/build-web-application-with-golang/blob/master/zh/02.2.md 49 | slice01 := arr01[2:5] //从arr01索引第二个元素开始,到第5个索引元素结束(不包含第5个)。 50 | fmt.Println("slice01 cap", cap(slice01)) //slice01的容量是10 - 2 = 8个 (slice开始位置到数组的最后位置的长度) 51 | fmt.Println("slice01 len", len(slice01)) //slice01的长度为切片的元素个数 52 | 53 | // 修改数组arr1的第一个元素的值 54 | arr1[0] = 100 55 | 56 | fmt.Println("arr1 = ", arr1) //arr1 = [100 0 0 0 0 0 0 0 0 0] 57 | fmt.Println("slice1 = ", slice1) //slice1 = [100 0 0 0 0 0 0 0 0 0] 58 | fmt.Println("slice2 = ", slice2) //slice2 = [100 0 0 0 0 0 0 0 0 0] 59 | 60 | //修改slice值 61 | slice1[1] = 200 62 | 63 | fmt.Println("arr1 = ", arr1) //arr1 = [100 200 0 0 0 0 0 0 0 0] 64 | fmt.Println("slice1 = ", slice1) //slice1 = [100 200 0 0 0 0 0 0 0 0] 65 | fmt.Println("slice2 = ", slice2) //slice2 = [100 200 0 0 0 0 0 0 0 0] 66 | 67 | //声明一个切片 68 | slice3 := []int{10, 20, 30, 40} 69 | //赋值 70 | slice4 := slice3 71 | 72 | // 73 | //append函数会改变slice所引用的数组的内容,从而影响到引用同一数组的其它slice。 74 | //但当slice中没有剩余空间(即(cap-len) == 0)时,此时将动态分配新的数组空间。 75 | //返回的slice数组指针将指向这个空间,而原数组的内容将保持不变;其它引用此数组的slice则不受影响 76 | // 77 | 78 | //重点:依据slice3的值,生成新的切片值,并把50,60追加到该值的背后,然后赋值操作会把这个新切片值在赋给slice3。所以新的slice3和旧的slice3的指向不同的底层数组。 79 | 80 | slice3 = append(slice3, 50, 60) 81 | fmt.Println("slice3=", slice3) //sice3= [10 20 30 40 50 60] 82 | fmt.Println("slice4=", slice4) //sice4= [10 20 30 40] 83 | 84 | /** 85 | * 使用make初始化切片 86 | * make([]type,len,cap) len <= cap 87 | */ 88 | var slice5 = make([]int, 20, 20) 89 | slice5 = append(slice5, slice3...) //当append的值是切片的时,请带上...符号 90 | fmt.Println("len(slice5) = ", len(slice5)) //len(slice5) = 26 91 | fmt.Println("cap(slice5) = ", cap(slice5)) //cap(slice5) = 40 //容量cap不足时将按总需要长度的2倍扩容 92 | fmt.Println("slice5 ", slice5) //slice5 [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 10 20 30 40 50 60] 93 | 94 | /** 95 | * 遍历切片 96 | */ 97 | 98 | var slice6 = []int{10, 20, 30, 40, 50} 99 | for _, item := range slice6 { 100 | item++ 101 | } 102 | fmt.Println("for range slice6", slice6) //for range slice6 [10 20 30 40 50] 103 | 104 | for index := 0; index < len(slice6); index++ { 105 | slice6[index]++ 106 | } 107 | fmt.Println("for slice6", slice6) //for slice6 [11 21 31 41 51] 108 | 109 | //slice 支持第三个参数 [startIndex:endIndex:cap] 并且 endIndex > cap 110 | var arr2 [10]int 111 | slice7 := arr2[2:5] 112 | _ = slice7 113 | fmt.Println(cap(slice7)) 114 | fmt.Println(len(slice7)) 115 | fmt.Println(slice7) 116 | 117 | //copy 118 | var tSlice = []int{1, 2, 3, 4, 5} 119 | var tmp = make([]int, len(tSlice)) 120 | 121 | copyCount := copy(tmp, tSlice) 122 | tmp[0] = 10 123 | fmt.Println("tmp:", tmp) //tmp: [10 2 3 4 5] 124 | fmt.Println("tSlice:", tSlice) //tSlice: [1 2 3 4 5] //不会随着改变 125 | fmt.Println("copyCount:", copyCount) //copyCount: 5 126 | 127 | //func 128 | _ = test(tSlice) 129 | // 引用传递 130 | fmt.Println("test tSlice", tSlice) //test tSlice [100 2 3 4 5] 131 | } 132 | 133 | func test(t []int) []int { 134 | if len(t) > 1 { 135 | t[0] = 100 136 | } 137 | return t 138 | } 139 | -------------------------------------------------------------------------------- /01_base/04_Type/struct2_main.go: -------------------------------------------------------------------------------- 1 | /** 2 | * datetime: 2017-05-25 3 | * Go语言-结构体2 4 | */ 5 | package main 6 | 7 | import "fmt" 8 | 9 | type human struct { 10 | name string 11 | age int 12 | phone string 13 | } 14 | 15 | type student struct { 16 | human 17 | phone string //human中也有phone字段 18 | } 19 | 20 | func main() { 21 | // 重载字段,就近原则 22 | jack := student{human{name: "jack", age: 20, phone: "110"}, "119"} 23 | fmt.Println("jack phone uumber is ", jack.phone) //119 24 | } 25 | -------------------------------------------------------------------------------- /01_base/04_Type/struct_main.go: -------------------------------------------------------------------------------- 1 | /** 2 | * datetime: 2017-05-25 3 | * Go语言-结构体 4 | */ 5 | package main 6 | 7 | import ( 8 | "fmt" 9 | ) 10 | 11 | /** 12 | * 声明一个person类型,包含两个字段,name 和 age 13 | */ 14 | type person struct { 15 | name string 16 | age int 17 | } 18 | 19 | /** 20 | * struct 21 | */ 22 | func older(p1, p2 person) (person, int) { 23 | if p1.age > p2.age { 24 | return p1, p1.age - p2.age 25 | } 26 | return p2, p2.age - p1.age 27 | } 28 | 29 | //struct 匿名字段 30 | // 内置类型, 自定义类型都可以作为匿名字段 31 | type human struct { 32 | name string 33 | age int 34 | weight int 35 | } 36 | 37 | //定义学生 38 | //student 对 human 实现字段继承 39 | type student struct { 40 | human //匿名字段 41 | schoolName string 42 | } 43 | 44 | func main() { 45 | 46 | //使用person类 47 | var p person 48 | p.name = "jsser" 49 | p.age = 20 50 | fmt.Printf("The person's name is %s\n", p.name) 51 | //初始化1 52 | tom := person{age: 10, name: "tom"} 53 | //初始化2 54 | jack := person{"jack", 15} 55 | 56 | older, ageDiff := older(tom, jack) 57 | fmt.Printf("this old is %s, diff %d\n", older.name, ageDiff) 58 | 59 | //初始化学生 60 | s1 := student{human{name: "jsser", age: 20, weight: 60}, "middle school"} 61 | fmt.Println("school Name is", s1.schoolName) 62 | fmt.Println("my name is ", s1.human.name) 63 | fmt.Println("my name is ", s1.name) //比较 64 | //修改年龄 65 | s1.age += 10 66 | fmt.Println("age is", s1.age) 67 | 68 | //匿名结构体 - 之间定义并且使用结构体 69 | //方式一 70 | var user struct{ username, nick string } 71 | user.username = "jsser" 72 | user.nick = "jsser-nick" 73 | fmt.Println("user.username", user.username) 74 | //方式二 75 | user2 := struct{ username, password string }{"test", "test"} 76 | fmt.Println("user2 name", user2.username) 77 | 78 | //方式三 79 | user3 := new(struct{ username, password string }) 80 | user3.username = "test" 81 | user3.password = "test" 82 | } 83 | -------------------------------------------------------------------------------- /01_base/04_Type/type_convert.go: -------------------------------------------------------------------------------- 1 | /** 2 | * datetime: 2017-05-28 3 | * Go类型转换 4 | * 不支持隐式类型转换,即便是从窄向宽转换也不行 5 | */ 6 | package main 7 | 8 | import ( 9 | "fmt" 10 | ) 11 | 12 | func main() { 13 | 14 | var b byte = 100 15 | n := int(b) //显示类型转换 16 | fmt.Printf("n = %d\n", n) 17 | 18 | //不能将其他类型的值当做布尔值来判断 19 | 20 | a := 10 21 | if a { //此处会报错 22 | fmt.Println(10) 23 | } 24 | } 25 | 26 | //$ go run type_convert.go 27 | 28 | //./type_convert.go:21: non-bool a (type int) used as if condition 29 | -------------------------------------------------------------------------------- /01_base/05_Func/anonymous_func.go: -------------------------------------------------------------------------------- 1 | /** 2 | * datetime: 2017-05-29 3 | * Go语言 - 匿名函数(闭包) 4 | * 函数返回的匿名函数属于引用类型 5 | * 内部函数访问或者改变外部函数的变量 6 | */ 7 | package main 8 | 9 | import "fmt" 10 | 11 | //定义一个函数squre , 返回值为一个匿名函数, 也就是通常说的闭包 12 | 13 | func square() func() int { 14 | var x int 15 | return func() int { 16 | x++ 17 | return x * x 18 | } 19 | } 20 | 21 | func main() { 22 | f := square() 23 | fmt.Println(f()) //将x的状态记录到了下来 24 | fmt.Println(f()) // 使用上一次执行得到的x值计算。 25 | fmt.Println(f()) 26 | } 27 | 28 | //$ go run anonymous_func.go 29 | 30 | //1 31 | //4 32 | //9 33 | -------------------------------------------------------------------------------- /01_base/05_Func/func_main.go: -------------------------------------------------------------------------------- 1 | /** 2 | * datetime: 2017-05-23 3 | * Go语言 - 函数 4 | * 0. 函数的零值是nil 5 | * 1. Go中函数声明包含:函数名称,参数列表, 参数名称,返回值名称,返回值类型。 6 | * 2. Go函数可以有多个返回结果。在函数有多个返回结果情况下,要么全部省略返回值名称,要么全部加上返回值名称 7 | * 3. 如果函数结果有名称,那么函数在被调用时,他们的变量就会被隐显声明。 8 | * 4. 在Go中习惯性的将错误类型作为函数结果列表中的最后一员。errors.New("异常") 9 | * 5. 函数在Go中是一等类型,函数可以当做其他函数的参数,也可以当做结果。 10 | * 6. Go中的函数闭包:内层函数引用了外层函数环境的变量,其返回值也是一个函数。 11 | */ 12 | package main 13 | 14 | import ( 15 | "errors" 16 | "fmt" 17 | ) 18 | 19 | type myint int 20 | 21 | /** 22 | * 变量函数 23 | * 调用方法:sumFunc(1,2) 24 | */ 25 | var sumFunc = func(i, j int) int { 26 | k := i + j 27 | return k 28 | } 29 | 30 | func main() { 31 | 32 | fmt.Println("") 33 | var i myint 34 | i = 10 35 | fmt.Println(f1(i)) 36 | 37 | /** 38 | * bop作为operat的闭包函数 39 | */ 40 | bop := func(op1, op2 int) (result int, err error) { 41 | if op2 == 0 { 42 | err = errors.New("divison by zero") 43 | } 44 | result = op1 / op2 45 | return 46 | } 47 | 48 | result, err := operate(20, 20, bop) 49 | if err == nil { 50 | fmt.Println("result = ", result) 51 | } 52 | 53 | /** 54 | * 调用变量函数 55 | */ 56 | fmt.Println("sumFunc(10, 20) = ", sumFunc(10, 20)) 57 | 58 | //可变参数函数 59 | total1 := sumNumbers(1, 2, 3, 4, 5) 60 | fmt.Printf("1 + 2 + 3 + 4 + 5 = %d\n", total1) 61 | 62 | } 63 | 64 | /** 65 | * 声明一个函数 66 | * 函数名:f1, 参数名称:i, 参数类型:myint, 返回结果类型int 67 | */ 68 | func f1(i myint) int { 69 | i++ 70 | r := +int(i + 1) 71 | return r 72 | } 73 | 74 | /** 75 | * 函数结果又名称t1, 结果参数t1会被隐式声明。所以在调用f2(1,2,3)的时候,函数返回结果为:0 76 | */ 77 | func f2(i, j, k int) (t1 int) { 78 | return 79 | } 80 | 81 | /** 82 | * 1. 函数中有异常信息一般作为函数结果列表中最后一个参数抛出。 83 | */ 84 | func divide(i, j int) (result int, err error) { 85 | 86 | if j == 0 { 87 | err = errors.New("divison by zero") 88 | return 89 | } 90 | result = i / j 91 | return 92 | } 93 | 94 | /** 95 | * 实现binaryOperation 闭包 96 | * 在main函数实现了调用 97 | */ 98 | type binaryOperation func(op1 int, op2 int) (result int, err error) 99 | 100 | func operate(op1 int, op2 int, bop binaryOperation) (result int, err error) { 101 | if bop == nil { 102 | err = errors.New("invalid binary operation function") 103 | return 104 | } 105 | //闭包 106 | return bop(op1, op2) 107 | } 108 | 109 | //可变参数,最多只能有一个可变参数,可变参数只能放到函数参数的末尾 110 | // sumNumbers(1,2,3,4,5) 111 | func sumNumbers(nums ...int) int { 112 | total := 0 113 | for _, num := range nums { 114 | total += num 115 | } 116 | return total 117 | } 118 | 119 | //$ go run func_main.go 120 | 121 | // 2 122 | // result = 1 123 | // sumFunc(10, 20) = 30 124 | -------------------------------------------------------------------------------- /01_base/05_Func/method_func.go: -------------------------------------------------------------------------------- 1 | /** 2 | * datetime: 2017-05-23 3 | * Go语言 - 方法 4 | * 方法是函数的一种,他是某个数据类型关联在一起的函数 5 | */ 6 | package main 7 | 8 | import "fmt" 9 | 10 | //User 定义User结构 11 | type User struct { 12 | name string 13 | age int 14 | } 15 | 16 | //方法声明 17 | //方法只是在func和函数名称之间加了一个圆括号包裹的接受者声明。(User), 表示getName方法是和User数据类型关联 18 | func (user *User) getName() (name string) { 19 | name = user.name 20 | return 21 | } 22 | 23 | func (user *User) getAge() (age int) { 24 | age = user.age 25 | return 26 | } 27 | 28 | // myint类型为值类型 29 | type myint int 30 | 31 | //值方法 32 | func (i myint) add(other int) myint { 33 | i = i + myint(other) 34 | return i 35 | } 36 | 37 | func main() { 38 | //声明一个User 39 | var u1 User 40 | u1.name = "jsser" 41 | u1.age = 19 42 | fmt.Println("u1.getName = ", u1.getName()) 43 | fmt.Println("u1.getAge = ", u1.getAge()) 44 | 45 | //myint 46 | 47 | } 48 | 49 | // $go run method_func.go 50 | 51 | // 52 | //u1.getName = jsser 53 | //u1.getAge = 19 54 | // 55 | -------------------------------------------------------------------------------- /01_base/05_Func/recursion.go: -------------------------------------------------------------------------------- 1 | /** 2 | * datetime: 2017-05-23 3 | * Go语言 - 递归 4 | * Go中函数递归深度没有做限制 5 | */ 6 | package main 7 | 8 | import ( 9 | "fmt" 10 | ) 11 | 12 | //1 * 2 * 3 * 4 * 5 13 | func fact(n int) int { 14 | if n == 0 { 15 | return 1 16 | } 17 | fmt.Println(n) 18 | return n * fact(n-1) 19 | } 20 | 21 | func main() { 22 | 23 | fmt.Println(fact(5)) 24 | // fmt.Println(fact(100)) 25 | } 26 | 27 | //$go run recursion.go 28 | 29 | // 5 30 | // 4 31 | // 3 32 | // 2 33 | // 1 34 | // 120 35 | -------------------------------------------------------------------------------- /01_base/06_Control/defer.go: -------------------------------------------------------------------------------- 1 | /** 2 | * datetime: 2017-05-27 3 | * defer 延迟调用。通常用于资源释放和错误处理 4 | */ 5 | package main 6 | 7 | import ( 8 | "fmt" 9 | ) 10 | 11 | func main() { 12 | 13 | fmt.Println("before") 14 | defer fmt.Println("defer1") 15 | defer fmt.Println("defer2") 16 | fmt.Println("after") 17 | //以上执行结果 - 当有多个defer时, 按照FILO次序进行(First in Last out) 顺序栈方式 18 | // before 19 | // after 20 | // defer2 21 | // defer1 22 | } 23 | -------------------------------------------------------------------------------- /01_base/06_Control/for.go: -------------------------------------------------------------------------------- 1 | /** 2 | * datetime: 2017-05-26 3 | * Go语言 - for 4 | */ 5 | package main 6 | 7 | import ( 8 | "fmt" 9 | "time" 10 | ) 11 | 12 | func main() { 13 | // 最常见的for循环结构 - 切记这里的i的作用域只是在for循环内部 14 | for i := 0; i < 10; i++ { 15 | fmt.Printf("i = %d\n", i) 16 | } 17 | // fmt.Printf("i = %d\n", i) - undefined: i 18 | 19 | //for 模拟while (golang中无while循环结构) 20 | s1 := 0 21 | for s1 < 10 { 22 | s1++ 23 | } 24 | fmt.Println("s1 = ", s1) 25 | 26 | //死循环 27 | for { //for true 28 | i := 0 29 | i++ 30 | time.Sleep(100 * time.Millisecond) 31 | fmt.Println(i) 32 | } 33 | 34 | } 35 | 36 | //$ go run for.go 37 | -------------------------------------------------------------------------------- /01_base/06_Control/if.go: -------------------------------------------------------------------------------- 1 | /** 2 | * datetime: 2017-05-26 3 | * Go语言 - if else 4 | * 1. 可省略条件表达式括号 5 | * 2. 支持初始化语句,可自定义代码块局部变量 6 | * 3. 代码块左大括号必须在条件表达式尾部 7 | */ 8 | package main 9 | 10 | import ( 11 | "fmt" 12 | ) 13 | 14 | func main() { 15 | 16 | v1 := 0 17 | if v1 > 1 { 18 | fmt.Println("v1 > 1") 19 | } else if v1 == 0 { 20 | fmt.Println("v1 == 1") 21 | } else { 22 | fmt.Println("v1 < 1") 23 | } 24 | 25 | //支持初始化语句 26 | 27 | if v2 := 0; v2 < 10 { 28 | fmt.Println("v2 < 10") 29 | } 30 | 31 | // go 不支持三元操作符 32 | 33 | } 34 | 35 | //$ go run if.go 36 | 37 | //v1 == 1 38 | //v2 < 10 39 | -------------------------------------------------------------------------------- /01_base/06_Control/range.go: -------------------------------------------------------------------------------- 1 | /** 2 | * datetime: 2017-05-26 3 | * Go语言 - range 4 | */ 5 | 6 | package main 7 | 8 | import ( 9 | "fmt" 10 | ) 11 | 12 | func main() { 13 | 14 | //初始化数组 15 | intArr1 := [10]int{1, 2, 3, 4, 5, 6, 7} 16 | //for range - 迭代器,返回 数组 每行的索引和值 17 | for index, item := range intArr1 { 18 | fmt.Printf("index = %d, item = %d\n", index, item) 19 | } 20 | 21 | // 遍历字符数组 22 | alp := "abcdefg" 23 | for i := range alp { 24 | fmt.Println(i) // 0,1,2,3,4,5,6 忽略值 25 | } 26 | 27 | //忽略索引 28 | for _, v := range alp { //忽略索引则必须用 _ 29 | fmt.Printf("%c\n", v) // a,b,c,d,e,f,g 30 | } 31 | 32 | //忽略值和索引 33 | 34 | for range alp { 35 | 36 | } 37 | 38 | //初始化map 39 | m1 := map[string]int{} 40 | m1["k1"] = 1 41 | m1["k2"] = 2 42 | m1["k3"] = 3 43 | 44 | for key, value := range m1 { 45 | fmt.Printf("key = %s, value = %d\n", key, value) 46 | } 47 | 48 | //初始化slice 49 | s1 := []int{10, 20, 30, 40, 50} 50 | 51 | for i, v := range s1 { 52 | if i == 0 { 53 | s1 = s1[:2] //这里对slice 修改不会影响到range迭代,也就是说 range引用类型,其底层数据不会被复制 54 | s1[1] = 100 55 | } 56 | fmt.Println(i, v) 57 | } 58 | // s1 59 | fmt.Println("s1 ", s1) // [10 100] 60 | fmt.Println("s1 cap", cap(s1)) //5 61 | fmt.Println("s1 len", len(s1)) // 2 62 | } 63 | 64 | //$ go run range.go 65 | -------------------------------------------------------------------------------- /01_base/06_Control/switch.go: -------------------------------------------------------------------------------- 1 | /** 2 | * datetime: 2017-05-26 3 | * Go语言 - switch 4 | * 分支表达式可以支持任意类型,并且可以省去break, 需要需要继续下一分支,可以使用fallthrough (但不在判断条件) 5 | */ 6 | 7 | package main 8 | 9 | import ( 10 | "fmt" 11 | "time" 12 | ) 13 | 14 | func main() { 15 | 16 | i := 10 17 | switch i { 18 | case 1: 19 | fmt.Println("one") 20 | case 2: 21 | fmt.Println("three") 22 | case 10: 23 | fmt.Println("ten") 24 | fallthrough 25 | default: 26 | fmt.Println("nothing") 27 | } 28 | 29 | // ten, nothing 30 | 31 | //case 分支 支持多个值 32 | 33 | switch time.Now().Weekday() { 34 | case time.Saturday, time.Sunday: 35 | fmt.Println("It's the weekend") 36 | default: 37 | fmt.Println("It's a weekday") 38 | } 39 | 40 | // case 分支 可以是表达式。可代替if else 41 | t := time.Now() 42 | switch { 43 | case t.Hour() < 12: 44 | fmt.Println("It's Before noon") 45 | default: 46 | fmt.Println("It's After noon") 47 | } 48 | } 49 | 50 | //$ go run switch.go 51 | // ten 52 | // nothing 53 | // It's the weekend 54 | // It's Before noon 55 | -------------------------------------------------------------------------------- /01_base/07_Point/arr_point_main.go: -------------------------------------------------------------------------------- 1 | /** 2 | * datetime: 2017-05-27 3 | * golang 数组指针 4 | * 5 | */ 6 | package main 7 | 8 | import ( 9 | "fmt" 10 | "reflect" 11 | ) 12 | 13 | //Max Constant Value 14 | const Max = 2 15 | 16 | func main() { 17 | 18 | slice1 := []int{10, 20, 30, 40} 19 | fmt.Println("slice1", slice1) 20 | //定义一个指针数组 21 | var ptr [Max]*int 22 | fmt.Println(reflect.TypeOf(ptr)) 23 | for i := 0; i < Max; i++ { 24 | ptr[i] = &slice1[i] //将元素值的内存地址赋值给指针数组 25 | } 26 | fmt.Println(ptr) 27 | 28 | //循环指针数组 29 | for i := 0; i < Max; i++ { 30 | fmt.Printf("ptr[%d] = %d\n", i, *ptr[i]) 31 | } 32 | 33 | } 34 | 35 | //$ go run arr_point_main.go 36 | 37 | // slice1 [10 20 30 40] 38 | // [2]*int 39 | // [0xc42006c0a0 0xc42006c0a8] 40 | // ptr[0] = 10 41 | // ptr[1] = 20 42 | -------------------------------------------------------------------------------- /01_base/07_Point/main.go: -------------------------------------------------------------------------------- 1 | /** 2 | * datetime: 2017-05-27 3 | * 指针 4 | * 支持指针类型 *T, 指针的指针 **T, 以及包含包名前缀的*.T 5 | * & 取址符, 取变量内存地址 6 | * * 取值符, 取变量内存地址对应的目标对象 7 | * 指针默认值nil, 没有NULL常量 8 | * 不支持指针运算,不支持"->"运算符,直接用"." 访问目标成员 9 | * 10 | * 11 | */ 12 | package main 13 | 14 | import ( 15 | "fmt" 16 | ) 17 | 18 | func main() { 19 | 20 | //指针使用流程 21 | // 1. 定义指针变量。2. 为指针变量赋值。3. 访问指针变量中指向地址的值 22 | 23 | var i int 24 | // 通过&符号,取得i变量的内存地址 25 | fmt.Printf("a 的变量地址:%x\n", &i) 26 | 27 | i = 100 28 | 29 | //声明指针 - 声明一个 指向int类型的指针 30 | var p1 *int 31 | 32 | p1 = &i //将i的地址赋予p1 33 | 34 | i = 101 //i的地址的值改变 35 | 36 | //为指针变量赋值 37 | fmt.Printf("p1变量内存地址%x\n", &p1) 38 | fmt.Printf("p1变量的值%d\n", *p1) 39 | 40 | //空指针 - nil 41 | var p3 *int 42 | fmt.Printf("指向int的空指针值为%x\n", p3) 43 | //空指针判断 44 | if p3 == nil { 45 | fmt.Println("空指针") 46 | } else { 47 | fmt.Println("非空指针") 48 | } 49 | 50 | type data struct{ user string } 51 | 52 | d1 := data{user: "jsser"} 53 | var p4 *data 54 | p4 = &d1 55 | fmt.Printf("p4=%p, p4.user=%v\n", p4, p4.user) 56 | 57 | } 58 | 59 | //$ go run main.go 60 | 61 | // a 的变量地址:c42000e238 62 | // p1变量内存地址c42000c028 63 | // p1变量的值101 64 | // 指向int的空指针值为0 65 | // 空指针 66 | // p4=0xc42000e280, p4.user=jsser 67 | -------------------------------------------------------------------------------- /01_base/08_Error/errors.go: -------------------------------------------------------------------------------- 1 | /** 2 | * datetime: 2017-05-28 3 | * Go错误处理 4 | * 5 | * 1. errors.New,fmt.Errorf 创建一个可描述性的错误信息,实现了error接口的错误对象 6 | * 2. 通过判断错误对象实例来确定具体错误类型 7 | * 3. 一般用作报告函数错误信息 8 | */ 9 | package main 10 | 11 | import ( 12 | "errors" 13 | "fmt" 14 | ) 15 | 16 | func main() { 17 | //当被除数为0时,会抛出err错误 18 | d1, err := divide(1, 0) 19 | if err != nil { 20 | fmt.Println(err) 21 | } else { 22 | fmt.Println(d1) 23 | } 24 | 25 | //fmt 标准库中 Errorf 创建一个可描述性的错误信息 26 | const name, id = "jsser", 100 27 | err2 := fmt.Errorf("user %q (id %d) not found", name, id) 28 | if err2 != nil { 29 | fmt.Println(err2) 30 | } 31 | 32 | } 33 | 34 | //函数通常在最后的返回值中返回错误信息 35 | //定义一个除法函数,并且判断了被除数为0时候,抛出错误"被除数不能为0" 36 | func divide(i1, i2 float64) (res float64, err error) { 37 | if i2 == 0 { 38 | err = errors.New("被除数不能为0") 39 | } 40 | res = float64(i1 / i2) 41 | 42 | return 43 | } 44 | 45 | // go run errors.go 46 | -------------------------------------------------------------------------------- /01_base/08_Error/panic_recover.go: -------------------------------------------------------------------------------- 1 | /** 2 | * datetime: 2017-05-28 3 | * Go错误处理2 4 | * 1. Go中提供 panic 函数来报告程序在运行过程中遇到的致命错误。Panic 可以传入任意类型参数,一般传递string或者error对象,用来方便查看异常信息 5 | * 2. Go中提供 recover 函数来捕捉运行时产生的panic报告的错误信息, 防止程序崩溃。recover一般会和defer一起使用,放在函数的开头, 可以有效的该函数及其下层调用中代码引起的恐慌。 6 | * 3. 编译器运行时系统报出的错误,recover不能捕捉到。(静态语言) 7 | */ 8 | package main 9 | 10 | import ( 11 | "errors" 12 | "fmt" 13 | ) 14 | 15 | func main() { 16 | 17 | defer func() { 18 | if p := recover(); p != nil { 19 | //执行到此,程序没有崩溃, 捕捉到了该错误,这里可以做错误类型判断,来处理对应的错误逻辑 20 | fmt.Printf("Recover a panic : %s \n", p) 21 | fmt.Println("程序会执行到这里") //如果捕捉到panic 那么这里会执行下去 22 | } 23 | }() 24 | 25 | panic(errors.New("this is fatal error")) 26 | fmt.Println("这里还会执行吗?") //这里不会执行 27 | arr1 := [3]int{1, 2, 3} 28 | _ = arr1 29 | //fmt.Printf("arr[3] = %d\n", arr1[3]) //数组越界访问错误,是由Go 运行时系统报告的。 30 | } 31 | 32 | // $ go run panic_recovier.go 33 | 34 | // Recover a panic : this is fatal error 35 | // 程序会执行到这里 36 | -------------------------------------------------------------------------------- /02_goroutine/01_Go/go1.go: -------------------------------------------------------------------------------- 1 | /** 2 | * datetime: 2017-05-30 3 | * Go提供原生的并发支持,类似协程,被称作goroutine机制 4 | * 在函数调用语句之前使用go关键字,就可以创建并发执行单元。 5 | * go并发执行,执行顺序是无序的 6 | * 当mian函数执行结束时,goroutine可能还未被运行 7 | * 8 | */ 9 | package main 10 | 11 | import ( 12 | "fmt" 13 | "runtime" 14 | "time" 15 | ) 16 | 17 | func main() { 18 | 19 | go f1() //无需等待 20 | for i := 0; i < 5; i++ { 21 | //注意:将变量i 传入go函数,而不是在函数中直接使用i 22 | go func(i int) { 23 | fmt.Printf("i = %d\n", i) 24 | //使用如下两种方案,不能保证go函数优先main函数执行, 后面可以结合channel通信机制 来正确获取go函数的执行结果 25 | runtime.Gosched() 26 | time.Sleep(time.Microsecond) 27 | }(i) 28 | } 29 | fmt.Println("main end~") 30 | } 31 | 32 | func f1() { 33 | fmt.Println("this is f1 func") 34 | } 35 | 36 | //$ go run go1.go 37 | // ... try to runing 38 | -------------------------------------------------------------------------------- /02_goroutine/01_Go/go_clock.go: -------------------------------------------------------------------------------- 1 | /** 2 | * datetime: 2017-05-30 3 | * 并发的clock 服务 4 | * The Go Programming Language example 5 | */ 6 | package main 7 | 8 | import ( 9 | "fmt" 10 | "io" 11 | "log" 12 | "net" 13 | "time" 14 | ) 15 | 16 | func main() { 17 | //创建一个对象监听网络连接,协议tcp, 端口8000 18 | listener, err := net.Listen("tcp", "localhost:8000") 19 | if err != nil { 20 | log.Fatal(err) 21 | } 22 | 23 | for { 24 | //接收新的连接,如果没有则阻塞 25 | conn, err := listener.Accept() 26 | fmt.Println("Client: : ", conn.RemoteAddr()) 27 | if err != nil { 28 | log.Print(err) 29 | continue 30 | } 31 | go handleConn(conn) // go并发执行 32 | } 33 | 34 | } 35 | 36 | func handleConn(c net.Conn) { 37 | defer c.Close() 38 | for { 39 | _, err := io.WriteString(c, time.Now().Format("15:04:05\n")) 40 | if err != nil { 41 | return 42 | } 43 | time.Sleep(time.Second * 1) 44 | } 45 | } 46 | 47 | //server: go run go_clock.go 48 | //client: go run go_netcat.go 49 | 50 | // 51 | // Client: : 127.0.0.1:62367 52 | // Client: : 127.0.0.1:62563 53 | // Client: : 127.0.0.1:62585 54 | // 55 | -------------------------------------------------------------------------------- /02_goroutine/01_Go/go_netcat.go: -------------------------------------------------------------------------------- 1 | /** 2 | * datetime: 2017-05-30 3 | * netcat - go_clock的客户端 4 | * The Go Programming Language example 5 | */ 6 | package main 7 | 8 | import ( 9 | "io" 10 | "log" 11 | "net" 12 | "os" 13 | ) 14 | 15 | func main() { 16 | conn, err := net.Dial("tcp", "localhost:8000") 17 | if err != nil { 18 | log.Fatal(err) 19 | } 20 | defer conn.Close() 21 | mustCopy(os.Stdout, conn) 22 | 23 | } 24 | 25 | func mustCopy(dst io.Writer, src io.Reader) { 26 | if _, err := io.Copy(dst, src); err != nil { 27 | log.Fatal(err) 28 | } 29 | } 30 | 31 | //server: go run go_clock.go 32 | //client: go run go_netcat.go 33 | 34 | // 35 | // Client: : 127.0.0.1:62367 36 | // Client: : 127.0.0.1:62563 37 | // Client: : 127.0.0.1:62585 38 | // 39 | -------------------------------------------------------------------------------- /02_goroutine/02_Channel/chan1.go: -------------------------------------------------------------------------------- 1 | /** 2 | * datetime: 2017-05-31 3 | * channel是有类型的通道, 可以使用channel操作符 <- 对其发送或者接收值 4 | * 1. ch <- v 将v发送到channel ch 5 | * 2. v := <- ch 从ch接收,并且赋值给v 6 | * 3. 使用make 创建channel 7 | */ 8 | package main 9 | 10 | import ( 11 | "fmt" 12 | ) 13 | 14 | func sum(a []int, c chan int) { 15 | sum := 0 16 | for _, v := range a { 17 | sum += v 18 | } 19 | c <- sum //将sum值发送入到c中 20 | } 21 | 22 | func main() { 23 | 24 | a := []int{2, 3, 4, 5, 6, 1, 4, 5} 25 | //3. 使用make 创建channel 26 | c := make(chan int, 1) 27 | go sum(a, c) 28 | go sum(a[:2], c) 29 | x := <-c //从c接收,赋值给x 30 | y := <-c 31 | fmt.Println(x, y, x+y) 32 | // fmt.Println(x, y) 33 | } 34 | 35 | //$ go run 36 | //5 30 35 37 | -------------------------------------------------------------------------------- /02_goroutine/02_Channel/chan2.go: -------------------------------------------------------------------------------- 1 | /** 2 | * datetime: 2017-05-31 3 | * channel是有类型的通道, 可以使用channel操作符 <- 对其发送或者接收值 4 | * 1. ch <- v 将v发送到channel ch 5 | * 2. v := <- ch 从ch接收,并且赋值给v 6 | * 3. 使用make 创建channel 7 | * 4. channel是可以带缓冲的,也就是make提供的第二个参数作为一个缓冲长度来初始化一个缓冲channel。 如果缓存长度参数为0,则是没有缓冲长度,发送给它的值立刻要被取走 8 | * 5. channel是典型的FIFO队列模型 9 | */ 10 | package main 11 | 12 | import ( 13 | "fmt" 14 | ) 15 | 16 | func main() { 17 | 18 | //make 提供第二个参数作为chan的缓冲长度, 如果缓存长度参数为0,则是没有缓冲长度。发送给它的值立刻要被取走 19 | ch := make(chan int, 2) 20 | //发送数据到ch 21 | ch <- 1 22 | ch <- 2 23 | //ch <- 3 // 发送第三个数据到ch, 导致缓冲溢出,程序报错 //fatal error: all goroutines are asleep - deadlock! 24 | //顺序赋值 25 | fmt.Println(<-ch) //1 26 | fmt.Println(<-ch) //2 27 | 28 | ch <- 3 29 | ch <- 4 30 | fmt.Println(<-ch) //3 31 | fmt.Println(<-ch) //4 32 | } 33 | 34 | //$ go run 35 | //5 30 35 36 | -------------------------------------------------------------------------------- /02_goroutine/02_Channel/chan3.go: -------------------------------------------------------------------------------- 1 | /** 2 | * datetime: 2017-05-31 3 | * channel是有类型的通道, 可以使用channel操作符 <- 对其发送或者接收值 4 | * 1. ch <- v 将v发送到channel ch 5 | * 2. v := <- ch 从ch接收,并且赋值给v 6 | * 3. 使用make 创建channel 7 | * 4. channel是可以带缓冲的,也就是make提供的第二个参数作为一个缓冲长度来初始化一个缓冲channel。 如果缓存长度参数为0,则是没有缓冲长度,发送给它的值立刻要被取走 8 | * 5. channel是典型的FIFO队列模型 9 | * 6. channel一般无需关闭他们,只有在需要告诉接受者没有更多的数据时,才需要手动关闭channel, 例如中断range 10 | * 7. channel 可以通过len获取当前通道元素,也可以通过cap获取通道容量 11 | */ 12 | package main 13 | 14 | import ( 15 | "fmt" 16 | ) 17 | 18 | // 斐波那契 19 | // 0,1,1,2,3,5 .... 20 | 21 | func fibonacci(n int, c chan int) { 22 | x, y := 0, 1 23 | for i := 0; i < n; i++ { 24 | c <- x 25 | x, y = y, x+y 26 | } 27 | close(c) 28 | } 29 | 30 | func main() { 31 | c := make(chan int, 10) 32 | go fibonacci(cap(c), c) 33 | for i := range c { // range 会不断的从c中接收值,直到c关闭 34 | fmt.Println(i) 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /02_goroutine/02_Channel/chan4.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | ) 6 | 7 | var chInt = make(chan int, 3) 8 | 9 | func main() { 10 | 11 | go func() { 12 | for i := 0; i < 10; i++ { 13 | chInt <- i 14 | } 15 | 16 | }() 17 | for { 18 | if i, err := <-chInt; err { 19 | fmt.Println(i) 20 | } 21 | } 22 | 23 | } 24 | -------------------------------------------------------------------------------- /02_goroutine/02_Channel/chan5.go: -------------------------------------------------------------------------------- 1 | /** 2 | * datetime: 2017-06-03 3 | * 单项通道 4 | */ 5 | package main 6 | 7 | import "fmt" 8 | 9 | func ping(pings chan<- string, msg string) { 10 | pings <- msg 11 | } 12 | 13 | func pong(pings <-chan string, pongs chan<- string) { 14 | msg := <-pings 15 | pongs <- msg 16 | } 17 | 18 | func main() { 19 | pings := make(chan string, 1) 20 | pongs := make(chan string, 1) 21 | ping(pings, "passed message") 22 | pong(pings, pongs) 23 | fmt.Println(<-pongs) 24 | } 25 | 26 | //$go run chan5.go 27 | //passed message 28 | -------------------------------------------------------------------------------- /02_goroutine/02_Channel/chan_base1.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "time" 6 | ) 7 | 8 | var strChan = make(chan string, 3) 9 | 10 | func main() { 11 | 12 | //初始化2个通道, synChan1, synChan2 13 | synChan1 := make(chan struct{}, 1) 14 | synChan2 := make(chan struct{}, 2) 15 | 16 | go func() { 17 | //演示发送操作 18 | for _, elem := range []string{"a", "b", "c"} { 19 | strChan <- elem 20 | fmt.Println("Sent:", elem, "[sender]") 21 | if elem == "c" { 22 | synChan1 <- struct{}{} 23 | fmt.Println("Sent a sync signal . [sender]") 24 | } 25 | } 26 | fmt.Println("wait 2 senconds ... [sender]") 27 | time.Sleep(time.Second * 2) 28 | close(strChan) 29 | synChan2 <- struct{}{} 30 | }() 31 | 32 | go func() { 33 | //演示接收操作 34 | <-synChan1 35 | fmt.Println("Received a sync signal and wait a second...[reveiver]") 36 | time.Sleep(time.Second) 37 | for { 38 | if elem, ok := <-strChan; ok { 39 | fmt.Println("Received: ", elem, "[reveiver]") 40 | } else { 41 | break 42 | } 43 | } 44 | 45 | fmt.Println("Stopped . [reveiver]") 46 | synChan2 <- struct{}{} 47 | }() 48 | 49 | <-synChan2 50 | <-synChan2 51 | 52 | } 53 | -------------------------------------------------------------------------------- /02_goroutine/03_Select/select1.go: -------------------------------------------------------------------------------- 1 | /** 2 | * datetime: 2017-06-01 3 | * select 语句似的一个goroutine在多个通讯操作上等待 4 | * 1. select是阻塞的,直到某个条件可以执行,如果多个条件都满足,select会随机执行一个条件 5 | * 2. 为了非阻塞的发送或者接受,select可以使用default分支,当所有条件都不可执行时,default分支会被执行 6 | * 3. select代码形式和switch很相似,select的case里面只能是IO操作 7 | */ 8 | package main 9 | 10 | import ( 11 | "fmt" 12 | ) 13 | 14 | func test() { 15 | 16 | } 17 | 18 | func main() { 19 | ch1 := make(chan int, 1) 20 | ch2 := make(chan int, 1) 21 | ch1 <- 1 22 | ch2 <- 2 23 | select { 24 | case <-ch1: 25 | fmt.Println("pop ch1") 26 | case <-ch2: 27 | fmt.Println("pop ch2") 28 | default: 29 | fmt.Println("default") 30 | } 31 | //会随机执行 32 | } 33 | 34 | //go run select1.go 35 | // pop cha1 or pop ch2 36 | -------------------------------------------------------------------------------- /02_goroutine/03_Select/select2.go: -------------------------------------------------------------------------------- 1 | /** 2 | * datetime: 2017-06-01 3 | * select example 4 | */ 5 | package main 6 | 7 | import "fmt" 8 | 9 | func fibonacci(c, quit chan int) { 10 | x, y := 0, 1 11 | for { 12 | select { 13 | case c <- x: 14 | x, y = y, x+y 15 | case <-quit: 16 | fmt.Println("quit") 17 | return 18 | } 19 | } 20 | } 21 | 22 | func main() { 23 | ch := make(chan int) 24 | quit := make(chan int) 25 | go func() { 26 | for i := 0; i < 10; i++ { 27 | fmt.Println(<-ch) 28 | } 29 | quit <- 0 30 | }() 31 | fibonacci(ch, quit) 32 | } 33 | 34 | // go run select2.go 35 | 36 | // 0 37 | // 1 38 | // 1 39 | // 2 40 | // 3 41 | // 5 42 | // 8 43 | // 13 44 | // 21 45 | // 34 46 | // quit 47 | -------------------------------------------------------------------------------- /02_goroutine/03_Select/select3.go: -------------------------------------------------------------------------------- 1 | /** 2 | * datetime: 2017-06-04 3 | * select和channel 模拟超时机制 4 | */ 5 | package main 6 | 7 | import ( 8 | "fmt" 9 | "time" 10 | ) 11 | 12 | func main() { 13 | c1 := make(chan string, 1) 14 | go func() { 15 | time.Sleep(time.Second * 2) 16 | c1 <- "result 1" 17 | }() 18 | 19 | select { 20 | case res := <-c1: 21 | fmt.Println("res = ", res) 22 | case <-time.After(time.Second * 1): 23 | fmt.Println("timeout 1") 24 | } 25 | 26 | c2 := make(chan string, 1) 27 | go func() { 28 | time.Sleep(time.Second * 2) 29 | c2 <- "result 2" 30 | }() 31 | 32 | select { 33 | case res := <-c2: 34 | fmt.Println("res = ", res) 35 | case <-time.After(time.Second * 3): 36 | fmt.Println("timeout 2") 37 | } 38 | 39 | } 40 | 41 | //$go run select2.go 42 | // timeout 1 43 | // res = result 2 44 | -------------------------------------------------------------------------------- /02_goroutine/04_Mutex/mutex.go: -------------------------------------------------------------------------------- 1 | /** 2 | * datetime: 2017-06-03 3 | * Sync.Mutex 4 | * 互斥锁 5 | * 在并发程序中,通过lock 和 unlock方法,保证同一个时刻只有一个goroutine访问一段代码。 6 | * 7 | */ 8 | package main 9 | 10 | import ( 11 | "fmt" 12 | "sync" 13 | "time" 14 | ) 15 | 16 | type SafeCounter struct { 17 | v map[string]int 18 | mux sync.Mutex 19 | } 20 | 21 | //Inc 递增计数 22 | func (c *SafeCounter) Inc(key string) { 23 | c.mux.Lock() 24 | //++ 25 | c.v[key]++ 26 | c.mux.Unlock() 27 | } 28 | 29 | //Value 返回当前递增后的值 30 | func (c *SafeCounter) Value(key string) int { 31 | c.mux.Lock() 32 | 33 | // 使用defer语句保证互斥锁会被解锁 34 | defer c.mux.Unlock() 35 | 36 | return c.v[key] 37 | } 38 | 39 | func main() { 40 | 41 | //使用SafeCounter 42 | c := SafeCounter{v: make(map[string]int)} 43 | for i := 0; i < 1000; i++ { 44 | go c.Inc("key") 45 | } 46 | time.Sleep(time.Second) 47 | fmt.Printf("c.Value(\"%s\") = %d\n", "key", c.Value("key")) 48 | } 49 | 50 | //$ go run mutex.go 51 | //c.Value("key") = 1000 52 | -------------------------------------------------------------------------------- /03_exmaples/Files/dir.go: -------------------------------------------------------------------------------- 1 | /** 2 | * datetime: 2017-06-09 3 | * Go 目录操作 4 | */ 5 | package main 6 | 7 | import ( 8 | "fmt" 9 | "os" 10 | ) 11 | 12 | func main() { 13 | 14 | //创建目录 15 | err := os.Mkdir("tmp_dir", 0755) 16 | if err != nil { 17 | return 18 | } 19 | //进入目录 20 | os.Chdir("tmp_dir") 21 | //进入目录创建文件 22 | os.Create("tmp.txt") 23 | 24 | //打开目录 25 | dir, err := os.Open(".") 26 | if err != nil { 27 | return 28 | } 29 | defer dir.Close() 30 | //删除目录 31 | os.Remove("tmp_dir") 32 | fileInfos, err := dir.Readdir(-1) 33 | 34 | if err != nil { 35 | return 36 | } 37 | 38 | for _, fi := range fileInfos { 39 | fmt.Printf("FileName:%s\n", fi.Name()) 40 | } 41 | } 42 | 43 | //$ go run readdir.go 44 | -------------------------------------------------------------------------------- /03_exmaples/Files/file.go: -------------------------------------------------------------------------------- 1 | /** 2 | * datetime: 2017-06-07 3 | * 文件操作 4 | */ 5 | package main 6 | 7 | import ( 8 | "fmt" 9 | "os" 10 | "reflect" 11 | ) 12 | 13 | func main() { 14 | 15 | //创建文件 16 | f, _ := os.Create("log.log") 17 | defer f.Close() 18 | //文件句柄类型 19 | fmt.Println(reflect.ValueOf(f).Type()) //*os.File 20 | //打开文件 21 | f2, _ := os.OpenFile("log.log", os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0777) 22 | // f2, _:=os.Open("log.log") 23 | defer f2.Close() 24 | fmt.Println(f2.Stat()) 25 | //文件信息 26 | f2Stat, _ := f2.Stat() 27 | //获取信息 28 | fmt.Println("文件大小:", f2Stat.Size()) 29 | fmt.Println("文件名称:", f2Stat.Name()) 30 | //文件最后修改时间 31 | fmt.Println("文件最后修改时间:", f2Stat.ModTime()) 32 | //判断文件是否存在 33 | var notExistsFilename = "not_exists.file" 34 | if _, err := os.Stat(notExistsFilename); os.IsNotExist(err) { 35 | fmt.Println(notExistsFilename + "文件不存在") 36 | } 37 | 38 | } 39 | 40 | //$ go run file.go 41 | // *os.File 42 | // &{log.log 0 420 {63632452529 0 0x110c4e0} {16777221 33188 1 670686 501 80 0 [0 0 0 0] {1496855162 0} {1496855729 0} {1496855729 0} {1496855162 0} 0 0 4096 0 0 0 [0 0]}} 43 | // 文件大小: 0 44 | // 文件名称: log.log 45 | // 文件最后修改时间: 2017-06-07 11:15:29 +0800 CST 46 | // not_exists.file文件不存在 47 | -------------------------------------------------------------------------------- /03_exmaples/Files/file_md5.go: -------------------------------------------------------------------------------- 1 | /* 2 | * datetime: 2017-06-08 3 | * 文件操作:三种方式获取文件md5值 4 | */ 5 | package main 6 | 7 | import ( 8 | "bufio" 9 | "crypto/md5" 10 | "fmt" 11 | "io" 12 | "io/ioutil" 13 | "os" 14 | ) 15 | 16 | func main() { 17 | 18 | //创建一个文件 19 | filename := "testfile.md5" 20 | var file *os.File 21 | if _, err := os.Stat(filename); os.IsNotExist(err) { 22 | //文件不存在-创建 23 | file, _ = os.Create(filename) 24 | } else { 25 | //文件存在-打开 26 | //openFile 可以设置读写权限,open函数只能是只读权限 27 | file, err = os.OpenFile(filename, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0777) 28 | } 29 | defer file.Close() 30 | //文件写入内容 31 | //也可以使用file.WriteString("这是写入的字符串") 32 | // _, err := io.WriteString(file, "这是写入的字符串") 33 | var content string 34 | content = "这是写入文件的内容-jsser" 35 | err := ioutil.WriteFile(filename, []byte(content), 0777) 36 | if err != nil { 37 | fmt.Println(err) 38 | return 39 | } 40 | //获取文件md5 方式一 41 | c, err := ioutil.ReadAll(file) 42 | if err == nil { 43 | fmt.Printf("方式一:md5 = %x\n", md5.Sum(c)) 44 | } 45 | 46 | //获取文件md5 方式2 47 | md5Hash := md5.New() 48 | _, err1 := io.Copy(md5Hash, file) 49 | if err1 == nil { 50 | fmt.Printf("方式二:md5 = %x\n", md5Hash.Sum(nil)) 51 | } 52 | 53 | //获取文件md5 方式3 54 | bf := bufio.NewReader(file) //增加bufio 缓存读取 55 | h := md5.New() 56 | _, err3 := io.Copy(h, bf) 57 | if err3 == nil { 58 | fmt.Printf("方式三:md5 = %x\n", h.Sum(nil)) 59 | } 60 | } 61 | 62 | //$ go run file_md5.go 63 | // 方式一:md5 = d41d8cd98f00b204e9800998ecf8427e 64 | // 方式二:md5 = d41d8cd98f00b204e9800998ecf8427e 65 | // 方式三:md5 = d41d8cd98f00b204e9800998ecf8427e 66 | 67 | //总结:优先选择bufio方式计算Md5,尽量避免使用readall计算文件md5值(大文件会有内存分配问题) 68 | -------------------------------------------------------------------------------- /03_exmaples/Files/tmp.txt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/TeamFat/learn-golang/6b7d05d3f7c0eafbc468bc88aa5be21ddabea765/03_exmaples/Files/tmp.txt -------------------------------------------------------------------------------- /03_exmaples/Files/wallk.go: -------------------------------------------------------------------------------- 1 | /** 2 | * datetime: 2017-06-09 3 | * 递归遍历目录 4 | */ 5 | package main 6 | 7 | import ( 8 | "fmt" 9 | "os" 10 | "path/filepath" 11 | ) 12 | 13 | func main() { 14 | 15 | filepath.Walk("../", func(path string, info os.FileInfo, err error) error { 16 | fmt.Println(path) 17 | return nil 18 | }) 19 | 20 | } 21 | -------------------------------------------------------------------------------- /03_exmaples/Http/simple_http.go: -------------------------------------------------------------------------------- 1 | /** 2 | * datetime: 2017-06-09 3 | * Go http包 simple web_server 4 | * https://github.com/astaxie/build-web-application-with-golang/blob/master/zh/03.4.md 5 | */ 6 | package main 7 | 8 | import ( 9 | "fmt" 10 | "net/http" 11 | ) 12 | 13 | // MyMux struct 14 | type MyMux struct { 15 | } 16 | 17 | func (p *MyMux) ServeHTTP(w http.ResponseWriter, r *http.Request) { 18 | 19 | if r.URL.Path == "/" { 20 | hello(w, r) 21 | return 22 | } 23 | http.NotFound(w, r) 24 | return 25 | } 26 | 27 | func hello(w http.ResponseWriter, r *http.Request) { 28 | fmt.Fprintf(w, "hello router") 29 | } 30 | 31 | func main() { 32 | 33 | mux := &MyMux{} 34 | http.ListenAndServe(":8899", mux) 35 | 36 | } 37 | 38 | //$ go run simple_http.go 39 | -------------------------------------------------------------------------------- /03_exmaples/Http/static/avatar.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/TeamFat/learn-golang/6b7d05d3f7c0eafbc468bc88aa5be21ddabea765/03_exmaples/Http/static/avatar.jpg -------------------------------------------------------------------------------- /03_exmaples/Http/static_server.go: -------------------------------------------------------------------------------- 1 | /** 2 | * datetime: 2017-06-08 3 | * Go http包 静态服务器 4 | * http://localhost:8899/static/avatar.jpg 5 | */ 6 | package main 7 | 8 | import ( 9 | "net/http" 10 | ) 11 | 12 | func main() { 13 | http.Handle( 14 | "/static/", 15 | http.StripPrefix( 16 | "/static/", 17 | http.FileServer(http.Dir("static")), 18 | ), 19 | ) 20 | http.ListenAndServe(":8899", nil) 21 | } 22 | -------------------------------------------------------------------------------- /03_exmaples/Http/web_server.go: -------------------------------------------------------------------------------- 1 | /** 2 | * datetime: 2017-06-08 3 | * Go http包 hello jsser 4 | */ 5 | package main 6 | 7 | import ( 8 | "io" 9 | "net/http" 10 | ) 11 | 12 | func hello(res http.ResponseWriter, req *http.Request) { 13 | 14 | res.Header().Set("Content-Type", "text/html") 15 | res.Header().Set("Server", "jsser") 16 | io.WriteString(res, ` 17 | 18 | 19 | 20 | hello go 21 | 22 | 23 | hello jsser! 24 | 25 | `) 26 | } 27 | 28 | func main() { 29 | //注册路由 30 | http.HandleFunc("/", hello) 31 | //监听端口,并且启动服务 32 | http.ListenAndServe(":8899", nil) 33 | 34 | } 35 | -------------------------------------------------------------------------------- /03_exmaples/Json/json_marshal.go: -------------------------------------------------------------------------------- 1 | /** 2 | * datetime: 2017-06-05 3 | * Go Json操作 - 编码 4 | * 使用encoding/json 中Marshal进行JSON编码 5 | * Go语言结构体的成员名字作为JSON对象(通过反射), 只有导出的结构体成员才会被编码(大写字母开头的成员) 6 | * 一个构体成员Tag是和在编译阶段关联到该成员的元信息字符串 7 | * 结构体的成员Tag可以是任意的字符串面值,但是通常是一系列用空格分隔的key:"value"键值对序列 8 | * json开头键名对应的值用于控制encoding/json包的编码和解码的行为,并且encoding/...下面其它的包也遵循这个约定 9 | * tag成员中可以有omitempty选项,表示当该结构体成员为零值时,JSON对象不包含该成员。 10 | * 11 | */ 12 | package main 13 | 14 | import ( 15 | "encoding/json" 16 | "fmt" 17 | ) 18 | 19 | type Student struct { 20 | Name string 21 | Age int 22 | } 23 | 24 | //Response json字段别名 25 | type Response struct { 26 | Page int `json:"page"` 27 | Fruits []string `json:"fruits"` 28 | Age int `json:"age,omitempty"` 29 | name string 30 | } 31 | 32 | func main() { 33 | 34 | //布尔值 35 | Jbool, _ := json.Marshal(true) 36 | fmt.Println(string(Jbool)) 37 | //int 38 | Jint, _ := json.Marshal(1) 39 | fmt.Println(string(Jint)) 40 | //float 41 | Jfloat, _ := json.Marshal(3.14) 42 | fmt.Println(string(Jfloat)) 43 | //string 44 | Jstring, _ := json.Marshal("hello 中国") 45 | fmt.Println(string(Jstring)) 46 | //切片 47 | s1 := []string{"hello", "world"} 48 | Js1, _ := json.Marshal(s1) 49 | fmt.Println(string(Js1)) 50 | //hash map 51 | m1 := map[string]string{"username": "jsser", "from": "china"} 52 | Jm1, _ := json.Marshal(m1) 53 | fmt.Println(string(Jm1)) 54 | //struct 55 | st1 := Student{Name: "jsser", Age: 20} 56 | Jst1, _ := json.Marshal(st1) 57 | fmt.Println(string(Jst1)) 58 | 59 | res2D := Response{ 60 | Page: 1, 61 | Fruits: []string{"apple", "peach", "pear"}, 62 | Age: 100, 63 | name: "jsser"} //小写字母name成员,不会被编码 64 | res2B, _ := json.Marshal(res2D) 65 | fmt.Printf("%s\n", res2B) 66 | // fmt.Println(string(res2B)) 67 | 68 | } 69 | 70 | //$ go run json_marshal.go 71 | 72 | // true 73 | // 1 74 | // 3.14 75 | // "hello 中国" 76 | // ["hello","world"] 77 | // {"from":"china","username":"jsser"} 78 | // {"Name":"jsser","Age":20} 79 | // {"page":1,"fruits":["apple","peach","pear"],"age":100} 80 | -------------------------------------------------------------------------------- /03_exmaples/Json/json_unmarshal.go: -------------------------------------------------------------------------------- 1 | /** 2 | * datetime: 2017-06-05 3 | * Go Json操作 - 解码操作 4 | */ 5 | package main 6 | 7 | import ( 8 | "encoding/json" 9 | "fmt" 10 | ) 11 | 12 | type Game struct { 13 | Id int `json:"game_id"` 14 | Name string `json:"game_name"` 15 | } 16 | 17 | func main() { 18 | 19 | game := Game{Name: "传奇霸业", Id: 100} 20 | //编码 21 | jsonStr, _ := json.Marshal(game) 22 | fmt.Printf("json encode %s\n", jsonStr) 23 | //解码 24 | var v map[string]interface{} 25 | json.Unmarshal([]byte(jsonStr), &v) 26 | fmt.Println(v["game_id"]) 27 | fmt.Println(v["game_name"]) 28 | } 29 | 30 | // 31 | // json encode {"game_id":100,"game_name":"传奇霸业"} 32 | // 100 33 | // 传奇霸业 34 | // 35 | -------------------------------------------------------------------------------- /03_exmaples/Os/env.go: -------------------------------------------------------------------------------- 1 | /** 2 | * datetime: 2017-06-07 3 | * 环境变量操作 4 | */ 5 | package main 6 | 7 | import ( 8 | "fmt" 9 | "os" 10 | ) 11 | 12 | func main() { 13 | 14 | os.Setenv("MYSQL.PASSWD", "1") 15 | fmt.Println("MYSQL.PASSWD = ", os.Getenv("MYSQL.PASSWD")) 16 | 17 | /** 遍历环境变量 18 | */ 19 | for _, e := range os.Environ() { 20 | fmt.Println(e) 21 | // pair := strings.Split(e, "=") 22 | // fmt.Println(pair[0]) 23 | } 24 | } 25 | 26 | //$ go run env.go 27 | -------------------------------------------------------------------------------- /03_exmaples/Strings/string_format.go: -------------------------------------------------------------------------------- 1 | /** 2 | * datetime: 2017-06-06 3 | * string format 字符串格式化 4 | * fmt.Printf 方法打印 5 | * 参考网址1:http://www.cnblogs.com/golove/p/3284304.html 6 | * 参考网址2:https://gobyexample.com/string-formatting 7 | * 格式字符串由普通字符和占位符组成,例如:abc%+ #8.3[3]vdef" 8 | * 其中 abc 和 def 是普通字符,其它部分是占位符,占位符以 % 开头(注:%% 将被转义为一个普通的 % 符号,这个不算开头),以动词结尾,格式如下: 9 | * %[旗标][宽度][.精度][arg索引]动词,方括号中的内容可以省略。 10 | */ 11 | package main 12 | 13 | import ( 14 | "fmt" 15 | ) 16 | 17 | type point struct { 18 | x, y int 19 | } 20 | 21 | func main() { 22 | 23 | /** 24 | * v:默认格式,不同类型的默认格式如下: 25 | 布尔型:t 26 |   整 型:d 27 |   浮点型:g 28 |   复数型:g 29 |   字符串:s 30 |   通 道:p 31 |   指 针:p 32 | * #v:默认格式,以符合Go语法方式输出,特殊类型语法格式如下:无符号整型:x 33 | * 34 | */ 35 | p := point{1, 2} 36 | //整数型 d 37 | fmt.Printf("%v\n", 1) 38 | //布尔型 t 39 | fmt.Printf("%v\n", true) 40 | //浮点数型 g 41 | fmt.Printf("%v\n", 3.13) 42 | //字符串 s 43 | fmt.Printf("%v\n", "jsser") 44 | //指针类型 p 45 | p1 := &p 46 | fmt.Printf("%v\n", &p1) 47 | //通道类型 p 48 | c1 := make(chan int, 1) 49 | fmt.Printf("%v\n", c1) 50 | //结构体 51 | fmt.Printf("%v\n", p) 52 | 53 | //使用无符号类型 54 | fmt.Printf("%#v\n", uint16(11)) //0xb 55 | 56 | /** 57 | * T: 输出变量或值的类型 58 | */ 59 | fmt.Printf("%T\n", true) //bool 60 | fmt.Printf("%T\n", 3) // int 61 | fmt.Printf("%T\n", p) // main.point 62 | 63 | /** 64 | * 整型 65 | * 66 | * b/o/d:输出2/8/10 进制格式 67 | * x/X:输出16进制格式(大写/小写) 68 | * c:输出数值所表示的Unicode字符 69 | * q:输出数值所表示的 Unicode字符(带单引号)。对于无法显示的字符,将输出其转义字符 70 | * U:输出 Unicode 码点(例如 U+1234,等同于字符串 "U+%04X" 的显示结果) 71 | */ 72 | 73 | //转换2进制 74 | fmt.Printf("%b\n", 10) 75 | //转换8进制 76 | fmt.Printf("%o\n", 10) 77 | //转换16进制[小写] 78 | fmt.Printf("%x\n", 10) 79 | //转换16进制[大写] 80 | fmt.Printf("%X\n", 10) 81 | 82 | } 83 | 84 | //$ go run string_format.go 85 | // 1 86 | // true 87 | // 3.13 88 | // jsser 89 | // 0xc42007e020 90 | // 0xc420086000 91 | // {1 2} 92 | // 0xb 93 | // bool 94 | // int 95 | // main.point 96 | // 1010 97 | // 12 98 | // a 99 | // A 100 | -------------------------------------------------------------------------------- /03_exmaples/Strings/strings.go: -------------------------------------------------------------------------------- 1 | /** 2 | * datetime: 2017-06-06 3 | * strings标准库 - 提供了许多有用的字符串相关函数 4 | */ 5 | package main 6 | 7 | import ( 8 | "fmt" 9 | s "strings" 10 | ) 11 | 12 | var p = fmt.Println 13 | 14 | func main() { 15 | //查找字符串是否包含子字符串 16 | p("Contains: ", s.Contains("jsser", "sser")) 17 | //查找字符串包含子字符的个数 18 | p("Count: ", s.Count("jsser", "sser")) 19 | //判断字符串开头字符 20 | p("HasPrefix: ", s.HasPrefix("jsser", "js")) 21 | //判断字符串结尾字符 22 | p("HasSuffix: ", s.HasSuffix("jsser", "er")) 23 | //查找子字符串在字符串中的索引位置 24 | p("Index: ", s.Index("jsser", "e")) 25 | //将切片join成字符串 26 | p("Join: ", s.Join([]string{"j", "s", "s", "e", "r"}, "-")) 27 | //填充字符串 - str_pad 28 | p("Repeat: ", s.Repeat("j", 5)) 29 | //字符串替换 30 | p("Replace: ", s.Replace("jsser", "s", "S", 1)) 31 | p("Replace: ", s.Replace("jsser", "s", "S", -1)) 32 | //split将字符串切割成数组 33 | p("Split: ", s.Split("jsser", "")) 34 | //将字符串转换成小写 35 | p("ToLower: ", s.ToLower("JSSer")) 36 | //将字符串转换成大写 37 | p("ToUpper", s.ToUpper("JSSER")) 38 | //获取字符串字符长度 39 | p("LEN: ", len("JSSER")) 40 | //以字符数组的形式访问,得到的结果为char类型 ASCII值 41 | p("Char: ", "jsser"[1]) 42 | } 43 | 44 | //$ go run strings.go 45 | 46 | // Contains: true 47 | // Count: 1 48 | // HasPrefix: true 49 | // HasSuffix: true 50 | // Index: 3 51 | // Join: j-s-s-e-r 52 | // Repeat: jjjjj 53 | // Replace: jSser 54 | // Replace: jSSer 55 | // Split: [j s s e r] 56 | // ToLower: jsser 57 | // ToUpper JSSER 58 | // LEN: 5 59 | // Char: 115 60 | -------------------------------------------------------------------------------- /03_exmaples/Template/.gitkeep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/TeamFat/learn-golang/6b7d05d3f7c0eafbc468bc88aa5be21ddabea765/03_exmaples/Template/.gitkeep -------------------------------------------------------------------------------- /04_framework/hello_beego/.gitignore: -------------------------------------------------------------------------------- 1 | hello_beego 2 | -------------------------------------------------------------------------------- /04_framework/hello_beego/README.MD: -------------------------------------------------------------------------------- 1 | hello beego 2 | ---- 3 | ## 介绍 4 | 5 | 依据文档学习beego使用方法 6 | 7 | ## 运行方式 8 | ```bash 9 | cd $GOPATH/src/github.com/TeamFat/learn-golang/04_framework/hello_beego 10 | bee run 11 | ``` 12 | ## 浏览器访问 13 | `http://localhost:8080` 14 | 15 | 16 | 17 | 18 | -------------------------------------------------------------------------------- /04_framework/hello_beego/conf/app.conf: -------------------------------------------------------------------------------- 1 | ;服务器配置 2 | appname = hello_beego 3 | httpport = 8080 4 | autorender = false 5 | runmode = dev 6 | ;应用监听地址 7 | HttpAddr = "127.0.0.1" 8 | ServerName = jsser 9 | ;开启gzip 10 | EnableGzip = true 11 | ;适用gzip的文件后缀 12 | StaticExtensionsToGzip = .css, .js 13 | ;是否开启session 14 | SessionOn = true 15 | SessionName = "sessionId" 16 | 17 | ;开启csrf 18 | EnableXSRF = true 19 | XSRFKEY = "FKLJ90LKJD798FSDLFNLJH" 20 | 21 | 22 | ;加载配置文件 23 | include "dev.conf" 24 | include "prod.conf" 25 | 26 | -------------------------------------------------------------------------------- /04_framework/hello_beego/conf/dev.conf: -------------------------------------------------------------------------------- 1 | [dev] 2 | ;mysql 3 | mysqluser = root 4 | mysqlpasswd = 123456 5 | mysqlhost = "127.0.0.1" 6 | mysqldb = hello_beego 7 | mysqlcharset = utf8mb4 -------------------------------------------------------------------------------- /04_framework/hello_beego/conf/prod.conf: -------------------------------------------------------------------------------- 1 | [prod] 2 | ;mysql 3 | mysqluser = beego 4 | mysqlpasswd = 123456 5 | mysqlhost = "127.0.0.1" 6 | mysqldb = hello_beego 7 | mysqlcharset = utf8mb4 -------------------------------------------------------------------------------- /04_framework/hello_beego/controllers/api/.gitkeep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/TeamFat/learn-golang/6b7d05d3f7c0eafbc468bc88aa5be21ddabea765/04_framework/hello_beego/controllers/api/.gitkeep -------------------------------------------------------------------------------- /04_framework/hello_beego/controllers/backend/base.go: -------------------------------------------------------------------------------- 1 | package backend 2 | 3 | import ( 4 | "strings" 5 | 6 | "strconv" 7 | 8 | "github.com/TeamFat/learn-golang/04_framework/hello_beego/models" 9 | "github.com/TeamFat/learn-golang/04_framework/hello_beego/utils" 10 | "github.com/astaxie/beego" 11 | ) 12 | 13 | type BaseController struct { 14 | beego.Controller 15 | isBackendLogin bool 16 | userId int 17 | username string 18 | moduleName string 19 | controllerName string 20 | actionName string 21 | } 22 | 23 | //获取用户IP地址 24 | func (this *BaseController) getClientIp() string { 25 | s := strings.Split(this.Ctx.Request.RemoteAddr, ":") 26 | 27 | return s[0] 28 | 29 | } 30 | 31 | func (this *BaseController) Prepare() { 32 | controllerName, actionName := this.GetControllerAndAction() 33 | this.moduleName = "backend" 34 | this.controllerName = strings.ToLower(controllerName[0 : len(controllerName)-10]) 35 | this.actionName = strings.ToLower(actionName) 36 | //验证 37 | this.auth() 38 | } 39 | 40 | func (this *BaseController) auth() { 41 | arr := strings.Split(this.Ctx.GetCookie("auth"), "|") 42 | if len(arr) == 2 { 43 | idstr, token := arr[0], arr[1] 44 | userId, _ := strconv.Atoi(idstr) 45 | if userId > 0 { 46 | var user models.User 47 | user.Id = userId 48 | if user.Read() == nil && token == utils.Md5([]byte(this.getClientIp()+"|"+user.Password)) { 49 | this.userId = user.Id 50 | this.username = user.Username 51 | } 52 | } 53 | } 54 | 55 | if this.userId == 0 { 56 | this.Redirect("/admin/login", 302) 57 | } 58 | 59 | } 60 | -------------------------------------------------------------------------------- /04_framework/hello_beego/controllers/backend/site.go: -------------------------------------------------------------------------------- 1 | package backend 2 | 3 | type SiteController struct { 4 | BaseController 5 | } 6 | 7 | func (this *SiteController) Login() { 8 | 9 | } 10 | -------------------------------------------------------------------------------- /04_framework/hello_beego/controllers/base.go: -------------------------------------------------------------------------------- 1 | package controllers 2 | 3 | import ( 4 | "github.com/TeamFat/learn-golang/04_framework/hello_beego/models" 5 | "github.com/astaxie/beego" 6 | ) 7 | 8 | type BaseController struct { 9 | beego.Controller 10 | isLogin bool 11 | user models.User 12 | } 13 | -------------------------------------------------------------------------------- /04_framework/hello_beego/controllers/default.go: -------------------------------------------------------------------------------- 1 | package controllers 2 | 3 | type MainController struct { 4 | BaseController 5 | } 6 | 7 | func (c *MainController) Get() { 8 | 9 | // c.Ctx.WriteString("hello") 10 | c.Data["title"] = "这是第一个beego文件标题" 11 | c.Data["Website"] = "beego.me" 12 | c.Data["Email"] = "astaxie@gmail.com" 13 | c.TplName = "index.tpl" 14 | } 15 | -------------------------------------------------------------------------------- /04_framework/hello_beego/controllers/user.go: -------------------------------------------------------------------------------- 1 | package controllers 2 | 3 | type UserController struct { 4 | BaseController 5 | } 6 | 7 | func (this *UserController) Get() { 8 | //方式1 9 | userId := this.Ctx.Input.Param(":id") 10 | _ = userId 11 | //方式2 - 直接获取的是int类型 , 如果获取其他类型: GetString(), GetStrings(), GetInt(), GetBool, GetFloat() 12 | userId2 := this.Input().Get("id") 13 | _ = userId2 14 | //方式3 15 | //支持数据绑定 - 将数据直接绑定到id上 16 | var id int 17 | this.Ctx.Input.Bind(&id, ":id") 18 | this.Data["json"] = map[string]interface{}{"user_id": id, "username": "jsser"} 19 | this.ServeJSON() 20 | } 21 | -------------------------------------------------------------------------------- /04_framework/hello_beego/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | _ "github.com/TeamFat/learn-golang/04_framework/hello_beego/routers" 5 | "github.com/astaxie/beego" 6 | ) 7 | 8 | func main() { 9 | beego.Run() 10 | } 11 | -------------------------------------------------------------------------------- /04_framework/hello_beego/models/user.go: -------------------------------------------------------------------------------- 1 | package models 2 | 3 | import ( 4 | "github.com/astaxie/beego/orm" 5 | ) 6 | 7 | type User struct { 8 | Id int 9 | Username string 10 | Password string 11 | } 12 | 13 | func (user *User) TableName() string { 14 | return "user" 15 | } 16 | 17 | func (user *User) Read(fields ...string) error { 18 | if err := orm.NewOrm().Read(user, fields...); err != nil { 19 | return err 20 | } 21 | return nil 22 | } 23 | -------------------------------------------------------------------------------- /04_framework/hello_beego/routers/router.go: -------------------------------------------------------------------------------- 1 | package routers 2 | 3 | import ( 4 | "encoding/json" 5 | 6 | "time" 7 | 8 | "github.com/TeamFat/learn-golang/04_framework/hello_beego/controllers" 9 | "github.com/astaxie/beego" 10 | "github.com/astaxie/beego/context" 11 | ) 12 | 13 | func init() { 14 | beego.Router("/", &controllers.MainController{}) 15 | //使用controller -router 16 | beego.Router("/user/:id", &controllers.UserController{}) 17 | 18 | //使用匿名函数 - router 19 | beego.Get("/payment/:user_id", func(ctx *context.Context) { 20 | userID := ctx.Input.Param(":user_id") 21 | ctx.Output.Header("Content-Type", "application/json") 22 | data := make(map[string]interface{}) 23 | data["code"] = 200 24 | data["timestamp"] = time.Now().Unix() 25 | _data := map[string]interface{}{"user_id": userID, "username": "jsser", "sn": "20170301023789172398123", "pay_type": "qrcode", "pay_method": "wechat"} 26 | data["data"] = _data 27 | json, _ := json.Marshal(data) 28 | ctx.Output.Body([]byte(json)) 29 | }) 30 | 31 | //admin - router 32 | 33 | } 34 | -------------------------------------------------------------------------------- /04_framework/hello_beego/static/js/reload.min.js: -------------------------------------------------------------------------------- 1 | function b(a){var c=new WebSocket(a);c.onclose=function(){setTimeout(function(){b(a)},2E3)};c.onmessage=function(){location.reload()}}try{if(window.WebSocket)try{b("ws://localhost:12450/reload")}catch(a){console.error(a)}else console.log("Your browser does not support WebSockets.")}catch(a){console.error("Exception during connecting to Reload:",a)}; 2 | -------------------------------------------------------------------------------- /04_framework/hello_beego/tests/default_test.go: -------------------------------------------------------------------------------- 1 | package test 2 | 3 | import ( 4 | "net/http" 5 | "net/http/httptest" 6 | "testing" 7 | "runtime" 8 | "path/filepath" 9 | _ "github.com/TeamFat/learn-golang/04_framework/hello_beego/routers" 10 | 11 | "github.com/astaxie/beego" 12 | . "github.com/smartystreets/goconvey/convey" 13 | ) 14 | 15 | func init() { 16 | _, file, _, _ := runtime.Caller(1) 17 | apppath, _ := filepath.Abs(filepath.Dir(filepath.Join(file, ".." + string(filepath.Separator)))) 18 | beego.TestBeegoInit(apppath) 19 | } 20 | 21 | 22 | // TestBeego is a sample to run an endpoint test 23 | func TestBeego(t *testing.T) { 24 | r, _ := http.NewRequest("GET", "/", nil) 25 | w := httptest.NewRecorder() 26 | beego.BeeApp.Handlers.ServeHTTP(w, r) 27 | 28 | beego.Trace("testing", "TestBeego", "Code[%d]\n%s", w.Code, w.Body.String()) 29 | 30 | Convey("Subject: Test Station Endpoint\n", t, func() { 31 | Convey("Status Code Should Be 200", func() { 32 | So(w.Code, ShouldEqual, 200) 33 | }) 34 | Convey("The Result Should Not Be Empty", func() { 35 | So(w.Body.Len(), ShouldBeGreaterThan, 0) 36 | }) 37 | }) 38 | } 39 | 40 | -------------------------------------------------------------------------------- /04_framework/hello_beego/utils/functions.go: -------------------------------------------------------------------------------- 1 | package utils 2 | 3 | import ( 4 | "crypto/md5" 5 | "fmt" 6 | ) 7 | 8 | /** 9 | * Md5 10 | */ 11 | func Md5(buf []byte) string { 12 | hash := md5.New() 13 | hash.Write(buf) 14 | return fmt.Sprintf("%x", hash.Sum(nil)) 15 | } 16 | -------------------------------------------------------------------------------- /04_framework/hello_beego/views/frontend/layout/main.html: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/TeamFat/learn-golang/6b7d05d3f7c0eafbc468bc88aa5be21ddabea765/04_framework/hello_beego/views/frontend/layout/main.html -------------------------------------------------------------------------------- /04_framework/hello_beego/views/index.tpl: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | {{ .title }} 6 | 7 | 8 |

9 | 邮件:{{ .Email }} 10 |

11 | 12 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | {one line to give the program's name and a brief idea of what it does.} 635 | Copyright (C) {year} {name of author} 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | {project} Copyright (C) {year} {fullname} 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Go语言学习笔记 2 | 本仓库是记录个人golang学习过程中的笔记和练习示例。 3 | 4 | ## Go语言简介 5 |   Go语言在2007年由Robert Griesemer、Rob Pike 和 Ken Thompson 在 Google开始开发,并且在2009年正式发布,如今被称为云计算的C语言。Go语言有如下几个特点:开放源代码、静态类型和编译型、跨平台、自动垃圾回收、原生的并发编程、完善的构建工具、代码风格强制统一、多编程范式、高效的编程和运行、丰富的标标准库。 6 | 7 | ## Go语言环境及开发工具 8 | 本人使用开发环境如下: 9 | * [Github Wiki](https://github.com/zhuzhenyu/lean-golang/wiki/Mac-Golang-%E5%BC%80%E5%8F%91%E7%8E%AF%E5%A2%83) 10 | * OS X EI Capian 10.11.6 11 | * Golang 1.8.1 [Download](https://golang.org/dl/) 12 | * Visual Studio Code 1.12.2 [Download](https://code.visualstudio.com/) 13 | * 编辑器扩展 14 | * [Go](https://marketplace.visualstudio.com/items?itemName=lukehoban.Go) 15 | * Git 16 | 17 | ## Go语言明星应用 18 | 19 | * [docker](https://www.docker.com) 开源的应用容器引擎 20 | * [Etcd](https://coreos.com/etcd/docs/latest/) 分布式键值存储引擎 21 | * [tidb](https://pingcap.com/index-zh) 新一代开源分布式 NewSQL 数据库 兼容MySQL语法 22 | * [beego](https://beego.me/)一个使用 Go 的思维来帮助您构建并开发 Go 应用程序的开源框架 23 | 24 | 25 | ## Go语言学习资料 26 | 27 | * [Go语言官网](https://golang.org) 28 | * [Go by Example](https://gobyexample.com) 29 | * [Go语言圣经(中文版)](http://docs.plhwin.com/gopl-zh/index.html) 30 | * [GitHub Awesome Go](https://github.com/avelino/awesome-go) 31 | * [astaxie build web application with golang](https://github.com/astaxie/build-web-application-with-golang/blob/master/zh/preface.md) 32 | * [Go语言标准库](https://github.com/polaris1119/The-Golang-Standard-Library-by-Example) 33 | * [雨痕 Go语言学习笔记](https://github.com/qyuhen/book) 34 | * [Go并发编程实战](https://github.com/gopcp/example.v2) 35 | 36 | -------------------------------------------------------------------------------- /hello.go: -------------------------------------------------------------------------------- 1 | /** 2 | * author: jsser 3 | * datetime: 2017-05-20 4 | * 01-hello.go 5 | * Go语言的第一个程序:hello world 6 | */ 7 | 8 | // 在go语言中,所有源码文件都必须是包的一部分,而main包为默认包 9 | package main 10 | 11 | // 引入fmt标准库 12 | // fmt标准库提供基本的标准格式化功能 13 | import "fmt" 14 | 15 | // main包中必须包含main函数,才能够被正确运行 16 | func main() { 17 | fmt.Print("hello world\n") 18 | } 19 | 20 | //$ go run hello.go 21 | --------------------------------------------------------------------------------