package handler
import (
"encoding/json""io/ioutil""net/http""github.com/labstack/echo""gitlab.com/ykyuen/golang-echo-template-example/model"
)
funcAboutHandler(c echo.Context) error {
tr := &http.Transport{}
client := &http.Client{Transport: tr}
// Call the api
resp, err := client.Get(
"http://localhost:1323/api/get-full-name?first_name=Kit&last_name=Yuen",
)
if err != nil {
return err
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
// Unmarshal the response into a ExampleResponse struct
var exampleResponse model.ExampleResponse
if err = json.Unmarshal(body, &exampleResponse); err != nil {
return err
}
// Please note the the second parameter "about.html" is the template name and should
// be equal to one of the keys in the TemplateRegistry array defined in main.go
return c.Render(http.StatusOK, "about.html", map[string]interface{}{
"name": "About",
"msg": exampleResponse.Msg,
})
}
handling-http-request-in-go-echo-example-1/
├── api/ # folder of api endpoints
│ ├── get_full_name.go # api for get full name
├── handler/ # folder of request handlers
│ ├── home_handler.go # handler for home page
│ └── about_handler.go # handler for about page
├── model/ # folder of custom struct types
│ ├── example_request.go # struct type of get_full_name request
│ └── example_response.go # hstruct type of get_full_name response
├── vendor/ # dependencies managed by dep
│ ├── github.com/*
│ └── golang.org/*
├── view/ # folder of html templates
│ ├── base.html # base layout template
│ ├── home.html # home page template
│ └── about.html # about page template
├── Gopkg.lock # dep config file
├── Gopkg.toml # dep config file
└── main.go # programme entrypoint
總結
本文介紹如何在 Echo 框架中設置簡單的 API 端點。由於 Go 是一種強型別語言,因此我們必須先將 JSON 請求與回應的結構型別,然後才能操作其內容。例如:
在 api/get_full_name.go 將 GET 請求綁定到 exampleRequest。
在 handler/about_handler.go 將 GET 回應解組為 exampleResponse。