1. 程式人生 > >Go語言實現簡單web應用cloudgo

Go語言實現簡單web應用cloudgo

cloudgo

框架選擇 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可以顯示客戶端與服務端收發資料的詳細資訊

[[email protected]_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個

[[email protected]_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)

程式碼地址

參考部落格