cloudgo-gin实践

框架

目前,基于Go的web框架也可谓是百花齐放了,之所以选择gin,没其他原因,就只是因为其在github上的star数是最多的,而且仅仅从README看,其文档也是相当丰富的。
还有一个原因就是,速度快,介绍中说相比于martini有40倍的提升。

code

router.go 把路由抽离出来,我们在路由文件中封装路由函数

package route

import (
	"github.com/gin-gonic/gin"
)

//把路由抽离出来,我们在路由文件中封装路由函数
func Router() *gin.Engine {
	// 生成默认路由
	router := gin.Default()

	// 设置路径的处理,后台作出的反应
	router.GET("/", indexHandler)

	router.POST("/login", loginHandler)

	return router
}

indexHandler.go

package route

import (
	"net/http"

	"github.com/gin-gonic/gin"
)

// index handler returns hello world
func indexHandler(c *gin.Context) {
	c.String(http.StatusOK, "hello World!")
}

loginHandler.go

package route

import (
	"github.com/gin-gonic/gin"
)

type user struct {
	Username string `json:"username"`
	Password string `json:"password"`
}

//login handler get form and judge if login successfully
func loginHandler(c *gin.Context) {
	form := user{}

	if c.Bind(&form) == nil {
		if form.Username == "root" && form.Password == "root" {
			c.JSON(200, gin.H{"status": "登陆成功"})
		} else {
			c.JSON(203, gin.H{"status": "账号或者密码错误"})
		}
	}

}

main.go

package main

import (
	"os"

	route "github.com/HzYoung/cloudgo/route"

	flag "github.com/spf13/pflag"
)

const (
	PORT string = "8080"
)

func main() {
	port := os.Getenv("PORT")
	//查看本地 port 如果不存在,便使用我们默认的端口
	if len(port) == 0 {
		port = PORT
	}
	// 读取终端中输入的端口号
	pPort := flag.StringP("port", "p", PORT, "PORT for httpd listening")
	flag.Parse()
	if len(*pPort) != 0 {
		port = *pPort
	}

	// 调用路由
	router := route.Router()

	// 启动服务,服务器为 host:port
	router.Run(":"+port)
}

测试

运行服务端

[yhz@centos-manager cloudgo]$ go run main.gGIN-debug] [WARNING] Creating an Engine instance with the Logger and Recovery middleware already attached.

[GIN-debug] [WARNING] Running in "debug" mode. Switch to "release" mode in production.
- using env:	export GIN_MODE=release
- using code:	gin.SetMode(gin.ReleaseMode)

[GIN-debug] GET    /                         --> github.com/HzYoung/cloudgo/route.indexHandler (3 handlers)
[GIN-debug] POST   /login                    --> github.com/HzYoung/cloudgo/route.loginHandler (3 handlers)
[GIN-debug] Listening and serving HTTP on :8080

打开 一个新的终端作客户端 ,对服务端进行访问

GET测试

[yhz@centos-manager 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/plain; charset=utf-8
< Date: Sun, 20 Jan 2019 00:20:17 GMT
< Content-Length: 12
< 
* Connection #0 to host localhost left intact
hello World!

POST测试(json数据)

[yhz@centos-manager cloudgo]$ curl -v http://localhost:8080/login -X POST -H "Content-Type:application/json" -d '{"username":"root","password":"root"}'
* About to connect() to localhost port 8080 (#0)
*   Trying ::1...
* Connected to localhost (::1) port 8080 (#0)
> POST /login HTTP/1.1
> User-Agent: curl/7.29.0
> Host: localhost:8080
> Accept: */*
> Content-Type:application/json
> Content-Length: 37
> 
* upload completely sent off: 37 out of 37 bytes
< HTTP/1.1 200 OK
< Content-Type: application/json; charset=utf-8
< Date: Sun, 20 Jan 2019 02:18:01 GMT
< Content-Length: 25
< 
* Connection #0 to host localhost left intact
{"status":"登陆成功"}

压力测试

[yhz@centos-manager 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:        12 bytes

Concurrency Level:      100
Time taken for tests:   0.142 seconds
Complete requests:      1000
Failed requests:        0
Write errors:           0
Total transferred:      129000 bytes
HTML transferred:       12000 bytes
Requests per second:    7049.45 [#/sec] (mean)
Time per request:       14.186 [ms] (mean)
Time per request:       0.142 [ms] (mean, across all concurrent requests)
Transfer rate:          888.07 [Kbytes/sec] received

Connection Times (ms)
              min  mean[+/-sd] median   max
Connect:        0    5   2.2      5      14
Processing:     1    8   4.7      7      27
Waiting:        0    6   4.4      5      26
Total:          5   13   4.1     12      29

Percentage of the requests served within a certain time (ms)
  50%     12
  66%     13
  75%     15
  80%     16
  90%     20
  95%     23
  98%     23
  99%     27
 100%     29 (longest request)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值