RESTfull API是现在很流行的API设计风格。众所周知HTTP1.1规范正是基于REST架构风格的指导原理来设计的。需要注意的是,REST是一种风格而不是标准。如果一个架构复合REST原则,我们就称它为RESTful架构。
先来实现一个最简单的,启动一个RESTFul服务。代码示例:
package main
import (
"net/http"
"fmt"
"html"
"log"
)
func main() {
http.HandleFunc("/", func(writer http.ResponseWriter, request *http.Request) {
fmt.Fprintln(writer, "Hello, ", html.EscapeString(request.URL.Path))
})
log.Fatal(http.ListenAndServe(":8080",nil))
}
运行这段代码,然后打开浏览器访问http://localhost:8080。
然后再加上路径看看http://localhost:8080/joel/mak。你会发现网页输出了如下内容:
hello, /joel/mak
是的,它输出了当前的路径。路径又称"终点"(endpoint),用来表示API的具体地址。在RESTFul架构中,每个网址代表一个个资源(resource)。为了更好的使用这些网址,我们需要有统一的路径分发功能。这里使用第三方的包(Gorila Muxpackage):"github.com/gorilla/mux"。
那么根据路径的不同,需要有不同的函数来各自实现。代码中,我们用Index、TodoIndex、TodoShow三个函数来实现不同内容的页面打印。
package main
import (
"github.com/gorilla/mux"
"net/http"
"fmt"
"log"
)
func main() {
router := mux.NewRouter().StrictSlash(true)
router.HandleFunc("/", Index)
router.HandleFunc("/todos", TodoIndex)
router.HandleFunc("/todos/{todoId}", TodoShow)
log.Fatal(http.ListenAndServe(":8080", router))
}
func TodoShow(writer http.ResponseWriter, request *http.Request) {
vars := mux.Vars(request)
todoId := vars["todoId"]
fmt.Fprintln(writer, "Todo show:", todoId)
}
func TodoIndex(writer http.ResponseWriter, request *http.Request) {
fmt.Fprintln(writer, "Todo Index!",request.URL.Path)
}
func Index(writer http.ResponseWriter, request *http.Request) {
fmt.Fprintln(writer, "Welcome!")
}
运行以上代码。然后,在浏览器中输入http://localhost:8080,页面显示:
Welcome!
在浏览器中输入http://localhost:8080/todos,页面显示:
Todo Index! /todos
在浏览器中输入http://localhost:8080/todos/{123},页面显示:
Todo show: {123}
按照一般的软件过程,我们再把上面的代码进行抽象,分别把数据模型和功能抽象成Todo.go, Routes.go、Handlers.go。
以下为代码示例
main.go
package main
import (
"net/http"
"log"
)
func main() {
router := NewRouter()
log.Fatal(http.ListenAndServe(":8080", router))
}
Todo.go
package main
import "time"
type Todo struct {
Id int `json:"id"`
Name string `json:"name"`
Completed bool `json:"completed"`
Due time.Time `json:"due"`
}
type Todos []Todo
go语言没有class,必须使用结构体来构造数据模型Todo。
Routes.go
package main
import "net/http"
type Route struct {
Name string
Method string
Pattern string
HandlerFunc http.HandlerFunc
}
type Routes []Route
var routes = Routes{
Route{Name:"Index", Method:"GET", Pattern:"/", HandlerFunc:Index},
Route{Name:"TodoIndex", Method:"GET", Pattern:"/todos", HandlerFunc:TodoIndex},
Route{Name:"TodoShow", Method:"GET", Pattern:"/todos/{todoId}", HandlerFunc:TodoShow},
}
go语言没有class,必须使用结构体来构造数据模型Route。
建立一个变量routes,按照Route结构存放了多个Route。而每个Route对应了不同的路径。其中不同的HandlerFunc在Handlers.go中实现。
Handlers.go
package main
import (
"net/http"
"fmt"
"encoding/json"
"github.com/gorilla/mux"
"time"
)
func Index(w http.ResponseWriter, r *http.Request) {
fmt.Fprintln(w, "Welcome!")
}
func TodoIndex(w http.ResponseWriter, r *http.Request) {
todos := Todos{
Todo{Name:"Write presentation"},
Todo{Name:"Host meetup"},
Todo{Id:22,Name:"Joel",Completed:true,Due:time.Now()},
}
if err := json.NewEncoder(w).Encode(todos); err != nil{
panic(err)
}
}
func TodoShow(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
todoId := vars["todoId"]
fmt.Fprintln(w, "Todo show:", todoId)
}
分别实现了Index、TodoIndex、TodoShow,以便Route调用。
Router.go
package main
import (
"github.com/gorilla/mux"
"net/http"
)
func NewRouter() *mux.Router {
router := mux.NewRouter().StrictSlash(true)
for _, route := range routes {
var handler http.Handler
handler = route.HandlerFunc
handler = logger(handler, route.Name)
router.
Methods(route.Method).
Path(route.Pattern).
Name(route.Name).
Handler(handler)
}
return router
}
Router里的handler=logger(handler,route.Name)是做什么的?这是日志。多数现代的web服务都会一个日志。go语言的标准库里没有web loging包。我们需要自己创建一个。
当程序运行的时候,就会有运行日志记录下来。
Logger.go
package main
import (
"net/http"
"time"
"log"
)
func logger(inner http.Handler, name string) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
start := time.Now()
inner.ServeHTTP(w, r)
log.Printf("CofoxAPI: %s\t%s\t%s\t%s", r.Method, r.RequestURI, name, time.Since(start))
})
}
记录每次访问的时间、方法、路径及耗时。
参考:
https://www.yuque.com/docs/share/36f37607-2228-4f77-81c0-a693b2df7564