From PHP Laravel to go iris--routing Chapter

Source: Internet
Author: User
Tags php web development subdomain
This is a creation in Article, where the information may have evolved or changed.

Laravel is my favorite PHP Web development framework, so I also want to be able to choose a useful and full stack frame like laravel in the Go Web frame, brush the Beego, Echo, Gin, and Iris documents, and finally choose Iris, Of course, I did not consider from a performance perspective, but from the rapid development, and support features are all there is to look at the psychological choice of the pleasing to the iris, there should be a lot of phper like me to use laravel at the same time in learning go, so in order to facilitate laravel developers can quickly go to iris development , I'm going to write a series of comparative articles on the two frameworks.

Basic routing

Iris constructs the basic route and the basic route of the laravel very much like the one that only requires a URI and a closure:

Laravel

Route::get('foo', function () {    return 'Hello World';});

Iris

app.Get("/foo", func(ctx iris.Context) {    ctx.WriteString("Hello World")})

Available Routing methods

Iris, like Laravel, can respond to any HTTP request routing:

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);

Iris

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){})

The same support for registering a route that can respond to multiple HTTP requests

Laravel

Route::match(['get', 'post'], '/', function () {});Route::any('foo', function () {});

Iris

app.Any("/", func(ctx iris.Context){})

Route parameters

Required Parameters

Iris's definition of route required parameter is similar to Laravel, it is important to note that the laravel routing parameter cannot contain - characters and can be _ replaced with underscores :

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)})

Regular constraints

Iris also supports regular constraints, which are easy to set up directly in the routing parameters, and the Laravel routing settings can be where linked and intuitive:

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) {})

Global constraints

Iris does not have global constraints on routing parameters, Laravel can be RouteServiceProvider defined by the boot definitions in pattern , but Iris can macro constrain parameters by standard or custom 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()方法即可

Named routes

Iris and Laravel both support naming the specified route and are similar in the way:

Laravel

Route::get('user/profile', function () {})->name('profile');

Iris

app.Get("/user/profile", func(ctx iris.Context) {}).Name = "profile"

Generate links for naming

Laravel uses a route() method to generate a URL link based on the route name and parameters, Iris also provides a way to generate the link:

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

Check current route

Check whether the current request points to a reason:

Laravel

if ($request->route()->named('profile')) {}

Iris

if ctx.GetCurrentRoute().Name() == "profile" {}

Routing groups

Routing groups can share routing properties, Laravel supports the routing group Properties Iris also basically supports, and very much like, are elegant.

Middleware

Through the middleware can be constrained to the routing request, for the daily development is very useful, such as doing auth verification, can be directly through the middleware to do the isolation:

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)}

Sub-domain Routing

In Laravel, a routing group can be used as a wildcard for a sub-domain name, using the key of the routing group property to domain declare the subdomain. Iiris can be Party set directly by:

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) {        //    })}

Route prefixes

Add a prefix to the URL, Laravel through prefix , Iris or pass Party it.

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    })}

OK, these two web framework routing basic comparison and application of these, there are some such as controller routing and how to customize the middleware and so on in the subsequent re-write it, or please consult the documentation yourself, the above content if there are errors please indicate.

reprint Please specify: reproduced from Ryan is a rookie | LNMP Technology Stack Notes

If you think this article is very useful to you, why not give it a reward?

This article link address: from PHP Laravel to go iris--routing Chapter

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.