Restful Development¶
路由注册¶
通过路由函数¶
type DummyResource struct {
}
func (r *DummyResource) Sayhello(b *restful.Context) {
id := b.ReadPathParameter("userid")
b.Write([]byte(id))
}
//URLPatterns helps to respond for corresponding API calls
func (r *DummyResource) URLPatterns() []restful.Route {
return []restful.Route{
{Method: http.MethodGet, Path: "/sayhello/{userid}", ResourceFunc: r.Sayhello,
Returns: []*restful.Returns{{Code: 200}}},
}
}
路由分组¶
相同资源的多个路由可能会具备同样的路由前缀,这时候你可以使用路由分组来避免重复的路由前缀
type DummyResource struct {
}
//GroupPath returns group path will auto
func (r *DummyResource) GroupPath() string {
return "/demo"
}
func (r *DummyResource) Sayhello(b *restful.Context) {
id := b.ReadPathParameter("userid")
b.Write([]byte(id))
}
func (r *DummyResource) Panic(b *restful.Context) {
panic("panic msg")
}
//URLPatterns helps to respond for corresponding API calls
func (r *DummyResource) URLPatterns() []restful.Route {
return []restful.Route{
// will register path:/demo/sayhello
{Method: http.MethodGet, Path: "/sayhello", ResourceFunc: r.Sayhello,
Returns: []*restful.Returns{{Code: 200}}},
// will register path:/demo/sayhelloagain
{Method: http.MethodGet, Path: "/sayhelloagain", ResourceFunc: r.Sayhello,
Returns: []*restful.Returns{{Code: 200}}},
}
}