[go] Golang入門教學: 使用gin-gonic建立API Server






gin-gonic是甚麼

gin-gonic是一個go的http web framework,在一些benchmark的測試中,效能算是數一數二的,使用起來也蠻容易的,可以參考官方在github的介紹。
https://github.com/gin-gonic/gin








安裝方法

使用go get就可以安裝了,相當簡單,在終端輸入:
go get -u github.com/gin-gonic/gin
就可以完成安裝。



Hello World API

延續上個Hello World的專案,我們將他修改為API Server,

▼將main.go修改一下
package main

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

func main() {
    apiServer := gin.New()
    apiServer.GET("/hello", HelloWorld)

    apiServer.Run(":3388")
}

func HelloWorld(context *gin.Context) {
    context.JSON(http.StatusOK, "Hello World")
}

▼簡單說明一下這段程式


意思就是建立一個apiserver,listen的port是3388,並加入一個method為GET的endpoint,endpoint要進行的工作對應到HelloWorld這個function。

▼接著我們在瀏覽器輸入http://127.0.0.1:3388/hello,就可以看到輸出結果了,非常輕鬆愉快。








Web Server

再稍微進階一點,我們可以把api server變成web server,首先我們先加入建立一個web的資料夾,並新增一個index.html檔案。

▼index.html
<html>
    <h1>
        Hello World !!
    </h1>
</html>

▼接著修改main.go
package main

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

func main() {
    apiServer := gin.New()
    apiServer.LoadHTMLGlob("web/*")

    apiServer.GET("/hello", HelloWorld)

    apiServer.Run(":3388")
}

func HelloWorld(context *gin.Context) {
    context.HTML(http.StatusOK, "index.html", "")
}

▼簡單說明一下這段程式


▼從瀏覽器可以看出已經依照index.html的內容回應了








Post Form

▼最後我們可以再將index.html修改成回應式的表單
<html>
    <h1>
        Hello {{ .username }} !!
    </h1>

    <form method="post">
        username:<input type="text" name="UserName"><br>
        <input type="submit" value="submit">
    </form>
</html>

{{ .username }}代表會根據從server端接收到的變數而有所不同。

▼再來修改一下main.go,讓endpoint增加可以支援POST的function
package main

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

func main() {
    apiServer := gin.New()
    apiServer.LoadHTMLGlob("web/*")

    apiServer.GET("/hello", HelloWorldGet)
    apiServer.POST("/hello", HelloWorldPost)

    apiServer.Run(":3388")
}

func HelloWorldGet(context *gin.Context) {
    context.HTML(http.StatusOK, "index.html", gin.H{
        "username": "",
    })
}

func HelloWorldPost(context *gin.Context) {
    username := context.PostForm("UserName")
    context.HTML(http.StatusOK, "index.html", gin.H{
        "username": username,
    })
}

▼說明一下main.go修改了甚麼內容


可以看出/hello這個endpoint,根據method的不同(GET,POST),對應到了兩個不同的function。而在POST對的function中,取得了表單送出的username後再回應給client端

▼最後測試跑一下看看,如此便完成了動態網頁的雛形。


較新的 較舊