handler ของ Laravel Go คือ function ธรรมดาที่รับ *web.Request แล้วคืน *web.Response ไม่มี controller class route ยังเขียนเรียงกันในไฟล์ routes/web.go คล้าย routes/web.php และ FormRequest กลายเป็น struct ที่มี method Rules() พอ validation ไม่ผ่าน แอปจะ redirect กลับหน้าเดิมหรือตอบ 422 เป็น JSON แบบเดียวกับที่ Laravel PHP ทำ frontend เดิมที่อ่าน errors อยู่แล้วเลยไม่ต้องแก้อะไร
ตัวอย่างทั้งหมดมาจากแอปทดลองที่มีตาราง posts (title, slug, votes) ลองยิง request จริงทุกตัวครับ
Handler แทน controller
ฝั่ง PHP เรามักมี PostController ที่รวม method index, show, store ไว้ด้วยกัน ฝั่ง Go เขียนเป็น package handlers/posts แล้วแต่ละ action เป็น function หนึ่งตัว
class PostController extends Controller
{
public function show(Post $post)
{
return $post;
}
}
package posts
func Show(r *web.Request) *web.Response {
post, err := model.FromRoute[models.Post](r, "post")
if err != nil {
return web.Fail(err)
}
return web.JSON(post)
}
สังเกตว่า Go ไม่ type-hint Post $post แล้วได้ model มาเอง เราเรียก model.FromRoute ขอ model จาก parameter ชื่อ post เอง ถ้าหาไม่เจอ (หรือค่าใน URL ไม่ใช่ id เลย เช่น /posts/abc) จะได้ error กลับมา แล้ว web.Fail แปลงเป็น 404 ให้
HTTP/1.1 404 Not Found
{"message":"db: no row in posts matched the query"}
รูปแบบ if err != nil { return web.Fail(err) } จะเจอแทบทุก handler เพราะ Go ไม่มี exception ทุกอย่างที่พังได้คืน error กลับมาให้เราส่งต่อเอง ช่วงแรกจะรู้สึกว่าเขียนซ้ำเยอะ แต่อ่านแล้วรู้ทันทีว่าบรรทัดไหนออกจาก function ได้บ้าง
response ที่ใช้บ่อยมี web.JSON, web.Text, web.Back(), web.Redirect และ web.RedirectRoute เทียบได้กับ response()->json(), back() และ to_route()
การเขียน route และ route group
Route::get('/posts/{post}', [PostController::class, 'show'])->name('posts.show');
Route::prefix('admin')->middleware('auth')->group(function () {
Route::get('/', [DashboardController::class, 'show']);
});
func Web(route *routing.Router, cfg *config.Config) {
route.Get("/posts/{post}", posts.Show).Name("posts.show")
route.Prefix("/admin").Middleware(auth.Authenticate{}).Group(func(route *routing.Router) {
route.Get("/", dashboard.Show)
})
}
อ่านแทบเหมือนกันทุกบรรทัด ต่างกันที่ middleware เป็น struct แทนชื่อ string และ Prefix คืน router ตัวใหม่ เราเก็บใส่ตัวแปรแล้วใช้ต่อแบบไม่ต้องมี Group ก็ได้
admin := route.Prefix("/admin").Middleware(auth.Authenticate{})
admin.Get("/", dashboard.Show)
admin.Get("/billing", billing.Show).Middleware(auth.RequireVerifiedEmail{})
route CRUD ครบชุดก็มี Resource ให้เหมือน Route::resource ชื่อ route ออกมาเป็น photos.index, photos.show และอื่น ๆ ตามแบบเดิม field ไหนไม่ใส่ก็ไม่สร้าง route นั้น
route.Resource("photos", routing.Resource{
Index: photos.Index,
Store: photos.Store,
Show: photos.Show,
Update: photos.Update,
Destroy: photos.Destroy,
})
ลิงก์ไปหา route ที่ตั้งชื่อไว้ใช้ urls.Route แทน helper route() ส่ง model เข้าไปแทน id ได้เลย
link, err := urls.Route(r, "posts.show", "post", &post) // http://localhost/posts/42
return web.RedirectRoute("posts.show", "post", &post)
Route parameter กับการหา model จาก URL
อยากหาด้วยคอลัมน์อื่นแทน id ก็เขียน {post:slug} แบบเดียวกับ PHP ได้เลย และจำกัดค่าด้วย Where กับ constraint ใน package routing เทียบได้กับ whereNumber() ของ PHP
route.Get("/posts/{post}", posts.Show).Name("posts.show").Where("post", routing.Number)
route.Get("/blog/{post:slug}", posts.Show).Name("blog.show")
handler posts.Show ตัวเดิมใช้ได้กับทั้งสอง route เพราะ FromRoute ดูเองว่า route นั้นหาด้วยคอลัมน์ไหน ลอง /blog/ ตามด้วย slug ภาษาไทยที่ encode แล้วก็หาเจอปกติ ลอง /posts/abc ได้ 404 ตั้งแต่ก่อนเข้า handler
ถ้าเผลอเขียน route สองตัวที่รับ request ชุดเดียวกัน เช่น /api/{name} กับ /api/{slug} แอปจะไม่ยอม start และบอกบรรทัดที่ชนกันมาเลยครับ
routing: 1 of the routes can't be registered:
routes/api.go:15: GET /api/{slug}: pattern "GET /api/{slug}" conflicts with pattern "GET /api/{name}": GET /api/{slug} matches the same requests as GET /api/{name}
Laravel PHP ใช้ route ตัวที่ประกาศก่อนแล้วเงียบไป บางทีเราเพิ่งรู้ตอนมีคนบอกว่าหน้าเปิดไม่ตรง
FormRequest ในรูป struct
ฝั่ง PHP เขียน FormRequest ประมาณนี้
class StorePostRequest extends FormRequest
{
public function rules(): array
{
return [
'title' => ['required', 'max:20'],
'votes' => ['integer', 'min:0'],
];
}
}
ฝั่ง Go เป็น struct ที่มี field ตรงกับ input แล้วผูก rule กับ field ด้วย pointer &f.Title ชื่อ field ใน JSON มาจาก tag json:"title"
type StorePost struct {
Title string `json:"title"`
Votes int64 `json:"votes"`
}
func (f *StorePost) Rules() validation.Rules {
return validation.For(f,
rule.Field(&f.Title, rule.Required, rule.Max(20)),
rule.Field(&f.Votes, rule.Min(0)),
)
}
func Store(r *web.Request) *web.Response {
form, err := r.Validate[StorePost]()
if err != nil {
return web.Fail(err)
}
post := models.Post{Title: form.Title, Slug: str.Slug(form.Title), Votes: form.Votes}
if err := model.Create(r, &post); err != nil {
return web.Fail(err)
}
return web.JSON(post)
}
r.Validate[StorePost]() อ่าน body เข้า struct แล้วตรวจ rule ให้ในคราวเดียว ได้ form ที่มี type ชัดเจนกลับมา ไม่ต้อง $request->validated() แล้วหยิบ key จาก array เอง ถ้าพิมพ์ชื่อ field ผิด เช่น form.Titel ก็ build ไม่ผ่าน
rule integer ไม่ต้องเขียน type int64 บอกอยู่แล้ว ลองส่ง title ว่างกับ votes เป็นตัวหนังสือดู
HTTP/1.1 422 Unprocessable Entity
{"message":"The title field is required. (and 1 more error)","errors":{"title":["The title field is required."],"votes":["The votes field must be an integer."]}}
หน้าตาเดียวกับ 422 ของ Laravel PHP ทุก key ถ้าเป็นฟอร์มบนหน้า web ที่ใช้ session หรือ Inertia จะได้ redirect กลับหน้าเดิมพร้อม errors แทน web.Fail เลือกให้เองตามชนิดของ request
ข้อความภาษาไทยตั้งได้ทีละ rule ด้วย .Message() และเปลี่ยนชื่อ field ที่โชว์ด้วย .Label() Laravel Go ยังไม่มีไฟล์แปลภาษาแบบ lang/th/validation.php
rule.Field(&f.Title, rule.Required.Message("กรุณากรอก:attribute"), rule.Max(20)).Label("หัวข้อ"),
{"errors":{"title":["กรุณากรอกหัวข้อ"],"votes":["The votes field must be an integer."]},"message":"กรุณากรอกหัวข้อ (and 1 more error)"}
สิทธิ์ส่งฟอร์มด้วย Authorize
authorize() ของ FormRequest ย้ายมาเป็น method Authorize บน struct เดียวกัน r.Validate เรียก method นี้ก่อนอ่าน input ถ้าไม่ผ่านก็ได้ 403 ไม่เห็น validation error
func (UpdatePost) Authorize(r *web.Request) error {
post, err := model.FromRoute[models.Post](r, "post")
if err != nil {
return err
}
user := r.User[models.User]()
if user == nil || user.ID != post.UserID {
return auth.Deny("แก้ได้เฉพาะโพสต์ของตัวเอง")
}
return nil
}
auth.Allow(bool) ใช้กับเงื่อนไขสั้น ๆ ฟอร์มที่ขอแค่ให้ล็อกอินก็คืน auth.Authenticated(r) guest จะเด้งไปหน้า login หรือได้ 401 ถ้าเป็น request JSON ถ้ามี policy อยู่แล้วก็เรียก auth.Authorize(r, policies.UpdatePost(&post)) ได้
Rules รับ r *web.Request ได้ด้วย เผื่อ rule ต้องเปลี่ยนตามคนที่ส่ง เช่น ผู้ใช้แพ็กเกจ premium ตั้งชื่อยาวได้กว่า
ฟอร์มแก้ไขที่ส่งมาแค่บาง field
request แบบ PATCH หรือฟอร์ม Inertia ที่ส่งเฉพาะ field ที่เปลี่ยน มีปัญหาที่ Go ต้องคิดมากกว่า PHP ครับ struct ของ Go ไม่มี "ไม่ได้ส่งมา" field ที่ไม่ได้ส่งจะเป็นค่าว่างของ type นั้น ("" หรือ 0) Laravel Go แก้ด้วย validation.Sometimes[T]
type EditProfile struct {
Name validation.Sometimes[string] `json:"name"`
Bio validation.Sometimes[*string] `json:"bio"`
}
func (f *EditProfile) Rules() validation.Rules {
return validation.For(f,
rule.Field(&f.Name, rule.Required, rule.Max(255)),
rule.Field(&f.Bio, rule.Max(1000)),
)
}
field ที่ไม่ได้ส่งมาจะข้าม rule ทั้งหมด rule.Required เลยมีความหมายว่า "ถ้าส่งมาต้องไม่ว่าง" คล้าย sometimes|required ของ PHP แล้วส่ง form.Name กับ form.Bio เข้า model.Update ตรง ๆ ได้ field ไหนไม่ได้ส่งมา ค่าเดิมในฐานข้อมูลก็อยู่ครบ ถ้าอยากให้ล้างค่าเป็น null ได้ ให้ใช้ pointer อย่าง *string
หน้า Inertia
Inertia::render() กลายเป็น inertia.Render ส่ง prop เป็น map แบบที่คุ้น และ Inertia::defer() ก็มี inertia.Defer ให้
func Page(r *web.Request) *web.Response {
posts := model.Query[models.Post]().Latest("created_at")
return inertia.Render("Posts/Index", inertia.Props{
"posts": inertia.Defer(posts.Get),
"count": 1,
})
}
ยิง request แบบ Inertia ดูจะเห็นว่า posts ยังไม่มาในรอบแรก แต่อยู่ใน deferredProps ให้ฝั่ง React ไปโหลดต่อหลังหน้าแสดงแล้ว
{"component":"Posts/Index","props":{"count":1,"errors":{},"name":"Laravel",...},"url":"/posts","deferredProps":{"default":["posts"]}}
ถ้าอยากให้ compiler ช่วยตรวจ prop ก็เขียนเป็น struct ที่มี method Component() แล้วใช้ inertia.RenderPage ลืมใส่ field หรือใส่ type ผิดจะรู้ตั้งแต่ตอน build
type ShowPostPage struct {
Post models.Post `json:"post"`
CanEdit bool `json:"canEdit"`
Comments *inertia.Prop `json:"comments"`
}
func (ShowPostPage) Component() string { return "Posts/Show" }
return inertia.RenderPage(ShowPostPage{
Post: post,
CanEdit: true,
Comments: inertia.Defer(comments.Get),
})
shared data ที่เคยอยู่ใน HandleInertiaRequests::share() ย้ายไปเป็น function share ที่ส่งให้ inertia.Middleware ใน bootstrap/app.go หน้า React ใน resources/js/pages เขียนเหมือนแอป Laravel PHP ทุกอย่าง ใช้ useForm, <Link> และ usePage ได้ตามปกติครับ






