# Golang_demo **Repository Path**: hackydh/Golang_demo ## Basic Information - **Project Name**: Golang_demo - **Description**: 学习Go的小例子 - **Primary Language**: Go - **License**: Not specified - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 0 - **Forks**: 0 - **Created**: 2015-08-31 - **Last Updated**: 2020-12-19 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README #Go Demo 学习Go小例子, 参见[中文Go编程教程](http://zh-golang.appspot.com/doc/effective_go.html) 和 [Go笔记](http://note.youdao.com/share/?id=bdc4941c7728052d6170a5ffbc60b602&type=note) ##内容 * 基本内容 包括包、函数、多值返回、闭包、输出中文、唯一循环结构for、判断if、数组Array、切片Alice、映射Map、集合Set、单元测试 * 接口Interface Go中的接口用法比较特殊,实现接口时不像PHP中需要使用implements关键字, Go中任何数据结构只要实现Interface中的函数,自动就实现这个Interface了。 * [Stringers](https://golang.org/pkg/fmt/#Stringer) Stringers是Go提供的fmt.stringers接口,任何类型只要实现接口中的String()函数就可以使用fmt模块中的输出函数了。 实现语法:`func (t T) String() string{}`, 类型T就实现了Stringers接口。 这相当于PHP中的`__toString()`函数或者Python中的`__str__`函数。 * Web 服务器 Go包http提供了web服务器和web客户端操作的函数。 包http通过任何实现了http.Handler接口的结构来响应 HTTP 请求,接口定义如下: ``` type Handler interface { ServeHTTP(w ResponseWriter, r *Request) } ``` 然后调用`http.Handle()`方法来接收请求;或者直接调用`http.HandleFunc()`函数。 处理请求过程中可以使用`fmt.Fprint或者io.WriteString`来输出文本。 最后调用`http.ListenAndServe("localhost:4000", nil)`来启动http服务。 具体实现见[webserver.go](webserver.go)文件。 github上有许多封装好的Go web库,例如简单封装的[web.go](http://webgo.io/index.html), 支持MVC模型的[Beego](http://beego.me/), 轻量级的[Golanger](http://www.golanger.com/), 微框架[Goji](https://goji.io/), 还有使用PHP渲染模板的[easygo](https://github.com/matyhtf/easygo)等等。 示例文件[web.go](web.go)使用了web.go。 项目中还包括一个简单的服务器封装模块simplewebserver,内容包含操作MySQL数据库,渲染HTML文件等。 * Go并行执行 Go提供Goroutine实现并行执行程序,Goroutine使用go命令启动。 Goroutine是一个超级轻量级的类似线程的独立执行单元,并不是线程。 Goroutine通过channel来实现通信和同步。运算符<-用来从channel接收或发送数据。 示例文件见[concurrency.go](concurrency.go)。