LoginSignup
8
3

More than 5 years have passed since last update.

[go,echo]formからputをリクエスト~methodOverRide~

Posted at

htmlのformには、action属性にgetとpostしか取れないため、deleteやputなどを指定できない。ではどうすれば、良いかというと、例えば、phpでは

<form>
 <input type="hidden" name="_method" value="PATCH">
</form>

を書き入れればphp側でよしなに、処理してくれ、patchメソッドが走るようにしてくれている。
しかし、goでは同じように書いても動くわけがなく、上記の仕組みを自分で作成する必要がある。

では、どのようにすればいいかと言うと、routerのprocessが走る前に、処理されるmiddlewareを用意しなければならない。以下、golangのechoを使用しますが、フレームワークを使わなくてもほぼ同じです。

まず、main関数内で以下のようにMethodOverrideを読み込みます。

e.Pre(controllers.MethodOverride)

これで、routerが走る前に最初に動かせます。私は、最初e.Useでも動くと思っていたのですが、うごかず積みました。公式にも、methodOverRideにはe.Preを使えと書いてありました。

スクリーンショット 2018-12-22 18.59.18.png

で、読み込むmiddleWareですが、以下のような関数になります。

func MethodOverride(next echo.HandlerFunc) echo.HandlerFunc {
    return func(c echo.Context) error {
        if c.Request().Method == "POST" {
            method := c.Request().PostFormValue("_method")
            if method == "PUT" || method == "PATCH" || method == "DELETE" {
                c.Request().Method = method
            }
        }
        fmt.Println(c.Request())
        return next(c)
    }
}

つまり、Postメソッドが動いた際に、if以下が処理されます。methodに自分が使いたいhttp method(putやdelete,patchなど)を代入し、requestのmethodを書き換えてやります。そしてチェインさせて、次の関数を呼び出します。

adminGroup.PATCH("/update", controllers.UpdateAdminUser)

以上です。

この記事に標準パッケージのみを使った同様の方法が書いてあります。
https://www.alexedwards.net/blog/http-method-spoofing

8
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
8
3