Laravel是我最喜歡的PHP Web開發框架,因此也但願能夠在Go的Web框架中選擇一個相似Laravel這樣的好用又全棧的框架,刷了一下Beego, Echo , Gin, 以及Iris的文檔,最終仍是選擇Iris,固然我是沒有從性能角度考慮,只是從能夠快速開發,且支持的特性全還有就是看着順眼的心理選擇了Iris,應該有很多PHPer像我同樣使用Laravel同時在學習Go,因此爲了便於Laravel開發者能夠快速的轉到Iris開發,我準備寫一系列這二者框架的比較文章。php
Iris構建基本路由和Laravel的基本路由很像,都只須要一個URI與一個閉包:laravel
Laravelgit
Route::get('foo', function () { return 'Hello World'; });
Irisgithub
app.Get("/foo", func(ctx iris.Context) { ctx.WriteString("Hello World") })
Iris和Laravel同樣,可以響應任何的HTTP請求路由:web
Laravel閉包
Route::get($uri, $callback); Route::post($uri, $callback); Route::put($uri, $callback); Route::patch($uri, $callback); Route::delete($uri, $callback); Route::options($uri, $callback);
Irisapp
app.Post("/", func(ctx iris.Context){}) app.Put("/", func(ctx iris.Context){}) app.Delete("/", func(ctx iris.Context){}) app.Options("/", func(ctx iris.Context){}) app.Trace("/", func(ctx iris.Context){}) app.Head("/", func(ctx iris.Context){}) app.Connect("/", func(ctx iris.Context){}) app.Patch("/", func(ctx iris.Context){})
對於註冊一個能夠響應多個HTTP請求的路由二者一樣都支持框架
Laraveldom
Route::match(['get', 'post'], '/', function () { }); Route::any('foo', function () { });
Iriside
app.Any("/", func(ctx iris.Context){})
Iris的定義路由必填參數和Laravel差很少,這裏須要注意下Laravel的路由參數不能包含 -
字符,能夠用用下劃線 _
替換:
Laravel
Route::get('user/{id}', function ($id) { return 'User '.$id; });
Iris
app.Get("/user/{id}", func(ctx iris.Context) { userID, err := ctx.Params().GetInt("userid") if err != nil { // } ctx.Writef("User %d", userID) })
Iris一樣支持正則約束,直接在路由參數中設置很方便,Laravel的路由設置能夠經過where
鏈式方法,也很直觀:
Laravel
Route::get('user/{name}', function ($name) { })->where('name', '[A-Za-z]+');
Iris
app.Get("/user/{name:string regexp(^[A-Za-z]+)}", func(ctx iris.Context) {})
Iris沒有對路由參數全局約束,Laravel能夠經過RouteServiceProvider
的boot
中定義pattern
來定義,可是Iris能夠經過標準的macro
或者自定義macro
來約束參數:
Laravel
public function boot() { Route::pattern('id', '[0-9]+'); parent::boot(); }
Iris
app.Get("/profile/{id:int min(3)}", func(ctx iris.Context) { }) //固然標準的 macro 除了int 還有string,alphabetical,file,path固然你也能夠本身註冊一個macro來改變約束規則 app.Macros().String.RegisterFunc("equal", func(argument string) func(paramValue string) bool { return func(paramValue string){ return argument == paramValue } }) //實現app.Macros().類型.RegisterFunc()方法便可
Iris和Laravel都支持給指定的路由命名,並且方式很像:
Laravel
Route::get('user/profile', function () { })->name('profile');
Iris
app.Get("/user/profile", func(ctx iris.Context) { }).Name = "profile"
Laravel經過route()
方法來根據路由名和參數生成URL連接,Iris也提供了對應的方法來生成連接:
Laravel
$url = route('profile', ['id' => 1]);
Iris
rv := router.NewRoutePathReverser(app) url := rv.URL("profile",1) //URL(routeName string, paramValues ...interface{}) //Path(routeName string, paramValues ...interface{} 不包含host 和 protocol
檢查當前請求是否指向了某理由:
Laravel
if ($request->route()->named('profile')) {}
Iris
if ctx.GetCurrentRoute().Name() == "profile" {}
路由組能夠共享路由屬性,Laravel所支持的路由組屬性Iris也基本都支持,並且很像,都很優雅.
經過中間件能夠對路由請求約束,對於平常開發很是有用,好比作Auth驗證,能夠直接經過中間件來作隔離:
Laravel
Route::middleware(['auth'])->group(function () { Route::get('user/profile', function () { // 使用 auth 中間件 }); });
Iris
authentication := basicauth.New(authConfig) needAuth := app.Party("/user", authentication) { needAuth.Get("/profile", h) }
在Laravel中,路由組能夠用做子域名的通配符,使用路由組屬性的 domain
鍵聲明子域名。Iiris能夠經過Party
來直接設置:
Laravel
Route::group(['domain' => '{subdomain}.myapp.com'], function () { Route::get('user/{id}', function ($account, $id) { // }); });
Iris
subdomain := app.Party("subdomain.") { subdomain.Get("/user/{id}", func(ctx iris.Context) { // }) } dynamicSubdomains := app.Party("*.") { dynamicSubdomains.Get("/user/{id}", func(ctx iris.Context) { // }) }
給URL添加前綴,Laravel 經過prefix
,Iris仍是經過Party
就能夠了
Laravel
Route::prefix('admin')->group(function () { Route::get('users', function () { // 匹配包含 "/admin/users" 的 URL }); });
Iris
adminUsers := app.Party("/admin") { adminUsers.Get("/users", , func(ctx iris.Context) { // 匹配包含 "/admin/users" 的 URL }) }
好了,這兩個web框架的路由基本比較和應用就這些了,還有一些好比控制器路由和如何自定義中間件等在後續再寫吧,或者請自行查閱文檔,以上內容若有錯誤請指出。
轉載請註明: 轉載自Ryan是菜鳥 | LNMP技術棧筆記
若是以爲本篇文章對您十分有益,何不 打賞一下
本文連接地址: 從PHP Laravel 到 Go Iris--路由篇