cloudgo
框架选择 Martini
Martini 是一个强大为了编写模块化Web应用而生的GO语言框架.
GitHub 地址 https://github.com/go-martini/martini
功能列表
- 使用极其简单.
- 无侵入式的设计.
- 很好的与其他的Go语言包协同使用.
- 超赞的路径匹配和路由.
- 模块化的设计 - 容易插入功能件,也容易将其拔出来.
- 已有很多的中间件可以直接使用.
- 框架内已拥有很好的开箱即用的功能支持.
- 完全兼容http.HandlerFunc接口.
安装
设计思路
一个简单的go服务器应用,可以进行路由和返回静态网页,以及表单提交功能
运行
go run main.go -p 8080
效果
实现
目录结构
main.go
程序入口,解析命令行参数作为web服务器监听的端口,调用server启动服务
func main() {
port := os.Getenv("PORT")
// default port : 8080
if len(port) == 0 {
port = PORT
}
// port for httpd listening
pPort := flag.StringP("port", "p", PORT, "PORT for httpd listening")
flag.Parse()
if len(*pPort) != 0 {
port = *pPort
}
// server.go receive para: port num
service.NewServer(port)
}
server.go
为了更快速的启用Martini, martini.Classic() 提供了一些默认的方便Web开发的工具:
下面是Martini核心已经包含的功能 martini.Classic():
- Request/Response Logging (请求/响应日志) - martini.Logger
- Panic Recovery (容错) - martini.Recovery
- Static File serving (静态文件服务) - martini.Static
- Routing (路由) - martini.Router
m := martini.Classic()
// use dir public
m.Use(martini.Static("public"))
m.Use(render.Renderer())
// ... middleware and routing goes here
m.Run()
martini-contrib/render包是martini用来渲染html模板的包,使用了go 的 html/template包
m.Use(martini.Static(“public”)) 使用public文件夹作为默认的资源文件目录
路由,开始页面,这里使用了time包来获取时间
r.HTML(200, “index”, newmap) 的参数为状态码,模板index.tmpl和封装在newmap中的数据
// routing
m.Get("/", func(r render.Render) {
t1 := time.Now().UTC().Format(time.UnixDate)
newmap := map[string]interface{}{"Name": "Zhi Hao","formatTime":t1}
r.HTML(200, "index", newmap)
})
处理post请求
这里使用了martini-contrib/binding包,可以自动把form表单提交的数据自动转化为go的数据结构,要先定义表单的结构体。获得表单数据之后再交给render渲染。
type Post struct {
Username string `form:"username" binding:"required"`
Password string `form:"password" binding:"required"`
}
m.Post("/", binding.Bind(Post{}), func(post Post, r render.Render) {
p:=Post{Username: post.Username, Password: post.Password}
newmap := map[string]interface{}{"metatitle": "created post", "post": p}
r.HTML(200, "form", newmap)
})
模板在templates文件夹下
测试
curl测试,-v可以显示客户端与服务端收发数据的详细信息
[curry@centos_base cloudgo]$ curl -v http://localhost:8080
* About to connect() to localhost port 8080 (#0)
* Trying ::1...
* Connected to localhost (::1) port 8080 (#0)
> GET / HTTP/1.1
> User-Agent: curl/7.29.0
> Host: localhost:8080
> Accept: */*
>
< HTTP/1.1 200 OK
< Content-Type: text/html; charset=UTF-8
< Date: Sat, 17 Nov 2018 05:28:46 GMT
< Content-Length: 855
<
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="index.css">
<link rel="icon" href="http://courses.cs.washington.edu/courses/cse190m/09sp/homework/1/pie_icon.gif" type="image/x-icon">
<meta charset="utf-8">
<title>Hello world</title>
</head>
<body>
<div id="image">
<img src="img.jpg" height="100%" width="100%" />
</div>
<div>
<p class="name">Welcome, Zhi Hao</p>
<p class="content">Now is Sat Nov 17 05:28:46 UTC 2018</p>
</div>
<div id="the_form">
<form method="post" action="/">
<p>Username:</p>
<input type="text" name="username"><br />
<p>Password:</p>
<input type="password" name="password"><br />
<input type="submit" value="登录" id="submit">
</form>
</div>
</body>
* Connection #0 to host localhost left intact
</html>
ab压力测试, -n 1000 -c 1000发送1000个请求,并发为100个
[curry@centos_base cloudgo]$ ab -n 1000 -c 100 http://localhost:8080/
This is ApacheBench, Version 2.3 <$Revision: 1430300 $>
Copyright 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/
Licensed to The Apache Software Foundation, http://www.apache.org/
Benchmarking localhost (be patient)
Completed 100 requests
Completed 200 requests
Completed 300 requests
Completed 400 requests
Completed 500 requests
Completed 600 requests
Completed 700 requests
Completed 800 requests
Completed 900 requests
Completed 1000 requests
Finished 1000 requests
Server Software:
Server Hostname: localhost
Server Port: 8080
Document Path: /
Document Length: 855 bytes
Concurrency Level: 100
Time taken for tests: 0.385 seconds
Complete requests: 1000
Failed requests: 0
Write errors: 0
Total transferred: 972000 bytes
HTML transferred: 855000 bytes
Requests per second: 2599.89 [#/sec] (mean)
Time per request: 38.463 [ms] (mean)
Time per request: 0.385 [ms] (mean, across all concurrent requests)
Transfer rate: 2467.87 [Kbytes/sec] received
Connection Times (ms)
min mean[+/-sd] median max
Connect: 0 4 5.5 3 35
Processing: 1 33 18.4 29 83
Waiting: 1 26 17.0 19 81
Total: 4 37 19.0 31 90
Percentage of the requests served within a certain time (ms)
50% 31
66% 48
75% 50
80% 52
90% 63
95% 79
98% 83
99% 83
100% 90 (longest request)
代码地址
https://github.com/CurryYuan/cloudgo
参考博客
http://techslides.com/simple-app-with-go-martini-gorp-and-mysql