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
如果您有一个大的单体服务器,您还可以将 handlers
、models
和所有路由功能都放在另一个名为 app
的包中。只要记住,go 不像 Java 或 Scala 那样可以有循环的包调用。因此你必须格外小心您的包结构。
这就是全部内容,希望本教程能对您有用。干杯!
注