设为首页 加入收藏

TOP

Golang:使用 httprouter 构建 API 服务器(四)
2017-10-21 06:06:53 】 浏览:2034
Tags:Golang 使用 httprouter 构建 API 服务器
ams) { return func(w http.ResponseWriter, r *http.Request, param httprouter.Params) { start := time.Now() log.Printf("%s %s", r.Method, r.URL.Path) fn(w, r, param) log.Printf("Done in %v (%s %s)", time.Since(start), r.Method, r.URL.Path) } }

我们来看看路由。首先,在一个地方集中定义所有路由,比如 routes.go

package main

import "github.com/julienschmidt/httprouter"

/*
Define all the routes here.
A new Route entry passed to the routes slice will be automatically
translated to a handler with the NewRouter() function
*/
type Route struct {
    Name        string
    Method      string
    Path        string
    HandlerFunc httprouter.Handle
}

type Routes []Route

func AllRoutes() Routes {
    routes := Routes{
        Route{"Index", "GET", "/", Index},
        Route{"BookIndex", "GET", "/books", BookIndex},
        Route{"Bookshow", "GET", "/books/:isdn", BookShow},
        Route{"Bookshow", "POST", "/books", BookCreate},
    }
    return routes
}

让我们创建一个 NewRouter 函数,它可以在 main 函数中调用,它读取上面定义的所有路由,并返回一个可用的 httprouter.Router。因此创建一个文件 router.go。我们还将使用新创建的 Logger 函数来包装 handler。

package main

import "github.com/julienschmidt/httprouter"

//Reads from the routes slice to translate the values to httprouter.Handle
func NewRouter(routes Routes) *httprouter.Router {

    router := httprouter.New()
    for _, route := range routes {
        var handle httprouter.Handle

        handle = route.HandlerFunc
        handle = Logger(handle)

        router.Handle(route.Method, route.Path, handle)
    }

    return router
}

您的目录此时应该像这样:

.
├── handlers.go
├── handlers_test.go
├── logger.go
├── main.go
├── models.go
├── responses.go
├── router.go
└── routes.go

这里[4]查看完整代码。

这应该可以让你开始编写你自己的 API 服务器了。 你当然需要把你的功能放在不同的包中,所以一个好办法就是:

.
├── LICENSE
├── README.md
├── handlers
│   ├── books_test.go
│   └── books.go
├── models
│   ├── book.go
│   └── *
├── store
│   ├── *
└── lib
|   ├── *
├── main.go
├── router.go
├── rotes.go

如果您有一个大的单体服务器,您还可以将 handlersmodels 和所有路由功能都放在另一个名为 app 的包中。只要记住,go 不像 Java 或 Scala 那样可以有循环的包调用。因此你必须格外小心您的包结构。

这就是全部内容,希望本教程能对您有用。干杯!

首页 上一页 1 2 3 4 下一页 尾页 4/4/4
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇golang单例模式 下一篇Go语言备忘录(3):net/http包的..

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目