├── .gitignore ├── 01.Golang网页笔记 ├── Golang 微信机器人包 - orlion - 博客园.html ├── Golang 微信机器人包 - orlion - 博客园_files │ ├── 20160331143213.png │ ├── 24442-20171027070203758-1397753435.jpg │ ├── 24442-20171029145139367-1787068412.jpg │ ├── 687474703a2f2f69342e6275696d672e636f6d2f3536373537312f343435326165303866646336383830622e6a7067 │ ├── analytics.js │ ├── blog-common.css │ ├── blog-common.js │ ├── bundle-LoveIsIntheAir-mobile.css │ ├── bundle-LoveIsIntheAir.css │ ├── icon_weibo_24.png │ ├── jquery.js │ ├── logo.gif │ ├── saved_resource.html │ ├── wechat.png │ └── xml.gif ├── Golang 笔记 1 基础、基本数据类型 - orlion - 博客园.html ├── Golang 笔记 1 基础、基本数据类型 - orlion - 博客园_files │ ├── 20160331143213.png │ ├── 24442-20171027070203758-1397753435.jpg │ ├── 24442-20171029145139367-1787068412.jpg │ ├── 798267-20170312181714857-165152327.png │ ├── 798267-20170312181736357-1843824288.png │ ├── 798267-20170312181809686-170726689.png │ ├── 798267-20170319181258807-380888326.png │ ├── 798267-20170319181326729-1059684011.png │ ├── 798267-20170319181416995-1480939339.png │ ├── analytics.js │ ├── blog-common.css │ ├── blog-common.js │ ├── bundle-LoveIsIntheAir-mobile.css │ ├── bundle-LoveIsIntheAir.css │ ├── icon_weibo_24.png │ ├── jquery.js │ ├── logo.gif │ ├── wechat.png │ └── xml.gif ├── Golang 笔记 2 函数、结构体、接口、指针 - orlion - 博客园.html ├── Golang 笔记 2 函数、结构体、接口、指针 - orlion - 博客园_files │ ├── 20160331143213.png │ ├── 24442-20171027070203758-1397753435.jpg │ ├── 24442-20171029145139367-1787068412.jpg │ ├── analytics.js │ ├── blog-common.css │ ├── blog-common.js │ ├── bundle-LoveIsIntheAir-mobile.css │ ├── bundle-LoveIsIntheAir.css │ ├── icon_weibo_24.png │ ├── jquery.js │ ├── logo.gif │ ├── wechat.png │ └── xml.gif ├── Golang 笔记 3 if、switch、for、select语句 - orlion - 博客园.html ├── Golang 笔记 3 if、switch、for、select语句 - orlion - 博客园_files │ ├── 20160331143213.png │ ├── 24442-20171027070203758-1397753435.jpg │ ├── 24442-20171029145139367-1787068412.jpg │ ├── 798267-20170319181108088-1859798310.png │ ├── analytics.js │ ├── blog-common.css │ ├── blog-common.js │ ├── bundle-LoveIsIntheAir-mobile.css │ ├── bundle-LoveIsIntheAir.css │ ├── icon_weibo_24.png │ ├── jquery.js │ ├── logo.gif │ ├── wechat.png │ └── xml.gif ├── Golang 笔记 4 defer、error、panic - orlion - 博客园.html ├── Golang 笔记 4 defer、error、panic - orlion - 博客园_files │ ├── 20160331143213.png │ ├── 24442-20171027070203758-1397753435.jpg │ ├── 24442-20171029145139367-1787068412.jpg │ ├── analytics.js │ ├── blog-common.css │ ├── blog-common.js │ ├── bundle-LoveIsIntheAir-mobile.css │ ├── bundle-LoveIsIntheAir.css │ ├── icon_weibo_24.png │ ├── jquery.js │ ├── logo.gif │ ├── wechat.png │ └── xml.gif ├── Golang 笔记 5 go语句 - orlion - 博客园.html └── Golang 笔记 5 go语句 - orlion - 博客园_files │ ├── 20160331143213.png │ ├── 24442-20171027070203758-1397753435.jpg │ ├── 24442-20171029145139367-1787068412.jpg │ ├── analytics.js │ ├── blog-common.css │ ├── blog-common.js │ ├── bundle-LoveIsIntheAir-mobile.css │ ├── bundle-LoveIsIntheAir.css │ ├── icon_weibo_24.png │ ├── jquery.js │ ├── logo.gif │ ├── wechat.png │ └── xml.gif ├── 02.RUNOOB例子代码 ├── 01HelloWrrld │ └── Demo01-HelloWorld.go ├── 02变量声明 │ ├── 变量声明.go │ └── 多变量声明.go ├── 03常量声明 │ ├── 1普通常量的定义.go │ ├── 2使用函数返回值作为常量赋值.go │ ├── 3iota.go │ └── 4iota-位运算.go ├── 04语言运算符 │ ├── 01算术运算符.go │ ├── 02关系运算符.go │ ├── 03逻辑运算符.go │ ├── 04位运算符.go │ ├── 05赋值运算符.go │ ├── 06指针运算符.go │ └── 07运算符优先级.go ├── 05条件语句 │ ├── 01ifelse.go │ ├── 02switch.go │ ├── 03TypeSwitch.go │ └── 04select.go ├── 06循环语句 │ ├── 01For.go │ ├── 02循环嵌套.go │ ├── 03break语句.go │ ├── 04continue语句.go │ ├── 05goto语句.go │ └── 06无限循环.go ├── 07函数 │ ├── 01函数调用.go │ ├── 02函数返回多个值.go │ ├── 03值传递.go │ ├── 04引用传递.go │ ├── 05函数作为值.go │ ├── 06闭包.go │ └── 07方法.go ├── 08变量作用域 │ ├── 01局部变量.go │ ├── 02全局变量.go │ └── 03形式参数.go ├── 09数组 │ ├── 01访问数组元素.go │ ├── 02多维数组.go │ └── 03向函数传递数组.go ├── 10指针 │ ├── 01展示变量内存地址.go │ ├── 02获取指针的值.go │ ├── 03Go空指针.go │ ├── 04数组指针.go │ ├── 05指向指针的指针.go │ └── 06指针作为函数参数.go ├── 11结构体 │ ├── 01结构体定义.go │ ├── 02访问结构体成员.go │ ├── 03结构体作为函数参数.go │ └── 04结构体指针.go ├── 12切片 │ ├── 01定义和初始化.go │ ├── 02len()和cap()函数.go │ ├── 03空切片.go │ ├── 04切片截取.go │ └── 05append()和copy()函数.go ├── 13范围Range │ └── 01实例.go ├── 14Map集合 │ ├── 01定义Map.go │ └── 02delete函数.go ├── 15函数递归 │ ├── 01阶乘.go │ └── 02斐波那契数列.go ├── 16类型转换 │ └── 01整型转化为浮点型.go ├── 17接口 │ └── 01接口的使用.go ├── 18错误处理 │ ├── 01错误处理简单使用.go │ └── 02错误处理复杂实例.go ├── 19并发 │ ├── 01简单使用.go │ ├── 02创建一个协程.go │ ├── 03开启多个协程.go │ ├── 04信道创建.go │ ├── 05信道简单使用.go │ ├── 06子协程传递字符串到主协程.go │ ├── 07平方和-立方和分别为子协程主协程求和.go │ ├── 08单向信道.go │ ├── 09关闭信道.go │ ├── 10使用rangeFor遍历信道.go │ └── 11多信道计算.go ├── Go笔记.docx └── 简单生产者消费者问题.go ├── 03.北风网Golang ├── Golang北风网笔记.docx ├── 第10讲 Go语言之面向对象下 1 │ ├── 01面向对象.go │ └── 02interface.go ├── 第10讲 Go语言之面向对象下_2 │ ├── 01对象实例赋值给接口.go │ ├── 02空接口使用.go │ ├── 03空接口类型查询Switch--Type.go │ └── 04空接口类型查询if---ok.go ├── 第11讲 Go语言并发编程之协程 │ └── 01协程简单使用.go ├── 第12讲 Go语言并发编程之channel │ ├── 01Channel-simple-use.go │ └── 02Channel-simple-use.go ├── 第13讲 Go语言并发编程之缓冲channel │ └── 缓冲Channel.go ├── 第14讲 Go语言并发编程之select │ ├── 01select.go │ ├── 02select.go │ └── 03select--time-after.go ├── 第15讲 Go语言并发编程之深入协程 │ ├── Thread.java │ ├── goroutine_1.go │ └── goroutine_2.go ├── 第16讲 Go语言之JSON与Md5 │ ├── 01JSON.go │ └── 02MD5.go ├── 第17讲 Go语言之HTTP │ ├── http_get.go │ └── http_server.go ├── 第18讲 Go语言之正则表达式_1 │ ├── 01Match使用.go │ ├── 02Compile使用.go │ └── 03Find使用.go ├── 第18讲 Go语言之正则表达式_2 │ └── simple_crawler.go ├── 第19讲 Go语言之Mysql_1 │ └── 01Mysql.go ├── 第19讲 Go语言之Mysql_2 │ ├── 01Mysql-update.go │ ├── 02Mysql-delete.go │ └── 03Mysql-select.go ├── 第1讲 Go语言简介 │ └── 01HelloWorld.go ├── 第20讲 Go语言之Redis │ └── redis.go ├── 第21讲 Go语言之聊天室_1 │ ├── Client.go │ └── Server.go ├── 第21讲 Go语言之聊天室_2 │ ├── Client.go │ └── Server.go ├── 第21讲 Go语言之聊天室_3 │ ├── Client.go │ └── Server.go ├── 第21讲 Go语言之聊天室_4 │ ├── Client.go │ ├── Server.go │ └── test.log ├── 第22讲 Beego框架简介 │ ├── pkg │ │ └── windows_amd64 │ │ │ ├── API │ │ │ ├── controllers.a │ │ │ ├── models.a │ │ │ └── routers.a │ │ │ └── WEB │ │ │ ├── controllers.a │ │ │ ├── models.a │ │ │ └── routers.a │ └── src │ │ ├── API │ │ ├── API.exe~ │ │ ├── conf │ │ │ └── app.conf │ │ ├── controllers │ │ │ ├── object.go │ │ │ └── user.go │ │ ├── main.go │ │ ├── models │ │ │ ├── object.go │ │ │ └── user.go │ │ ├── routers │ │ │ └── router.go │ │ └── tests │ │ │ └── default_test.go │ │ └── WEB │ │ ├── conf │ │ ├── app.conf │ │ └── testini.conf │ │ ├── controllers │ │ ├── default.go │ │ ├── test.go │ │ ├── testConfig.go │ │ ├── testContext.go │ │ ├── testHttpLib.go │ │ ├── testInput.go │ │ ├── testLogin.go │ │ ├── testModel.go │ │ └── testView.go │ │ ├── main.go │ │ ├── models │ │ └── user.go │ │ ├── routers │ │ └── router.go │ │ ├── static │ │ └── js │ │ │ └── reload.min.js │ │ ├── testini.conf │ │ ├── tests │ │ └── default_test.go │ │ └── views │ │ ├── index.tpl │ │ └── test_view.tpl ├── 第2讲 理解GOPATH │ ├── 01main.go │ └── print_hello.go ├── 第30讲 Beego框架之爬虫项目实战_1 │ ├── pkg │ │ └── windows_amd64 │ │ │ └── crawl_movices │ │ │ ├── controllers.a │ │ │ ├── models.a │ │ │ └── routers.a │ ├── sql │ │ └── movie.sql │ └── src │ │ └── crawl_movices │ │ ├── conf │ │ └── app.conf │ │ ├── controllers │ │ ├── crawlMovie.go │ │ └── default.go │ │ ├── crawl_movices.exe~ │ │ ├── main.go │ │ ├── models │ │ ├── movie_info.go │ │ └── redis.go │ │ ├── routers │ │ └── router.go │ │ ├── static │ │ └── js │ │ │ └── reload.min.js │ │ ├── tests │ │ └── default_test.go │ │ └── views │ │ └── index.tpl ├── 第3讲 Go语言基础上 │ ├── 01基础类型.go │ ├── 02基础类型_复数.go │ └── 03基础类型_数组1.go ├── 第4讲 Go语言基础下 │ ├── 01Slice_1.go │ ├── 02Slice_2.go │ └── 03map.go ├── 第5讲 Go语言之流程控制 │ ├── 01IF.go │ ├── 02for.go │ ├── 03switch.go │ └── 04range.go ├── 第6讲 Go语言之函数上 │ └── 01函数.go ├── 第7讲 Go语言之函数下 │ ├── 01匿名函数.go │ ├── 02getSum.go │ ├── 03函数传值和传址.go │ ├── 04defer.go │ └── 05panic和recover.go ├── 第8讲 Go语言之struct │ └── 01Struct.go └── 第9讲 Go语言之面向对象上 │ └── 01面向对象.go ├── 04.慕课网-Go语言第一课 └── Go语言第一课.docx ├── 05.慕课网-搭建并行处理管道,感受GO语言魅力 └── 搭建并行处理管道,感受GO语言魅力.docx ├── 06.(重点)慕课网-Google资深工程师深度讲解Go语言 ├── 01.基本语法 │ ├── 01HelloWorld │ │ └── main.go │ ├── 02.变量 │ │ ├── 01变量零值.go │ │ ├── 02变量初始化与赋值.go │ │ └── 03全局变量与其简写.go │ ├── 03复数 │ │ └── 欧拉公式.go │ ├── 04类型转换 │ │ └── 强制转换.go │ ├── 05常量 │ │ ├── 01常量.go │ │ └── 02枚举.go │ ├── 06条件选择 │ │ ├── abc.txt │ │ ├── for.go │ │ ├── if.go │ │ ├── switch.go │ │ └── test.go │ └── 07函数 │ │ ├── 01函数的一般使用.go │ │ ├── 02函数式编程.go │ │ ├── 03值传递与引用传递.go │ │ └── test.go ├── 02.数据结构 │ ├── 1.数组 │ │ └── arrays.go │ ├── 2.切片 │ │ ├── 1.slice.go │ │ ├── 2.sliece拓展.go │ │ ├── 3.slice操作方法.go │ │ ├── 4.slice创建方法.go │ │ └── 5.slice头尾部获取.go │ ├── 3.map │ │ ├── 1.map.go │ │ └── 2.nonrepeating.go │ └── 4.rune │ │ ├── 2.nonrepeating.go │ │ └── 4.rune.go ├── 03.面向对象 │ ├── 01.tree │ │ ├── entry │ │ │ └── entry.go │ │ ├── node.go │ │ └── traversal.go │ ├── 02.queue │ │ ├── entry │ │ │ └── entry.go │ │ ├── queue.go │ │ └── queue2.go │ └── 03.接口 │ │ ├── mock │ │ └── mockretriever.go │ │ ├── real │ │ └── realretriever.go │ │ ├── retriever │ │ └── main.go │ │ └── test.go ├── 04.函数式编程 │ ├── 01.tree │ │ ├── entry │ │ │ └── entry.go │ │ ├── node.go │ │ └── traversal.go │ ├── 1.斐波那契数列.go │ ├── 2.为函数实现接口.go │ ├── 3.使用函数来遍历二叉树.go │ └── adder │ │ └── adder.go ├── 05.资源管理与出错处理 │ ├── 01.defer.go │ ├── 02.panic.go │ ├── 03.统一错误处理 │ │ └── web.go │ └── 04.cover.go ├── 06.测试 │ ├── basic │ │ ├── basic.go │ │ ├── profile001.svg │ │ ├── test │ │ │ └── triangle_test.go │ │ └── triangle_test.go │ └── http │ │ ├── errwrapper_test.go │ │ └── web.go ├── 07.生成文档与实例代码 │ ├── queue.go │ └── queue_test.go ├── 08.goroutine │ └── 01.simple.go ├── 09.channel │ ├── 01.entry │ │ └── 01.channnel.go │ ├── 02.entry │ │ └── 02.channnel.go │ ├── 03.entry │ │ └── bufferedChannel.go │ ├── 04.entry │ │ └── done.go │ ├── 05.entry │ │ └── waitGroup.go │ ├── 06.entry │ │ └── waitGroup2.go │ └── 07.tree │ │ ├── entry │ │ └── entry.go │ │ ├── node.go │ │ └── traversal.go ├── 10.select │ └── 01.select.go ├── 11.传统同步机制 │ ├── 01.entry │ │ └── 01.atomic.go │ └── 02.entry │ │ └── 02.atomic-mutex.go ├── 12.Golang标准库 │ ├── 01.entry │ │ └── 01.httpclient-get.go │ ├── 02 │ │ └── http │ │ │ ├── errwrapper_test.go │ │ │ └── web.go │ └── test.go ├── 13.迷宫-广度优先算法 │ ├── maze.go │ └── migong.ini ├── 14.正则表达式 │ └── regex.go ├── 15.爬虫实现--单任务版-并发版 │ ├── crawler(暂时无用了) │ │ ├── .gitignore │ │ ├── config │ │ │ └── config.go │ │ ├── engine │ │ │ ├── concurrent.go │ │ │ ├── simple.go │ │ │ └── types.go │ │ ├── fetcher │ │ │ └── fetcher.go │ │ ├── glide.yaml │ │ ├── main.go │ │ ├── main_old.go │ │ ├── model │ │ │ └── profile.go │ │ ├── persist │ │ │ ├── itemsaver.go │ │ │ └── itemsaver_test.go │ │ ├── scheduler │ │ │ ├── queued.go │ │ │ └── simple.go │ │ └── zhenai │ │ │ └── parse │ │ │ ├── city.go │ │ │ ├── citylist.go │ │ │ ├── citylist_test.go │ │ │ ├── profile.go │ │ │ ├── profile_test.go │ │ │ ├── profile_test_data.html │ │ │ └── test.html │ └── crawler │ │ ├── .gitignore │ │ ├── config │ │ └── config.go │ │ ├── engine │ │ ├── concurrent.go │ │ ├── simple.go │ │ ├── types.go │ │ └── worker.go │ │ ├── fetcher │ │ └── fetcher.go │ │ ├── frontend │ │ ├── controller │ │ │ └── searchresult.go │ │ ├── model │ │ │ └── page.go │ │ ├── starter.go │ │ └── view │ │ │ ├── css │ │ │ └── style.css │ │ │ ├── index.html │ │ │ ├── js │ │ │ └── index.js │ │ │ ├── logo.png │ │ │ ├── searchresult.go │ │ │ ├── searchresult_test.go │ │ │ └── template.html │ │ ├── glide.yaml │ │ ├── main.go │ │ ├── model │ │ └── profile.go │ │ ├── persist │ │ ├── itemsaver.go │ │ └── itemsaver_test.go │ │ ├── scheduler │ │ ├── queued.go │ │ └── simple.go │ │ └── zhenai │ │ └── parser │ │ ├── city.go │ │ ├── citylist.go │ │ ├── citylist_test.go │ │ ├── citylist_test_data.html │ │ ├── profile.go │ │ ├── profile_test.go │ │ └── profile_test_data.html ├── 16.分布式爬搭建 │ ├── crawler │ │ ├── .gitignore │ │ ├── config │ │ │ └── config.go │ │ ├── engine │ │ │ ├── concurrent.go │ │ │ ├── simple.go │ │ │ ├── types.go │ │ │ └── worker.go │ │ ├── fetcher │ │ │ └── fetcher.go │ │ ├── frontend │ │ │ ├── controller │ │ │ │ └── searchresult.go │ │ │ ├── model │ │ │ │ └── page.go │ │ │ ├── starter.go │ │ │ └── view │ │ │ │ ├── css │ │ │ │ └── style.css │ │ │ │ ├── index.html │ │ │ │ ├── js │ │ │ │ └── index.js │ │ │ │ ├── logo.png │ │ │ │ ├── searchresult.go │ │ │ │ ├── searchresult_test.go │ │ │ │ └── template.html │ │ ├── glide.yaml │ │ ├── main.go │ │ ├── model │ │ │ └── profile.go │ │ ├── persist │ │ │ ├── itemsaver.go │ │ │ └── itemsaver_test.go │ │ ├── scheduler │ │ │ ├── queued.go │ │ │ └── simple.go │ │ └── zhenai │ │ │ └── parser │ │ │ ├── city.go │ │ │ ├── citylist.go │ │ │ ├── citylist_test.go │ │ │ ├── citylist_test_data.html │ │ │ ├── profile.go │ │ │ ├── profile_test.go │ │ │ └── profile_test_data.html │ ├── distributed │ │ ├── config │ │ │ └── config.go │ │ ├── main.go │ │ ├── persist │ │ │ ├── client │ │ │ │ └── itemsaver.go │ │ │ ├── rpc.go │ │ │ └── server │ │ │ │ ├── client_test.go │ │ │ │ └── itemsaver.go │ │ ├── rpcsupport │ │ │ └── rpc.go │ │ └── worker │ │ │ ├── client │ │ │ └── worker.go │ │ │ ├── rpc.go │ │ │ ├── server │ │ │ ├── client_test.go │ │ │ └── worker.go │ │ │ └── types.go │ └── readme.md ├── 17.TCPclient文件上传 │ ├── mian.go │ └── tcp │ │ └── goTcpClient.go ├── 18.RPC │ └── rpc │ │ ├── client │ │ └── main.go │ │ ├── rpc.go │ │ └── server │ │ └── main.go ├── 19.json │ └── main.go ├── fib.txt └── 深度讲解Golang笔记.docx ├── 07.基于Golang协程实现流量统计系统 ├── StatisticalSystemWithCSP │ ├── 01.并发编程 │ │ ├── 01 │ │ │ └── 01.HelloWorld.go │ │ ├── 02 │ │ │ └── 02.BufferChannel.go │ │ ├── 03 │ │ │ └── 03.解决channel产生死锁的写法.go │ │ ├── 04 │ │ │ └── Select随机选择.go │ │ └── 05 │ │ │ └── Select等待机制.go │ └── 02.项目1 │ │ └── 1.高并发CURL访问主站 │ │ ├── 1.curl_run.go │ │ └── 2.analysis.go └── 基于Golang协程实现流量统计系统.docx ├── 08.glide的使用备忘 ├── glide使用内容.txt └── glide使用备忘.txt ├── 09.基于Go语言构建企业级的Restful API服务 ├── demo01 │ ├── handler │ │ └── sd │ │ │ └── check.go │ ├── main.go │ └── router │ │ ├── middleware │ │ └── header.go │ │ └── router.go ├── demo02 │ ├── conf │ │ └── config.yaml │ ├── config │ │ └── config.go │ ├── handler │ │ └── sd │ │ │ └── check.go │ ├── main.go │ └── router │ │ ├── middleware │ │ └── header.go │ │ └── router.go ├── demo03 │ ├── conf │ │ └── config.yaml │ ├── config │ │ └── config.go │ ├── handler │ │ └── sd │ │ │ └── check.go │ ├── log │ │ ├── apiserver.log │ │ ├── apiserver.log.20180702161825197 │ │ └── apiserver.log.20180702161825197.zip │ ├── main.go │ └── router │ │ ├── middleware │ │ └── header.go │ │ └── router.go ├── demo04 │ ├── conf │ │ └── config.yaml │ ├── config │ │ └── config.go │ ├── db │ │ └── db.sql │ ├── handler │ │ └── sd │ │ │ └── check.go │ ├── log │ │ ├── apiserver.log │ │ ├── apiserver.log.20180702161825197 │ │ └── apiserver.log.20180702161825197.zip │ ├── main.go │ ├── model │ │ └── init.go │ └── router │ │ ├── middleware │ │ └── header.go │ │ └── router.go ├── demo05 │ ├── conf │ │ └── config.yaml │ ├── config │ │ └── config.go │ ├── db │ │ └── db.sql │ ├── handler │ │ ├── sd │ │ │ └── check.go │ │ └── user │ │ │ └── create.go │ ├── log │ │ ├── apiserver.log │ │ └── apiserver.log.20180702161825197.zip │ ├── main.go │ ├── model │ │ └── init.go │ ├── pkg │ │ └── errno │ │ │ ├── code.go │ │ │ └── errno.go │ └── router │ │ ├── middleware │ │ └── header.go │ │ └── router.go ├── demo06 │ ├── conf │ │ └── config.yaml │ ├── config │ │ └── config.go │ ├── db │ │ └── db.sql │ ├── handler │ │ ├── handler.go │ │ ├── sd │ │ │ └── check.go │ │ └── user │ │ │ ├── create.go │ │ │ └── user.go │ ├── log │ │ ├── apiserver.log │ │ └── apiserver.log.20180702161825197.zip │ ├── main.go │ ├── model │ │ └── init.go │ ├── pkg │ │ └── errno │ │ │ ├── code.go │ │ │ └── errno.go │ └── router │ │ ├── middleware │ │ └── header.go │ │ └── router.go ├── demo07 │ ├── README.md │ ├── conf │ │ └── config.yaml │ ├── config │ │ └── config.go │ ├── db │ │ └── db.sql │ ├── handler │ │ ├── handler.go │ │ ├── sd │ │ │ └── check.go │ │ └── user │ │ │ ├── create.go │ │ │ ├── delete.go │ │ │ ├── get.go │ │ │ ├── list.go │ │ │ ├── update.go │ │ │ └── user.go │ ├── log │ │ ├── apiserver.log │ │ └── apiserver.log.20180702161825197.zip │ ├── main.go │ ├── model │ │ ├── init.go │ │ ├── model.go │ │ └── user.go │ ├── pkg │ │ ├── auth │ │ │ └── auth.go │ │ ├── constvar │ │ │ └── constvar.go │ │ └── errno │ │ │ ├── code.go │ │ │ └── errno.go │ ├── router │ │ ├── middleware │ │ │ └── header.go │ │ └── router.go │ ├── service │ │ └── service.go │ └── util │ │ └── util.go ├── demo08 │ ├── README.md │ ├── conf │ │ └── config.yaml │ ├── config │ │ └── config.go │ ├── db │ │ └── db.sql │ ├── handler │ │ ├── handler.go │ │ ├── sd │ │ │ └── check.go │ │ └── user │ │ │ ├── create.go │ │ │ ├── delete.go │ │ │ ├── get.go │ │ │ ├── list.go │ │ │ ├── update.go │ │ │ └── user.go │ ├── log │ │ ├── apiserver.log │ │ └── apiserver.log.20180702161825197.zip │ ├── main.go │ ├── model │ │ ├── init.go │ │ ├── model.go │ │ └── user.go │ ├── pkg │ │ ├── auth │ │ │ └── auth.go │ │ ├── constvar │ │ │ └── constvar.go │ │ └── errno │ │ │ ├── code.go │ │ │ └── errno.go │ ├── router │ │ ├── middleware │ │ │ ├── header.go │ │ │ ├── logging.go │ │ │ └── requestid.go │ │ └── router.go │ ├── service │ │ └── service.go │ └── util │ │ └── util.go ├── demo09 │ ├── README.md │ ├── conf │ │ └── config.yaml │ ├── config │ │ └── config.go │ ├── db │ │ └── db.sql │ ├── handler │ │ ├── handler.go │ │ ├── sd │ │ │ └── check.go │ │ └── user │ │ │ ├── create.go │ │ │ ├── delete.go │ │ │ ├── get.go │ │ │ ├── list.go │ │ │ ├── login.go │ │ │ ├── update.go │ │ │ └── user.go │ ├── log │ │ ├── apiserver.log │ │ └── apiserver.log.20180702161825197.zip │ ├── main.go │ ├── model │ │ ├── init.go │ │ ├── model.go │ │ └── user.go │ ├── pkg │ │ ├── auth │ │ │ └── auth.go │ │ ├── constvar │ │ │ └── constvar.go │ │ ├── errno │ │ │ ├── code.go │ │ │ └── errno.go │ │ └── token │ │ │ └── token.go │ ├── router │ │ ├── middleware │ │ │ ├── auth.go │ │ │ ├── header.go │ │ │ ├── logging.go │ │ │ └── requestid.go │ │ └── router.go │ ├── service │ │ └── service.go │ └── util │ │ └── util.go └── 基于 Go 语言构建企业级的 RESTful API 服务.rar ├── 10.GO实现千万级WebSocket消息推送服务(MOOC) ├── GO实现千万级WebSocket消息推送服务.docx └── wsServer │ ├── 01server--普通WS版本 │ └── server1.go │ ├── 02server--WS封装版本 │ ├── impl │ │ └── connection.go │ └── server2.go │ └── client.html ├── 11.各种场景写法优雅退出 ├── Context │ └── main.go ├── chanSelect │ └── main.go ├── channel │ └── channel.go ├── process │ └── main.go ├── tcp优雅退出 │ └── server.go └── waitGroup │ └── main.go ├── 12.各种场景下的永久阻塞 └── README.md ├── 14.RabbitMQ使用 └── 01.简单队列 │ ├── receive │ └── main.go │ └── send │ └── main.go ├── 15.Golang开发分布式任务调度 ├── Golang开发分布式任务调度.docx └── go-crontab │ └── 01prepare │ ├── cmd_usage │ ├── demo01 │ │ └── main.go │ ├── demo02 │ │ └── main.go │ └── demo03 │ │ └── main.go │ ├── cron_usage │ ├── demo1 │ │ └── main.go │ └── demo2 │ │ └── main.go │ ├── etcd_usage │ ├── demo01 │ │ └── main.go │ ├── demo02 │ │ └── main.go │ ├── demo03 │ │ └── main.go │ ├── demo04 │ │ └── main.go │ ├── demo05 │ │ └── main.go │ ├── demo06 │ │ └── main.go │ ├── demo07 │ │ └── main.go │ ├── demo08 │ │ └── main.go │ └── demo09 │ │ └── main.go │ └── mongodb_usage │ ├── demo01 │ └── main.go │ ├── demo02 │ └── main.go │ ├── demo03 │ └── main.go │ ├── demo04 │ └── main.go │ └── demo05 │ └── main.go ├── 16.Go语言打造高并发web即时聊天(IM)应用 └── Go语言打造高并发web即时聊天(IM)应用.docx ├── LICENSE ├── README.md ├── chatroom ├── README.md ├── client.go ├── home.html ├── hub.go └── main.go ├── command ├── README.md ├── home.html └── main.go ├── gRPC简单使用 └── grpcStudy │ ├── client │ └── main.go │ ├── helloworld.proto │ ├── helloworld │ └── helloworld.pb.go │ └── server │ └── main.go └── 各种数据结构推荐使用库.txt /.gitignore: -------------------------------------------------------------------------------- 1 | # Binaries for programs and plugins 2 | *.exe 3 | *.dll 4 | *.so 5 | *.dylib 6 | 7 | # Test binary, build with `go test -c` 8 | *.test 9 | 10 | # Output of the go coverage tool, specifically when used with LiteIDE 11 | *.out 12 | 13 | # Project-local glide cache, RE: https://github.com/Masterminds/glide/issues/736 14 | .glide/ 15 | 16 | .idea/ 17 | 18 | -------------------------------------------------------------------------------- /01.Golang网页笔记/Golang 微信机器人包 - orlion - 博客园_files/20160331143213.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Goular/GolangModule/6f5ea735e919e4d2521b85ebb470a012bc05baf3/01.Golang网页笔记/Golang 微信机器人包 - orlion - 博客园_files/20160331143213.png -------------------------------------------------------------------------------- /01.Golang网页笔记/Golang 微信机器人包 - orlion - 博客园_files/24442-20171027070203758-1397753435.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Goular/GolangModule/6f5ea735e919e4d2521b85ebb470a012bc05baf3/01.Golang网页笔记/Golang 微信机器人包 - orlion - 博客园_files/24442-20171027070203758-1397753435.jpg -------------------------------------------------------------------------------- /01.Golang网页笔记/Golang 微信机器人包 - orlion - 博客园_files/24442-20171029145139367-1787068412.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Goular/GolangModule/6f5ea735e919e4d2521b85ebb470a012bc05baf3/01.Golang网页笔记/Golang 微信机器人包 - orlion - 博客园_files/24442-20171029145139367-1787068412.jpg -------------------------------------------------------------------------------- /01.Golang网页笔记/Golang 微信机器人包 - orlion - 博客园_files/687474703a2f2f69342e6275696d672e636f6d2f3536373537312f343435326165303866646336383830622e6a7067: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Goular/GolangModule/6f5ea735e919e4d2521b85ebb470a012bc05baf3/01.Golang网页笔记/Golang 微信机器人包 - orlion - 博客园_files/687474703a2f2f69342e6275696d672e636f6d2f3536373537312f343435326165303866646336383830622e6a7067 -------------------------------------------------------------------------------- /01.Golang网页笔记/Golang 微信机器人包 - orlion - 博客园_files/icon_weibo_24.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Goular/GolangModule/6f5ea735e919e4d2521b85ebb470a012bc05baf3/01.Golang网页笔记/Golang 微信机器人包 - orlion - 博客园_files/icon_weibo_24.png -------------------------------------------------------------------------------- /01.Golang网页笔记/Golang 微信机器人包 - orlion - 博客园_files/logo.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Goular/GolangModule/6f5ea735e919e4d2521b85ebb470a012bc05baf3/01.Golang网页笔记/Golang 微信机器人包 - orlion - 博客园_files/logo.gif -------------------------------------------------------------------------------- /01.Golang网页笔记/Golang 微信机器人包 - orlion - 博客园_files/wechat.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Goular/GolangModule/6f5ea735e919e4d2521b85ebb470a012bc05baf3/01.Golang网页笔记/Golang 微信机器人包 - orlion - 博客园_files/wechat.png -------------------------------------------------------------------------------- /01.Golang网页笔记/Golang 微信机器人包 - orlion - 博客园_files/xml.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Goular/GolangModule/6f5ea735e919e4d2521b85ebb470a012bc05baf3/01.Golang网页笔记/Golang 微信机器人包 - orlion - 博客园_files/xml.gif -------------------------------------------------------------------------------- /01.Golang网页笔记/Golang 笔记 1 基础、基本数据类型 - orlion - 博客园_files/20160331143213.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Goular/GolangModule/6f5ea735e919e4d2521b85ebb470a012bc05baf3/01.Golang网页笔记/Golang 笔记 1 基础、基本数据类型 - orlion - 博客园_files/20160331143213.png -------------------------------------------------------------------------------- /01.Golang网页笔记/Golang 笔记 1 基础、基本数据类型 - orlion - 博客园_files/24442-20171027070203758-1397753435.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Goular/GolangModule/6f5ea735e919e4d2521b85ebb470a012bc05baf3/01.Golang网页笔记/Golang 笔记 1 基础、基本数据类型 - orlion - 博客园_files/24442-20171027070203758-1397753435.jpg -------------------------------------------------------------------------------- /01.Golang网页笔记/Golang 笔记 1 基础、基本数据类型 - orlion - 博客园_files/24442-20171029145139367-1787068412.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Goular/GolangModule/6f5ea735e919e4d2521b85ebb470a012bc05baf3/01.Golang网页笔记/Golang 笔记 1 基础、基本数据类型 - orlion - 博客园_files/24442-20171029145139367-1787068412.jpg -------------------------------------------------------------------------------- /01.Golang网页笔记/Golang 笔记 1 基础、基本数据类型 - orlion - 博客园_files/798267-20170312181714857-165152327.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Goular/GolangModule/6f5ea735e919e4d2521b85ebb470a012bc05baf3/01.Golang网页笔记/Golang 笔记 1 基础、基本数据类型 - orlion - 博客园_files/798267-20170312181714857-165152327.png -------------------------------------------------------------------------------- /01.Golang网页笔记/Golang 笔记 1 基础、基本数据类型 - orlion - 博客园_files/798267-20170312181736357-1843824288.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Goular/GolangModule/6f5ea735e919e4d2521b85ebb470a012bc05baf3/01.Golang网页笔记/Golang 笔记 1 基础、基本数据类型 - orlion - 博客园_files/798267-20170312181736357-1843824288.png -------------------------------------------------------------------------------- /01.Golang网页笔记/Golang 笔记 1 基础、基本数据类型 - orlion - 博客园_files/798267-20170312181809686-170726689.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Goular/GolangModule/6f5ea735e919e4d2521b85ebb470a012bc05baf3/01.Golang网页笔记/Golang 笔记 1 基础、基本数据类型 - orlion - 博客园_files/798267-20170312181809686-170726689.png -------------------------------------------------------------------------------- /01.Golang网页笔记/Golang 笔记 1 基础、基本数据类型 - orlion - 博客园_files/798267-20170319181258807-380888326.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Goular/GolangModule/6f5ea735e919e4d2521b85ebb470a012bc05baf3/01.Golang网页笔记/Golang 笔记 1 基础、基本数据类型 - orlion - 博客园_files/798267-20170319181258807-380888326.png -------------------------------------------------------------------------------- /01.Golang网页笔记/Golang 笔记 1 基础、基本数据类型 - orlion - 博客园_files/798267-20170319181326729-1059684011.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Goular/GolangModule/6f5ea735e919e4d2521b85ebb470a012bc05baf3/01.Golang网页笔记/Golang 笔记 1 基础、基本数据类型 - orlion - 博客园_files/798267-20170319181326729-1059684011.png -------------------------------------------------------------------------------- /01.Golang网页笔记/Golang 笔记 1 基础、基本数据类型 - orlion - 博客园_files/798267-20170319181416995-1480939339.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Goular/GolangModule/6f5ea735e919e4d2521b85ebb470a012bc05baf3/01.Golang网页笔记/Golang 笔记 1 基础、基本数据类型 - orlion - 博客园_files/798267-20170319181416995-1480939339.png -------------------------------------------------------------------------------- /01.Golang网页笔记/Golang 笔记 1 基础、基本数据类型 - orlion - 博客园_files/icon_weibo_24.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Goular/GolangModule/6f5ea735e919e4d2521b85ebb470a012bc05baf3/01.Golang网页笔记/Golang 笔记 1 基础、基本数据类型 - orlion - 博客园_files/icon_weibo_24.png -------------------------------------------------------------------------------- /01.Golang网页笔记/Golang 笔记 1 基础、基本数据类型 - orlion - 博客园_files/logo.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Goular/GolangModule/6f5ea735e919e4d2521b85ebb470a012bc05baf3/01.Golang网页笔记/Golang 笔记 1 基础、基本数据类型 - orlion - 博客园_files/logo.gif -------------------------------------------------------------------------------- /01.Golang网页笔记/Golang 笔记 1 基础、基本数据类型 - orlion - 博客园_files/wechat.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Goular/GolangModule/6f5ea735e919e4d2521b85ebb470a012bc05baf3/01.Golang网页笔记/Golang 笔记 1 基础、基本数据类型 - orlion - 博客园_files/wechat.png -------------------------------------------------------------------------------- /01.Golang网页笔记/Golang 笔记 1 基础、基本数据类型 - orlion - 博客园_files/xml.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Goular/GolangModule/6f5ea735e919e4d2521b85ebb470a012bc05baf3/01.Golang网页笔记/Golang 笔记 1 基础、基本数据类型 - orlion - 博客园_files/xml.gif -------------------------------------------------------------------------------- /01.Golang网页笔记/Golang 笔记 2 函数、结构体、接口、指针 - orlion - 博客园_files/20160331143213.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Goular/GolangModule/6f5ea735e919e4d2521b85ebb470a012bc05baf3/01.Golang网页笔记/Golang 笔记 2 函数、结构体、接口、指针 - orlion - 博客园_files/20160331143213.png -------------------------------------------------------------------------------- /01.Golang网页笔记/Golang 笔记 2 函数、结构体、接口、指针 - orlion - 博客园_files/24442-20171027070203758-1397753435.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Goular/GolangModule/6f5ea735e919e4d2521b85ebb470a012bc05baf3/01.Golang网页笔记/Golang 笔记 2 函数、结构体、接口、指针 - orlion - 博客园_files/24442-20171027070203758-1397753435.jpg -------------------------------------------------------------------------------- /01.Golang网页笔记/Golang 笔记 2 函数、结构体、接口、指针 - orlion - 博客园_files/24442-20171029145139367-1787068412.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Goular/GolangModule/6f5ea735e919e4d2521b85ebb470a012bc05baf3/01.Golang网页笔记/Golang 笔记 2 函数、结构体、接口、指针 - orlion - 博客园_files/24442-20171029145139367-1787068412.jpg -------------------------------------------------------------------------------- /01.Golang网页笔记/Golang 笔记 2 函数、结构体、接口、指针 - orlion - 博客园_files/icon_weibo_24.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Goular/GolangModule/6f5ea735e919e4d2521b85ebb470a012bc05baf3/01.Golang网页笔记/Golang 笔记 2 函数、结构体、接口、指针 - orlion - 博客园_files/icon_weibo_24.png -------------------------------------------------------------------------------- /01.Golang网页笔记/Golang 笔记 2 函数、结构体、接口、指针 - orlion - 博客园_files/logo.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Goular/GolangModule/6f5ea735e919e4d2521b85ebb470a012bc05baf3/01.Golang网页笔记/Golang 笔记 2 函数、结构体、接口、指针 - orlion - 博客园_files/logo.gif -------------------------------------------------------------------------------- /01.Golang网页笔记/Golang 笔记 2 函数、结构体、接口、指针 - orlion - 博客园_files/wechat.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Goular/GolangModule/6f5ea735e919e4d2521b85ebb470a012bc05baf3/01.Golang网页笔记/Golang 笔记 2 函数、结构体、接口、指针 - orlion - 博客园_files/wechat.png -------------------------------------------------------------------------------- /01.Golang网页笔记/Golang 笔记 2 函数、结构体、接口、指针 - orlion - 博客园_files/xml.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Goular/GolangModule/6f5ea735e919e4d2521b85ebb470a012bc05baf3/01.Golang网页笔记/Golang 笔记 2 函数、结构体、接口、指针 - orlion - 博客园_files/xml.gif -------------------------------------------------------------------------------- /01.Golang网页笔记/Golang 笔记 3 if、switch、for、select语句 - orlion - 博客园_files/20160331143213.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Goular/GolangModule/6f5ea735e919e4d2521b85ebb470a012bc05baf3/01.Golang网页笔记/Golang 笔记 3 if、switch、for、select语句 - orlion - 博客园_files/20160331143213.png -------------------------------------------------------------------------------- /01.Golang网页笔记/Golang 笔记 3 if、switch、for、select语句 - orlion - 博客园_files/24442-20171027070203758-1397753435.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Goular/GolangModule/6f5ea735e919e4d2521b85ebb470a012bc05baf3/01.Golang网页笔记/Golang 笔记 3 if、switch、for、select语句 - orlion - 博客园_files/24442-20171027070203758-1397753435.jpg -------------------------------------------------------------------------------- /01.Golang网页笔记/Golang 笔记 3 if、switch、for、select语句 - orlion - 博客园_files/24442-20171029145139367-1787068412.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Goular/GolangModule/6f5ea735e919e4d2521b85ebb470a012bc05baf3/01.Golang网页笔记/Golang 笔记 3 if、switch、for、select语句 - orlion - 博客园_files/24442-20171029145139367-1787068412.jpg -------------------------------------------------------------------------------- /01.Golang网页笔记/Golang 笔记 3 if、switch、for、select语句 - orlion - 博客园_files/798267-20170319181108088-1859798310.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Goular/GolangModule/6f5ea735e919e4d2521b85ebb470a012bc05baf3/01.Golang网页笔记/Golang 笔记 3 if、switch、for、select语句 - orlion - 博客园_files/798267-20170319181108088-1859798310.png -------------------------------------------------------------------------------- /01.Golang网页笔记/Golang 笔记 3 if、switch、for、select语句 - orlion - 博客园_files/icon_weibo_24.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Goular/GolangModule/6f5ea735e919e4d2521b85ebb470a012bc05baf3/01.Golang网页笔记/Golang 笔记 3 if、switch、for、select语句 - orlion - 博客园_files/icon_weibo_24.png -------------------------------------------------------------------------------- /01.Golang网页笔记/Golang 笔记 3 if、switch、for、select语句 - orlion - 博客园_files/logo.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Goular/GolangModule/6f5ea735e919e4d2521b85ebb470a012bc05baf3/01.Golang网页笔记/Golang 笔记 3 if、switch、for、select语句 - orlion - 博客园_files/logo.gif -------------------------------------------------------------------------------- /01.Golang网页笔记/Golang 笔记 3 if、switch、for、select语句 - orlion - 博客园_files/wechat.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Goular/GolangModule/6f5ea735e919e4d2521b85ebb470a012bc05baf3/01.Golang网页笔记/Golang 笔记 3 if、switch、for、select语句 - orlion - 博客园_files/wechat.png -------------------------------------------------------------------------------- /01.Golang网页笔记/Golang 笔记 3 if、switch、for、select语句 - orlion - 博客园_files/xml.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Goular/GolangModule/6f5ea735e919e4d2521b85ebb470a012bc05baf3/01.Golang网页笔记/Golang 笔记 3 if、switch、for、select语句 - orlion - 博客园_files/xml.gif -------------------------------------------------------------------------------- /01.Golang网页笔记/Golang 笔记 4 defer、error、panic - orlion - 博客园_files/20160331143213.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Goular/GolangModule/6f5ea735e919e4d2521b85ebb470a012bc05baf3/01.Golang网页笔记/Golang 笔记 4 defer、error、panic - orlion - 博客园_files/20160331143213.png -------------------------------------------------------------------------------- /01.Golang网页笔记/Golang 笔记 4 defer、error、panic - orlion - 博客园_files/24442-20171027070203758-1397753435.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Goular/GolangModule/6f5ea735e919e4d2521b85ebb470a012bc05baf3/01.Golang网页笔记/Golang 笔记 4 defer、error、panic - orlion - 博客园_files/24442-20171027070203758-1397753435.jpg -------------------------------------------------------------------------------- /01.Golang网页笔记/Golang 笔记 4 defer、error、panic - orlion - 博客园_files/24442-20171029145139367-1787068412.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Goular/GolangModule/6f5ea735e919e4d2521b85ebb470a012bc05baf3/01.Golang网页笔记/Golang 笔记 4 defer、error、panic - orlion - 博客园_files/24442-20171029145139367-1787068412.jpg -------------------------------------------------------------------------------- /01.Golang网页笔记/Golang 笔记 4 defer、error、panic - orlion - 博客园_files/icon_weibo_24.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Goular/GolangModule/6f5ea735e919e4d2521b85ebb470a012bc05baf3/01.Golang网页笔记/Golang 笔记 4 defer、error、panic - orlion - 博客园_files/icon_weibo_24.png -------------------------------------------------------------------------------- /01.Golang网页笔记/Golang 笔记 4 defer、error、panic - orlion - 博客园_files/logo.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Goular/GolangModule/6f5ea735e919e4d2521b85ebb470a012bc05baf3/01.Golang网页笔记/Golang 笔记 4 defer、error、panic - orlion - 博客园_files/logo.gif -------------------------------------------------------------------------------- /01.Golang网页笔记/Golang 笔记 4 defer、error、panic - orlion - 博客园_files/wechat.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Goular/GolangModule/6f5ea735e919e4d2521b85ebb470a012bc05baf3/01.Golang网页笔记/Golang 笔记 4 defer、error、panic - orlion - 博客园_files/wechat.png -------------------------------------------------------------------------------- /01.Golang网页笔记/Golang 笔记 4 defer、error、panic - orlion - 博客园_files/xml.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Goular/GolangModule/6f5ea735e919e4d2521b85ebb470a012bc05baf3/01.Golang网页笔记/Golang 笔记 4 defer、error、panic - orlion - 博客园_files/xml.gif -------------------------------------------------------------------------------- /01.Golang网页笔记/Golang 笔记 5 go语句 - orlion - 博客园_files/20160331143213.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Goular/GolangModule/6f5ea735e919e4d2521b85ebb470a012bc05baf3/01.Golang网页笔记/Golang 笔记 5 go语句 - orlion - 博客园_files/20160331143213.png -------------------------------------------------------------------------------- /01.Golang网页笔记/Golang 笔记 5 go语句 - orlion - 博客园_files/24442-20171027070203758-1397753435.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Goular/GolangModule/6f5ea735e919e4d2521b85ebb470a012bc05baf3/01.Golang网页笔记/Golang 笔记 5 go语句 - orlion - 博客园_files/24442-20171027070203758-1397753435.jpg -------------------------------------------------------------------------------- /01.Golang网页笔记/Golang 笔记 5 go语句 - orlion - 博客园_files/24442-20171029145139367-1787068412.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Goular/GolangModule/6f5ea735e919e4d2521b85ebb470a012bc05baf3/01.Golang网页笔记/Golang 笔记 5 go语句 - orlion - 博客园_files/24442-20171029145139367-1787068412.jpg -------------------------------------------------------------------------------- /01.Golang网页笔记/Golang 笔记 5 go语句 - orlion - 博客园_files/icon_weibo_24.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Goular/GolangModule/6f5ea735e919e4d2521b85ebb470a012bc05baf3/01.Golang网页笔记/Golang 笔记 5 go语句 - orlion - 博客园_files/icon_weibo_24.png -------------------------------------------------------------------------------- /01.Golang网页笔记/Golang 笔记 5 go语句 - orlion - 博客园_files/logo.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Goular/GolangModule/6f5ea735e919e4d2521b85ebb470a012bc05baf3/01.Golang网页笔记/Golang 笔记 5 go语句 - orlion - 博客园_files/logo.gif -------------------------------------------------------------------------------- /01.Golang网页笔记/Golang 笔记 5 go语句 - orlion - 博客园_files/wechat.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Goular/GolangModule/6f5ea735e919e4d2521b85ebb470a012bc05baf3/01.Golang网页笔记/Golang 笔记 5 go语句 - orlion - 博客园_files/wechat.png -------------------------------------------------------------------------------- /01.Golang网页笔记/Golang 笔记 5 go语句 - orlion - 博客园_files/xml.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Goular/GolangModule/6f5ea735e919e4d2521b85ebb470a012bc05baf3/01.Golang网页笔记/Golang 笔记 5 go语句 - orlion - 博客园_files/xml.gif -------------------------------------------------------------------------------- /02.RUNOOB例子代码/01HelloWrrld/Demo01-HelloWorld.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func main(){ 6 | fmt.Println("Hello Goular,Hello World!"); 7 | } 8 | -------------------------------------------------------------------------------- /02.RUNOOB例子代码/02变量声明/变量声明.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func main() { 6 | //第一种 7 | var a int 8 | a = 11 9 | fmt.Println("a:", a); 10 | //第二种 11 | var b = 22 12 | fmt.Println("b:", b); 13 | //第三种(不能用在全局变量定义中) 14 | c := 33; 15 | fmt.Println("c:", c); 16 | } 17 | -------------------------------------------------------------------------------- /02.RUNOOB例子代码/02变量声明/多变量声明.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | ) 6 | 7 | //第一种 8 | var a1,a2 int 9 | //外部只能进行声明,赋值的话会报错 10 | //a1 = 11 11 | //a2 = 12 12 | 13 | //第二种 14 | var b1,b2 = 21,22 15 | 16 | //第四种 17 | var( 18 | d1 int 19 | d2 bool = true 20 | ) 21 | 22 | func main() { 23 | a1 = 11 24 | a2 = 12 25 | 26 | d1 = 41 27 | 28 | //第三种 29 | c1,c2 := 31,32 30 | 31 | fmt.Println(a1,a2) 32 | fmt.Println(b1,b2) 33 | fmt.Println(c1,c2) 34 | fmt.Println(d1,d2) 35 | } 36 | 37 | -------------------------------------------------------------------------------- /02.RUNOOB例子代码/03常量声明/1普通常量的定义.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | const ( 6 | a1 = true 7 | b1 = "天鹅湖" 8 | c1 = 8.28 9 | ) 10 | 11 | func main() { 12 | const LENGTH int = 100 13 | const WIDTH int = 200 14 | var area int 15 | const a, b, c = 1, false, "加油" 16 | 17 | area = LENGTH * WIDTH; 18 | fmt.Printf("面积为:%d\n", area) 19 | 20 | println() 21 | println(a, b, c) 22 | println(a1, b1, c1) 23 | } 24 | -------------------------------------------------------------------------------- /02.RUNOOB例子代码/03常量声明/2使用函数返回值作为常量赋值.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "unsafe" 6 | ) 7 | 8 | const ( 9 | a = "abc" 10 | b = len(a) 11 | c = unsafe.Sizeof(a) 12 | ) 13 | 14 | func main() { 15 | fmt.Println(a, b, c) 16 | } 17 | -------------------------------------------------------------------------------- /02.RUNOOB例子代码/03常量声明/3iota.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | 6 | func main() { 7 | const ( 8 | a1 = iota 9 | b1 = iota 10 | c1 = iota 11 | ) 12 | //会自动添加并赋值给下面的b2,c2 13 | const ( 14 | a2 = iota 15 | b2 16 | c2 17 | ) 18 | 19 | const ( 20 | a = iota 21 | b 22 | c 23 | d = "ha" 24 | e 25 | f = 100 26 | g 27 | h = iota 28 | i 29 | ) 30 | 31 | fmt.Println(a1, b1, c1) 32 | fmt.Println(a2, b2, c2) 33 | fmt.Println(a,b,c,d,e,f,g,h,i) 34 | } 35 | -------------------------------------------------------------------------------- /02.RUNOOB例子代码/03常量声明/4iota-位运算.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | const ( 6 | i = 1<>iota 14 | j2 15 | k2 16 | l2 17 | ) 18 | 19 | func main() { 20 | //每次定义的往左移动一位,iota在每次定义的时候都增加1 21 | fmt.Println("i=",i) //1 -- 1>>1 22 | fmt.Println("j=",j) //2 -- 1>>2 23 | fmt.Println("k=",k) //4 -- 1>>3 24 | fmt.Println("l=",l) //8 -- 1>>4 25 | 26 | fmt.Println("i2=",i2) //1 27 | fmt.Println("j2=",j2) //2 28 | fmt.Println("k2=",k2) //4 29 | fmt.Println("l2=",l2) //8 30 | } 31 | -------------------------------------------------------------------------------- /02.RUNOOB例子代码/04语言运算符/01算术运算符.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func main() { 6 | var a int = 21 7 | var b int = 10 8 | var c int 9 | 10 | c = a + b 11 | fmt.Printf("第一行 - c 的值为 %d\n", c ) 12 | c = a - b 13 | fmt.Printf("第二行 - c 的值为 %d\n", c ) 14 | c = a * b 15 | fmt.Printf("第三行 - c 的值为 %d\n", c ) 16 | c = a / b 17 | fmt.Printf("第四行 - c 的值为 %d\n", c ) 18 | c = a % b 19 | fmt.Printf("第五行 - c 的值为 %d\n", c ) 20 | a++ 21 | fmt.Printf("第六行 - c 的值为 %d\n", a ) 22 | a-- 23 | fmt.Printf("第七行 - c 的值为 %d\n", a ) 24 | 25 | } 26 | -------------------------------------------------------------------------------- /02.RUNOOB例子代码/04语言运算符/02关系运算符.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func main() { 6 | var a int = 21 7 | var b int = 10 8 | 9 | if( a == b ) { 10 | fmt.Printf("第一行 - a 等于 b\n" ) 11 | } else { 12 | fmt.Printf("第一行 - a 不等于 b\n" ) 13 | } 14 | if ( a < b ) { 15 | fmt.Printf("第二行 - a 小于 b\n" ) 16 | } else { 17 | fmt.Printf("第二行 - a 不小于 b\n" ) 18 | } 19 | 20 | if ( a > b ) { 21 | fmt.Printf("第三行 - a 大于 b\n" ) 22 | } else { 23 | fmt.Printf("第三行 - a 不大于 b\n" ) 24 | } 25 | /* Lets change value of a and b */ 26 | a = 5 27 | b = 20 28 | if ( a <= b ) { 29 | fmt.Printf("第四行 - a 小于等于 b\n" ) 30 | } 31 | if ( b >= a ) { 32 | fmt.Printf("第五行 - b 大于等于 a\n" ) 33 | } 34 | } -------------------------------------------------------------------------------- /02.RUNOOB例子代码/04语言运算符/03逻辑运算符.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func main() { 6 | var a bool = true 7 | var b bool = false 8 | if ( a && b ) { 9 | fmt.Printf("第一行 - 条件为 true\n" ) 10 | } 11 | if ( a || b ) { 12 | fmt.Printf("第二行 - 条件为 true\n" ) 13 | } 14 | /* 修改 a 和 b 的值 */ 15 | a = false 16 | b = true 17 | if ( a && b ) { 18 | fmt.Printf("第三行 - 条件为 true\n" ) 19 | } else { 20 | fmt.Printf("第三行 - 条件为 false\n" ) 21 | } 22 | if ( !(a && b) ) { 23 | fmt.Printf("第四行 - 条件为 true\n" ) 24 | } 25 | } -------------------------------------------------------------------------------- /02.RUNOOB例子代码/04语言运算符/04位运算符.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func main() { 6 | //a, b := 1, 0 7 | //c, d := true, false 8 | //fmt.Printf("%d,%d\n", a, b) 9 | //fmt.Println(a & b); 10 | //fmt.Println(a | b); 11 | //fmt.Println(a ^ b); 12 | //fmt.Println(!(c && d)); 13 | 14 | var a uint = 60 /* 60 = 0011 1100 */ 15 | var b uint = 13 /* 13 = 0000 1101 */ 16 | var c uint = 0 17 | 18 | c = a & b /* 12 = 0000 1100 */ 19 | fmt.Printf("第一行 - c 的值为 %d\n", c ) 20 | 21 | c = a | b /* 61 = 0011 1101 */ 22 | fmt.Printf("第二行 - c 的值为 %d\n", c ) 23 | 24 | c = a ^ b /* 49 = 0011 0001 */ 25 | fmt.Printf("第三行 - c 的值为 %d\n", c ) 26 | 27 | c = a << 2 /* 240 = 1111 0000 */ 28 | fmt.Printf("第四行 - c 的值为 %d\n", c ) 29 | 30 | c = a >> 2 /* 15 = 0000 1111 */ 31 | fmt.Printf("第五行 - c 的值为 %d\n", c ) 32 | } 33 | -------------------------------------------------------------------------------- /02.RUNOOB例子代码/04语言运算符/05赋值运算符.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func main() { 6 | var a int = 21 7 | var c int 8 | 9 | c = a 10 | fmt.Printf("第 1 行 - = 运算符实例,c 值为 = %d\n", c ) 11 | 12 | c += a 13 | fmt.Printf("第 2 行 - += 运算符实例,c 值为 = %d\n", c ) 14 | 15 | c -= a 16 | fmt.Printf("第 3 行 - -= 运算符实例,c 值为 = %d\n", c ) 17 | 18 | c *= a 19 | fmt.Printf("第 4 行 - *= 运算符实例,c 值为 = %d\n", c ) 20 | 21 | c /= a 22 | fmt.Printf("第 5 行 - /= 运算符实例,c 值为 = %d\n", c ) 23 | 24 | c = 200; 25 | 26 | c <<= 2 27 | fmt.Printf("第 6行 - <<= 运算符实例,c 值为 = %d\n", c ) 28 | 29 | c >>= 2 30 | fmt.Printf("第 7 行 - >>= 运算符实例,c 值为 = %d\n", c ) 31 | 32 | c &= 2 33 | fmt.Printf("第 8 行 - &= 运算符实例,c 值为 = %d\n", c ) 34 | 35 | c ^= 2 36 | fmt.Printf("第 9 行 - ^= 运算符实例,c 值为 = %d\n", c ) 37 | 38 | c |= 2 39 | fmt.Printf("第 10 行 - |= 运算符实例,c 值为 = %d\n", c ) 40 | } -------------------------------------------------------------------------------- /02.RUNOOB例子代码/04语言运算符/06指针运算符.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func main() { 6 | var a int = 11 7 | var b int32 = 12333 8 | var c float32 =8.5624 9 | var ptr *int 10 | var ptr2 *int32 11 | var ptr3 *float32 12 | 13 | 14 | /** 15 | * 运算符实例 16 | */ 17 | fmt.Println("第1行 - a 变量类型为 = %T\n",a) 18 | fmt.Println("第2行 - a 变量类型为 = %T\n",b) 19 | fmt.Println("第3行 - a 变量类型为 = %T\n",c) 20 | 21 | /* 22 | * & 和 * 运算符实例 23 | */ 24 | ptr = &a 25 | ptr2 = &b 26 | ptr3 = &c 27 | fmt.Println("a的值为 %d\n",a) 28 | 29 | fmt.Println("*ptr的内存值为 %d\n",ptr) 30 | fmt.Println("ptr的值为 %d\n",*ptr) 31 | 32 | fmt.Println("*ptr2的内存值为 %d\n",ptr2) 33 | fmt.Println("ptr2的值为 %d\n",*ptr2) 34 | 35 | fmt.Println("*ptr3的内存值为 %d\n",ptr3) 36 | fmt.Println("ptr3的值为 %d\n",*ptr3) 37 | } -------------------------------------------------------------------------------- /02.RUNOOB例子代码/04语言运算符/07运算符优先级.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func main() { 6 | var a int = 20 7 | var b int = 10 8 | var c int = 15 9 | var d int = 5 10 | var e int; 11 | 12 | e = (a + b) * c / d; // ( 30 * 15 ) / 5 13 | fmt.Printf("(a + b) * c / d 的值为 : %d\n", e ); 14 | 15 | e = ((a + b) * c) / d; // (30 * 15 ) / 5 16 | fmt.Printf("((a + b) * c) / d 的值为 : %d\n" , e ); 17 | 18 | e = (a + b) * (c / d); // (30) * (15/5) 19 | fmt.Printf("(a + b) * (c / d) 的值为 : %d\n", e ); 20 | 21 | e = a + (b * c) / d; // 20 + (150/5) 22 | fmt.Printf("a + (b * c) / d 的值为 : %d\n" , e ); 23 | } -------------------------------------------------------------------------------- /02.RUNOOB例子代码/05条件语句/01ifelse.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func main() { 6 | //a := 10 7 | //if a<20 { 8 | // fmt.Printf("a 小于 20 \n") 9 | //}else{ 10 | // fmt.Printf("a 大于 20 \n") 11 | //} 12 | //fmt.Printf("a 的值是 %d \n",a) 13 | 14 | /* 定义局部变量 */ 15 | var a int = 100 16 | var b int = 200 17 | 18 | /* 判断条件 */ 19 | if a == 100 { 20 | /* if 条件语句为 true 执行 */ 21 | if b == 200 { 22 | /* if 条件语句为 true 执行 */ 23 | fmt.Printf("a 的值为 100 , b 的值为 200\n" ); 24 | } 25 | } 26 | fmt.Printf("a 值为 : %d\n", a ); 27 | fmt.Printf("b 值为 : %d\n", b ); 28 | } 29 | -------------------------------------------------------------------------------- /02.RUNOOB例子代码/05条件语句/02switch.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func main() { 6 | var grade string = "B" 7 | var marks int = 90 8 | 9 | switch marks { 10 | case 90: 11 | grade = "A" 12 | case 80: 13 | grade = "B" 14 | case 50, 60, 70: 15 | grade = "C" 16 | default: 17 | grade = "D" 18 | } 19 | 20 | switch { 21 | case grade == "A" : 22 | fmt.Printf("优秀!\n" ) 23 | case grade == "B", grade == "C" : 24 | fmt.Printf("良好\n" ) 25 | case grade == "D" : 26 | fmt.Printf("及格\n" ) 27 | case grade == "F": 28 | fmt.Printf("不及格\n" ) 29 | default: 30 | fmt.Printf("差\n" ); 31 | } 32 | 33 | fmt.Printf("你的等级是 %s\n", grade ); 34 | } 35 | -------------------------------------------------------------------------------- /02.RUNOOB例子代码/05条件语句/03TypeSwitch.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | var x interface { 6 | } 7 | 8 | func main() { 9 | switch i := x.(type) { 10 | case nil: 11 | fmt.Printf(" x 的类型 :%T", i) 12 | case int: 13 | fmt.Printf("x 是 int 型") 14 | case float64: 15 | fmt.Printf("x 是 float64 型") 16 | case func(int) float64: 17 | fmt.Printf("x 是 func(int) 型") 18 | case bool, string: 19 | fmt.Printf("x 是 bool 或 string 型") 20 | default: 21 | fmt.Printf("未知型") 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /02.RUNOOB例子代码/05条件语句/04select.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | /** 6 | * select用于通讯的switch使用,有阻塞的特性 7 | */ 8 | func main() { 9 | var c1, c2, c3 chan int 10 | var i1, i2 int 11 | select { 12 | case i1 = <-c1: 13 | fmt.Printf("received ", i1, " from c1\n") 14 | case c2 <- i2: 15 | fmt.Printf("sent ", i2, " to c2\n") 16 | case i3, ok := (<-c3): // same as: i3, ok := <-c3 17 | if ok { 18 | fmt.Printf("received ", i3, " from c3\n") 19 | } else { 20 | fmt.Printf("c3 is closed\n") 21 | } 22 | default: 23 | fmt.Printf("no communication\n") 24 | 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /02.RUNOOB例子代码/06循环语句/01For.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func main() { 6 | var b int = 15 7 | var a int 8 | 9 | numbers := [6]int{1, 2, 4, 5} 10 | 11 | //for 循环 12 | for a := 0; a < 10; a++ { 13 | fmt.Printf("a的值为:%d\n", a) 14 | } 15 | 16 | fmt.Println("********") 17 | 18 | for a < b { 19 | a++ 20 | fmt.Printf("a的值为:%d\n", a) 21 | } 22 | 23 | fmt.Println("********") 24 | 25 | for key, value := range numbers { 26 | fmt.Printf("第 %d 位 x 的值 = %d\n", key, value) 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /02.RUNOOB例子代码/06循环语句/02循环嵌套.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func main() { 6 | /* 定义局部变量 */ 7 | var i, j int 8 | 9 | for i = 2; i < 100; i++ { 10 | for j = 2; j <= (i / j); j++ { 11 | if (i%j == 0) { 12 | break; // 如果发现因子,则不是素数 13 | } 14 | } 15 | if (j > (i / j)) { 16 | fmt.Printf("%d 是素数\n", i); 17 | } 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /02.RUNOOB例子代码/06循环语句/03break语句.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | ) 6 | 7 | func main() { 8 | //Switch不使用break,现在使用break只有for了 9 | var a int = 10 10 | //for循环 11 | for a < 20 { 12 | fmt.Printf("a 的值为 : %d\n", a) 13 | a++ 14 | if a > 15 { 15 | //使用break语句跳出循环 16 | break 17 | } 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /02.RUNOOB例子代码/06循环语句/04continue语句.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func main() { 6 | var a int = 10 7 | for a < 20 { 8 | if a == 15 { 9 | //跳过此次循环 10 | a += 1 11 | continue 12 | } 13 | fmt.Printf("a的值为:%d\n", a); 14 | a++ 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /02.RUNOOB例子代码/06循环语句/05goto语句.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func main() { 6 | /* 定义局部变量 */ 7 | var a int = 10 8 | 9 | /* 循环 */ 10 | LOOP: for a < 20 { 11 | if a == 15 { 12 | /* 跳过迭代 */ 13 | a = a + 1 14 | goto LOOP 15 | } 16 | fmt.Printf("a的值为 : %d\n", a) 17 | a++ 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /02.RUNOOB例子代码/06循环语句/06无限循环.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func main() { 6 | for true { 7 | fmt.Println("这个是无限循环.") 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /02.RUNOOB例子代码/07函数/01函数调用.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | //当创建函数时,你定义了函数需要做什么,通过调用改函数来执行指定任务。 6 | func main() { 7 | //定义局部数据 8 | a, b := 100, 200 9 | var ret int 10 | ret = max(a, b); 11 | fmt.Printf("最大值是 : %d\n", ret) 12 | } 13 | 14 | /* 函数返回两个数的最大值 */ 15 | func max(num1, num2 int) int { 16 | /* 定义局部变量 */ 17 | var result int 18 | 19 | if (num1 > num2) { 20 | result = num1 21 | } else { 22 | result = num2 23 | } 24 | return result 25 | } 26 | -------------------------------------------------------------------------------- /02.RUNOOB例子代码/07函数/02函数返回多个值.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | ) 6 | 7 | //参数返回并返回多参数 8 | func main() { 9 | a, b := swap("Mahesh", "Kumar") 10 | fmt.Println(a, b) 11 | } 12 | 13 | func swap(x, y string) (string, string) { 14 | return y, x 15 | } 16 | -------------------------------------------------------------------------------- /02.RUNOOB例子代码/07函数/03值传递.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func main() { 6 | /* 定义局部变量 */ 7 | var a int = 100 8 | var b int = 200 9 | 10 | fmt.Printf("交换前 a 的值为 : %d\n", a ) 11 | fmt.Printf("交换前 b 的值为 : %d\n", b ) 12 | 13 | /* 通过调用函数来交换值 */ 14 | swap(a, b) 15 | 16 | fmt.Printf("交换后 a 的值 : %d\n", a ) 17 | fmt.Printf("交换后 b 的值 : %d\n", b ) 18 | } 19 | 20 | /* 定义相互交换值的函数 */ 21 | func swap(x, y int) int { 22 | var temp int 23 | 24 | temp = x /* 保存 x 的值 */ 25 | x = y /* 将 y 值赋给 x */ 26 | y = temp /* 将 temp 值赋给 y*/ 27 | 28 | return temp; 29 | } -------------------------------------------------------------------------------- /02.RUNOOB例子代码/07函数/04引用传递.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | //使用指针进行交换数据的的引用传递例子 6 | func main() { 7 | /* 定义局部变量 */ 8 | var a int = 100 9 | var b int = 200 10 | 11 | fmt.Printf("交换前 a 的值为 : %d\n", a) 12 | fmt.Printf("交换前 b 的值为 : %d\n", b) 13 | 14 | /* 通过调用函数来交换值 */ 15 | swap(&a, &b) 16 | 17 | fmt.Printf("交换后 a 的值 : %d\n", a) 18 | fmt.Printf("交换后 b 的值 : %d\n", b) 19 | } 20 | 21 | /* 定义相互交换值的函数 */ 22 | func swap(a, b *int) { 23 | var temp int 24 | temp = *a /* 保存 x 的值 */ 25 | *a = *b /* 将 y 值赋给 x */ 26 | *b = temp /* 将 temp 值赋给 y*/ 27 | } 28 | -------------------------------------------------------------------------------- /02.RUNOOB例子代码/07函数/05函数作为值.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "math" 5 | "fmt" 6 | ) 7 | 8 | func main() { 9 | //声明函数变量 10 | getSquareRoot := func(x float64) float64 { 11 | return math.Sqrt(x) 12 | } 13 | //使用函数 14 | fmt.Println(getSquareRoot(9)) 15 | } 16 | -------------------------------------------------------------------------------- /02.RUNOOB例子代码/07函数/06闭包.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func getSequence() func() int { 6 | i:=0 7 | return func() int { 8 | i+=1 9 | return i 10 | } 11 | } 12 | 13 | func main(){ 14 | /* nextNumber 为一个函数,函数 i 为 0 */ 15 | nextNumber := getSequence() 16 | 17 | /* 调用 nextNumber 函数,i 变量自增 1 并返回 */ 18 | fmt.Println(nextNumber()) 19 | fmt.Println(nextNumber()) 20 | fmt.Println(nextNumber()) 21 | 22 | /* 创建新的函数 nextNumber1,并查看结果 */ 23 | nextNumber1 := getSequence() 24 | fmt.Println(nextNumber1()) 25 | fmt.Println(nextNumber1()) 26 | } -------------------------------------------------------------------------------- /02.RUNOOB例子代码/07函数/07方法.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | //定义函数 6 | type Circle struct { 7 | radius float64 8 | } 9 | 10 | func main() { 11 | var c1 Circle 12 | c1.radius = 10.00 13 | fmt.Println("Area of Circle(c1) =", c1.getArea()) 14 | } 15 | 16 | //该 method 属于 Circle 类型对象中的方法 17 | func (c Circle) getArea() float64 { 18 | //c.radius 即为 Circle 类型对象中的属性 19 | return 3.14 * c.radius * c.radius 20 | } 21 | -------------------------------------------------------------------------------- /02.RUNOOB例子代码/08变量作用域/01局部变量.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func main() { 6 | var a, b, c int 7 | a = 10 8 | b = 20 9 | c = a + b 10 | fmt.Printf ("结果: a = %d, b = %d and c = %d\n", a, b, c) 11 | } 12 | -------------------------------------------------------------------------------- /02.RUNOOB例子代码/08变量作用域/02全局变量.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | /* 声明全局变量 */ 6 | var g int 7 | 8 | func main() { 9 | /* 声明局部变量 */ 10 | var a, b int 11 | 12 | /* 初始化参数 */ 13 | a = 10 14 | b = 20 15 | g = a + b 16 | 17 | fmt.Printf("结果: a = %d, b = %d and g = %d\n", a, b, g) 18 | } 19 | -------------------------------------------------------------------------------- /02.RUNOOB例子代码/08变量作用域/03形式参数.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func main() { 6 | /* main 函数中声明局部变量 */ 7 | var a int = 10 8 | var b int = 20 9 | var c int = 0 10 | 11 | fmt.Printf("main()函数中 a = %d\n", a); 12 | c = sum( a, b); 13 | fmt.Printf("main()函数中 c = %d\n", c); 14 | } 15 | 16 | /* 函数定义-两数相加 */ 17 | func sum(a, b int) int { 18 | fmt.Printf("sum() 函数中 a = %d\n", a); 19 | fmt.Printf("sum() 函数中 b = %d\n", b); 20 | 21 | return a + b; 22 | } 23 | -------------------------------------------------------------------------------- /02.RUNOOB例子代码/09数组/01访问数组元素.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func main() { 6 | //定义一个长度为10的整型数组 7 | var n [10]int 8 | var i, j int 9 | 10 | //为数组n初始化元素 11 | for i = 0; i < 10; i++ { 12 | n[i] = i + 100 /* 设置元素为 i + 100 */ 13 | } 14 | //输出每个数组元素的值 15 | for j = 0; j < 10; j++ { 16 | fmt.Printf("Element[%d] = %d\n", j, n[j]) 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /02.RUNOOB例子代码/09数组/02多维数组.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func main() { 6 | //定义5*2的多维数组 7 | var a = [5][2]int{{0, 0}, {1, 2}, {2, 4}, {3, 6}, {4, 8}} 8 | var i, j int 9 | 10 | //输出数组元素 11 | for i = 0; i < 5; i++ { 12 | for j = 0; j < 2; j++ { 13 | fmt.Printf("a[%d][%d] = %d\n", i, j, a[i][j]) 14 | } 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /02.RUNOOB例子代码/09数组/03向函数传递数组.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | /*使用的形参并为设定数组大小。*/ 6 | func main() { 7 | //定义数组的长度 8 | var balance = []int{1000, 2, 3, 17, 50} 9 | var avg float32 10 | 11 | /* 数组作为参数传递给函数 */ 12 | avg = getAverage(balance, 5); 13 | /* 输出返回的平均值 */ 14 | fmt.Printf( "平均值为: %f ", avg ); 15 | } 16 | 17 | func getAverage(arr []int, size int) float32 { 18 | var i, sum int 19 | var avg float32 20 | 21 | for i = 0; i < size; i++ { 22 | sum += arr[i] 23 | } 24 | 25 | avg = float32(sum / size) 26 | 27 | return avg; 28 | } 29 | -------------------------------------------------------------------------------- /02.RUNOOB例子代码/10指针/01展示变量内存地址.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func main() { 6 | a := 120 7 | fmt.Printf("变量的内存地址是:%d",&a) 8 | } 9 | -------------------------------------------------------------------------------- /02.RUNOOB例子代码/10指针/02获取指针的值.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func main() { 6 | var a int = 20 7 | var ptr *int 8 | 9 | ptr = &a 10 | 11 | fmt.Printf("a 变量的地址是: %x\n", &a ) 12 | 13 | /* 指针变量的存储地址 */ 14 | fmt.Printf("ip 变量储存的指针地址: %x\n", ptr ) 15 | 16 | /* 使用指针访问值 */ 17 | fmt.Printf("*ip 变量的值: %d\n", *ptr ) 18 | } 19 | -------------------------------------------------------------------------------- /02.RUNOOB例子代码/10指针/03Go空指针.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func main() { 6 | var ptr *int 7 | 8 | fmt.Printf("ptr 的值为:%x\n",ptr) 9 | } 10 | -------------------------------------------------------------------------------- /02.RUNOOB例子代码/10指针/04数组指针.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | const MAX int = 3 6 | 7 | func main() { 8 | a := []int{10,100,200} 9 | var i int 10 | var ptr [MAX]*int 11 | 12 | for i = 0; i < MAX; i++ { 13 | ptr[i] = &a[i] /* 整数地址赋值给指针数组 */ 14 | } 15 | 16 | for i = 0; i < MAX; i++ { 17 | fmt.Printf("a[%d] = %d\n", i,*ptr[i] ) 18 | } 19 | } -------------------------------------------------------------------------------- /02.RUNOOB例子代码/10指针/05指向指针的指针.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func main() { 6 | var a int 7 | var ptr *int 8 | var pptr *int 9 | 10 | a = 3000 11 | 12 | ptr = &a 13 | pptr = &ptr 14 | 15 | /* 获取 pptr 的值 */ 16 | fmt.Printf("变量 a = %d\n", a ) 17 | fmt.Printf("指针变量 *ptr = %d\n", *ptr ) 18 | fmt.Printf("指向指针的指针变量 **pptr = %d\n", **pptr) 19 | } 20 | -------------------------------------------------------------------------------- /02.RUNOOB例子代码/10指针/06指针作为函数参数.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func main() { 6 | /* 定义局部变量 */ 7 | var a int = 100 8 | var b int = 200 9 | 10 | fmt.Printf("交换前 a 的值 : %d\n", a) 11 | fmt.Printf("交换前 b 的值 : %d\n", b) 12 | 13 | swap(&a, &b) 14 | 15 | fmt.Printf("交换后 a 的值 : %d\n", a ) 16 | fmt.Printf("交换后 b 的值 : %d\n", b ) 17 | } 18 | 19 | func swap(a, b *int) { 20 | var temp int 21 | temp = *a /* 保存 x 地址的值 */ 22 | *a = *b /* 将 y 赋值给 x */ 23 | *b = temp /* 将 temp 赋值给 y */ 24 | } 25 | -------------------------------------------------------------------------------- /02.RUNOOB例子代码/11结构体/01结构体定义.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | //显式定义结构体 6 | type Book struct { 7 | name string 8 | number int32 9 | } 10 | 11 | 12 | func main() { 13 | kitchen := Book{"诺曼底",1125} 14 | fmt.Println(kitchen.name) 15 | } 16 | -------------------------------------------------------------------------------- /02.RUNOOB例子代码/11结构体/03结构体作为函数参数.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | type Books struct { 6 | title string 7 | author string 8 | subject string 9 | book_id int 10 | } 11 | 12 | func main() { 13 | var Book1 Books 14 | var Book2 Books 15 | 16 | /* book 1 描述 */ 17 | Book1.title = "Go 语言" 18 | Book1.author = "www.runoob.com" 19 | Book1.subject = "Go 语言教程" 20 | Book1.book_id = 6495407 21 | 22 | /* book 2 描述 */ 23 | Book2.title = "Python 教程" 24 | Book2.author = "www.runoob.com" 25 | Book2.subject = "Python 语言教程" 26 | Book2.book_id = 6495700 27 | 28 | //打印Book1信息 29 | printBook(Book1) 30 | 31 | //打印Book2信息 32 | printBook(Book2) 33 | } 34 | 35 | func printBook(book Books) { 36 | fmt.Printf( "Book title : %s\n", book.title); 37 | fmt.Printf( "Book author : %s\n", book.author); 38 | fmt.Printf( "Book subject : %s\n", book.subject); 39 | fmt.Printf( "Book book_id : %d\n", book.book_id); 40 | } 41 | -------------------------------------------------------------------------------- /02.RUNOOB例子代码/12切片/01定义和初始化.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | var identifier []int 6 | 7 | func main() { 8 | var slice1 []int = make([]int,5) 9 | slice2 := make([]string,6) 10 | fmt.Println(slice1) 11 | fmt.Println(slice2) 12 | 13 | s2 := []int{2,5,8} 14 | //s := []int{1,2,3} 15 | s1 := s2 16 | s3 := s2[0:2] 17 | s4 := s2[2:] 18 | s5 := s2[:5] 19 | s6 := s2[1:2] 20 | s7 := make([]int,5,9) 21 | } 22 | -------------------------------------------------------------------------------- /02.RUNOOB例子代码/12切片/02len()和cap()函数.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func main() { 6 | var numbers = make([]int, 3, 5) 7 | printSlice(numbers) 8 | } 9 | 10 | func printSlice(x []int) { 11 | fmt.Printf("len:%d,cap=%d,slice=%v\n", len(x), cap(x), x) 12 | } 13 | -------------------------------------------------------------------------------- /02.RUNOOB例子代码/12切片/03空切片.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func main() { 6 | var numbers []int 7 | printSlice(numbers) 8 | if (numbers == nil) { 9 | fmt.Printf("切片是空的") 10 | } 11 | } 12 | 13 | func printSlice(x []int) { 14 | fmt.Printf("len=%d cap=%d slice=%v\n", len(x), cap(x), x) 15 | } 16 | -------------------------------------------------------------------------------- /02.RUNOOB例子代码/12切片/04切片截取.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func main() { 6 | numbers := []int{0, 1, 2, 3, 4, 5, 6, 7, 8} 7 | printSlice(numbers) 8 | 9 | //打印原始的切片 10 | fmt.Println("numbers ==", numbers) 11 | 12 | /* 打印子切片从索引1(包含) 到索引4(不包含)*/ 13 | fmt.Println("numbers ==", numbers[1:4]) 14 | 15 | //默认下限为 0 16 | fmt.Println("numbers ==", numbers[:4]) 17 | 18 | //默认上限为 len(s) 19 | fmt.Println("numbers[4:] ==", numbers[4:]) 20 | 21 | number1 := make([]int, 0, 5) 22 | printSlice(number1) 23 | 24 | //打印子切片从索引 0(包含) 到索引 2(不包含) 25 | number2 := numbers[:2] 26 | printSlice(number2) 27 | 28 | //打印子切片从索引 2(包含) 到索引 5(不包含) 29 | number3 := numbers[2:5] 30 | printSlice(number3) 31 | } 32 | 33 | func printSlice(x []int) { 34 | fmt.Printf("len=%d cap=%d slice=%v\n", len(x), cap(x), x) 35 | } 36 | -------------------------------------------------------------------------------- /02.RUNOOB例子代码/12切片/05append()和copy()函数.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func main() { 6 | 7 | var numbers []int 8 | printSlice(numbers) 9 | 10 | //允许追加空切片 11 | numbers = append(numbers, 0) 12 | printSlice(numbers) 13 | 14 | //向切片添加一个元素 15 | numbers = append(numbers, 11) 16 | printSlice(numbers) 17 | 18 | //同时添加多个元素 19 | numbers = append(numbers, 2, 3, 4) 20 | printSlice(numbers) 21 | 22 | //创建切片 numbers1 是之前切片的两倍容量 23 | numbers1 := make([]int, len(numbers), (cap(numbers))*2) 24 | 25 | /* 拷贝 numbers 的内容到 numbers1 */ 26 | copy(numbers1,numbers) 27 | printSlice(numbers1) 28 | 29 | //拷贝 numbers 的内容到 numbers1 30 | copy(numbers1,numbers) 31 | printSlice(numbers1) 32 | } 33 | 34 | func printSlice(x []int) { 35 | fmt.Printf("len=%d cap=%d slice=%v\n", len(x), cap(x), x) 36 | } 37 | -------------------------------------------------------------------------------- /02.RUNOOB例子代码/13范围Range/01实例.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func main() { 6 | nums := []int{2, 3, 4} 7 | sum := 0 8 | for _, num := range nums { 9 | sum += num 10 | } 11 | fmt.Printf("Sum:%d", sum) 12 | //Go 语言中 range 关键字用于for循环中迭代数组(array)、切片(slice)、通道(channel)或集合(map)的元素。在数组和切片中它返回元素的索引值,在集合中返回 key-value 对的 key 值。 13 | for i, num := range nums { 14 | if num == 3 { 15 | fmt.Println("Index:", i) 16 | } 17 | } 18 | //range也可以用在Map的键值对上 19 | kvs := map[string]string{"a": "apple", "b": "banana"} 20 | for k, v := range kvs { 21 | fmt.Printf("%s -> %s\n", k, v) 22 | } 23 | //range也可以用来枚举Unicode字符串。第一个参数是字符的索引,第二个是字符(Unicode的值)本身。 24 | for i, c := range "go" { 25 | fmt.Println(i, c) 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /02.RUNOOB例子代码/14Map集合/01定义Map.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func main() { 6 | var countryMap map[string]string 7 | //创建集合 8 | countryMap = make(map[string]string) 9 | //插入相关的key-value值 10 | countryMap["France"] = "Paris" 11 | countryMap["Italy"] = "Rome" 12 | countryMap["Japan"] = "Tokyo" 13 | countryMap["India"] = "New Delhi" 14 | 15 | //使用key 输出map的值 16 | for key, value := range countryMap { 17 | fmt.Println(key, value) 18 | } 19 | 20 | //查看元素在集合中是否存在 21 | key1,value1 := countryMap["USA"] 22 | if(value1){ 23 | fmt.Println("Capital of United States is", key1) 24 | }else{ 25 | fmt.Println("Capital of United States is not present") 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /02.RUNOOB例子代码/14Map集合/02delete函数.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func main() { 6 | /* 创建 map */ 7 | countryCapitalMap := map[string]string{"France": "Paris", "Italy": "Rome", "Japan": "Tokyo", "India": "New Delhi"} 8 | 9 | fmt.Println("原始 map") 10 | 11 | /* 打印 map */ 12 | for country := range countryCapitalMap { 13 | fmt.Println("Capital of", country, "is", countryCapitalMap[country]) 14 | } 15 | 16 | //删除元素 17 | delete(countryCapitalMap,"France") 18 | fmt.Println("Entry for France is deleted") 19 | fmt.Println("删除元素后 map") 20 | /* 打印 map */ 21 | for country := range countryCapitalMap { 22 | fmt.Println("Capital of",country,"is",countryCapitalMap[country]) 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /02.RUNOOB例子代码/15函数递归/01阶乘.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func Factorial(n uint64) (result uint64) { 6 | if n > 0 { 7 | result = n*Factorial(n-1) 8 | return result 9 | } 10 | return 1 11 | } 12 | 13 | func main() { 14 | i := 15 15 | fmt.Printf("%d 的阶乘是 %d\n",i,Factorial(uint64(i))) 16 | } 17 | -------------------------------------------------------------------------------- /02.RUNOOB例子代码/15函数递归/02斐波那契数列.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func fibonacci(n int) (result int) { 6 | if n < 2 { 7 | return n 8 | } 9 | return fibonacci(n-2) + fibonacci(n-1) 10 | } 11 | 12 | func main() { 13 | var i int 14 | for i = 0; i < 10; i++ { 15 | fmt.Printf("%d\t",fibonacci(i)) 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /02.RUNOOB例子代码/16类型转换/01整型转化为浮点型.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func main() { 6 | var sum int = 17 7 | var count int = 5 8 | var mean float32 9 | 10 | mean = float32(sum)/float32(count) 11 | fmt.Printf("mean的值为:%f\n",mean) 12 | } 13 | -------------------------------------------------------------------------------- /02.RUNOOB例子代码/17接口/01接口的使用.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | //接口是实现覆盖方法使用的 6 | 7 | //接口 8 | type Phone interface { 9 | call() 10 | } 11 | 12 | //结构体 13 | type NokiaPhone struct { 14 | } 15 | 16 | func (nokiaPhone NokiaPhone) call() { 17 | fmt.Println("I am Nokia, I can call you!") 18 | } 19 | 20 | type IPhone struct { 21 | 22 | } 23 | 24 | func (iPhone IPhone) call() { 25 | fmt.Println("I am iPhone, I can call you!") 26 | } 27 | 28 | 29 | func main() { 30 | var phone Phone; 31 | 32 | phone = new(NokiaPhone) 33 | phone.call() 34 | 35 | phone = new(IPhone) 36 | phone.call() 37 | } 38 | -------------------------------------------------------------------------------- /02.RUNOOB例子代码/18错误处理/01错误处理简单使用.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "errors" 5 | "fmt" 6 | ) 7 | 8 | type error interface { 9 | Error() string 10 | } 11 | 12 | func Sqrt(f float64) (float64, error) { 13 | if f < 0 { 14 | return 0, errors.New("math: square root of negative number") 15 | } else { 16 | return -1, nil 17 | } 18 | } 19 | 20 | func main() { 21 | _, err := Sqrt(-1) 22 | if (err != nil) { 23 | fmt.Println(err); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /02.RUNOOB例子代码/19并发/01简单使用.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "time" 5 | "fmt" 6 | ) 7 | 8 | func say(s string) { 9 | for i := 0; i < 5; i++ { 10 | time.Sleep(100 * time.Millisecond) 11 | fmt.Println(s) 12 | } 13 | } 14 | func main() { 15 | go say("World") 16 | say("Hello") 17 | } 18 | -------------------------------------------------------------------------------- /02.RUNOOB例子代码/19并发/02创建一个协程.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "time" 6 | ) 7 | 8 | func hello() { 9 | fmt.Println("欢迎来到Golang协程的世界") 10 | } 11 | 12 | //写法一 13 | //由于主协程直接执行下一条打印后没有代码执行,直接退出,所以子协程的返回输出因主协程的结束而结束,没有输出 14 | //func main() { 15 | // go hello() 16 | // fmt.Println("Main Function") 17 | //} 18 | 19 | //写法二 20 | //创建执行hello子协程后,休眠1s,然后继续执行主协程,这样子协程执行完返回的内容能够成功输出 21 | //注意:在主协程中使用 Sleep 函数等待其他协程结束的方法是不正规的 22 | func main() { 23 | go hello() 24 | time.Sleep(1 * time.Second) 25 | fmt.Println("Main Function") 26 | } 27 | -------------------------------------------------------------------------------- /02.RUNOOB例子代码/19并发/03开启多个协程.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "time" 5 | "fmt" 6 | ) 7 | 8 | func numbers() { 9 | for i := 1; i <= 5; i++ { 10 | time.Sleep(250 * time.Millisecond) 11 | fmt.Printf("%d ", i) 12 | } 13 | } 14 | 15 | func alphabets() { 16 | for i := 'a'; i <= 'e'; i++ { 17 | time.Sleep(400 * time.Millisecond) 18 | fmt.Printf("%c ", i) 19 | } 20 | } 21 | 22 | func main() { 23 | go numbers() 24 | go alphabets() 25 | time.Sleep(3000 * time.Millisecond) 26 | fmt.Println("main terminated") 27 | } 28 | -------------------------------------------------------------------------------- /02.RUNOOB例子代码/19并发/04信道创建.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | //创建信道 6 | func main() { 7 | var a chan int 8 | if a == nil { 9 | fmt.Println("Channel a is nil,going to define it") 10 | a = make(chan int) 11 | fmt.Printf("Type of a is %T", a) 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /02.RUNOOB例子代码/19并发/05信道简单使用.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func hello(done chan bool) { 6 | fmt.Println("Hello World goroutine") 7 | done<-true 8 | } 9 | 10 | func main() { 11 | done := make(chan bool) 12 | go hello(done) 13 | <-done 14 | fmt.Println("main function") 15 | } 16 | -------------------------------------------------------------------------------- /02.RUNOOB例子代码/19并发/06子协程传递字符串到主协程.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "bytes" 6 | "strconv" 7 | "time" 8 | ) 9 | 10 | func hello(xinDao chan string) { 11 | a := "I think I will use Golang In My Feture Project" 12 | //xinDao <- a 13 | 14 | for i := 0; i < 15; i++ { 15 | var buf bytes.Buffer 16 | buf.WriteString(a) 17 | buf.WriteString(strconv.Itoa(i)) 18 | xinDao <- buf.String() 19 | time.Sleep(1 * time.Second) 20 | } 21 | xinDao <- "stop" 22 | } 23 | 24 | func main() { 25 | fmt.Println("创建子协程") 26 | xinDao := make(chan string) 27 | go hello(xinDao) 28 | fmt.Println("等待子协程信息的接收") 29 | for true { 30 | b := <-xinDao 31 | if b != "stop" { 32 | fmt.Println(b) 33 | } else { 34 | break; 35 | } 36 | } 37 | fmt.Println("主协程结束") 38 | } 39 | -------------------------------------------------------------------------------- /02.RUNOOB例子代码/19并发/07平方和-立方和分别为子协程主协程求和.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func calcSquares(number int, squareop chan int) { 6 | sum := 0 7 | for number != 0 { 8 | digit := number % 10 9 | sum += digit * digit 10 | number /= 10 11 | } 12 | squareop <- sum 13 | } 14 | 15 | func calcCubes(number int, cubeop chan int) { 16 | sum := 0 17 | for number != 0 { 18 | digit := number % 10 19 | sum += digit * digit * digit 20 | number /= 10 21 | } 22 | cubeop <- sum 23 | } 24 | 25 | func main() { 26 | number := 589 27 | sqrch := make(chan int) 28 | cubech := make(chan int) 29 | go calcSquares(number, sqrch) 30 | go calcCubes(number, cubech) 31 | squares, cubes := <-sqrch, <-cubech 32 | fmt.Println("Final output", squares + cubes) 33 | } 34 | -------------------------------------------------------------------------------- /02.RUNOOB例子代码/19并发/08单向信道.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func sendData(sendch chan<- int) { 6 | sendch <- 10 7 | } 8 | 9 | func main() { 10 | sendch := make(chan<- int) 11 | go sendData(sendch) 12 | fmt.Println(<-sendch) 13 | } -------------------------------------------------------------------------------- /02.RUNOOB例子代码/19并发/09关闭信道.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | ) 6 | 7 | func producer(chnl chan int) { 8 | for i := 0; i < 10; i++ { 9 | chnl <- i 10 | } 11 | close(chnl) 12 | } 13 | func main() { 14 | ch := make(chan int) 15 | go producer(ch) 16 | for { 17 | v, ok := <-ch 18 | if ok == false { 19 | break 20 | } 21 | fmt.Println("Received ", v, ok) 22 | } 23 | } -------------------------------------------------------------------------------- /02.RUNOOB例子代码/19并发/10使用rangeFor遍历信道.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | ) 6 | 7 | /* 8 | for range 不断从信道 ch 中接收数据,直到该信道关闭。一旦 ch 关闭,循环自动退出。 9 | */ 10 | func producer(chnl chan int) { 11 | for i := 0; i < 10; i++ { 12 | chnl <- i 13 | } 14 | close(chnl) 15 | } 16 | func main() { 17 | ch := make(chan int) 18 | go producer(ch) 19 | for v := range ch { 20 | fmt.Println("Received ",v) 21 | } 22 | } -------------------------------------------------------------------------------- /02.RUNOOB例子代码/19并发/11多信道计算.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | ) 6 | 7 | func digits(number int, dchnl chan int) { 8 | for number != 0 { 9 | digit := number % 10 10 | dchnl <- digit 11 | number /= 10 12 | } 13 | close(dchnl) 14 | } 15 | func calcSquares(number int, squareop chan int) { 16 | sum := 0 17 | dch := make(chan int) 18 | go digits(number, dch) 19 | for digit := range dch { 20 | sum += digit * digit 21 | } 22 | squareop <- sum 23 | } 24 | 25 | func calcCubes(number int, cubeop chan int) { 26 | sum := 0 27 | dch := make(chan int) 28 | go digits(number, dch) 29 | for digit := range dch { 30 | sum += digit * digit * digit 31 | } 32 | cubeop <- sum 33 | } 34 | 35 | func main() { 36 | number := 589 37 | sqrch := make(chan int) 38 | cubech := make(chan int) 39 | go calcSquares(number, sqrch) 40 | go calcCubes(number, cubech) 41 | squares, cubes := <-sqrch, <-cubech 42 | fmt.Println("Final output", squares+cubes) 43 | } -------------------------------------------------------------------------------- /02.RUNOOB例子代码/Go笔记.docx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Goular/GolangModule/6f5ea735e919e4d2521b85ebb470a012bc05baf3/02.RUNOOB例子代码/Go笔记.docx -------------------------------------------------------------------------------- /02.RUNOOB例子代码/简单生产者消费者问题.go: -------------------------------------------------------------------------------- 1 | package _2_RUNOOB例子代码 2 | 3 | import ( 4 | "fmt" 5 | "time" 6 | ) 7 | 8 | func consumer(cname string, ch chan int) { 9 | for i := range ch { 10 | fmt.Println("consumer--", cname, ":", i) 11 | } 12 | fmt.Println("ch closed.") 13 | } 14 | 15 | func producer(pname string, ch chan int) { 16 | for i := 0; i < 4; i++ { 17 | fmt.Println("Producer--", pname, ":", i) 18 | ch <- i 19 | fmt.Println("阻塞",pname,i) 20 | } 21 | } 22 | 23 | func main() { 24 | //用channel来传递"产品", 不再需要自己去加锁维护一个全局的阻塞队列 25 | data := make(chan int) 26 | go producer("生产者1", data) 27 | go producer("生产者2", data) 28 | go consumer("消费者1", data) 29 | go consumer("消费者2", data) 30 | 31 | time.Sleep(10 * time.Second) 32 | defer close(data); 33 | time.Sleep(10 * time.Second) 34 | } 35 | -------------------------------------------------------------------------------- /03.北风网Golang/Golang北风网笔记.docx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Goular/GolangModule/6f5ea735e919e4d2521b85ebb470a012bc05baf3/03.北风网Golang/Golang北风网笔记.docx -------------------------------------------------------------------------------- /03.北风网Golang/第10讲 Go语言之面向对象下 1/01面向对象.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | type Person struct { 6 | name string 7 | age int 8 | } 9 | 10 | func (person Person) getNameAndAge() (string, int) { 11 | return person.name, person.age 12 | } 13 | 14 | type Student struct { 15 | Person 16 | speciality string 17 | } 18 | 19 | func (student Student) getSpeciality() string { 20 | return student.speciality 21 | } 22 | 23 | 24 | func main() { 25 | student := new(Student) 26 | student.name = "ZhangSan" 27 | student.age = 26 28 | student.speciality = "Hello Golang!" 29 | name,age := student.getNameAndAge() 30 | speciality := student.getSpeciality() 31 | fmt.Println(name,age) 32 | fmt.Println(speciality) 33 | } 34 | -------------------------------------------------------------------------------- /03.北风网Golang/第10讲 Go语言之面向对象下 1/02interface.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | type Animal interface { 6 | Fly() 7 | Run() 8 | } 9 | 10 | type Bird struct { 11 | } 12 | 13 | func (bird Bird) Fly() { 14 | fmt.Println("Bird is flying!!!!") 15 | } 16 | 17 | func (bird Bird) Run() { 18 | fmt.Println("Bird is running!!!!") 19 | } 20 | 21 | func main() { 22 | //接口使用标准写法 23 | var animal1 Animal 24 | bird := new(Bird) 25 | animal1 = bird //将实例赋给接口作为其实现 26 | animal1.Fly() 27 | animal1.Run() 28 | } 29 | -------------------------------------------------------------------------------- /03.北风网Golang/第10讲 Go语言之面向对象下_2/01对象实例赋值给接口.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | /* 6 | 只能是打接口实现赋值给小接口,反之会报错 7 | */ 8 | 9 | type Bird struct { 10 | } 11 | 12 | type Animal interface { 13 | Run() 14 | } 15 | 16 | type Animal2 interface { 17 | Run() 18 | Walk() 19 | } 20 | 21 | func (bird Bird) Run() { 22 | fmt.Println("小鸟在跑步") 23 | } 24 | 25 | func (bird Bird) Walk() { 26 | fmt.Println("小鸟在走路") 27 | } 28 | 29 | func main() { 30 | var animal Animal 31 | var animal2 Animal2 32 | 33 | bird := new(Bird) 34 | animal2 = bird 35 | 36 | //尝试过animal2=animal会引起IDE报错,所以就没有使用例子了 37 | animal = animal2 38 | 39 | animal.Run() 40 | } 41 | -------------------------------------------------------------------------------- /03.北风网Golang/第10讲 Go语言之面向对象下_2/02空接口使用.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | /** 6 | 空接口的使用 7 | */ 8 | func main() { 9 | var v1 interface{} = 1 10 | var v2 interface{} = "abc" 11 | var v3 interface{} = 2.345 12 | var v4 interface{} = make(map[string]string) 13 | fmt.Println(v1) 14 | fmt.Println(v2) 15 | fmt.Println(v3) 16 | fmt.Println(v4) 17 | } 18 | -------------------------------------------------------------------------------- /03.北风网Golang/第10讲 Go语言之面向对象下_2/03空接口类型查询Switch--Type.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "reflect" 6 | ) 7 | 8 | func main() { 9 | var v1 interface{} 10 | //v1 = "123" 11 | v1 = 11223 12 | switch v1.(type) { 13 | case int: 14 | fmt.Println("Int") 15 | case int8: 16 | fmt.Println("Int8") 17 | case int32: 18 | fmt.Println("Int32") 19 | case float32: 20 | fmt.Println("Float32") 21 | case string: 22 | fmt.Println("字符串") 23 | default: 24 | fmt.Println("暂无相关类型") 25 | } 26 | fmt.Println(reflect.TypeOf(v1)) 27 | } 28 | -------------------------------------------------------------------------------- /03.北风网Golang/第10讲 Go语言之面向对象下_2/04空接口类型查询if---ok.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | ) 6 | 7 | func main() { 8 | var v1 interface{} 9 | v1 = "123" 10 | //v1 = 11223 11 | if value, ok := v1.(int); ok { 12 | fmt.Println(value, ok) 13 | } else { 14 | fmt.Println("暂时不属于此类型!") 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /03.北风网Golang/第11讲 Go语言并发编程之协程/01协程简单使用.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "time" 6 | ) 7 | 8 | func test_Routine() { 9 | fmt.Println("This is one routine!!!") 10 | } 11 | 12 | func Add(x,y int) { 13 | z:=x+y 14 | fmt.Println(z) 15 | } 16 | 17 | func main() { 18 | //简单使用协程 19 | //go test_Routine() 20 | 21 | 22 | for i:=1;i<10;i++{ 23 | go Add(i,i) 24 | } 25 | 26 | time.Sleep(2) 27 | } 28 | -------------------------------------------------------------------------------- /03.北风网Golang/第12讲 Go语言并发编程之channel/01Channel-simple-use.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "strconv" 6 | "time" 7 | ) 8 | 9 | func Add(x, y int, quit chan int) { 10 | z := x + y 11 | fmt.Println(z) 12 | quit <- 1 13 | } 14 | 15 | func Read(ch chan int) { 16 | fmt.Println("读协程运行") 17 | value := <-ch 18 | fmt.Println("value:" + strconv.Itoa(value)) 19 | } 20 | 21 | func Write(ch chan int) { 22 | fmt.Println("写协程运行") 23 | time.Sleep(4*time.Second) 24 | ch <- 10 25 | } 26 | 27 | func main() { 28 | ch := make(chan int) 29 | go Read(ch) 30 | go Write(ch) 31 | time.Sleep(10*time.Second) 32 | fmt.Println("主程序结束") 33 | } 34 | -------------------------------------------------------------------------------- /03.北风网Golang/第12讲 Go语言并发编程之channel/02Channel-simple-use.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "strconv" 6 | ) 7 | 8 | func Add(x, y int, quit chan int) { 9 | z := x + y 10 | fmt.Println(z) 11 | quit <- 1 12 | } 13 | 14 | func Read(ch chan int) { 15 | fmt.Println("读协程运行") 16 | value := <-ch 17 | fmt.Println("value:" + strconv.Itoa(value)) 18 | } 19 | 20 | func Write(ch chan int) { 21 | fmt.Println("写协程运行") 22 | ch <- 10 23 | } 24 | 25 | func main() { 26 | chs := make([]chan int, 10) 27 | length := len(chs) 28 | 29 | 30 | fmt.Println("length:",length) 31 | 32 | for i := 0; i (.*)`) 19 | result := reg.FindAllStringSubmatch(string(sHtml),-1) 20 | fmt.Println(result[0][1]); 21 | 22 | reg1 := regexp.MustCompile(`(.*)`) 23 | result1 := reg1.FindAllStringSubmatch(string(sHtml), -1) 24 | 25 | fmt.Println(result1[0][1]) 26 | } 27 | -------------------------------------------------------------------------------- /03.北风网Golang/第19讲 Go语言之Mysql_1/01Mysql.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "database/sql" 5 | //仅用于调用指定包的init方法 6 | _ "github.com/go-sql-driver/mysql" 7 | "fmt" 8 | ) 9 | 10 | func main() { 11 | db, err := sql.Open("mysql", "root:123456@tcp(127.0.0.1:3306)/test?charset=utf8"); 12 | if err != nil { 13 | panic(err) 14 | } 15 | stmt, err := db.Prepare("INSERT INTO T_USER (NAME,add_time) values(?,?)"); 16 | res,err := stmt.Exec("Goular22","2017-11-02 23:10:09") 17 | id,err := res.LastInsertId() 18 | if err != nil { 19 | panic(err) 20 | } 21 | fmt.Println(id) 22 | 23 | } 24 | -------------------------------------------------------------------------------- /03.北风网Golang/第19讲 Go语言之Mysql_2/01Mysql-update.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "database/sql" 5 | _ "github.com/go-sql-driver/mysql" 6 | "fmt" 7 | ) 8 | 9 | 10 | func main() { 11 | db, err := sql.Open("mysql", "root:123456@tcp(127.0.0.1:3306)/test?charset=utf8") 12 | if err != nil { 13 | panic(err) 14 | } 15 | stmt,err := db.Prepare("UPDATE t_user set name=? where id =?") 16 | res,err := stmt.Exec("jack",1) 17 | id,err := res.RowsAffected() 18 | if err!=nil{ 19 | panic(err) 20 | } 21 | fmt.Println(id) 22 | } 23 | -------------------------------------------------------------------------------- /03.北风网Golang/第19讲 Go语言之Mysql_2/02Mysql-delete.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "database/sql" 5 | _ "github.com/go-sql-driver/mysql" 6 | "fmt" 7 | ) 8 | 9 | 10 | func main() { 11 | db, err := sql.Open("mysql", "root:123456@tcp(127.0.0.1:3306)/test?charset=utf8") 12 | if err != nil { 13 | panic(err) 14 | } 15 | stmt,err := db.Prepare("DELETE FROM t_user WHERE id =?") 16 | res,err := stmt.Exec(2) 17 | id,err := res.RowsAffected() 18 | if err!=nil{ 19 | panic(err) 20 | } 21 | fmt.Println(id) 22 | } 23 | -------------------------------------------------------------------------------- /03.北风网Golang/第19讲 Go语言之Mysql_2/03Mysql-select.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "database/sql" 5 | _ "github.com/go-sql-driver/mysql" 6 | "fmt" 7 | ) 8 | 9 | 10 | func main() { 11 | db, err := sql.Open("mysql", "root:123456@tcp(127.0.0.1:3306)/test?charset=utf8") 12 | if err != nil { 13 | panic(err) 14 | } 15 | rows,err := db.Query("SELECT * from t_user") 16 | if err!=nil{ 17 | panic(err) 18 | } 19 | for rows.Next(){ 20 | var id int 21 | var name string 22 | var time string 23 | err := rows.Scan(&id,&name,&time) 24 | if err != nil { 25 | panic(err) 26 | } 27 | fmt.Println(id,name,time) 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /03.北风网Golang/第1讲 Go语言简介/01HelloWorld.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func main() { 6 | a:=2; 7 | fmt.Printf("hello,world!%d",a); 8 | } 9 | -------------------------------------------------------------------------------- /03.北风网Golang/第21讲 Go语言之聊天室_1/Client.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "os" 6 | "net" 7 | ) 8 | 9 | func CheckError(err error) { 10 | if err != nil { 11 | fmt.Println("Error:%s", err.Error()) 12 | //系统退出,0代表正常退出,非零代表异常退出 13 | os.Exit(1) 14 | } 15 | } 16 | 17 | func main() { 18 | //客户端要进行拨号 19 | conn, err := net.Dial("tcp", "127.0.0.1:8080") 20 | CheckError(err) 21 | defer conn.Close() 22 | 23 | //进行写 操作 24 | conn.Write([]byte("Hello,I come from GuangZhou")) 25 | fmt.Println("Client sent the Message to Server") 26 | } 27 | -------------------------------------------------------------------------------- /03.北风网Golang/第21讲 Go语言之聊天室_4/test.log: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Goular/GolangModule/6f5ea735e919e4d2521b85ebb470a012bc05baf3/03.北风网Golang/第21讲 Go语言之聊天室_4/test.log -------------------------------------------------------------------------------- /03.北风网Golang/第22讲 Beego框架简介/pkg/windows_amd64/API/controllers.a: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Goular/GolangModule/6f5ea735e919e4d2521b85ebb470a012bc05baf3/03.北风网Golang/第22讲 Beego框架简介/pkg/windows_amd64/API/controllers.a -------------------------------------------------------------------------------- /03.北风网Golang/第22讲 Beego框架简介/pkg/windows_amd64/API/models.a: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Goular/GolangModule/6f5ea735e919e4d2521b85ebb470a012bc05baf3/03.北风网Golang/第22讲 Beego框架简介/pkg/windows_amd64/API/models.a -------------------------------------------------------------------------------- /03.北风网Golang/第22讲 Beego框架简介/pkg/windows_amd64/API/routers.a: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Goular/GolangModule/6f5ea735e919e4d2521b85ebb470a012bc05baf3/03.北风网Golang/第22讲 Beego框架简介/pkg/windows_amd64/API/routers.a -------------------------------------------------------------------------------- /03.北风网Golang/第22讲 Beego框架简介/pkg/windows_amd64/WEB/controllers.a: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Goular/GolangModule/6f5ea735e919e4d2521b85ebb470a012bc05baf3/03.北风网Golang/第22讲 Beego框架简介/pkg/windows_amd64/WEB/controllers.a -------------------------------------------------------------------------------- /03.北风网Golang/第22讲 Beego框架简介/pkg/windows_amd64/WEB/models.a: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Goular/GolangModule/6f5ea735e919e4d2521b85ebb470a012bc05baf3/03.北风网Golang/第22讲 Beego框架简介/pkg/windows_amd64/WEB/models.a -------------------------------------------------------------------------------- /03.北风网Golang/第22讲 Beego框架简介/pkg/windows_amd64/WEB/routers.a: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Goular/GolangModule/6f5ea735e919e4d2521b85ebb470a012bc05baf3/03.北风网Golang/第22讲 Beego框架简介/pkg/windows_amd64/WEB/routers.a -------------------------------------------------------------------------------- /03.北风网Golang/第22讲 Beego框架简介/src/API/API.exe~: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Goular/GolangModule/6f5ea735e919e4d2521b85ebb470a012bc05baf3/03.北风网Golang/第22讲 Beego框架简介/src/API/API.exe~ -------------------------------------------------------------------------------- /03.北风网Golang/第22讲 Beego框架简介/src/API/conf/app.conf: -------------------------------------------------------------------------------- 1 | appname = API 2 | httpport = 8080 3 | runmode = dev 4 | autorender = false 5 | copyrequestbody = true 6 | EnableDocs = true 7 | -------------------------------------------------------------------------------- /03.北风网Golang/第22讲 Beego框架简介/src/API/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | _ "API/routers" 5 | 6 | "github.com/astaxie/beego" 7 | ) 8 | 9 | func main() { 10 | if beego.BConfig.RunMode == "dev" { 11 | beego.BConfig.WebConfig.DirectoryIndex = true 12 | beego.BConfig.WebConfig.StaticDir["/swagger"] = "swagger" 13 | } 14 | beego.Run() 15 | } 16 | -------------------------------------------------------------------------------- /03.北风网Golang/第22讲 Beego框架简介/src/API/routers/router.go: -------------------------------------------------------------------------------- 1 | // @APIVersion 1.0.0 2 | // @Title beego Test API 3 | // @Description beego has a very cool tools to autogenerate documents for your API 4 | // @Contact astaxie@gmail.com 5 | // @TermsOfServiceUrl http://beego.me/ 6 | // @License Apache 2.0 7 | // @LicenseUrl http://www.apache.org/licenses/LICENSE-2.0.html 8 | package routers 9 | 10 | import ( 11 | "API/controllers" 12 | 13 | "github.com/astaxie/beego" 14 | ) 15 | 16 | func init() { 17 | ns := beego.NewNamespace("/v1", 18 | beego.NSNamespace("/object", 19 | beego.NSInclude( 20 | &controllers.ObjectController{}, 21 | ), 22 | ), 23 | beego.NSNamespace("/user", 24 | beego.NSInclude( 25 | &controllers.UserController{}, 26 | ), 27 | ), 28 | ) 29 | beego.AddNamespace(ns) 30 | } 31 | -------------------------------------------------------------------------------- /03.北风网Golang/第22讲 Beego框架简介/src/WEB/conf/app.conf: -------------------------------------------------------------------------------- 1 | appname = WEB 2 | runmode = dev 3 | 4 | [dev] 5 | httpport=8080 6 | [test] 7 | httpport=8081 8 | [prod] 9 | httpport=8082 10 | 11 | sessionon = true -------------------------------------------------------------------------------- /03.北风网Golang/第22讲 Beego框架简介/src/WEB/conf/testini.conf: -------------------------------------------------------------------------------- 1 | appname = 吃屎吧大傻 -------------------------------------------------------------------------------- /03.北风网Golang/第22讲 Beego框架简介/src/WEB/controllers/default.go: -------------------------------------------------------------------------------- 1 | package controllers 2 | 3 | import ( 4 | "github.com/astaxie/beego" 5 | ) 6 | 7 | type MainController struct { 8 | beego.Controller 9 | } 10 | 11 | func (c *MainController) Get() { 12 | c.Data["Website"] = "beego.me" 13 | c.Data["Email"] = "astaxie@gmail.com" 14 | c.TplName = "index.tpl" 15 | } 16 | 17 | func (c *MainController) Post() { 18 | c.Ctx.WriteString("This is method post!") 19 | } 20 | -------------------------------------------------------------------------------- /03.北风网Golang/第22讲 Beego框架简介/src/WEB/controllers/test.go: -------------------------------------------------------------------------------- 1 | package controllers 2 | 3 | import "github.com/astaxie/beego" 4 | 5 | type TestController struct { 6 | beego.Controller 7 | } 8 | 9 | func (controller *TestController) Get() { 10 | //相当于php里面的echo 函数 11 | controller.Ctx.WriteString("welcome test controller!") 12 | } 13 | -------------------------------------------------------------------------------- /03.北风网Golang/第22讲 Beego框架简介/src/WEB/controllers/testConfig.go: -------------------------------------------------------------------------------- 1 | package controllers 2 | 3 | import ( 4 | "github.com/astaxie/beego" 5 | "github.com/astaxie/beego/config" 6 | ) 7 | 8 | type TestConfigController struct { 9 | beego.Controller 10 | } 11 | 12 | func (this *TestConfigController)Get() { 13 | iniconf, err := config.NewConfig("ini", "testini.conf") 14 | if err != nil { 15 | //t.Fatal(err) 16 | } 17 | str := iniconf.String("appname") 18 | this.Ctx.WriteString(str) 19 | } 20 | 21 | 22 | -------------------------------------------------------------------------------- /03.北风网Golang/第22讲 Beego框架简介/src/WEB/controllers/testContext.go: -------------------------------------------------------------------------------- 1 | package controllers 2 | 3 | import ( 4 | "github.com/astaxie/beego" 5 | "strconv" 6 | ) 7 | 8 | type TestContextController struct { 9 | beego.Controller 10 | } 11 | 12 | func (this *TestContextController) Get() { 13 | this.Ctx.WriteString(this.Ctx.Input.IP() + ":" + strconv.Itoa(this.Ctx.Input.Port())) 14 | this.Ctx.WriteString(this.Ctx.Input.Query("name")) //等价于php中的 $_REQUEST["name"] 15 | m := make(map[string]float64) 16 | m["zhangsna"] = 98.7 17 | this.Ctx.Output.JSON(m, false, false) 18 | } 19 | -------------------------------------------------------------------------------- /03.北风网Golang/第22讲 Beego框架简介/src/WEB/controllers/testHttpLib.go: -------------------------------------------------------------------------------- 1 | package controllers 2 | 3 | import ( 4 | "github.com/astaxie/beego" 5 | "github.com/astaxie/beego/httplib" 6 | ) 7 | 8 | type TestHttpLibController struct { 9 | beego.Controller 10 | } 11 | 12 | func (this *TestHttpLibController) Get() { 13 | req := httplib.Get("http://www.baidu.com") 14 | result, err := req.String() 15 | if err != nil { 16 | // 17 | } 18 | this.Ctx.WriteString(result) 19 | } 20 | -------------------------------------------------------------------------------- /03.北风网Golang/第22讲 Beego框架简介/src/WEB/controllers/testView.go: -------------------------------------------------------------------------------- 1 | package controllers 2 | 3 | import ( 4 | "github.com/astaxie/beego" 5 | "WEB/models" 6 | ) 7 | 8 | type TestViewController struct { 9 | beego.Controller 10 | } 11 | 12 | func (this *TestViewController) Get() { 13 | var users []models.UserInfo 14 | models.ReadUserInfo(&users) 15 | this.Data["Users"] = users 16 | this.Data["title"] = "欢迎来到加工屋" 17 | this.Data["len"] = len(users) 18 | this.Data["Content1"] = "沉默是金111" 19 | this.Data["Content2"] = "沉默是金222" 20 | this.TplName = "test_view.tpl" 21 | } 22 | -------------------------------------------------------------------------------- /03.北风网Golang/第22讲 Beego框架简介/src/WEB/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | _ "WEB/routers" 5 | "github.com/astaxie/beego" 6 | ) 7 | 8 | func main() { 9 | beego.Run() 10 | } 11 | 12 | -------------------------------------------------------------------------------- /03.北风网Golang/第22讲 Beego框架简介/src/WEB/models/user.go: -------------------------------------------------------------------------------- 1 | package models 2 | 3 | import ( 4 | _ "github.com/go-sql-driver/mysql" 5 | "github.com/astaxie/beego/orm" 6 | ) 7 | 8 | var ( 9 | db orm.Ormer 10 | ) 11 | 12 | //由于model这个名字叫 UserInfo 那么操作的表其实 user_info 13 | type UserInfo struct { 14 | Id int64 15 | Username string 16 | Password string 17 | } 18 | 19 | func init() { 20 | orm.Debug = true // 是否开启调试模式 调试模式下会打印出sql语句 21 | orm.RegisterDataBase("default", "mysql", "root:123456@tcp(127.0.0.1:3306)/test?charset=utf8", 30) 22 | orm.RegisterModel(new(UserInfo)) 23 | db = orm.NewOrm() 24 | } 25 | 26 | func AddUser(user_info *UserInfo) (int64, error) { 27 | id, err := db.Insert(user_info) 28 | return id, err 29 | } 30 | 31 | func ReadUserInfo(users *[]UserInfo) { 32 | qb, _ := orm.NewQueryBuilder("mysql") 33 | 34 | qb.Select("*").From("user_info") 35 | 36 | sql := qb.String() 37 | db.Raw(sql).QueryRows(users) 38 | } 39 | -------------------------------------------------------------------------------- /03.北风网Golang/第22讲 Beego框架简介/src/WEB/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 | -------------------------------------------------------------------------------- /03.北风网Golang/第22讲 Beego框架简介/src/WEB/testini.conf: -------------------------------------------------------------------------------- 1 | appname = 吃屎吧大傻 -------------------------------------------------------------------------------- /03.北风网Golang/第22讲 Beego框架简介/src/WEB/views/test_view.tpl: -------------------------------------------------------------------------------- 1 | 2 | 3 | {{.title}} 4 | 5 | {{if .IsDisplay}} 6 | {{.Content1}} 7 | {{else}} 8 | {{.Content2}} 9 | {{end}} 10 |
11 | {{range .Users}} 12 | {{.Username}}{{$.len}} 13 | {{end}} 14 | 15 | 16 | -------------------------------------------------------------------------------- /03.北风网Golang/第2讲 理解GOPATH/01main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "test" 5 | ) 6 | 7 | 8 | func main() { 9 | test.Hello() 10 | } 11 | -------------------------------------------------------------------------------- /03.北风网Golang/第2讲 理解GOPATH/print_hello.go: -------------------------------------------------------------------------------- 1 | package test 2 | 3 | import "fmt" 4 | 5 | //这个是用于main.go调用的 6 | func Hello() { 7 | fmt.Printf("Hello Beego!") 8 | } 9 | -------------------------------------------------------------------------------- /03.北风网Golang/第30讲 Beego框架之爬虫项目实战_1/pkg/windows_amd64/crawl_movices/controllers.a: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Goular/GolangModule/6f5ea735e919e4d2521b85ebb470a012bc05baf3/03.北风网Golang/第30讲 Beego框架之爬虫项目实战_1/pkg/windows_amd64/crawl_movices/controllers.a -------------------------------------------------------------------------------- /03.北风网Golang/第30讲 Beego框架之爬虫项目实战_1/pkg/windows_amd64/crawl_movices/models.a: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Goular/GolangModule/6f5ea735e919e4d2521b85ebb470a012bc05baf3/03.北风网Golang/第30讲 Beego框架之爬虫项目实战_1/pkg/windows_amd64/crawl_movices/models.a -------------------------------------------------------------------------------- /03.北风网Golang/第30讲 Beego框架之爬虫项目实战_1/pkg/windows_amd64/crawl_movices/routers.a: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Goular/GolangModule/6f5ea735e919e4d2521b85ebb470a012bc05baf3/03.北风网Golang/第30讲 Beego框架之爬虫项目实战_1/pkg/windows_amd64/crawl_movices/routers.a -------------------------------------------------------------------------------- /03.北风网Golang/第30讲 Beego框架之爬虫项目实战_1/src/crawl_movices/conf/app.conf: -------------------------------------------------------------------------------- 1 | appname = crawl_movices 2 | httpport = 8080 3 | runmode = dev 4 | -------------------------------------------------------------------------------- /03.北风网Golang/第30讲 Beego框架之爬虫项目实战_1/src/crawl_movices/controllers/default.go: -------------------------------------------------------------------------------- 1 | package controllers 2 | 3 | import ( 4 | "github.com/astaxie/beego" 5 | ) 6 | 7 | type MainController struct { 8 | beego.Controller 9 | } 10 | 11 | func (c *MainController) Get() { 12 | c.Data["Website"] = "beego.me" 13 | c.Data["Email"] = "astaxie@gmail.com" 14 | c.TplName = "index.tpl" 15 | } 16 | -------------------------------------------------------------------------------- /03.北风网Golang/第30讲 Beego框架之爬虫项目实战_1/src/crawl_movices/crawl_movices.exe~: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Goular/GolangModule/6f5ea735e919e4d2521b85ebb470a012bc05baf3/03.北风网Golang/第30讲 Beego框架之爬虫项目实战_1/src/crawl_movices/crawl_movices.exe~ -------------------------------------------------------------------------------- /03.北风网Golang/第30讲 Beego框架之爬虫项目实战_1/src/crawl_movices/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | _ "crawl_movices/routers" 5 | "github.com/astaxie/beego" 6 | ) 7 | 8 | func main() { 9 | beego.Run() 10 | } 11 | 12 | -------------------------------------------------------------------------------- /03.北风网Golang/第30讲 Beego框架之爬虫项目实战_1/src/crawl_movices/routers/router.go: -------------------------------------------------------------------------------- 1 | package routers 2 | 3 | import ( 4 | "crawl_movices/controllers" 5 | "github.com/astaxie/beego" 6 | ) 7 | 8 | func init() { 9 | beego.Router("/", &controllers.MainController{}) 10 | beego.Router("/crawl_movie", &controllers.CrawlMovieController{}, "*:CrawlMovie") 11 | } 12 | -------------------------------------------------------------------------------- /03.北风网Golang/第30讲 Beego框架之爬虫项目实战_1/src/crawl_movices/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 | -------------------------------------------------------------------------------- /03.北风网Golang/第3讲 Go语言基础上/01基础类型.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func main() { 6 | var x1 int 7 | x1 = 1 8 | var x2 = 2 9 | x3 := 3 10 | fmt.Printf("%d\n",x1) 11 | fmt.Printf("%d\n",x2) 12 | fmt.Printf("%d\n",x3) 13 | } 14 | -------------------------------------------------------------------------------- /03.北风网Golang/第3讲 Go语言基础上/02基础类型_复数.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "reflect" 6 | ) 7 | 8 | func main() { 9 | var x = 2 + 4i 10 | fmt.Print(x + x) 11 | fmt.Println() 12 | fmt.Print(reflect.TypeOf(x)) //获取变量X的类型 13 | } 14 | -------------------------------------------------------------------------------- /03.北风网Golang/第3讲 Go语言基础上/03基础类型_数组1.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | import "reflect" 5 | 6 | var y [10]int 7 | 8 | 9 | func main() { 10 | x:=[]int{1,2,3,4,5,6} 11 | fmt.Println("%v",x) 12 | y[0] = 22 13 | y[1] = 23 14 | y[2] = 24 15 | y[3] = 25 16 | y[4] = 26 17 | fmt.Println("%v",y) 18 | 19 | //x[7] = 2//执行这个会报错,因为数组长度是固定的 20 | fmt.Println(reflect.TypeOf(x)) 21 | } 22 | -------------------------------------------------------------------------------- /03.北风网Golang/第4讲 Go语言基础下/01Slice_1.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func main() { 6 | x:= [...]int{1,2,3,4,5,6,7,8,9,10} 7 | fmt.Println(len(x)) 8 | 9 | var y1 []int 10 | y1 = x[3:] 11 | fmt.Printf("%v\n", y1) 12 | 13 | y2 := x[:3] 14 | fmt.Printf("%v\n", y2) 15 | } 16 | -------------------------------------------------------------------------------- /03.北风网Golang/第4讲 Go语言基础下/02Slice_2.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func main() { 6 | x := make([]int,3,5) 7 | x = append(x, 2,4,5,6) 8 | 9 | //展示内容 10 | fmt.Printf("%v\n",x) 11 | //代表现在slice中元素的个数 12 | fmt.Printf("%v\n",len(x)) 13 | //代表现在slice底层的分配的空间是多大 当append加入的元素个数超过此值时 底层会自动扩充 14 | fmt.Printf("%v\n",cap(x)) 15 | 16 | } 17 | -------------------------------------------------------------------------------- /03.北风网Golang/第4讲 Go语言基础下/03map.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func main() { 6 | 7 | //下面呢那个是错误示范 8 | //var x map[string]float32 9 | //x["zhangsan"] = 91.65 10 | //fmt.Printf("%v",x) 11 | 12 | //正确使用map的例子 13 | x1 := make(map[string]float32) 14 | x1["Jack"] = 120.68 15 | x1["Tom"] = 125.98 16 | fmt.Printf("%v",x1) 17 | } 18 | -------------------------------------------------------------------------------- /03.北风网Golang/第5讲 Go语言之流程控制/01IF.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | func main() { 4 | i := 2; 5 | if i<2{ 6 | println(111); 7 | }else if i==2{ 8 | println(222); 9 | }else{ 10 | println(333); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /03.北风网Golang/第5讲 Go语言之流程控制/02for.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | func main() { 4 | for i:=0;i<10;i++{ 5 | println(i) 6 | } 7 | for{ 8 | println(2255) 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /03.北风网Golang/第5讲 Go语言之流程控制/03switch.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func main() { 6 | i:=3 7 | switch i { 8 | case 1,2: 9 | fmt.Printf("111") 10 | case 3:fallthrough //case穿透的使用 11 | case 4: 12 | fmt.Printf("222") 13 | default: 14 | fmt.Printf("000") 15 | 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /03.北风网Golang/第5讲 Go语言之流程控制/04range.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | func main() { 4 | x:="Hello World!" 5 | for _,str := range x{ 6 | println(string(str)) 7 | } 8 | y:=[10]float32{12.2,15.3,2,2.6,8.77} 9 | for _,value := range y{ 10 | println(value) 11 | } 12 | z:=make(map[string]string) 13 | z["GuangZhou"]="花城" 14 | z["BeiJing"]="京城" 15 | z["ShangHai"]="申城" 16 | for key,value := range z{ 17 | println(key,value) 18 | } 19 | 20 | 21 | //如何让两个数进行交换 22 | a:=12 23 | b:=19 24 | a,b = b,a 25 | println(a,b) 26 | 27 | } 28 | -------------------------------------------------------------------------------- /03.北风网Golang/第6讲 Go语言之函数上/01函数.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func main() { 6 | x:=2 7 | x2 := &x 8 | println(x2) 9 | println(*x2) 10 | a:=4 11 | add(&a) 12 | fmt.Println(a) 13 | } 14 | 15 | func swap(a,b int)(int,int) { 16 | return b,a 17 | } 18 | 19 | func add(a *int) *int { 20 | *a = *a +1 21 | return a 22 | } 23 | -------------------------------------------------------------------------------- /03.北风网Golang/第7讲 Go语言之函数下/01匿名函数.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func main() { 6 | type sum func() 7 | var y sum 8 | y = func() { 9 | fmt.Println("Hello World!12333") 10 | } 11 | y() 12 | 13 | x := func(a, b int) int { 14 | return a + b 15 | } 16 | fmt.Println(x(2,8)) 17 | } 18 | -------------------------------------------------------------------------------- /03.北风网Golang/第7讲 Go语言之函数下/02getSum.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func main() { 6 | num := []int{1, 2, 3, 4, 5, 6} 7 | sum := getSum(num) 8 | fmt.Println(sum) 9 | } 10 | 11 | func getSum(num []int) int { 12 | sum := 0 13 | for _, value := range num { 14 | sum += value 15 | } 16 | return sum 17 | } 18 | -------------------------------------------------------------------------------- /03.北风网Golang/第7讲 Go语言之函数下/03函数传值和传址.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func swap(a,b int)(int,int) { 6 | return b,a 7 | } 8 | 9 | func add(a *int)*int { 10 | *a = *a+1 11 | return a 12 | } 13 | 14 | func main() { 15 | a:=5 16 | add(&a) 17 | fmt.Println(a) 18 | } 19 | -------------------------------------------------------------------------------- /03.北风网Golang/第7讲 Go语言之函数下/04defer.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | ) 6 | 7 | func main() { 8 | for i:=1;i<=5;i++{ 9 | defer fmt.Println(i) 10 | } 11 | fmt.Println("Behind To 223344") 12 | } 13 | -------------------------------------------------------------------------------- /03.北风网Golang/第7讲 Go语言之函数下/05panic和recover.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | /** 6 | 遇到错误,首先会执行defer栈的内容,然后才出现错误内容的错误树,如果使用recover来捕获,那么就不会产生错误树,而知根据捕获错误来处理 7 | */ 8 | func main() { 9 | defer func() { 10 | error :=recover() 11 | if (error!=nil){ 12 | fmt.Println(error) 13 | } 14 | }() 15 | defer func() { 16 | fmt.Println("end 222") 17 | }() 18 | createPanic() 19 | fmt.Println("operate end") 20 | } 21 | 22 | func createPanic() { 23 | panic("错误内容产生") 24 | } 25 | -------------------------------------------------------------------------------- /03.北风网Golang/第8讲 Go语言之struct/01Struct.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | type Person struct { 6 | name string 7 | age int8 8 | } 9 | 10 | type Student struct { 11 | Person 12 | specialStr string 13 | } 14 | 15 | func main() { 16 | s1:=Student{Person{"四维电脑",28},"学术性"} 17 | fmt.Printf("%v",s1) 18 | fmt.Println(s1.name) 19 | } 20 | -------------------------------------------------------------------------------- /03.北风网Golang/第9讲 Go语言之面向对象上/01面向对象.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | //func (a int) compare(b,c int)bool { 6 | // return a= start { 13 | start = lastI + 1 14 | } 15 | if i-start+1 > maxLength { 16 | maxLength = i - start + 1 17 | } 18 | lastOccurred[ch] = i 19 | } 20 | return maxLength 21 | } 22 | 23 | func main() { 24 | fmt.Println(lengthOfNonRepeatingSubStr("abcabcbb")) 25 | fmt.Println(lengthOfNonRepeatingSubStr("bbbbbb")) 26 | fmt.Println(lengthOfNonRepeatingSubStr("pwwke2w")) 27 | } 28 | -------------------------------------------------------------------------------- /06.(重点)慕课网-Google资深工程师深度讲解Go语言/02.数据结构/4.rune/2.nonrepeating.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | // 寻找不重复字符串 -- 国际版 6 | func lengthOfNonRepeatingSubStr(s string) int { 7 | // 创建map记录次数 8 | lastOccurred := make(map[rune]int) 9 | start := 0 10 | maxLength := 0 11 | for i, ch := range []rune(s) { 12 | // fmt.Println("start::", start) 13 | if lastI, ok := lastOccurred[ch]; ok && lastI >= start { 14 | start = lastI + 1 15 | } 16 | if i-start+1 > maxLength { 17 | maxLength = i - start + 1 18 | } 19 | lastOccurred[ch] = i 20 | } 21 | return maxLength 22 | } 23 | 24 | func main() { 25 | fmt.Println(lengthOfNonRepeatingSubStr("abcabcbb")) 26 | fmt.Println(lengthOfNonRepeatingSubStr("bbbbbb")) 27 | fmt.Println(lengthOfNonRepeatingSubStr("pwwke2w")) 28 | fmt.Println(lengthOfNonRepeatingSubStr("统一奶茶一")) 29 | fmt.Println(lengthOfNonRepeatingSubStr("天南第一峰9958")) 30 | } 31 | -------------------------------------------------------------------------------- /06.(重点)慕课网-Google资深工程师深度讲解Go语言/02.数据结构/4.rune/4.rune.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "unicode/utf8" 6 | ) 7 | 8 | func main() { 9 | s := "Yes 我爱慕课网!" 10 | for _, b := range []byte(s) { 11 | fmt.Printf("%X ", b) 12 | } 13 | fmt.Println() 14 | 15 | for i, ch := range s { 16 | fmt.Printf("(%d %X)", i, ch) 17 | } 18 | fmt.Println() 19 | 20 | // 打印rune长度 21 | fmt.Println("Rune Count :", utf8.RuneCountInString(s)) 22 | // 解码byte 23 | bytes := []byte(s) 24 | for len(bytes) > 0 { 25 | // 每一次解完,获取最后的位置用于切片截取 26 | ch, size := utf8.DecodeRune(bytes) // 根据rune来解析 27 | bytes = bytes[size:] 28 | fmt.Printf("%c ", ch) 29 | } 30 | fmt.Println() 31 | // 直接使用rune来解码字符串 32 | for index, char := range []rune(s) { 33 | fmt.Printf("(%d , %c )", index, char) 34 | } 35 | fmt.Println() 36 | 37 | } 38 | -------------------------------------------------------------------------------- /06.(重点)慕课网-Google资深工程师深度讲解Go语言/03.面向对象/01.tree/node.go: -------------------------------------------------------------------------------- 1 | package _1_tree 2 | 3 | import ( 4 | "fmt" 5 | ) 6 | 7 | type TreeNode struct { 8 | Value int 9 | Left, Right *TreeNode 10 | } 11 | 12 | // 工厂方法创建对象 13 | func CreateNode(value int) *TreeNode { 14 | return &TreeNode{Value: value} 15 | } 16 | 17 | func (node TreeNode) Print() { 18 | fmt.Print(node.Value, " ") 19 | } 20 | 21 | func (node *TreeNode) SetValue(value int) { 22 | if node == nil { 23 | fmt.Println("Setting Value to nil node.Ignored.") 24 | } 25 | node.Value = value 26 | } 27 | -------------------------------------------------------------------------------- /06.(重点)慕课网-Google资深工程师深度讲解Go语言/03.面向对象/01.tree/traversal.go: -------------------------------------------------------------------------------- 1 | package _1_tree 2 | 3 | // 遍历tree 4 | func (node *TreeNode) Traverse() { 5 | if node == nil { 6 | return 7 | } 8 | node.Left.Traverse() 9 | node.Print() 10 | node.Right.Traverse() 11 | } 12 | -------------------------------------------------------------------------------- /06.(重点)慕课网-Google资深工程师深度讲解Go语言/03.面向对象/02.queue/entry/entry.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | 6 | "baseLearn/03.面向对象/02.queue" 7 | ) 8 | 9 | func main() { 10 | q := _2_queue.Queue{1} 11 | var Q1 *_2_queue.Queue = &q 12 | fmt.Println(Q1) 13 | q.Push(2) 14 | q.Push(3) 15 | fmt.Println(q.Pop()) 16 | fmt.Println(q.IsEmpty()) 17 | fmt.Println(q.Pop()) 18 | fmt.Println(q.IsEmpty()) 19 | fmt.Println(q.Pop()) 20 | fmt.Println(q.IsEmpty()) 21 | fmt.Println(&q) 22 | } 23 | -------------------------------------------------------------------------------- /06.(重点)慕课网-Google资深工程师深度讲解Go语言/03.面向对象/02.queue/queue.go: -------------------------------------------------------------------------------- 1 | package queue 2 | 3 | type Queue []int 4 | 5 | func (q *Queue) Push(v int) { 6 | *q = append(*q, v) 7 | } 8 | 9 | func (q *Queue) Pop() int { 10 | head := (*q)[0] 11 | *q = (*q)[1:] 12 | return head 13 | } 14 | 15 | func (q *Queue) IsEmpty() bool { 16 | return len(*q) == 0 17 | } 18 | -------------------------------------------------------------------------------- /06.(重点)慕课网-Google资深工程师深度讲解Go语言/03.面向对象/02.queue/queue2.go: -------------------------------------------------------------------------------- 1 | package queue 2 | 3 | // 通用类型版队列 4 | // 通用版的缺陷是类型需要在运行的时候才能动态判断 5 | type Queue2 []interface{} 6 | 7 | func (q *Queue2) Push(v interface{}) { 8 | *q = append(*q, v.(int)) 9 | } 10 | 11 | func (q *Queue2) Pop() interface{} { 12 | head := (*q)[0] 13 | *q = (*q)[1:] 14 | return head.(int) 15 | } 16 | 17 | func (q *Queue2) IsEmpty() bool { 18 | return len(*q) == 0 19 | } 20 | -------------------------------------------------------------------------------- /06.(重点)慕课网-Google资深工程师深度讲解Go语言/03.面向对象/03.接口/mock/mockretriever.go: -------------------------------------------------------------------------------- 1 | package mock 2 | 3 | type Retriever struct { 4 | Contents string 5 | } 6 | 7 | func (r *Retriever) Get(url string) string { 8 | return r.Contents 9 | } 10 | -------------------------------------------------------------------------------- /06.(重点)慕课网-Google资深工程师深度讲解Go语言/03.面向对象/03.接口/real/realretriever.go: -------------------------------------------------------------------------------- 1 | package real 2 | 3 | import ( 4 | "net/http" 5 | "net/http/httputil" 6 | "time" 7 | ) 8 | 9 | type Retriever struct { 10 | UserAgent string 11 | TimeOut time.Duration 12 | } 13 | 14 | func (r *Retriever) Get(url string) string { 15 | resp, err := http.Get(url) 16 | if err != nil { 17 | panic(err) 18 | } 19 | result, err := httputil.DumpResponse(resp, true) 20 | resp.Body.Close() 21 | if err != nil { 22 | panic(err) 23 | } 24 | return string(result) 25 | } 26 | -------------------------------------------------------------------------------- /06.(重点)慕课网-Google资深工程师深度讲解Go语言/03.面向对象/03.接口/test.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | ) 6 | 7 | type One interface { 8 | Get(url string) 9 | } 10 | 11 | type Two interface { 12 | Post(url string) 13 | } 14 | 15 | type BothOneTwo interface { 16 | One 17 | Two 18 | Put(url string) 19 | } 20 | 21 | type S1 struct { 22 | } 23 | 24 | func (s1 *S1) String() string { 25 | return "S1" 26 | } 27 | 28 | func (s1 *S1) Get(url string) { 29 | fmt.Println("GET") 30 | } 31 | 32 | func (s1 *S1) Post(url string) { 33 | fmt.Println("POST") 34 | } 35 | 36 | func (s1 *S1) Put(url string) { 37 | fmt.Println("Put") 38 | } 39 | 40 | func main() { 41 | var one One = &S1{} 42 | one.Get("") 43 | var both BothOneTwo = &S1{} 44 | both.Post("") 45 | both.Put("") 46 | fmt.Println(&S1{}) 47 | } 48 | -------------------------------------------------------------------------------- /06.(重点)慕课网-Google资深工程师深度讲解Go语言/04.函数式编程/01.tree/node.go: -------------------------------------------------------------------------------- 1 | package _1_tree 2 | 3 | import ( 4 | "fmt" 5 | ) 6 | 7 | type TreeNode struct { 8 | Value int 9 | Left, Right *TreeNode 10 | } 11 | 12 | // 工厂方法创建对象 13 | func CreateNode(value int) *TreeNode { 14 | return &TreeNode{Value: value} 15 | } 16 | 17 | func (node TreeNode) Print() { 18 | fmt.Print(node.Value, " ") 19 | } 20 | 21 | func (node *TreeNode) SetValue(value int) { 22 | if node == nil { 23 | fmt.Println("Setting Value to nil node.Ignored.") 24 | } 25 | node.Value = value 26 | } 27 | -------------------------------------------------------------------------------- /06.(重点)慕课网-Google资深工程师深度讲解Go语言/04.函数式编程/01.tree/traversal.go: -------------------------------------------------------------------------------- 1 | package _1_tree 2 | 3 | import ( 4 | "fmt" 5 | ) 6 | 7 | // 遍历tree 8 | func (node *TreeNode) Traverse() { 9 | node.TraverseFunc(func(node *TreeNode) { 10 | node.Print() 11 | }) 12 | fmt.Println() 13 | } 14 | 15 | func (node *TreeNode) TraverseFunc(f func(node *TreeNode)) { 16 | if node == nil { 17 | return 18 | } 19 | node.Left.Traverse() 20 | f(node) 21 | node.Right.Traverse() 22 | } 23 | 24 | func (node *TreeNode) TraverseWithChannel() chan *TreeNode { 25 | out := make(chan *TreeNode) 26 | go func() { 27 | // 这是一个同步顺序递归方法,所以最后才会去执行 close(out) 28 | node.TraverseFunc(func(node *TreeNode) { 29 | out <- node 30 | }) 31 | // 这个仅仅会执行一次,不会执行多次的,不用担心 32 | close(out) 33 | }() 34 | return out 35 | } 36 | -------------------------------------------------------------------------------- /06.(重点)慕课网-Google资深工程师深度讲解Go语言/04.函数式编程/1.斐波那契数列.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func fibonacci() func() int { 6 | a, b := 0, 1 7 | return func() int { 8 | a, b = b, a+b 9 | return a 10 | } 11 | } 12 | 13 | func main() { 14 | // 创建斐波那契的对象方法 15 | f := fibonacci() 16 | fmt.Println(f()) 17 | fmt.Println(f()) 18 | fmt.Println(f()) 19 | fmt.Println(f()) 20 | fmt.Println(f()) 21 | fmt.Println(f()) 22 | fmt.Println(f()) 23 | fmt.Println(f()) 24 | 25 | } 26 | -------------------------------------------------------------------------------- /06.(重点)慕课网-Google资深工程师深度讲解Go语言/04.函数式编程/2.为函数实现接口.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "bufio" 5 | "fmt" 6 | "io" 7 | "strings" 8 | ) 9 | 10 | func fibonacci2() intGen { 11 | a, b := 0, 1 12 | return func() int { 13 | a, b = b, a+b 14 | return a 15 | } 16 | } 17 | 18 | type intGen func() int 19 | 20 | // 函数也能进行接口的实现 21 | func (g intGen) Read(p []byte) (n int, err error) { 22 | next := g() //由于这里会不断的读,所以需要进行隔断 23 | if next > 10000 { 24 | return 0, io.EOF 25 | } 26 | s := fmt.Sprintf("%d\n", next) 27 | // todo:如果数值太小的时候,会出错,因为[]byte作为缓存起来了,不够大,不输出 28 | return strings.NewReader(s).Read(p) 29 | } 30 | 31 | func printFileContents(reader io.Reader) { 32 | scanner := bufio.NewScanner(reader) 33 | for scanner.Scan() { 34 | fmt.Println(scanner.Text()) 35 | } 36 | } 37 | 38 | func main() { 39 | f := fibonacci2() 40 | printFileContents(f) 41 | } 42 | -------------------------------------------------------------------------------- /06.(重点)慕课网-Google资深工程师深度讲解Go语言/04.函数式编程/3.使用函数来遍历二叉树.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | func main() { 4 | 5 | } 6 | -------------------------------------------------------------------------------- /06.(重点)慕课网-Google资深工程师深度讲解Go语言/04.函数式编程/adder/adder.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func adder() func(int) int { 6 | sum := 0 7 | return func(v int) int { 8 | sum += v 9 | return sum 10 | } 11 | } 12 | 13 | // 正统函数式编程的写法(没有变量,只有常量和函数,函数只有一个参数) 14 | type iAdder func(int) (int, iAdder) 15 | 16 | func adder2(base int) iAdder { 17 | return func(v int) (int, iAdder) { 18 | return base + v, adder2(base + v) 19 | } 20 | } 21 | 22 | func main() { 23 | a := adder() 24 | for i := 0; i < 10; i++ { 25 | fmt.Printf("0+1+...+%d = %d\n", i, a(i)) 26 | } 27 | fmt.Println("") 28 | //正统函数式编程写法 29 | a2 := adder2(0) 30 | for i := 0; i < 10; i++ { 31 | var s int 32 | s, a2 = a2(i) 33 | fmt.Printf("0+1+...+%d = %d\n", i, s) 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /06.(重点)慕课网-Google资深工程师深度讲解Go语言/05.资源管理与出错处理/04.cover.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | ) 6 | 7 | func tryRecover() { 8 | defer func() { 9 | r := recover() 10 | if err, ok := r.(error); ok { 11 | fmt.Println(err) 12 | } else { 13 | // 如果不是error,直接执行panic 14 | panic(fmt.Sprintf("I don't know what to do :%v", r)) 15 | } 16 | }() 17 | // panic(errors.New("This is An Error")) 18 | panic(123) 19 | b := 0 20 | fmt.Println(5 / b) 21 | } 22 | 23 | func main() { 24 | tryRecover() 25 | } 26 | -------------------------------------------------------------------------------- /06.(重点)慕课网-Google资深工程师深度讲解Go语言/07.生成文档与实例代码/queue.go: -------------------------------------------------------------------------------- 1 | package queue 2 | 3 | type Queue []int 4 | 5 | func (q *Queue) Push(v int) { 6 | *q = append(*q, v) 7 | } 8 | 9 | func (q *Queue) Pop() int { 10 | head := (*q)[0] 11 | *q = (*q)[1:] 12 | return head 13 | } 14 | 15 | func (q *Queue) IsEmpty() bool { 16 | return len(*q) == 0 17 | } 18 | -------------------------------------------------------------------------------- /06.(重点)慕课网-Google资深工程师深度讲解Go语言/07.生成文档与实例代码/queue_test.go: -------------------------------------------------------------------------------- 1 | package queue 2 | 3 | import "fmt" 4 | 5 | func ExampleQueue_Pop() { 6 | q := Queue{1} 7 | q.Push(2) 8 | q.Push(3) 9 | fmt.Println(q.Pop()) 10 | fmt.Println(q.Pop()) 11 | fmt.Println(q.IsEmpty()) 12 | 13 | fmt.Println(q.Pop()) 14 | fmt.Println(q.IsEmpty()) 15 | 16 | // Output: 17 | // 1 18 | // 2 19 | // false 20 | // 3 21 | // true 22 | } 23 | -------------------------------------------------------------------------------- /06.(重点)慕课网-Google资深工程师深度讲解Go语言/08.goroutine/01.simple.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "time" 6 | ) 7 | 8 | func main() { 9 | var a [10]int 10 | for i := 0; i < 10; i++ { 11 | go func(i int) { 12 | for { 13 | a[i]++ 14 | } 15 | }(i) 16 | } 17 | time.Sleep(time.Millisecond) 18 | fmt.Println(a) 19 | } 20 | -------------------------------------------------------------------------------- /06.(重点)慕课网-Google资深工程师深度讲解Go语言/09.channel/01.entry/01.channnel.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "time" 6 | ) 7 | 8 | func worker(id int, c chan int) { 9 | for { 10 | fmt.Printf("Worker %d received %c \n", id, <-c) 11 | } 12 | } 13 | 14 | func chanDemo() { 15 | var channels [10]chan int 16 | for i := 0; i < 10; i++ { 17 | channels[i] = make(chan int) 18 | go worker(i, channels[i]) 19 | } 20 | for i := 0; i < 10; i++ { 21 | channels[i] <- 'a' + i 22 | } 23 | for i := 0; i < 10; i++ { 24 | channels[i] <- 'A' + i 25 | } 26 | time.Sleep(time.Second) 27 | } 28 | 29 | func main() { 30 | chanDemo() 31 | } 32 | -------------------------------------------------------------------------------- /06.(重点)慕课网-Google资深工程师深度讲解Go语言/09.channel/02.entry/02.channnel.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "time" 6 | ) 7 | 8 | func createWorker(id int) chan<- int { 9 | c := make(chan int) 10 | go func() { 11 | for { 12 | fmt.Printf("Worker %d received %c \n", id, <-c) 13 | } 14 | }() 15 | return c 16 | } 17 | 18 | func chanDemo() { 19 | var channels [10]chan<- int 20 | for i := 0; i < 10; i++ { 21 | channels[i] = createWorker(i) 22 | } 23 | for i := 0; i < 10; i++ { 24 | channels[i] <- 'a' + i 25 | } 26 | for i := 0; i < 10; i++ { 27 | channels[i] <- 'A' + i 28 | } 29 | time.Sleep(10 * time.Second) 30 | } 31 | 32 | func main() { 33 | chanDemo() 34 | } 35 | -------------------------------------------------------------------------------- /06.(重点)慕课网-Google资深工程师深度讲解Go语言/09.channel/03.entry/bufferedChannel.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "time" 6 | ) 7 | 8 | //func worker(id int, c <-chan int) { 9 | // for { 10 | // val, ok := <-c 11 | // if !ok { 12 | // break 13 | // } 14 | // fmt.Printf("Worker %d received %d \n", id, val) 15 | // } 16 | //} 17 | 18 | func worker(id int, c <-chan int) { 19 | for { 20 | for val := range c { 21 | fmt.Printf("Worker %d received %d \n", id, val) 22 | } 23 | } 24 | } 25 | 26 | func createWorker(id int) chan<- int { 27 | c := make(chan int) 28 | go worker(id, c) 29 | return c 30 | } 31 | 32 | func channelClose() { 33 | 34 | } 35 | 36 | func bufferedChannel() { 37 | c := make(chan int, 3) 38 | go worker(0, c) 39 | c <- 1 40 | c <- 2 41 | c <- 3 42 | c <- 4 43 | c <- 5 44 | close(c) 45 | time.Sleep(time.Second) 46 | } 47 | 48 | func main() { 49 | bufferedChannel() 50 | } 51 | -------------------------------------------------------------------------------- /06.(重点)慕课网-Google资深工程师深度讲解Go语言/09.channel/07.tree/node.go: -------------------------------------------------------------------------------- 1 | package _1_tree 2 | 3 | import ( 4 | "fmt" 5 | ) 6 | 7 | type TreeNode struct { 8 | Value int 9 | Left, Right *TreeNode 10 | } 11 | 12 | // 工厂方法创建对象 13 | func CreateNode(value int) *TreeNode { 14 | return &TreeNode{Value: value} 15 | } 16 | 17 | func (node TreeNode) Print() { 18 | fmt.Print(node.Value, " ") 19 | } 20 | 21 | func (node *TreeNode) SetValue(value int) { 22 | if node == nil { 23 | fmt.Println("Setting Value to nil node.Ignored.") 24 | } 25 | node.Value = value 26 | } 27 | -------------------------------------------------------------------------------- /06.(重点)慕课网-Google资深工程师深度讲解Go语言/09.channel/07.tree/traversal.go: -------------------------------------------------------------------------------- 1 | package _1_tree 2 | 3 | import "fmt" 4 | 5 | // 遍历tree 6 | func (node *TreeNode) Traverse() { 7 | node.TraverseFunc(func(node *TreeNode) { 8 | node.Print() 9 | }) 10 | fmt.Println() 11 | } 12 | 13 | func (node *TreeNode) TraverseFunc(f func(node *TreeNode)) { 14 | if node == nil { 15 | return 16 | } 17 | node.Left.Traverse() 18 | f(node) 19 | node.Right.Traverse() 20 | } 21 | -------------------------------------------------------------------------------- /06.(重点)慕课网-Google资深工程师深度讲解Go语言/11.传统同步机制/01.entry/01.atomic.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "time" 6 | ) 7 | 8 | // 读写容易产生冲突 9 | type atomicInt int 10 | 11 | func (a *atomicInt) increment() { 12 | *a++ 13 | } 14 | 15 | func (a *atomicInt) get() int { 16 | return int(*a) 17 | } 18 | 19 | // 运行后存在冲突 20 | func main() { 21 | var a atomicInt 22 | a.increment() 23 | go func() { 24 | a.increment() 25 | }() 26 | time.Sleep(time.Millisecond) 27 | fmt.Println(a) 28 | } 29 | -------------------------------------------------------------------------------- /06.(重点)慕课网-Google资深工程师深度讲解Go语言/11.传统同步机制/02.entry/02.atomic-mutex.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "sync" 6 | "time" 7 | ) 8 | 9 | type atomicInt struct { 10 | value int 11 | lock sync.Mutex 12 | } 13 | 14 | func (a *atomicInt) increment() { 15 | fmt.Println("啦啦啦啦,逻辑代码") 16 | func() { 17 | a.lock.Lock() 18 | defer a.lock.Unlock() 19 | a.value++ 20 | }() 21 | fmt.Println("啦啦啦啦,逻辑代码") 22 | } 23 | 24 | func (a *atomicInt) get() int { 25 | fmt.Println("啦啦啦啦,逻辑代码") 26 | a.lock.Lock() 27 | // 这个锁在函数执行完的最后才执行,可能会影响后面的代码,因为阻塞了,所以我们采用匿名函数的方式并执行的方式解决问题 28 | defer a.lock.Unlock() 29 | fmt.Println("啦啦啦啦,逻辑代码") 30 | return a.value 31 | } 32 | 33 | // 运行后存在冲突 34 | func main() { 35 | var a atomicInt 36 | a.increment() 37 | go func() { 38 | a.increment() 39 | }() 40 | time.Sleep(time.Millisecond) 41 | fmt.Println(a.get()) 42 | } 43 | -------------------------------------------------------------------------------- /06.(重点)慕课网-Google资深工程师深度讲解Go语言/12.Golang标准库/01.entry/01.httpclient-get.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "net/http" 6 | "net/http/httputil" 7 | ) 8 | 9 | func main() { 10 | request, err := http.NewRequest( 11 | http.MethodGet, 12 | "http://www.imooc.com", nil, 13 | ) 14 | request.Header.Add("User-Agent", 15 | "Mozilla/5.0 (Linux; Android 5.0; SM-G900P Build/LRX21T) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/48.0.2564.23 Mobile Safari/537.36") 16 | 17 | client := http.Client{ 18 | CheckRedirect: func(req *http.Request, 19 | via []*http.Request) error { 20 | fmt.Println("Redirect : ", req) 21 | return nil 22 | }, 23 | } 24 | 25 | resp, err := client.Do(request) 26 | if err != nil { 27 | panic(err) 28 | } 29 | defer resp.Body.Close() 30 | s, err := httputil.DumpResponse(resp, true) 31 | if err != nil { 32 | panic(err) 33 | } 34 | fmt.Printf("%s\n", s) 35 | } 36 | -------------------------------------------------------------------------------- /06.(重点)慕课网-Google资深工程师深度讲解Go语言/12.Golang标准库/test.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "encoding/binary" 5 | "fmt" 6 | "math" 7 | ) 8 | 9 | func main() { 10 | arr := []byte{51, 46, 52} 11 | bits := binary.BigEndian.Uint32(arr) 12 | value := math.Float32frombits(bits) 13 | fmt.Println(value) 14 | } 15 | -------------------------------------------------------------------------------- /06.(重点)慕课网-Google资深工程师深度讲解Go语言/13.迷宫-广度优先算法/migong.ini: -------------------------------------------------------------------------------- 1 | 6 5 2 | 0 1 0 0 0 3 | 0 0 0 1 0 4 | 0 1 0 1 0 5 | 1 1 1 0 0 6 | 0 1 0 0 1 7 | 0 1 0 0 0 -------------------------------------------------------------------------------- /06.(重点)慕课网-Google资深工程师深度讲解Go语言/14.正则表达式/regex.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "regexp" 6 | ) 7 | 8 | //const text = "My email is ccmouse@gmail.com" 9 | const text = ` 10 | My email is ccmouse@gmail.com 11 | email2: abc@126.com 12 | email3: def@163.com.cn 13 | ` 14 | 15 | func main() { 16 | // 1.普通搜索 17 | // re, _ := regexp.Compile(`[0-9A-Za-z]+@[0-9A-Za-z.]+\.[0-9A-Za-z]+`) 18 | // 2. 部分提取 -子匹配 19 | re, _ := regexp.Compile(`([0-9A-Za-z]+)@([0-9A-Za-z]+)(\.[0-9A-Za-z]+)`) 20 | // 1. 21 | //match := re.FindString(text) 22 | // 1. 23 | //match := re.FindAllString(text, -1) 24 | // 2. 搜索子匹配 返回的是一个二维的数组 25 | match := re.FindAllStringSubmatch(text, -1) 26 | for _, m := range match { 27 | fmt.Println(m) 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /06.(重点)慕课网-Google资深工程师深度讲解Go语言/15.爬虫实现--单任务版-并发版/crawler(暂时无用了)/.gitignore: -------------------------------------------------------------------------------- 1 | /vendor -------------------------------------------------------------------------------- /06.(重点)慕课网-Google资深工程师深度讲解Go语言/15.爬虫实现--单任务版-并发版/crawler(暂时无用了)/config/config.go: -------------------------------------------------------------------------------- 1 | package config 2 | 3 | const ( 4 | // Parser names 5 | ParseCity = "ParseCity" 6 | ParseCityList = "ParseCityList" 7 | ParseProfile = "ParseProfile" 8 | NilParser = "NilParser" 9 | 10 | // ElasticSearch 11 | ElasticIndex = "dating_profile" 12 | 13 | // Rate limiting 14 | Qps = 20 15 | ) 16 | -------------------------------------------------------------------------------- /06.(重点)慕课网-Google资深工程师深度讲解Go语言/15.爬虫实现--单任务版-并发版/crawler(暂时无用了)/engine/types.go: -------------------------------------------------------------------------------- 1 | package engine 2 | 3 | type Request struct { 4 | Url string 5 | ParserFunc func([]byte) ParseResult 6 | } 7 | 8 | type ParseResult struct { 9 | Requests []Request 10 | Items []Item 11 | } 12 | 13 | // 方法作用 :创建一个空的parse,这样是为了安全的定义类型 14 | func NilParser([]byte) ParseResult { 15 | return ParseResult{} 16 | } 17 | 18 | type Item struct { 19 | Url string 20 | Type string 21 | Id string 22 | Payload interface{} 23 | } 24 | -------------------------------------------------------------------------------- /06.(重点)慕课网-Google资深工程师深度讲解Go语言/15.爬虫实现--单任务版-并发版/crawler(暂时无用了)/glide.yaml: -------------------------------------------------------------------------------- 1 | glipackage: baseLearn/15.爬虫实现--单任务版-并发版/crawler(c) 2 | import: 3 | - package: golang.org/x/net/html/charset 4 | - package: golang.org/x/text/encoding 5 | subpackages: 6 | - unicode 7 | - package: golang.org/x/text/transform 8 | -------------------------------------------------------------------------------- /06.(重点)慕课网-Google资深工程师深度讲解Go语言/15.爬虫实现--单任务版-并发版/crawler(暂时无用了)/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "baseLearn/15.爬虫实现--单任务版-并发版/crawler(暂时无用了)/engine" 5 | "baseLearn/15.爬虫实现--单任务版-并发版/crawler(暂时无用了)/persist" 6 | "baseLearn/15.爬虫实现--单任务版-并发版/crawler(暂时无用了)/scheduler" 7 | "baseLearn/15.爬虫实现--单任务版-并发版/crawler(暂时无用了)/zhenai/parse" 8 | ) 9 | 10 | func main() { 11 | e := engine.ConcurrentEngine{ 12 | //Scheduler: &scheduler.SimpleScheduler{}, 13 | Scheduler: &scheduler.QueuedScheduler{}, 14 | WorkerCount: 100, 15 | ItemChan: persist.ItemSaver(), 16 | } 17 | 18 | e.Run(engine.Request{ 19 | Url: "http://www.zhenai.com/zhenghun", 20 | ParserFunc: parse.ParseCityList, 21 | }) 22 | 23 | //e.Run(engine.Request{ 24 | // Url: "http://www.zhenai.com/zhenghun/shanghai", 25 | // ParserFunc: parse.ParseCity, 26 | //}) 27 | } 28 | -------------------------------------------------------------------------------- /06.(重点)慕课网-Google资深工程师深度讲解Go语言/15.爬虫实现--单任务版-并发版/crawler(暂时无用了)/model/profile.go: -------------------------------------------------------------------------------- 1 | package model 2 | 3 | import "encoding/json" 4 | 5 | type Profile struct { 6 | Url string 7 | Id string 8 | 9 | Name string 10 | Gender string 11 | Age int 12 | Height int 13 | Weight int 14 | Income string 15 | Marriage string 16 | Education string 17 | Occupation string 18 | Hukou string 19 | Xinzuo string 20 | House string 21 | Car string 22 | } 23 | 24 | // 将陌生的字符串转为对象的json字符串 25 | func FromJsonObj(o interface{}) (Profile, error) { 26 | var profile Profile 27 | s, err := json.Marshal(o) 28 | if err != nil { 29 | return profile, err 30 | } 31 | err = json.Unmarshal(s, &profile) 32 | return profile, err 33 | } 34 | -------------------------------------------------------------------------------- /06.(重点)慕课网-Google资深工程师深度讲解Go语言/15.爬虫实现--单任务版-并发版/crawler(暂时无用了)/scheduler/simple.go: -------------------------------------------------------------------------------- 1 | package scheduler 2 | 3 | import "baseLearn/15.爬虫实现--单任务版-并发版/crawler(暂时无用了)/engine" 4 | 5 | type SimpleScheduler struct { 6 | workerChan chan engine.Request 7 | } 8 | 9 | func (s *SimpleScheduler) WorkerChan() chan engine.Request { 10 | return s.workerChan 11 | } 12 | 13 | func (s *SimpleScheduler) WorkerReady(chan engine.Request) { 14 | } 15 | 16 | func (s *SimpleScheduler) Run() { 17 | s.workerChan = make(chan engine.Request) 18 | } 19 | 20 | func (s *SimpleScheduler) Submit(request engine.Request) { 21 | // send request down to worker chan 22 | go func() { s.workerChan <- request }() 23 | } 24 | -------------------------------------------------------------------------------- /06.(重点)慕课网-Google资深工程师深度讲解Go语言/15.爬虫实现--单任务版-并发版/crawler(暂时无用了)/zhenai/parse/citylist.go: -------------------------------------------------------------------------------- 1 | package parse 2 | 3 | import ( 4 | "regexp" 5 | 6 | "baseLearn/15.爬虫实现--单任务版-并发版/crawler(暂时无用了)/engine" 7 | ) 8 | 9 | const cityListRe = `]*>([^<]+)` 10 | 11 | // 解析城市列表的内容 12 | func ParseCityList(contents []byte) engine.ParseResult { 13 | re := regexp.MustCompile(cityListRe) 14 | matches := re.FindAllSubmatch(contents, -1) 15 | result := engine.ParseResult{} 16 | //limit := 10 17 | for _, m := range matches { 18 | // 返回城市的名字 19 | //result.Items = append(result.Items, "City "+string(m[2])) 20 | result.Requests = append(result.Requests, engine.Request{ 21 | Url: string(m[1]), 22 | ParserFunc: ParseCity, 23 | }) 24 | // 减少页数,使尽快出Profile数据 25 | //limit-- 26 | //if limit == 0 { 27 | // break 28 | //} 29 | } 30 | return result 31 | } 32 | -------------------------------------------------------------------------------- /06.(重点)慕课网-Google资深工程师深度讲解Go语言/15.爬虫实现--单任务版-并发版/crawler/.gitignore: -------------------------------------------------------------------------------- 1 | /vendor -------------------------------------------------------------------------------- /06.(重点)慕课网-Google资深工程师深度讲解Go语言/15.爬虫实现--单任务版-并发版/crawler/config/config.go: -------------------------------------------------------------------------------- 1 | package config 2 | 3 | const ( 4 | // Parser names 5 | ParseCity = "ParseCity" 6 | ParseCityList = "ParseCityList" 7 | ParseProfile = "ParseProfile" 8 | NilParser = "NilParser" 9 | 10 | // ElasticSearch 11 | ElasticIndex = "dating_profile" 12 | 13 | // Rate limiting 14 | Qps = 20 15 | ) 16 | -------------------------------------------------------------------------------- /06.(重点)慕课网-Google资深工程师深度讲解Go语言/15.爬虫实现--单任务版-并发版/crawler/engine/simple.go: -------------------------------------------------------------------------------- 1 | package engine 2 | 3 | import ( 4 | "log" 5 | ) 6 | 7 | type SimpleEngine struct{} 8 | 9 | func (e SimpleEngine) Run(seeds ...Request) { 10 | var requests []Request 11 | for _, r := range seeds { 12 | requests = append(requests, r) 13 | } 14 | 15 | for len(requests) > 0 { 16 | r := requests[0] 17 | requests = requests[1:] 18 | 19 | parseResult, err := Worker(r) 20 | if err != nil { 21 | continue 22 | } 23 | 24 | requests = append(requests, 25 | parseResult.Requests...) 26 | 27 | for _, item := range parseResult.Items { 28 | log.Printf("Got item: %v", item) 29 | } 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /06.(重点)慕课网-Google资深工程师深度讲解Go语言/15.爬虫实现--单任务版-并发版/crawler/engine/worker.go: -------------------------------------------------------------------------------- 1 | package engine 2 | 3 | import ( 4 | "log" 5 | 6 | "baseLearn/15.爬虫实现--单任务版-并发版/crawler/fetcher" 7 | ) 8 | 9 | func Worker(r Request) (ParseResult, error) { 10 | body, err := fetcher.Fetch(r.Url) 11 | if err != nil { 12 | log.Printf("Fetcher: error "+ 13 | "fetching url %s: %v", 14 | r.Url, err) 15 | return ParseResult{}, err 16 | } 17 | 18 | return r.Parser.Parse(body, r.Url), nil 19 | } 20 | -------------------------------------------------------------------------------- /06.(重点)慕课网-Google资深工程师深度讲解Go语言/15.爬虫实现--单任务版-并发版/crawler/frontend/model/page.go: -------------------------------------------------------------------------------- 1 | package model 2 | 3 | type SearchResult struct { 4 | Hits int64 5 | Start int 6 | Query string 7 | PrevFrom int 8 | NextFrom int 9 | Items []interface{} 10 | } 11 | -------------------------------------------------------------------------------- /06.(重点)慕课网-Google资深工程师深度讲解Go语言/15.爬虫实现--单任务版-并发版/crawler/frontend/starter.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "net/http" 5 | 6 | "baseLearn/15.爬虫实现--单任务版-并发版/crawler/frontend/controller" 7 | ) 8 | 9 | func main() { 10 | http.Handle("/", http.FileServer( 11 | http.Dir("crawler/frontend/view"))) 12 | http.Handle("/search", 13 | controller.CreateSearchResultHandler( 14 | "crawler/frontend/view/template.html")) 15 | err := http.ListenAndServe(":8888", nil) 16 | if err != nil { 17 | panic(err) 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /06.(重点)慕课网-Google资深工程师深度讲解Go语言/15.爬虫实现--单任务版-并发版/crawler/frontend/view/logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Goular/GolangModule/6f5ea735e919e4d2521b85ebb470a012bc05baf3/06.(重点)慕课网-Google资深工程师深度讲解Go语言/15.爬虫实现--单任务版-并发版/crawler/frontend/view/logo.png -------------------------------------------------------------------------------- /06.(重点)慕课网-Google资深工程师深度讲解Go语言/15.爬虫实现--单任务版-并发版/crawler/frontend/view/searchresult.go: -------------------------------------------------------------------------------- 1 | package view 2 | 3 | import ( 4 | "html/template" 5 | "io" 6 | 7 | "baseLearn/15.爬虫实现--单任务版-并发版/crawler/frontend/model" 8 | ) 9 | 10 | type SearchResultView struct { 11 | template *template.Template 12 | } 13 | 14 | func CreateSearchResultView( 15 | filename string) SearchResultView { 16 | return SearchResultView{ 17 | template: template.Must( 18 | template.ParseFiles(filename)), 19 | } 20 | } 21 | 22 | func (s SearchResultView) Render( 23 | w io.Writer, data model.SearchResult) error { 24 | return s.template.Execute(w, data) 25 | } 26 | -------------------------------------------------------------------------------- /06.(重点)慕课网-Google资深工程师深度讲解Go语言/15.爬虫实现--单任务版-并发版/crawler/glide.yaml: -------------------------------------------------------------------------------- 1 | glipackage: baseLearn/15.爬虫实现--单任务版-并发版/crawler(c) 2 | import: 3 | - package: golang.org/x/net/html/charset 4 | - package: golang.org/x/text/encoding 5 | subpackages: 6 | - unicode 7 | - package: golang.org/x/text/transform 8 | -------------------------------------------------------------------------------- /06.(重点)慕课网-Google资深工程师深度讲解Go语言/15.爬虫实现--单任务版-并发版/crawler/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "baseLearn/15.爬虫实现--单任务版-并发版/crawler/config" 5 | "baseLearn/15.爬虫实现--单任务版-并发版/crawler/engine" 6 | "baseLearn/15.爬虫实现--单任务版-并发版/crawler/persist" 7 | "baseLearn/15.爬虫实现--单任务版-并发版/crawler/scheduler" 8 | "baseLearn/15.爬虫实现--单任务版-并发版/crawler/zhenai/parser" 9 | ) 10 | 11 | func main() { 12 | itemChan, err := persist.ItemSaver( 13 | config.ElasticIndex) 14 | if err != nil { 15 | panic(err) 16 | } 17 | 18 | e := engine.ConcurrentEngine{ 19 | Scheduler: &scheduler.QueuedScheduler{}, 20 | WorkerCount: 100, 21 | ItemChan: itemChan, 22 | RequestProcessor: engine.Worker, 23 | } 24 | 25 | e.Run(engine.Request{ 26 | Url: "http://www.zhenai.com/zhenghun", 27 | Parser: engine.NewFuncParser( 28 | parser.ParseCityList, 29 | config.ParseCityList), 30 | }) 31 | } 32 | -------------------------------------------------------------------------------- /06.(重点)慕课网-Google资深工程师深度讲解Go语言/15.爬虫实现--单任务版-并发版/crawler/model/profile.go: -------------------------------------------------------------------------------- 1 | package model 2 | 3 | import "encoding/json" 4 | 5 | type Profile struct { 6 | Name string 7 | Gender string 8 | Age int 9 | Height int 10 | Weight int 11 | Income string 12 | Marriage string 13 | Education string 14 | Occupation string 15 | Hokou string 16 | Xinzuo string 17 | House string 18 | Car string 19 | } 20 | 21 | func FromJsonObj(o interface{}) (Profile, error) { 22 | var profile Profile 23 | s, err := json.Marshal(o) 24 | if err != nil { 25 | return profile, err 26 | } 27 | err = json.Unmarshal(s, &profile) 28 | return profile, err 29 | } 30 | -------------------------------------------------------------------------------- /06.(重点)慕课网-Google资深工程师深度讲解Go语言/15.爬虫实现--单任务版-并发版/crawler/scheduler/simple.go: -------------------------------------------------------------------------------- 1 | package scheduler 2 | 3 | import "baseLearn/15.爬虫实现--单任务版-并发版/crawler/engine" 4 | 5 | type SimpleScheduler struct { 6 | workerChan chan engine.Request 7 | } 8 | 9 | func (s *SimpleScheduler) WorkerChan() chan engine.Request { 10 | return s.workerChan 11 | } 12 | 13 | func (s *SimpleScheduler) WorkerReady(chan engine.Request) { 14 | } 15 | 16 | func (s *SimpleScheduler) Run() { 17 | s.workerChan = make(chan engine.Request) 18 | } 19 | 20 | func (s *SimpleScheduler) Submit( 21 | r engine.Request) { 22 | go func() { s.workerChan <- r }() 23 | } 24 | -------------------------------------------------------------------------------- /06.(重点)慕课网-Google资深工程师深度讲解Go语言/15.爬虫实现--单任务版-并发版/crawler/zhenai/parser/citylist.go: -------------------------------------------------------------------------------- 1 | package parser 2 | 3 | import ( 4 | "regexp" 5 | 6 | "baseLearn/15.爬虫实现--单任务版-并发版/crawler/config" 7 | "baseLearn/15.爬虫实现--单任务版-并发版/crawler/engine" 8 | ) 9 | 10 | const cityListRe = `]*>([^<]+)` 11 | 12 | func ParseCityList( 13 | contents []byte, _ string) engine.ParseResult { 14 | re := regexp.MustCompile(cityListRe) 15 | matches := re.FindAllSubmatch(contents, -1) 16 | 17 | result := engine.ParseResult{} 18 | for _, m := range matches { 19 | result.Requests = append( 20 | result.Requests, engine.Request{ 21 | Url: string(m[1]), 22 | Parser: engine.NewFuncParser( 23 | ParseCity, config.ParseCity), 24 | }) 25 | } 26 | 27 | return result 28 | } 29 | -------------------------------------------------------------------------------- /06.(重点)慕课网-Google资深工程师深度讲解Go语言/16.分布式爬搭建/crawler/.gitignore: -------------------------------------------------------------------------------- 1 | /vendor -------------------------------------------------------------------------------- /06.(重点)慕课网-Google资深工程师深度讲解Go语言/16.分布式爬搭建/crawler/config/config.go: -------------------------------------------------------------------------------- 1 | package config 2 | 3 | const ( 4 | // Parser names 5 | ParseCity = "ParseCity" 6 | ParseCityList = "ParseCityList" 7 | ParseProfile = "ParseProfile" 8 | NilParser = "NilParser" 9 | 10 | // ElasticSearch 11 | ElasticIndex = "dating_profile" 12 | 13 | // Rate limiting 14 | Qps = 20 15 | 16 | // ElasticSearch 17 | ItemSaverPort = 1234 18 | // RPC EndPoint 19 | WorkerPort0 = 9000 20 | ) 21 | -------------------------------------------------------------------------------- /06.(重点)慕课网-Google资深工程师深度讲解Go语言/16.分布式爬搭建/crawler/engine/simple.go: -------------------------------------------------------------------------------- 1 | package engine 2 | 3 | import ( 4 | "log" 5 | ) 6 | 7 | type SimpleEngine struct{} 8 | 9 | func (e SimpleEngine) Run(seeds ...Request) { 10 | var requests []Request 11 | for _, r := range seeds { 12 | requests = append(requests, r) 13 | } 14 | 15 | for len(requests) > 0 { 16 | r := requests[0] 17 | requests = requests[1:] 18 | 19 | parseResult, err := Worker(r) 20 | if err != nil { 21 | continue 22 | } 23 | 24 | requests = append(requests, 25 | parseResult.Requests...) 26 | 27 | for _, item := range parseResult.Items { 28 | log.Printf("Got item: %v", item) 29 | } 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /06.(重点)慕课网-Google资深工程师深度讲解Go语言/16.分布式爬搭建/crawler/engine/worker.go: -------------------------------------------------------------------------------- 1 | package engine 2 | 3 | import ( 4 | "log" 5 | 6 | "baseLearn/16.分布式爬搭建/crawler/fetcher" 7 | ) 8 | 9 | func Worker(r Request) (ParseResult, error) { 10 | body, err := fetcher.Fetch(r.Url) 11 | if err != nil { 12 | log.Printf("Fetcher: error "+ 13 | "fetching url %s: %v", 14 | r.Url, err) 15 | return ParseResult{}, err 16 | } 17 | 18 | return r.Parser.Parse(body, r.Url), nil 19 | } 20 | -------------------------------------------------------------------------------- /06.(重点)慕课网-Google资深工程师深度讲解Go语言/16.分布式爬搭建/crawler/frontend/model/page.go: -------------------------------------------------------------------------------- 1 | package model 2 | 3 | type SearchResult struct { 4 | Hits int64 5 | Start int 6 | Query string 7 | PrevFrom int 8 | NextFrom int 9 | Items []interface{} 10 | } 11 | -------------------------------------------------------------------------------- /06.(重点)慕课网-Google资深工程师深度讲解Go语言/16.分布式爬搭建/crawler/frontend/starter.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "net/http" 5 | 6 | "baseLearn/16.分布式爬搭建/crawler/frontend/controller" 7 | ) 8 | 9 | func main() { 10 | http.Handle("/", http.FileServer( 11 | http.Dir("crawler/frontend/view"))) 12 | http.Handle("/search", 13 | controller.CreateSearchResultHandler( 14 | "crawler/frontend/view/template.html")) 15 | err := http.ListenAndServe(":8888", nil) 16 | if err != nil { 17 | panic(err) 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /06.(重点)慕课网-Google资深工程师深度讲解Go语言/16.分布式爬搭建/crawler/frontend/view/logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Goular/GolangModule/6f5ea735e919e4d2521b85ebb470a012bc05baf3/06.(重点)慕课网-Google资深工程师深度讲解Go语言/16.分布式爬搭建/crawler/frontend/view/logo.png -------------------------------------------------------------------------------- /06.(重点)慕课网-Google资深工程师深度讲解Go语言/16.分布式爬搭建/crawler/frontend/view/searchresult.go: -------------------------------------------------------------------------------- 1 | package view 2 | 3 | import ( 4 | "html/template" 5 | "io" 6 | 7 | "baseLearn/16.分布式爬搭建/crawler/frontend/model" 8 | ) 9 | 10 | type SearchResultView struct { 11 | template *template.Template 12 | } 13 | 14 | func CreateSearchResultView( 15 | filename string) SearchResultView { 16 | return SearchResultView{ 17 | template: template.Must( 18 | template.ParseFiles(filename)), 19 | } 20 | } 21 | 22 | func (s SearchResultView) Render( 23 | w io.Writer, data model.SearchResult) error { 24 | return s.template.Execute(w, data) 25 | } 26 | -------------------------------------------------------------------------------- /06.(重点)慕课网-Google资深工程师深度讲解Go语言/16.分布式爬搭建/crawler/glide.yaml: -------------------------------------------------------------------------------- 1 | glipackage: baseLearn/15.爬虫实现--单任务版-并发版/crawler(c) 2 | import: 3 | - package: golang.org/x/net/html/charset 4 | - package: golang.org/x/text/encoding 5 | subpackages: 6 | - unicode 7 | - package: golang.org/x/text/transform 8 | -------------------------------------------------------------------------------- /06.(重点)慕课网-Google资深工程师深度讲解Go语言/16.分布式爬搭建/crawler/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "baseLearn/16.分布式爬搭建/crawler/config" 5 | "baseLearn/16.分布式爬搭建/crawler/engine" 6 | "baseLearn/16.分布式爬搭建/crawler/persist" 7 | "baseLearn/16.分布式爬搭建/crawler/scheduler" 8 | "baseLearn/16.分布式爬搭建/crawler/zhenai/parser" 9 | ) 10 | 11 | // 单机版 12 | func main() { 13 | itemChan, err := persist.ItemSaver( 14 | config.ElasticIndex) 15 | if err != nil { 16 | panic(err) 17 | } 18 | 19 | e := engine.ConcurrentEngine{ 20 | Scheduler: &scheduler.QueuedScheduler{}, 21 | WorkerCount: 100, 22 | ItemChan: itemChan, 23 | RequestProcessor: engine.Worker, 24 | } 25 | 26 | e.Run(engine.Request{ 27 | Url: "http://www.zhenai.com/zhenghun", 28 | Parser: engine.NewFuncParser( 29 | parser.ParseCityList, 30 | config.ParseCityList), 31 | }) 32 | } 33 | -------------------------------------------------------------------------------- /06.(重点)慕课网-Google资深工程师深度讲解Go语言/16.分布式爬搭建/crawler/model/profile.go: -------------------------------------------------------------------------------- 1 | package model 2 | 3 | import "encoding/json" 4 | 5 | type Profile struct { 6 | Name string 7 | Gender string 8 | Age int 9 | Height int 10 | Weight int 11 | Income string 12 | Marriage string 13 | Education string 14 | Occupation string 15 | Hokou string 16 | Xinzuo string 17 | House string 18 | Car string 19 | } 20 | 21 | func FromJsonObj(o interface{}) (Profile, error) { 22 | var profile Profile 23 | s, err := json.Marshal(o) 24 | if err != nil { 25 | return profile, err 26 | } 27 | err = json.Unmarshal(s, &profile) 28 | return profile, err 29 | } 30 | -------------------------------------------------------------------------------- /06.(重点)慕课网-Google资深工程师深度讲解Go语言/16.分布式爬搭建/crawler/scheduler/simple.go: -------------------------------------------------------------------------------- 1 | package scheduler 2 | 3 | import "baseLearn/16.分布式爬搭建/crawler/engine" 4 | 5 | type SimpleScheduler struct { 6 | workerChan chan engine.Request 7 | } 8 | 9 | func (s *SimpleScheduler) WorkerChan() chan engine.Request { 10 | return s.workerChan 11 | } 12 | 13 | func (s *SimpleScheduler) WorkerReady(chan engine.Request) { 14 | } 15 | 16 | func (s *SimpleScheduler) Run() { 17 | s.workerChan = make(chan engine.Request) 18 | } 19 | 20 | func (s *SimpleScheduler) Submit( 21 | r engine.Request) { 22 | go func() { s.workerChan <- r }() 23 | } 24 | -------------------------------------------------------------------------------- /06.(重点)慕课网-Google资深工程师深度讲解Go语言/16.分布式爬搭建/crawler/zhenai/parser/citylist.go: -------------------------------------------------------------------------------- 1 | package parser 2 | 3 | import ( 4 | "regexp" 5 | 6 | "baseLearn/16.分布式爬搭建/crawler/config" 7 | "baseLearn/16.分布式爬搭建/crawler/engine" 8 | ) 9 | 10 | const cityListRe = `]*>([^<]+)` 11 | 12 | func ParseCityList( 13 | contents []byte, _ string) engine.ParseResult { 14 | re := regexp.MustCompile(cityListRe) 15 | matches := re.FindAllSubmatch(contents, -1) 16 | 17 | result := engine.ParseResult{} 18 | for _, m := range matches { 19 | result.Requests = append( 20 | result.Requests, engine.Request{ 21 | Url: string(m[1]), 22 | Parser: engine.NewFuncParser( 23 | ParseCity, config.ParseCity), 24 | }) 25 | } 26 | 27 | return result 28 | } 29 | -------------------------------------------------------------------------------- /06.(重点)慕课网-Google资深工程师深度讲解Go语言/16.分布式爬搭建/distributed/config/config.go: -------------------------------------------------------------------------------- 1 | package config 2 | 3 | const ( 4 | ItemSaverRpc = "ItemSaverService.Save" 5 | CrawlServiceRpc = "CrawlService.Process" 6 | ) 7 | -------------------------------------------------------------------------------- /06.(重点)慕课网-Google资深工程师深度讲解Go语言/16.分布式爬搭建/distributed/persist/client/itemsaver.go: -------------------------------------------------------------------------------- 1 | package client 2 | 3 | import ( 4 | "log" 5 | 6 | "baseLearn/16.分布式爬搭建/crawler/engine" 7 | "baseLearn/16.分布式爬搭建/distributed/config" 8 | "baseLearn/16.分布式爬搭建/distributed/rpcsupport" 9 | ) 10 | 11 | func ItemSaver(host string) (chan engine.Item, error) { 12 | client, err := rpcsupport.NewClient(host) 13 | if err != nil { 14 | return nil, err 15 | } 16 | out := make(chan engine.Item) 17 | go func() { 18 | itemCount := 0 19 | for { 20 | item := <-out 21 | log.Printf("Item Saver: got item "+ 22 | "#%d: %v", itemCount, item) 23 | itemCount++ 24 | 25 | // Call RPC to Save item 26 | result := "" 27 | err := client.Call(config.ItemSaverRpc, item, &result) 28 | if err != nil { 29 | log.Printf("Item Saver: error "+ 30 | "saving item %v: %v", 31 | item, err) 32 | } 33 | } 34 | }() 35 | 36 | return out, nil 37 | } 38 | -------------------------------------------------------------------------------- /06.(重点)慕课网-Google资深工程师深度讲解Go语言/16.分布式爬搭建/distributed/persist/rpc.go: -------------------------------------------------------------------------------- 1 | package persist 2 | 3 | import ( 4 | "baseLearn/16.分布式爬搭建/crawler/engine" 5 | 6 | "log" 7 | 8 | "baseLearn/16.分布式爬搭建/crawler/persist" 9 | "gopkg.in/olivere/elastic.v5" 10 | ) 11 | 12 | type ItemSaverService struct { 13 | Client *elastic.Client 14 | Index string 15 | } 16 | 17 | func (s *ItemSaverService) Save( 18 | item engine.Item, result *string) error { 19 | err := persist.Save(s.Client, s.Index, item) 20 | log.Printf("Item %v saved.", item) 21 | if err == nil { 22 | *result = "ok" 23 | } else { 24 | log.Printf("Error saving item %v: %v", 25 | item, err) 26 | } 27 | return err 28 | } 29 | -------------------------------------------------------------------------------- /06.(重点)慕课网-Google资深工程师深度讲解Go语言/16.分布式爬搭建/distributed/worker/client/worker.go: -------------------------------------------------------------------------------- 1 | package client 2 | 3 | import ( 4 | "net/rpc" 5 | 6 | "baseLearn/16.分布式爬搭建/crawler/engine" 7 | cconfig "baseLearn/16.分布式爬搭建/distributed/config" 8 | "baseLearn/16.分布式爬搭建/distributed/worker" 9 | ) 10 | 11 | func CreateProcessor(clientChan chan *rpc.Client) engine.Processor { 12 | //client, err := rpcsupport.NewClient(fmt.Sprintf(":%d", config.WorkerPort0)) 13 | //if err != nil { 14 | // return nil, err 15 | //} 16 | return func(request engine.Request) (engine.ParseResult, error) { 17 | sReq := worker.SerializeRequest(request) 18 | var sResult worker.ParseResult 19 | c := <-clientChan 20 | err := c.Call(cconfig.CrawlServiceRpc, sReq, &sResult) 21 | if err != nil { 22 | return engine.ParseResult{}, err 23 | } 24 | return worker.DeserializeResult(sResult), nil 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /06.(重点)慕课网-Google资深工程师深度讲解Go语言/16.分布式爬搭建/distributed/worker/rpc.go: -------------------------------------------------------------------------------- 1 | package worker 2 | 3 | import "baseLearn/16.分布式爬搭建/crawler/engine" 4 | 5 | type CrawlService struct { 6 | } 7 | 8 | func (CrawlService) Process(req Request, result *ParseResult) error { 9 | engineReq, err := DeserializeRequest(req) 10 | if err != nil { 11 | return err 12 | } 13 | engineResult, err := engine.Worker(engineReq) 14 | if err != nil { 15 | return err 16 | } 17 | *result = SerializeResult(engineResult) 18 | return nil 19 | } 20 | -------------------------------------------------------------------------------- /06.(重点)慕课网-Google资深工程师深度讲解Go语言/16.分布式爬搭建/distributed/worker/server/worker.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | 6 | "log" 7 | 8 | "flag" 9 | 10 | "baseLearn/16.分布式爬搭建/distributed/rpcsupport" 11 | "baseLearn/16.分布式爬搭建/distributed/worker" 12 | ) 13 | 14 | // 创建启动配置参数,第三个参数就是我们的解析参数解析语句,使用go run xxxx.go --help即可查询 15 | var port = flag.Int("port", 0, "The port for me to Listen on") 16 | 17 | func main() { 18 | flag.Parse() 19 | if *port == 0 { 20 | fmt.Println("Must Specify a Port") 21 | return 22 | } 23 | log.Fatal(rpcsupport.ServeRpc(fmt.Sprintf(":%d", *port), worker.CrawlService{})) 24 | } 25 | -------------------------------------------------------------------------------- /06.(重点)慕课网-Google资深工程师深度讲解Go语言/16.分布式爬搭建/readme.md: -------------------------------------------------------------------------------- 1 | 启动顺序 (第三个必须最后启动不然会报错) 2 | 1.distributed/persist/itemsaver.go 3 | 2.distributed/worker/worker.go/ 4 | 3.distributed/main.go -------------------------------------------------------------------------------- /06.(重点)慕课网-Google资深工程师深度讲解Go语言/18.RPC/rpc/client/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "net" 5 | "net/rpc/jsonrpc" 6 | 7 | "fmt" 8 | 9 | "baseLearn/18.RPC/rpc" 10 | ) 11 | 12 | func main() { 13 | conn, err := net.Dial("tcp", ":1234") 14 | if err != nil { 15 | panic(err) 16 | } 17 | client := jsonrpc.NewClient(conn) 18 | var result float64 19 | err = client.Call("DemoService.Div", rpcDemo.Args{10, 3}, &result) 20 | if err != nil { 21 | fmt.Println(err) 22 | } else { 23 | fmt.Println(result) 24 | } 25 | err = client.Call("DemoService.Div", rpcDemo.Args{10, 0}, &result) 26 | if err != nil { 27 | fmt.Println(err) 28 | } else { 29 | fmt.Println(result) 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /06.(重点)慕课网-Google资深工程师深度讲解Go语言/18.RPC/rpc/rpc.go: -------------------------------------------------------------------------------- 1 | package rpcDemo 2 | 3 | import "errors" 4 | 5 | type DemoService struct { 6 | } 7 | 8 | type Args struct { 9 | A, B int 10 | } 11 | 12 | func (DemoService) Div(args Args, result *float64) error { 13 | if args.B == 0 { 14 | return errors.New("division by zero") 15 | } 16 | *result = float64(args.A) / float64(args.B) 17 | return nil 18 | } 19 | -------------------------------------------------------------------------------- /06.(重点)慕课网-Google资深工程师深度讲解Go语言/18.RPC/rpc/server/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "net/rpc" 5 | 6 | "log" 7 | "net" 8 | 9 | "net/rpc/jsonrpc" 10 | 11 | "baseLearn/18.RPC/rpc" 12 | ) 13 | 14 | func main() { 15 | rpc.Register(rpcDemo.DemoService{}) 16 | // 创建TCP连接 17 | listener, err := net.Listen("tcp", ":1234") 18 | if err != nil { 19 | panic(err) 20 | } 21 | for { 22 | conn, err := listener.Accept() 23 | if err != nil { 24 | log.Printf("accept error :%v", err) 25 | continue 26 | } 27 | // 为了不阻塞tcp所以我们开一个协程进行处理 28 | go jsonrpc.ServeConn(conn) 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /06.(重点)慕课网-Google资深工程师深度讲解Go语言/fib.txt: -------------------------------------------------------------------------------- 1 | 1 2 | 1 3 | 2 4 | 3 5 | 5 6 | 8 7 | 13 8 | 21 9 | 34 10 | 55 11 | 89 12 | 144 13 | 233 14 | 377 15 | 610 16 | 987 17 | 1597 18 | 2584 19 | 4181 20 | 6765 21 | -------------------------------------------------------------------------------- /06.(重点)慕课网-Google资深工程师深度讲解Go语言/深度讲解Golang笔记.docx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Goular/GolangModule/6f5ea735e919e4d2521b85ebb470a012bc05baf3/06.(重点)慕课网-Google资深工程师深度讲解Go语言/深度讲解Golang笔记.docx -------------------------------------------------------------------------------- /07.基于Golang协程实现流量统计系统/StatisticalSystemWithCSP/01.并发编程/01/01.HelloWorld.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | var message = make(chan string) 6 | 7 | func sample() { 8 | message <- "Hello Imooc!" 9 | } 10 | 11 | func sample2() { 12 | message <- "I'm Sample2" 13 | } 14 | 15 | func main() { 16 | go sample() 17 | go sample2() 18 | fmt.Println("Hello World!") 19 | fmt.Println(<-message) 20 | fmt.Println(<-message) 21 | } 22 | -------------------------------------------------------------------------------- /07.基于Golang协程实现流量统计系统/StatisticalSystemWithCSP/01.并发编程/02/02.BufferChannel.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "strconv" 6 | ) 7 | 8 | func sample(ch chan string) { 9 | for i := 0; i < 3; i++ { 10 | ch <- "Hello Imooc!Num:" + strconv.Itoa(i) 11 | } 12 | } 13 | 14 | func sample2(ch chan string) { 15 | for i := 0; i < 3; i++ { 16 | ch <- "Hello Sample 2!Num:" + strconv.Itoa(i) 17 | } 18 | } 19 | 20 | func main() { 21 | ch := make(chan string, 3) 22 | fmt.Println("---begin------") 23 | for i := 0; i < 3; i++ { 24 | go sample(ch) 25 | go sample2(ch) 26 | } 27 | 28 | // 普通写法 29 | //for i := 0; i < 18; i++ { 30 | // fmt.Println(<-ch) 31 | //} 32 | 33 | //range写法,由于读多于写,会产生死锁 34 | for str := range ch { 35 | fmt.Println(str) 36 | } 37 | 38 | fmt.Println("--- end ------") 39 | } 40 | -------------------------------------------------------------------------------- /07.基于Golang协程实现流量统计系统/StatisticalSystemWithCSP/01.并发编程/03/03.解决channel产生死锁的写法.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "strconv" 6 | "sync" 7 | "time" 8 | ) 9 | 10 | func sample(ch chan string) { 11 | for i := 0; i < 5; i++ { 12 | ch <- "Hello Imooc!Num:" + strconv.Itoa(i) 13 | } 14 | close(ch) 15 | } 16 | 17 | func main() { 18 | jobs := make(chan int) 19 | timeout := make(chan bool) 20 | var wg sync.WaitGroup 21 | go func() { 22 | time.Sleep(time.Second * 3) 23 | timeout <- true 24 | }() 25 | go func() { 26 | for i := 0; ; i++ { 27 | select { 28 | case <-timeout: 29 | close(jobs) 30 | return 31 | 32 | default: 33 | jobs <- i 34 | fmt.Println("produce:", i) 35 | } 36 | } 37 | }() 38 | wg.Add(1) 39 | go func() { 40 | defer wg.Done() 41 | for i := range jobs { 42 | fmt.Println("consume:", i) 43 | } 44 | }() 45 | wg.Wait() 46 | } 47 | -------------------------------------------------------------------------------- /07.基于Golang协程实现流量统计系统/StatisticalSystemWithCSP/01.并发编程/05/Select等待机制.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "strconv" 5 | "time" 6 | "fmt" 7 | ) 8 | 9 | func sample(ch chan string) { 10 | for i := 0; i < 10; i++ { 11 | ch <- "I'm sample 1 num :" + strconv.Itoa(i) 12 | time.Sleep(1 * time.Second) 13 | } 14 | } 15 | 16 | func sample2(ch chan int) { 17 | for i := 0; i < 10; i++ { 18 | ch <- i 19 | time.Sleep(2 * time.Second) 20 | } 21 | } 22 | 23 | func main() { 24 | ch1 := make(chan string, 3) 25 | ch2 := make(chan int, 5) 26 | for i := 0; i < 10; i++ { 27 | go sample(ch1) 28 | go sample2(ch2) 29 | } 30 | for { 31 | select { 32 | case _str, ok := <-ch1: 33 | if !ok { 34 | fmt.Println("CH1 Failed!") 35 | } 36 | fmt.Println(_str) 37 | case _int, ok := <-ch2: 38 | if !ok { 39 | fmt.Println("CH2 Failed!") 40 | } 41 | fmt.Println(_int) 42 | default: 43 | // fmt.Println("随机") 44 | } 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /07.基于Golang协程实现流量统计系统/基于Golang协程实现流量统计系统.docx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Goular/GolangModule/6f5ea735e919e4d2521b85ebb470a012bc05baf3/07.基于Golang协程实现流量统计系统/基于Golang协程实现流量统计系统.docx -------------------------------------------------------------------------------- /08.glide的使用备忘/glide使用内容.txt: -------------------------------------------------------------------------------- 1 | 有时候要执行 glide cc 才能出现 2 | 设置好的镜像连接执行成功 3 | 4 | 5 | 注意:有时候不能使用glide install 获取 golang/x 的内容的时候,我们可以删除yaml,同时glide cc 6 | 重新操作 7 | 8 | $ rm -rf ~/.glide 9 | $ mkdir -p ~/.glide 10 | $ glide mirror set https://golang.org/x/mobile https://github.com/golang/mobile --vcs git 11 | $ glide mirror set https://golang.org/x/crypto https://github.com/golang/crypto --vcs git 12 | $ glide mirror set https://golang.org/x/net https://github.com/golang/net --vcs git 13 | $ glide mirror set https://golang.org/x/tools https://github.com/golang/tools --vcs git 14 | $ glide mirror set https://golang.org/x/text https://github.com/golang/text --vcs git 15 | $ glide mirror set https://golang.org/x/image https://github.com/golang/image --vcs git 16 | $ glide mirror set https://golang.org/x/sys https://github.com/golang/sys --vcs git 17 | 18 | 然后在项目中执行 19 | $ glide init 20 | $ glide install 21 | 22 | https://github.com/Masterminds/glide/issues/772 -------------------------------------------------------------------------------- /08.glide的使用备忘/glide使用备忘.txt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Goular/GolangModule/6f5ea735e919e4d2521b85ebb470a012bc05baf3/08.glide的使用备忘/glide使用备忘.txt -------------------------------------------------------------------------------- /09.基于Go语言构建企业级的Restful API服务/demo01/router/router.go: -------------------------------------------------------------------------------- 1 | package router 2 | 3 | import ( 4 | "github.com/gin-gonic/gin" 5 | "ApiServer/demo01/router/middleware" 6 | "net/http" 7 | "ApiServer/demo01/handler/sd" 8 | ) 9 | 10 | // Load loads the middlewares, routes, handlers. 11 | func Load(g *gin.Engine, mw ...gin.HandlerFunc) *gin.Engine { 12 | // Middlewares. 13 | g.Use(gin.Recovery()) 14 | g.Use(middleware.NoCache) 15 | g.Use(middleware.Options) 16 | g.Use(middleware.Secure) 17 | g.Use(mw...) 18 | // 404 Handler. 19 | g.NoRoute(func(c *gin.Context) { 20 | c.String(http.StatusNotFound, "The incorrect API route.") 21 | }) 22 | 23 | // The health check handlers 24 | svcd := g.Group("/sd") 25 | { 26 | svcd.GET("/health", sd.HealthCheck) 27 | svcd.GET("/disk", sd.DiskCheck) 28 | svcd.GET("/cpu", sd.CPUCheck) 29 | svcd.GET("/ram", sd.RAMCheck) 30 | } 31 | 32 | return g 33 | } -------------------------------------------------------------------------------- /09.基于Go语言构建企业级的Restful API服务/demo02/conf/config.yaml: -------------------------------------------------------------------------------- 1 | runmode: debug # 开发模式, debug, release, test 2 | addr: :8080 # HTTP绑定端口 3 | name: apiserver # API Server的名字 4 | url: http://127.0.0.1:8080 # pingServer函数请求的API服务器的ip:port 5 | max_ping_count: 10 # pingServer函数try的次数 -------------------------------------------------------------------------------- /09.基于Go语言构建企业级的Restful API服务/demo02/router/router.go: -------------------------------------------------------------------------------- 1 | package router 2 | 3 | import ( 4 | "github.com/gin-gonic/gin" 5 | "ApiServer/demo02/router/middleware" 6 | "net/http" 7 | "ApiServer/demo02/handler/sd" 8 | ) 9 | 10 | // Load loads the middlewares, routes, handlers. 11 | func Load(g *gin.Engine, mw ...gin.HandlerFunc) *gin.Engine { 12 | // Middlewares. 13 | g.Use(gin.Recovery()) 14 | g.Use(middleware.NoCache) 15 | g.Use(middleware.Options) 16 | g.Use(middleware.Secure) 17 | g.Use(mw...) 18 | // 404 Handler. 19 | g.NoRoute(func(c *gin.Context) { 20 | c.String(http.StatusNotFound, "The incorrect API route.") 21 | }) 22 | 23 | // The health check handlers 24 | svcd := g.Group("/sd") 25 | { 26 | svcd.GET("/health", sd.HealthCheck) 27 | svcd.GET("/disk", sd.DiskCheck) 28 | svcd.GET("/cpu", sd.CPUCheck) 29 | svcd.GET("/ram", sd.RAMCheck) 30 | } 31 | 32 | return g 33 | } -------------------------------------------------------------------------------- /09.基于Go语言构建企业级的Restful API服务/demo03/conf/config.yaml: -------------------------------------------------------------------------------- 1 | runmode: test # 开发模式, debug, release, test 2 | addr: :8080 # HTTP绑定端口 3 | name: apiserver # API Server的名字 4 | url: http://127.0.0.1:8080 # pingServer函数请求的API服务器的ip:port 5 | max_ping_count: 10 # pingServer函数try的次数 6 | log: 7 | writers: file,stdout 8 | logger_level: DEBUG 9 | logger_file: log/apiserver.log 10 | log_format_text: false 11 | rollingPolicy: size 12 | log_rotate_date: 1 13 | log_rotate_size: 1 14 | log_backup_count: 7 15 | -------------------------------------------------------------------------------- /09.基于Go语言构建企业级的Restful API服务/demo03/log/apiserver.log.20180702161825197.zip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Goular/GolangModule/6f5ea735e919e4d2521b85ebb470a012bc05baf3/09.基于Go语言构建企业级的Restful API服务/demo03/log/apiserver.log.20180702161825197.zip -------------------------------------------------------------------------------- /09.基于Go语言构建企业级的Restful API服务/demo03/router/router.go: -------------------------------------------------------------------------------- 1 | package router 2 | 3 | import ( 4 | "github.com/gin-gonic/gin" 5 | "ApiServer/demo03/router/middleware" 6 | "net/http" 7 | "ApiServer/demo03/handler/sd" 8 | ) 9 | 10 | // Load loads the middlewares, routes, handlers. 11 | func Load(g *gin.Engine, mw ...gin.HandlerFunc) *gin.Engine { 12 | // Middlewares. 13 | g.Use(gin.Recovery()) 14 | g.Use(middleware.NoCache) 15 | g.Use(middleware.Options) 16 | g.Use(middleware.Secure) 17 | g.Use(mw...) 18 | // 404 Handler. 19 | g.NoRoute(func(c *gin.Context) { 20 | c.String(http.StatusNotFound, "The incorrect API route.") 21 | }) 22 | 23 | // The health check handlers 24 | svcd := g.Group("/sd") 25 | { 26 | svcd.GET("/health", sd.HealthCheck) 27 | svcd.GET("/disk", sd.DiskCheck) 28 | svcd.GET("/cpu", sd.CPUCheck) 29 | svcd.GET("/ram", sd.RAMCheck) 30 | } 31 | 32 | return g 33 | } -------------------------------------------------------------------------------- /09.基于Go语言构建企业级的Restful API服务/demo04/conf/config.yaml: -------------------------------------------------------------------------------- 1 | runmode: test # 开发模式, debug, release, test 2 | addr: :8080 # HTTP绑定端口 3 | name: apiserver # API Server的名字 4 | url: http://127.0.0.1:8080 # pingServer函数请求的API服务器的ip:port 5 | max_ping_count: 10 # pingServer函数try的次数 6 | log: 7 | writers: file,stdout 8 | logger_level: DEBUG 9 | logger_file: log/apiserver.log 10 | log_format_text: false 11 | rollingPolicy: size 12 | log_rotate_date: 1 13 | log_rotate_size: 1 14 | log_backup_count: 7 15 | db: 16 | name: db_apiserver 17 | addr: 127.0.0.1:3306 18 | username: root 19 | password: 123456 20 | docker_db: 21 | name: db_apiserver 22 | addr: 127.0.0.1:3306 23 | username: root 24 | password: root 25 | -------------------------------------------------------------------------------- /09.基于Go语言构建企业级的Restful API服务/demo04/log/apiserver.log.20180702161825197.zip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Goular/GolangModule/6f5ea735e919e4d2521b85ebb470a012bc05baf3/09.基于Go语言构建企业级的Restful API服务/demo04/log/apiserver.log.20180702161825197.zip -------------------------------------------------------------------------------- /09.基于Go语言构建企业级的Restful API服务/demo04/router/router.go: -------------------------------------------------------------------------------- 1 | package router 2 | 3 | import ( 4 | "github.com/gin-gonic/gin" 5 | "ApiServer/demo04/router/middleware" 6 | "net/http" 7 | "ApiServer/demo04/handler/sd" 8 | ) 9 | 10 | // Load loads the middlewares, routes, handlers. 11 | func Load(g *gin.Engine, mw ...gin.HandlerFunc) *gin.Engine { 12 | // Middlewares. 13 | g.Use(gin.Recovery()) 14 | g.Use(middleware.NoCache) 15 | g.Use(middleware.Options) 16 | g.Use(middleware.Secure) 17 | g.Use(mw...) 18 | // 404 Handler. 19 | g.NoRoute(func(c *gin.Context) { 20 | c.String(http.StatusNotFound, "The incorrect API route.") 21 | }) 22 | 23 | // The health check handlers 24 | svcd := g.Group("/sd") 25 | { 26 | svcd.GET("/health", sd.HealthCheck) 27 | svcd.GET("/disk", sd.DiskCheck) 28 | svcd.GET("/cpu", sd.CPUCheck) 29 | svcd.GET("/ram", sd.RAMCheck) 30 | } 31 | 32 | return g 33 | } -------------------------------------------------------------------------------- /09.基于Go语言构建企业级的Restful API服务/demo05/conf/config.yaml: -------------------------------------------------------------------------------- 1 | runmode: debug # 开发模式, debug, release, test 2 | addr: :8080 # HTTP绑定端口 3 | name: apiserver # API Server的名字 4 | url: http://127.0.0.1:8080 # pingServer函数请求的API服务器的ip:port 5 | max_ping_count: 10 # pingServer函数try的次数 6 | log: 7 | writers: file,stdout 8 | logger_level: DEBUG 9 | logger_file: log/apiserver.log 10 | log_format_text: false 11 | rollingPolicy: size 12 | log_rotate_date: 1 13 | log_rotate_size: 1 14 | log_backup_count: 7 15 | db: 16 | name: db_apiserver 17 | addr: 127.0.0.1:3306 18 | username: root 19 | password: 123456 20 | docker_db: 21 | name: db_apiserver 22 | addr: 127.0.0.1:3306 23 | username: root 24 | password: root 25 | -------------------------------------------------------------------------------- /09.基于Go语言构建企业级的Restful API服务/demo05/log/apiserver.log.20180702161825197.zip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Goular/GolangModule/6f5ea735e919e4d2521b85ebb470a012bc05baf3/09.基于Go语言构建企业级的Restful API服务/demo05/log/apiserver.log.20180702161825197.zip -------------------------------------------------------------------------------- /09.基于Go语言构建企业级的Restful API服务/demo06/conf/config.yaml: -------------------------------------------------------------------------------- 1 | runmode: debug # 开发模式, debug, release, test 2 | addr: :8080 # HTTP绑定端口 3 | name: apiserver # API Server的名字 4 | url: http://127.0.0.1:8080 # pingServer函数请求的API服务器的ip:port 5 | max_ping_count: 10 # pingServer函数try的次数 6 | log: 7 | writers: file,stdout 8 | logger_level: DEBUG 9 | logger_file: log/apiserver.log 10 | log_format_text: false 11 | rollingPolicy: size 12 | log_rotate_date: 1 13 | log_rotate_size: 1 14 | log_backup_count: 7 15 | db: 16 | name: db_apiserver 17 | addr: 127.0.0.1:3306 18 | username: root 19 | password: 123456 20 | docker_db: 21 | name: db_apiserver 22 | addr: 127.0.0.1:3306 23 | username: root 24 | password: root 25 | -------------------------------------------------------------------------------- /09.基于Go语言构建企业级的Restful API服务/demo06/handler/handler.go: -------------------------------------------------------------------------------- 1 | package handler 2 | 3 | import ( 4 | "net/http" 5 | "github.com/gin-gonic/gin" 6 | "ApiServer/demo06/pkg/errno" 7 | ) 8 | 9 | // 统一响应的结构体 10 | type Response struct { 11 | Code int `json:"code"` 12 | Message string `json:"message"` 13 | Data interface{} `json:"data"` 14 | } 15 | 16 | // 发送统一的响应 17 | func SendResponse(c *gin.Context, err error, data interface{}) { 18 | code, message := errno.DecodeErr(err) 19 | 20 | // always return http.StatusOK 21 | c.JSON(http.StatusOK, Response{ 22 | Code: code, 23 | Message: message, 24 | Data: data, 25 | }) 26 | } 27 | -------------------------------------------------------------------------------- /09.基于Go语言构建企业级的Restful API服务/demo06/handler/user/user.go: -------------------------------------------------------------------------------- 1 | package user 2 | 3 | type CreateRequest struct { 4 | Username string `json:"username"` 5 | Password string `json:"password"` 6 | } 7 | 8 | type CreateResponse struct { 9 | Username string `json:"username"` 10 | } 11 | -------------------------------------------------------------------------------- /09.基于Go语言构建企业级的Restful API服务/demo06/log/apiserver.log.20180702161825197.zip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Goular/GolangModule/6f5ea735e919e4d2521b85ebb470a012bc05baf3/09.基于Go语言构建企业级的Restful API服务/demo06/log/apiserver.log.20180702161825197.zip -------------------------------------------------------------------------------- /09.基于Go语言构建企业级的Restful API服务/demo07/README.md: -------------------------------------------------------------------------------- 1 | 使用 go-playground/validator 作为表单校验库 -------------------------------------------------------------------------------- /09.基于Go语言构建企业级的Restful API服务/demo07/conf/config.yaml: -------------------------------------------------------------------------------- 1 | runmode: debug # 开发模式, debug, release, test 2 | addr: :8080 # HTTP绑定端口 3 | name: apiserver # API Server的名字 4 | url: http://127.0.0.1:8080 # pingServer函数请求的API服务器的ip:port 5 | max_ping_count: 10 # pingServer函数try的次数 6 | log: 7 | writers: file,stdout 8 | logger_level: DEBUG 9 | logger_file: log/apiserver.log 10 | log_format_text: false 11 | rollingPolicy: size 12 | log_rotate_date: 1 13 | log_rotate_size: 1 14 | log_backup_count: 7 15 | db: 16 | name: db_apiserver 17 | addr: 127.0.0.1:3306 18 | username: root 19 | password: 123456 20 | docker_db: 21 | name: db_apiserver 22 | addr: 127.0.0.1:3306 23 | username: root 24 | password: root 25 | -------------------------------------------------------------------------------- /09.基于Go语言构建企业级的Restful API服务/demo07/handler/handler.go: -------------------------------------------------------------------------------- 1 | package handler 2 | 3 | import ( 4 | "net/http" 5 | "github.com/gin-gonic/gin" 6 | "ApiServer/demo06/pkg/errno" 7 | ) 8 | 9 | // 统一响应的结构体 10 | type Response struct { 11 | Code int `json:"code"` 12 | Message string `json:"message"` 13 | Data interface{} `json:"data"` 14 | } 15 | 16 | // 发送统一的响应 17 | func SendResponse(c *gin.Context, err error, data interface{}) { 18 | code, message := errno.DecodeErr(err) 19 | 20 | // always return http.StatusOK 21 | c.JSON(http.StatusOK, Response{ 22 | Code: code, 23 | Message: message, 24 | Data: data, 25 | }) 26 | } 27 | -------------------------------------------------------------------------------- /09.基于Go语言构建企业级的Restful API服务/demo07/handler/user/delete.go: -------------------------------------------------------------------------------- 1 | package user 2 | 3 | import ( 4 | "strconv" 5 | . "ApiServer/demo07/handler" 6 | "github.com/gin-gonic/gin" 7 | "ApiServer/demo07/pkg/errno" 8 | "ApiServer/demo07/model" 9 | ) 10 | 11 | // Delete delete an user by the user identifier. 12 | func Delete(c *gin.Context) { 13 | userId, _ := strconv.Atoi(c.Param("id")) 14 | if err := model.DeleteUser(uint64(userId)); err != nil { 15 | SendResponse(c, errno.ErrDatabase, nil) 16 | return 17 | } 18 | 19 | SendResponse(c, nil, nil) 20 | } 21 | -------------------------------------------------------------------------------- /09.基于Go语言构建企业级的Restful API服务/demo07/handler/user/get.go: -------------------------------------------------------------------------------- 1 | package user 2 | 3 | import ( 4 | . "ApiServer/demo07/handler" 5 | "github.com/gin-gonic/gin" 6 | "ApiServer/demo07/model" 7 | "ApiServer/demo07/pkg/errno" 8 | ) 9 | 10 | // Get gets an user by the user identifier. 11 | func Get(c *gin.Context) { 12 | username := c.Param("username") 13 | // Get the user by the `username` from the database. 14 | user, err := model.GetUser(username) 15 | if err != nil { 16 | SendResponse(c, errno.ErrUserNotFound, nil) 17 | return 18 | } 19 | 20 | SendResponse(c, nil, user) 21 | } 22 | -------------------------------------------------------------------------------- /09.基于Go语言构建企业级的Restful API服务/demo07/handler/user/list.go: -------------------------------------------------------------------------------- 1 | package user 2 | 3 | import ( 4 | . "ApiServer/demo07/handler" 5 | "github.com/gin-gonic/gin" 6 | "ApiServer/demo07/pkg/errno" 7 | "ApiServer/demo07/service" 8 | ) 9 | 10 | // List list the users in the database. 11 | func List(c *gin.Context) { 12 | var r ListRequest 13 | if err := c.Bind(&r); err != nil { 14 | SendResponse(c, errno.ErrBind, nil) 15 | return 16 | } 17 | 18 | infos, count, err := service.ListUser(r.Username, r.Offset, r.Limit) 19 | if err != nil { 20 | SendResponse(c, err, nil) 21 | return 22 | } 23 | 24 | SendResponse(c, nil, ListResponse{ 25 | TotalCount: count, 26 | UserList: infos, 27 | }) 28 | } 29 | -------------------------------------------------------------------------------- /09.基于Go语言构建企业级的Restful API服务/demo07/handler/user/user.go: -------------------------------------------------------------------------------- 1 | package user 2 | 3 | import "ApiServer/demo07/model" 4 | 5 | type CreateRequest struct { 6 | Username string `json:"username"` 7 | Password string `json:"password"` 8 | } 9 | 10 | type CreateResponse struct { 11 | Username string `json:"username"` 12 | } 13 | 14 | type ListRequest struct { 15 | Username string `json:"username"` 16 | Offset int `json:"offset"` 17 | Limit int `json:"limit"` 18 | } 19 | 20 | type ListResponse struct { 21 | TotalCount uint64 `json:"totalCount"` 22 | UserList []*model.UserInfo `json:"userList"` 23 | } -------------------------------------------------------------------------------- /09.基于Go语言构建企业级的Restful API服务/demo07/log/apiserver.log.20180702161825197.zip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Goular/GolangModule/6f5ea735e919e4d2521b85ebb470a012bc05baf3/09.基于Go语言构建企业级的Restful API服务/demo07/log/apiserver.log.20180702161825197.zip -------------------------------------------------------------------------------- /09.基于Go语言构建企业级的Restful API服务/demo07/model/model.go: -------------------------------------------------------------------------------- 1 | package model 2 | 3 | import ( 4 | "sync" 5 | "time" 6 | ) 7 | 8 | type BaseModel struct { 9 | Id uint64 `gorm:"primary_key;AUTO_INCREMENT;column:id" json:"-"` 10 | CreatedAt time.Time `gorm:"column:createdAt" json:"-"` 11 | UpdatedAt time.Time `gorm:"column:updatedAt" json:"-"` 12 | DeletedAt *time.Time `gorm:"column:deletedAt" sql:"index" json:"-"` 13 | } 14 | 15 | type UserInfo struct { 16 | Id uint64 `json:"id"` 17 | Username string `json:"username"` 18 | SayHello string `json:"sayHello"` 19 | Password string `json:"password"` 20 | CreatedAt string `json:"createdAt"` 21 | UpdatedAt string `json:"updatedAt"` 22 | } 23 | 24 | type UserList struct { 25 | Lock *sync.Mutex 26 | IdMap map[uint64]*UserInfo 27 | } 28 | 29 | // Token represents a JSON web token. 30 | type Token struct { 31 | Token string `json:"token"` 32 | } 33 | -------------------------------------------------------------------------------- /09.基于Go语言构建企业级的Restful API服务/demo07/pkg/auth/auth.go: -------------------------------------------------------------------------------- 1 | package auth 2 | 3 | import "golang.org/x/crypto/bcrypt" 4 | 5 | // 用户密码授权的加密与比较 6 | 7 | // Encrypt encrypts the plain text with bcrypt. 8 | func Encrypt(source string) (string, error) { 9 | hashedBytes, err := bcrypt.GenerateFromPassword([]byte(source), bcrypt.DefaultCost) 10 | return string(hashedBytes), err 11 | } 12 | 13 | // Compare compares the encrypted text with the plain text if it's the same. 14 | func Compare(hashedPassword, password string) error { 15 | return bcrypt.CompareHashAndPassword([]byte(hashedPassword), []byte(password)) 16 | } 17 | -------------------------------------------------------------------------------- /09.基于Go语言构建企业级的Restful API服务/demo07/pkg/constvar/constvar.go: -------------------------------------------------------------------------------- 1 | package constvar 2 | 3 | const ( 4 | DefaultLimit = 50 5 | ) 6 | -------------------------------------------------------------------------------- /09.基于Go语言构建企业级的Restful API服务/demo07/util/util.go: -------------------------------------------------------------------------------- 1 | package util 2 | 3 | import ( 4 | "github.com/gin-gonic/gin" 5 | "github.com/teris-io/shortid" 6 | ) 7 | 8 | func GenShortId() (string, error) { 9 | return shortid.Generate() 10 | } 11 | 12 | func GetReqID(c *gin.Context) string { 13 | v, ok := c.Get("X-Request-Id") 14 | if !ok { 15 | return "" 16 | } 17 | if requestId, ok := v.(string); ok { 18 | return requestId 19 | } 20 | return "" 21 | } 22 | -------------------------------------------------------------------------------- /09.基于Go语言构建企业级的Restful API服务/demo08/README.md: -------------------------------------------------------------------------------- 1 | 使用 go-playground/validator 作为表单校验库 2 | 3 | 在 gin 中可以设置 3 种类型的 middleware: 4 | 5 | 全局中间件 6 | 单个路由中间件 7 | 群组中间件 8 | 9 | 全局中间件:注册中间件的过程之前设置的路由,将不会受注册的中间件所影响。只有注册了中间件之后代码的路由函数规则,才会被中间件装饰。 10 | 单个路由中间件:需要在注册路由时注册中间件 11 | r.GET("/benchmark", MyBenchLogger(), benchEndpoint) 12 | 群组中间件:只要在群组路由上注册中间件函数即可。 13 | 14 | -------------------------------------------------------------------------------- /09.基于Go语言构建企业级的Restful API服务/demo08/conf/config.yaml: -------------------------------------------------------------------------------- 1 | runmode: debug # 开发模式, debug, release, test 2 | addr: :8080 # HTTP绑定端口 3 | name: apiserver # API Server的名字 4 | url: http://127.0.0.1:8080 # pingServer函数请求的API服务器的ip:port 5 | max_ping_count: 10 # pingServer函数try的次数 6 | log: 7 | writers: file,stdout 8 | logger_level: DEBUG 9 | logger_file: log/apiserver.log 10 | log_format_text: false 11 | rollingPolicy: size 12 | log_rotate_date: 1 13 | log_rotate_size: 1 14 | log_backup_count: 7 15 | db: 16 | name: db_apiserver 17 | addr: 127.0.0.1:3306 18 | username: root 19 | password: 123456 20 | docker_db: 21 | name: db_apiserver 22 | addr: 127.0.0.1:3306 23 | username: root 24 | password: root 25 | -------------------------------------------------------------------------------- /09.基于Go语言构建企业级的Restful API服务/demo08/handler/handler.go: -------------------------------------------------------------------------------- 1 | package handler 2 | 3 | import ( 4 | "net/http" 5 | "github.com/gin-gonic/gin" 6 | "ApiServer/demo08/pkg/errno" 7 | ) 8 | 9 | // 统一响应的结构体 10 | type Response struct { 11 | Code int `json:"code"` 12 | Message string `json:"message"` 13 | Data interface{} `json:"data"` 14 | } 15 | 16 | // 发送统一的响应 17 | func SendResponse(c *gin.Context, err error, data interface{}) { 18 | code, message := errno.DecodeErr(err) 19 | 20 | // always return http.StatusOK 21 | c.JSON(http.StatusOK, Response{ 22 | Code: code, 23 | Message: message, 24 | Data: data, 25 | }) 26 | } 27 | -------------------------------------------------------------------------------- /09.基于Go语言构建企业级的Restful API服务/demo08/handler/user/delete.go: -------------------------------------------------------------------------------- 1 | package user 2 | 3 | import ( 4 | "strconv" 5 | . "ApiServer/demo08/handler" 6 | "github.com/gin-gonic/gin" 7 | "ApiServer/demo08/pkg/errno" 8 | "ApiServer/demo08/model" 9 | ) 10 | 11 | // Delete delete an user by the user identifier. 12 | func Delete(c *gin.Context) { 13 | userId, _ := strconv.Atoi(c.Param("id")) 14 | if err := model.DeleteUser(uint64(userId)); err != nil { 15 | SendResponse(c, errno.ErrDatabase, nil) 16 | return 17 | } 18 | 19 | SendResponse(c, nil, nil) 20 | } 21 | -------------------------------------------------------------------------------- /09.基于Go语言构建企业级的Restful API服务/demo08/handler/user/get.go: -------------------------------------------------------------------------------- 1 | package user 2 | 3 | import ( 4 | . "ApiServer/demo08/handler" 5 | "github.com/gin-gonic/gin" 6 | "ApiServer/demo08/model" 7 | "ApiServer/demo08/pkg/errno" 8 | ) 9 | 10 | // Get gets an user by the user identifier. 11 | func Get(c *gin.Context) { 12 | username := c.Param("username") 13 | // Get the user by the `username` from the database. 14 | user, err := model.GetUser(username) 15 | if err != nil { 16 | SendResponse(c, errno.ErrUserNotFound, nil) 17 | return 18 | } 19 | 20 | SendResponse(c, nil, user) 21 | } 22 | -------------------------------------------------------------------------------- /09.基于Go语言构建企业级的Restful API服务/demo08/handler/user/list.go: -------------------------------------------------------------------------------- 1 | package user 2 | 3 | import ( 4 | . "ApiServer/demo08/handler" 5 | "github.com/gin-gonic/gin" 6 | "ApiServer/demo08/pkg/errno" 7 | "ApiServer/demo08/service" 8 | ) 9 | 10 | // List list the users in the database. 11 | func List(c *gin.Context) { 12 | var r ListRequest 13 | if err := c.Bind(&r); err != nil { 14 | SendResponse(c, errno.ErrBind, nil) 15 | return 16 | } 17 | 18 | infos, count, err := service.ListUser(r.Username, r.Offset, r.Limit) 19 | if err != nil { 20 | SendResponse(c, err, nil) 21 | return 22 | } 23 | 24 | SendResponse(c, nil, ListResponse{ 25 | TotalCount: count, 26 | UserList: infos, 27 | }) 28 | } 29 | -------------------------------------------------------------------------------- /09.基于Go语言构建企业级的Restful API服务/demo08/handler/user/user.go: -------------------------------------------------------------------------------- 1 | package user 2 | 3 | import "ApiServer/demo08/model" 4 | 5 | type CreateRequest struct { 6 | Username string `json:"username"` 7 | Password string `json:"password"` 8 | } 9 | 10 | type CreateResponse struct { 11 | Username string `json:"username"` 12 | } 13 | 14 | type ListRequest struct { 15 | Username string `json:"username"` 16 | Offset int `json:"offset"` 17 | Limit int `json:"limit"` 18 | } 19 | 20 | type ListResponse struct { 21 | TotalCount uint64 `json:"totalCount"` 22 | UserList []*model.UserInfo `json:"userList"` 23 | } -------------------------------------------------------------------------------- /09.基于Go语言构建企业级的Restful API服务/demo08/log/apiserver.log.20180702161825197.zip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Goular/GolangModule/6f5ea735e919e4d2521b85ebb470a012bc05baf3/09.基于Go语言构建企业级的Restful API服务/demo08/log/apiserver.log.20180702161825197.zip -------------------------------------------------------------------------------- /09.基于Go语言构建企业级的Restful API服务/demo08/model/model.go: -------------------------------------------------------------------------------- 1 | package model 2 | 3 | import ( 4 | "sync" 5 | "time" 6 | ) 7 | 8 | type BaseModel struct { 9 | Id uint64 `gorm:"primary_key;AUTO_INCREMENT;column:id" json:"-"` 10 | CreatedAt time.Time `gorm:"column:createdAt" json:"-"` 11 | UpdatedAt time.Time `gorm:"column:updatedAt" json:"-"` 12 | DeletedAt *time.Time `gorm:"column:deletedAt" sql:"index" json:"-"` 13 | } 14 | 15 | type UserInfo struct { 16 | Id uint64 `json:"id"` 17 | Username string `json:"username"` 18 | SayHello string `json:"sayHello"` 19 | Password string `json:"password"` 20 | CreatedAt string `json:"createdAt"` 21 | UpdatedAt string `json:"updatedAt"` 22 | } 23 | 24 | type UserList struct { 25 | Lock *sync.Mutex 26 | IdMap map[uint64]*UserInfo 27 | } 28 | 29 | // Token represents a JSON web token. 30 | type Token struct { 31 | Token string `json:"token"` 32 | } 33 | -------------------------------------------------------------------------------- /09.基于Go语言构建企业级的Restful API服务/demo08/pkg/auth/auth.go: -------------------------------------------------------------------------------- 1 | package auth 2 | 3 | import "golang.org/x/crypto/bcrypt" 4 | 5 | // 用户密码授权的加密与比较 6 | 7 | // Encrypt encrypts the plain text with bcrypt. 8 | func Encrypt(source string) (string, error) { 9 | hashedBytes, err := bcrypt.GenerateFromPassword([]byte(source), bcrypt.DefaultCost) 10 | return string(hashedBytes), err 11 | } 12 | 13 | // Compare compares the encrypted text with the plain text if it's the same. 14 | func Compare(hashedPassword, password string) error { 15 | return bcrypt.CompareHashAndPassword([]byte(hashedPassword), []byte(password)) 16 | } 17 | -------------------------------------------------------------------------------- /09.基于Go语言构建企业级的Restful API服务/demo08/pkg/constvar/constvar.go: -------------------------------------------------------------------------------- 1 | package constvar 2 | 3 | const ( 4 | DefaultLimit = 50 5 | ) 6 | -------------------------------------------------------------------------------- /09.基于Go语言构建企业级的Restful API服务/demo08/router/middleware/requestid.go: -------------------------------------------------------------------------------- 1 | package middleware 2 | 3 | import ( 4 | "github.com/gin-gonic/gin" 5 | "github.com/satori/go.uuid" 6 | ) 7 | 8 | func RequestId() gin.HandlerFunc { 9 | return func(c *gin.Context) { 10 | // Check for incoming header, use it if exists 11 | requestId := c.Request.Header.Get("X-Request-Id") 12 | 13 | // Create request id with UUID4 14 | if requestId == "" { 15 | u4, _ := uuid.NewV4() 16 | requestId = u4.String() 17 | } 18 | 19 | // Expose it for use in the application 20 | c.Set("X-Request-Id", requestId) 21 | 22 | // Set X-Request-Id header 23 | c.Writer.Header().Set("X-Request-Id", requestId) 24 | c.Next() 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /09.基于Go语言构建企业级的Restful API服务/demo08/util/util.go: -------------------------------------------------------------------------------- 1 | package util 2 | 3 | import ( 4 | "github.com/gin-gonic/gin" 5 | "github.com/teris-io/shortid" 6 | ) 7 | 8 | func GenShortId() (string, error) { 9 | return shortid.Generate() 10 | } 11 | 12 | func GetReqID(c *gin.Context) string { 13 | v, ok := c.Get("X-Request-Id") 14 | if !ok { 15 | return "" 16 | } 17 | if requestId, ok := v.(string); ok { 18 | return requestId 19 | } 20 | return "" 21 | } 22 | -------------------------------------------------------------------------------- /09.基于Go语言构建企业级的Restful API服务/demo09/README.md: -------------------------------------------------------------------------------- 1 | 使用 go-playground/validator 作为表单校验库 2 | 3 | 在 gin 中可以设置 3 种类型的 middleware: 4 | 5 | 全局中间件 6 | 单个路由中间件 7 | 群组中间件 8 | 9 | 全局中间件:注册中间件的过程之前设置的路由,将不会受注册的中间件所影响。只有注册了中间件之后代码的路由函数规则,才会被中间件装饰。 10 | 单个路由中间件:需要在注册路由时注册中间件 11 | r.GET("/benchmark", MyBenchLogger(), benchEndpoint) 12 | 群组中间件:只要在群组路由上注册中间件函数即可。 13 | 14 | JWT由三段内容构成 15 | 即header,payload,signature三部分构成 16 | 17 | 如何进行 API 身份验证 18 | API 身份认证包括两步: 19 | 20 | 签发 token 21 | API 添加认证 middleware 22 | 23 | 可以看到携带 token 后验证通过,成功创建用户。通过 HTTP Header Authorization: Bearer $token 来携带 token。携带 token 后不需要再次查询数据库核对密码,即可完成授权。 24 | -------------------------------------------------------------------------------- /09.基于Go语言构建企业级的Restful API服务/demo09/conf/config.yaml: -------------------------------------------------------------------------------- 1 | runmode: debug # 开发模式, debug, release, test 2 | addr: :8080 # HTTP绑定端口 3 | name: apiserver # API Server的名字 4 | url: http://127.0.0.1:8080 # pingServer函数请求的API服务器的ip:port 5 | max_ping_count: 10 # pingServer函数try的次数 6 | jwt_secret: Rtg8BPKNEf2mB4mgvKONGPZZQSaJWNLijxR42qRgq0iBb5 7 | log: 8 | writers: file,stdout 9 | logger_level: DEBUG 10 | logger_file: log/apiserver.log 11 | log_format_text: false 12 | rollingPolicy: size 13 | log_rotate_date: 1 14 | log_rotate_size: 1 15 | log_backup_count: 7 16 | db: 17 | name: db_apiserver 18 | addr: 127.0.0.1:3306 19 | username: root 20 | password: 21 | docker_db: 22 | name: db_apiserver 23 | addr: 127.0.0.1:3306 24 | username: root 25 | password: root 26 | -------------------------------------------------------------------------------- /09.基于Go语言构建企业级的Restful API服务/demo09/handler/handler.go: -------------------------------------------------------------------------------- 1 | package handler 2 | 3 | import ( 4 | "net/http" 5 | "github.com/gin-gonic/gin" 6 | "ApiServer/demo09/pkg/errno" 7 | ) 8 | 9 | // 统一响应的结构体 10 | type Response struct { 11 | Code int `json:"code"` 12 | Message string `json:"message"` 13 | Data interface{} `json:"data"` 14 | } 15 | 16 | // 发送统一的响应 17 | func SendResponse(c *gin.Context, err error, data interface{}) { 18 | code, message := errno.DecodeErr(err) 19 | 20 | // always return http.StatusOK 21 | c.JSON(http.StatusOK, Response{ 22 | Code: code, 23 | Message: message, 24 | Data: data, 25 | }) 26 | } 27 | -------------------------------------------------------------------------------- /09.基于Go语言构建企业级的Restful API服务/demo09/handler/user/delete.go: -------------------------------------------------------------------------------- 1 | package user 2 | 3 | import ( 4 | "strconv" 5 | . "ApiServer/demo09/handler" 6 | "github.com/gin-gonic/gin" 7 | "ApiServer/demo09/pkg/errno" 8 | "ApiServer/demo09/model" 9 | ) 10 | 11 | // Delete delete an user by the user identifier. 12 | func Delete(c *gin.Context) { 13 | userId, _ := strconv.Atoi(c.Param("id")) 14 | if err := model.DeleteUser(uint64(userId)); err != nil { 15 | SendResponse(c, errno.ErrDatabase, nil) 16 | return 17 | } 18 | 19 | SendResponse(c, nil, nil) 20 | } 21 | -------------------------------------------------------------------------------- /09.基于Go语言构建企业级的Restful API服务/demo09/handler/user/get.go: -------------------------------------------------------------------------------- 1 | package user 2 | 3 | import ( 4 | . "ApiServer/demo09/handler" 5 | "github.com/gin-gonic/gin" 6 | "ApiServer/demo09/model" 7 | "ApiServer/demo09/pkg/errno" 8 | ) 9 | 10 | // Get gets an user by the user identifier. 11 | func Get(c *gin.Context) { 12 | username := c.Param("username") 13 | // Get the user by the `username` from the database. 14 | user, err := model.GetUser(username) 15 | if err != nil { 16 | SendResponse(c, errno.ErrUserNotFound, nil) 17 | return 18 | } 19 | 20 | SendResponse(c, nil, user) 21 | } 22 | -------------------------------------------------------------------------------- /09.基于Go语言构建企业级的Restful API服务/demo09/handler/user/list.go: -------------------------------------------------------------------------------- 1 | package user 2 | 3 | import ( 4 | . "ApiServer/demo09/handler" 5 | "github.com/gin-gonic/gin" 6 | "ApiServer/demo09/pkg/errno" 7 | "ApiServer/demo09/service" 8 | ) 9 | 10 | // List list the users in the database. 11 | func List(c *gin.Context) { 12 | var r ListRequest 13 | if err := c.Bind(&r); err != nil { 14 | SendResponse(c, errno.ErrBind, nil) 15 | return 16 | } 17 | 18 | infos, count, err := service.ListUser(r.Username, r.Offset, r.Limit) 19 | if err != nil { 20 | SendResponse(c, err, nil) 21 | return 22 | } 23 | 24 | SendResponse(c, nil, ListResponse{ 25 | TotalCount: count, 26 | UserList: infos, 27 | }) 28 | } 29 | -------------------------------------------------------------------------------- /09.基于Go语言构建企业级的Restful API服务/demo09/handler/user/user.go: -------------------------------------------------------------------------------- 1 | package user 2 | 3 | import "ApiServer/demo09/model" 4 | 5 | type CreateRequest struct { 6 | Username string `json:"username"` 7 | Password string `json:"password"` 8 | } 9 | 10 | type CreateResponse struct { 11 | Username string `json:"username"` 12 | } 13 | 14 | type ListRequest struct { 15 | Username string `json:"username"` 16 | Offset int `json:"offset"` 17 | Limit int `json:"limit"` 18 | } 19 | 20 | type ListResponse struct { 21 | TotalCount uint64 `json:"totalCount"` 22 | UserList []*model.UserInfo `json:"userList"` 23 | } -------------------------------------------------------------------------------- /09.基于Go语言构建企业级的Restful API服务/demo09/log/apiserver.log.20180702161825197.zip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Goular/GolangModule/6f5ea735e919e4d2521b85ebb470a012bc05baf3/09.基于Go语言构建企业级的Restful API服务/demo09/log/apiserver.log.20180702161825197.zip -------------------------------------------------------------------------------- /09.基于Go语言构建企业级的Restful API服务/demo09/model/model.go: -------------------------------------------------------------------------------- 1 | package model 2 | 3 | import ( 4 | "sync" 5 | "time" 6 | ) 7 | 8 | type BaseModel struct { 9 | Id uint64 `gorm:"primary_key;AUTO_INCREMENT;column:id" json:"-"` 10 | CreatedAt time.Time `gorm:"column:createdAt" json:"-"` 11 | UpdatedAt time.Time `gorm:"column:updatedAt" json:"-"` 12 | DeletedAt *time.Time `gorm:"column:deletedAt" sql:"index" json:"-"` 13 | } 14 | 15 | type UserInfo struct { 16 | Id uint64 `json:"id"` 17 | Username string `json:"username"` 18 | SayHello string `json:"sayHello"` 19 | Password string `json:"password"` 20 | CreatedAt string `json:"createdAt"` 21 | UpdatedAt string `json:"updatedAt"` 22 | } 23 | 24 | type UserList struct { 25 | Lock *sync.Mutex 26 | IdMap map[uint64]*UserInfo 27 | } 28 | 29 | // Token represents a JSON web token. 30 | type Token struct { 31 | Token string `json:"token"` 32 | } 33 | -------------------------------------------------------------------------------- /09.基于Go语言构建企业级的Restful API服务/demo09/pkg/auth/auth.go: -------------------------------------------------------------------------------- 1 | package auth 2 | 3 | import "golang.org/x/crypto/bcrypt" 4 | 5 | // 用户密码授权的加密与比较 6 | 7 | // Encrypt encrypts the plain text with bcrypt. 8 | func Encrypt(source string) (string, error) { 9 | hashedBytes, err := bcrypt.GenerateFromPassword([]byte(source), bcrypt.DefaultCost) 10 | return string(hashedBytes), err 11 | } 12 | 13 | // Compare compares the encrypted text with the plain text if it's the same. 14 | func Compare(hashedPassword, password string) error { 15 | return bcrypt.CompareHashAndPassword([]byte(hashedPassword), []byte(password)) 16 | } 17 | -------------------------------------------------------------------------------- /09.基于Go语言构建企业级的Restful API服务/demo09/pkg/constvar/constvar.go: -------------------------------------------------------------------------------- 1 | package constvar 2 | 3 | const ( 4 | DefaultLimit = 50 5 | ) 6 | -------------------------------------------------------------------------------- /09.基于Go语言构建企业级的Restful API服务/demo09/router/middleware/auth.go: -------------------------------------------------------------------------------- 1 | package middleware 2 | 3 | import ( 4 | "github.com/gin-gonic/gin" 5 | "ApiServer/demo09/handler" 6 | "ApiServer/demo09/pkg/errno" 7 | "ApiServer/demo09/pkg/token" 8 | ) 9 | 10 | func AuthMiddleware() gin.HandlerFunc { 11 | return func(c *gin.Context) { 12 | // Parse the json web token. 13 | if _, err := token.ParseRequest(c); err != nil { 14 | handler.SendResponse(c, errno.ErrTokenInvalid, nil) 15 | c.Abort() 16 | return 17 | } 18 | 19 | c.Next() 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /09.基于Go语言构建企业级的Restful API服务/demo09/router/middleware/requestid.go: -------------------------------------------------------------------------------- 1 | package middleware 2 | 3 | import ( 4 | "github.com/gin-gonic/gin" 5 | "github.com/satori/go.uuid" 6 | ) 7 | 8 | func RequestId() gin.HandlerFunc { 9 | return func(c *gin.Context) { 10 | // Check for incoming header, use it if exists 11 | requestId := c.Request.Header.Get("X-Request-Id") 12 | 13 | // Create request id with UUID4 14 | if requestId == "" { 15 | u4, _ := uuid.NewV4() 16 | requestId = u4.String() 17 | } 18 | 19 | // Expose it for use in the application 20 | c.Set("X-Request-Id", requestId) 21 | 22 | // Set X-Request-Id header 23 | c.Writer.Header().Set("X-Request-Id", requestId) 24 | c.Next() 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /09.基于Go语言构建企业级的Restful API服务/demo09/util/util.go: -------------------------------------------------------------------------------- 1 | package util 2 | 3 | import ( 4 | "github.com/gin-gonic/gin" 5 | "github.com/teris-io/shortid" 6 | ) 7 | 8 | func GenShortId() (string, error) { 9 | return shortid.Generate() 10 | } 11 | 12 | func GetReqID(c *gin.Context) string { 13 | v, ok := c.Get("X-Request-Id") 14 | if !ok { 15 | return "" 16 | } 17 | if requestId, ok := v.(string); ok { 18 | return requestId 19 | } 20 | return "" 21 | } 22 | -------------------------------------------------------------------------------- /09.基于Go语言构建企业级的Restful API服务/基于 Go 语言构建企业级的 RESTful API 服务.rar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Goular/GolangModule/6f5ea735e919e4d2521b85ebb470a012bc05baf3/09.基于Go语言构建企业级的Restful API服务/基于 Go 语言构建企业级的 RESTful API 服务.rar -------------------------------------------------------------------------------- /10.GO实现千万级WebSocket消息推送服务(MOOC)/GO实现千万级WebSocket消息推送服务.docx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Goular/GolangModule/6f5ea735e919e4d2521b85ebb470a012bc05baf3/10.GO实现千万级WebSocket消息推送服务(MOOC)/GO实现千万级WebSocket消息推送服务.docx -------------------------------------------------------------------------------- /11.各种场景写法优雅退出/chanSelect/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "time" 6 | ) 7 | 8 | 9 | // chan通知关闭协程 10 | func main() { 11 | stop := make(chan bool) 12 | 13 | go func() { 14 | for { 15 | select { 16 | case <-stop: 17 | fmt.Println("监控退出,停止了...") 18 | return 19 | default: 20 | fmt.Println("goroutine监控中...") 21 | time.Sleep(2 * time.Second) 22 | } 23 | } 24 | }() 25 | 26 | time.Sleep(10 * time.Second) 27 | fmt.Println("可以了,通知监控停止") 28 | stop<- true 29 | //为了检测监控过是否停止,如果没有监控输出,就表示停止了 30 | time.Sleep(5 * time.Second) 31 | 32 | } 33 | -------------------------------------------------------------------------------- /11.各种场景写法优雅退出/waitGroup/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "sync" 5 | "time" 6 | "fmt" 7 | ) 8 | 9 | func main() { 10 | var wg sync.WaitGroup 11 | 12 | wg.Add(2) 13 | go func() { 14 | time.Sleep(2*time.Second) 15 | fmt.Println("1号完成") 16 | wg.Done() 17 | }() 18 | go func() { 19 | time.Sleep(2*time.Second) 20 | fmt.Println("2号完成") 21 | wg.Done() 22 | }() 23 | wg.Wait() 24 | fmt.Println("好了,大家都干完了,放工") 25 | } 26 | -------------------------------------------------------------------------------- /12.各种场景下的永久阻塞/README.md: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Goular/GolangModule/6f5ea735e919e4d2521b85ebb470a012bc05baf3/12.各种场景下的永久阻塞/README.md -------------------------------------------------------------------------------- /15.Golang开发分布式任务调度/Golang开发分布式任务调度.docx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Goular/GolangModule/6f5ea735e919e4d2521b85ebb470a012bc05baf3/15.Golang开发分布式任务调度/Golang开发分布式任务调度.docx -------------------------------------------------------------------------------- /15.Golang开发分布式任务调度/go-crontab/01prepare/cmd_usage/demo01/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "os/exec" 6 | ) 7 | 8 | // 该main方法没有进行捕获输出 9 | func main() { 10 | var ( 11 | cmd *exec.Cmd 12 | err error 13 | ) 14 | // todo:下面的指令针对的linux系统 15 | //cmd = exec.Command("/bin/bash", "-c", "echo 1;echo 2;") 16 | // todo:下面的指令针对的window系统 17 | cmd = exec.Command("E:\\cygwin64\\bin\\bash.exe", "-c", "echo 1;echo 3;") 18 | err = cmd.Run() 19 | if err != nil { 20 | fmt.Println(err) 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /15.Golang开发分布式任务调度/go-crontab/01prepare/cmd_usage/demo02/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "os/exec" 6 | "time" 7 | ) 8 | 9 | // 该main方法没有进行捕获输出 10 | func main() { 11 | var ( 12 | cmd *exec.Cmd 13 | output []byte 14 | err error 15 | ) 16 | // 生成CMD 17 | cmd = exec.Command("E:\\cygwin64\\bin\\bash.exe", "-c", "sleep 2;ls -l") 18 | // 执行命令,不获取子进程的输出 19 | if output, err = cmd.CombinedOutput(); err != nil { 20 | fmt.Println(err) 21 | return 22 | } 23 | time.Sleep(1 * time.Second) 24 | // 捕获到内容 25 | fmt.Println(string(output)) 26 | } 27 | -------------------------------------------------------------------------------- /15.Golang开发分布式任务调度/go-crontab/01prepare/cron_usage/demo1/main.go: -------------------------------------------------------------------------------- 1 | package demo1 2 | 3 | import ( 4 | "fmt" 5 | "github.com/gorhill/cronexpr" 6 | "time" 7 | ) 8 | 9 | var ( 10 | expr *cronexpr.Expression // cron的任务的对象 11 | err error 12 | now time.Time // 当前时间 13 | nextTime time.Time // 下一次运行的时间 14 | flag = make(chan struct{}) 15 | ) 16 | 17 | func main() { 18 | // linux crontab 19 | // 秒粒度, 年配置(2018-2099) 20 | // 哪一分钟(0-59),哪小时(0-23),哪天(1-31),哪月(1-12),星期几(0-6) 21 | 22 | // 定义5分钟运行一次 每隔5分钟执行一次 23 | if expr, err = cronexpr.Parse("*/5 * * * * * *"); err != nil { 24 | fmt.Println(err) 25 | return 26 | } 27 | // 获取当前时间 28 | now = time.Now() 29 | //下一次调度的时间 30 | nextTime = expr.Next(now) 31 | 32 | fmt.Println(now) 33 | fmt.Println(nextTime) 34 | 35 | // 计算两者的时间差,等待这个定时器超时 36 | time.AfterFunc(nextTime.Sub(now), func() { 37 | fmt.Println("任务被调度了:", nextTime) 38 | }) 39 | 40 | select {} 41 | } 42 | -------------------------------------------------------------------------------- /15.Golang开发分布式任务调度/go-crontab/01prepare/etcd_usage/demo01/main.go: -------------------------------------------------------------------------------- 1 | package demo01 2 | 3 | import ( 4 | "fmt" 5 | "go.etcd.io/etcd/clientv3" 6 | "time" 7 | ) 8 | 9 | // demo01 etcd golang 客户端连接 10 | // 106.12.118.76 11 | func main() { 12 | var ( 13 | config clientv3.Config 14 | client *clientv3.Client 15 | err error 16 | ) 17 | 18 | // 客户端配置 19 | config = clientv3.Config{ 20 | Endpoints: []string{"106.12.118.76:2379"}, 21 | DialTimeout: 5 * time.Second, 22 | } 23 | 24 | // 建立连接 25 | if client, err = clientv3.New(config); err != nil { 26 | fmt.Println(err) 27 | return 28 | } 29 | 30 | client = client 31 | fmt.Println(client) 32 | } 33 | -------------------------------------------------------------------------------- /15.Golang开发分布式任务调度/go-crontab/01prepare/etcd_usage/demo04/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "context" 5 | "fmt" 6 | "go.etcd.io/etcd/clientv3" 7 | "time" 8 | ) 9 | 10 | var ( 11 | config clientv3.Config 12 | client *clientv3.Client 13 | err error 14 | kv clientv3.KV 15 | getResp *clientv3.GetResponse 16 | ) 17 | 18 | func main() { 19 | // 构建etcd client的config 20 | config = clientv3.Config{ 21 | Endpoints: []string{"106.12.118.76:2379"}, 22 | DialTimeout: 5 * time.Second, 23 | } 24 | // 构建etcd client 25 | if client, err = clientv3.New(config); err != nil { 26 | fmt.Println(err) 27 | } 28 | kv = clientv3.NewKV(client) 29 | if getResp, err = kv.Get(context.TODO(), "/crontab/jobs/", clientv3.WithPrefix()); err != nil { 30 | fmt.Println(err) 31 | } else { 32 | for _, value := range getResp.Kvs { 33 | fmt.Println(value) 34 | } 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /15.Golang开发分布式任务调度/go-crontab/01prepare/mongodb_usage/demo01/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "context" 5 | "fmt" 6 | "go.mongodb.org/mongo-driver/mongo" 7 | "go.mongodb.org/mongo-driver/mongo/options" 8 | "time" 9 | ) 10 | 11 | // 建立连接 12 | func main() { 13 | var ( 14 | client *mongo.Client 15 | err error 16 | database *mongo.Database 17 | collection *mongo.Collection 18 | ) 19 | // 1.建立连接 20 | ctx, _ := context.WithTimeout(context.Background(), 10*time.Second) 21 | if client, err = mongo.Connect(ctx, options.Client().ApplyURI("mongodb://localhost:27017")); err != nil { 22 | fmt.Println(err) 23 | return 24 | } 25 | 26 | // fmt.Println(client) 27 | 28 | // 2.选择数据库my_db 29 | database = client.Database("testing") 30 | collection = client.Database("test_db").Collection("numbers") 31 | 32 | // 3.选择my_collection 33 | database = database 34 | collection = collection 35 | } 36 | -------------------------------------------------------------------------------- /16.Go语言打造高并发web即时聊天(IM)应用/Go语言打造高并发web即时聊天(IM)应用.docx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Goular/GolangModule/6f5ea735e919e4d2521b85ebb470a012bc05baf3/16.Go语言打造高并发web即时聊天(IM)应用/Go语言打造高并发web即时聊天(IM)应用.docx -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # GolangModule 2 | Golang学习与交流 3 | -------------------------------------------------------------------------------- /chatroom/client.go: -------------------------------------------------------------------------------- 1 | // Copyright 2013 The Gorilla WebSocket Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | package main 6 | 7 | -------------------------------------------------------------------------------- /chatroom/hub.go: -------------------------------------------------------------------------------- 1 | // Copyright 2013 The Gorilla WebSocket Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | package main 6 | 7 | 8 | -------------------------------------------------------------------------------- /command/README.md: -------------------------------------------------------------------------------- 1 | # Command example 2 | 3 | This example connects a websocket connection to stdin and stdout of a command. 4 | Received messages are written to stdin followed by a `\n`. Each line read from 5 | standard out is sent as a message to the client. 6 | 7 | $ go get github.com/gorilla/websocket 8 | $ cd `go list -f '{{.Dir}}' github.com/gorilla/websocket/examples/command` 9 | $ go run main.go 10 | # Open http://localhost:8080/ . 11 | 12 | Try the following commands. 13 | 14 | # Echo sent messages to the output area. 15 | $ go run main.go cat 16 | 17 | # Run a shell.Try sending "ls" and "cat main.go". 18 | $ go run main.go sh 19 | 20 | -------------------------------------------------------------------------------- /gRPC简单使用/grpcStudy/client/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "log" 5 | "os" 6 | 7 | "golang.org/x/net/context" 8 | "google.golang.org/grpc" 9 | pb "grpcStudy/helloworld" 10 | ) 11 | 12 | const ( 13 | address = "localhost:50051" 14 | defaultName = "world" 15 | ) 16 | 17 | func main() { 18 | conn, err := grpc.Dial(address, grpc.WithInsecure()) 19 | if err != nil { 20 | log.Fatal("did not connect: %v", err) 21 | } 22 | defer conn.Close() 23 | c := pb.NewGreeterClient(conn) 24 | 25 | name := defaultName 26 | if len(os.Args) > 1 { 27 | name = os.Args[1] 28 | } 29 | r, err := c.SayHello(context.Background(), &pb.HelloRequest{Name: name}) 30 | if err != nil { 31 | log.Fatal("could not greet: %v", err) 32 | } 33 | log.Printf("Greeting: %s", r.Message) 34 | } 35 | -------------------------------------------------------------------------------- /gRPC简单使用/grpcStudy/helloworld.proto: -------------------------------------------------------------------------------- 1 | syntax = "proto3"; 2 | 3 | package helloworld; 4 | 5 | // The greeting service definition. 6 | service Greeter { 7 | // Sends a greeting 8 | rpc SayHello (HelloRequest) returns (HelloReply) {} 9 | } 10 | 11 | // The request message containing the user's name. 12 | message HelloRequest { 13 | string name = 1; 14 | } 15 | 16 | // The response message containing the greetings 17 | message HelloReply { 18 | string message = 1; 19 | } -------------------------------------------------------------------------------- /gRPC简单使用/grpcStudy/server/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "log" 5 | "net" 6 | 7 | "golang.org/x/net/context" 8 | "google.golang.org/grpc" 9 | pb "grpcStudy/helloworld" 10 | ) 11 | 12 | const ( 13 | port = ":50051" 14 | ) 15 | 16 | type server struct{} 17 | 18 | func (s *server) SayHello(ctx context.Context, in *pb.HelloRequest) (*pb.HelloReply, error) { 19 | return &pb.HelloReply{Message: "Hello " + in.Name}, nil 20 | } 21 | 22 | func main() { 23 | lis, err := net.Listen("tcp", port) 24 | if err != nil { 25 | log.Fatal("failed to listen: %v", err) 26 | } 27 | s := grpc.NewServer() 28 | pb.RegisterGreeterServer(s, &server{}) 29 | s.Serve(lis) 30 | } 31 | -------------------------------------------------------------------------------- /各种数据结构推荐使用库.txt: -------------------------------------------------------------------------------- 1 | set(协程安全) 2 | https://github.com/fatih/set 3 | 4 | map(协程安全) 5 | https://github.com/orcaman/concurrent-map --------------------------------------------------------------------------------