فصل 3.5.
جداسازی مسیرهای برنامه
در حالی که در حال بازسازی کد خود هستیم، یک تغییر دیگر ارزش انجام دارد.
تابع main() ما شروع به شلوغ شدن کرده است، بنابراین برای نگه داشتن آن واضح و متمرکز، میخواهم اعلانهای مسیر برنامه را به یک فایل مستقل routes.go منتقل کنم، مانند این:
$ touch cmd/web/routes.go
package main import "net/http" // The routes() method returns a servemux containing our application routes. func (app *application) routes() *http.ServeMux { mux := http.NewServeMux() fileServer := http.FileServer(http.Dir("./ui/static/")) mux.Handle("GET /static/", http.StripPrefix("/static", fileServer)) mux.HandleFunc("GET /{$}", app.home) mux.HandleFunc("GET /snippet/view/{id}", app.snippetView) mux.HandleFunc("GET /snippet/create", app.snippetCreate) mux.HandleFunc("POST /snippet/create", app.snippetCreatePost) return mux }
سپس میتوانیم فایل main.go را برای استفاده از این بهروزرسانی کنیم:
package main ... func main() { addr := flag.String("addr", ":4000", "HTTP network address") flag.Parse() logger := slog.New(slog.NewTextHandler(os.Stdout, nil)) app := &application{ logger: logger, } logger.Info("starting server", "addr", *addr) // Call the new app.routes() method to get the servemux containing our routes, // and pass that to http.ListenAndServe(). err := http.ListenAndServe(*addr, app.routes()) logger.Error(err.Error()) os.Exit(1) }
این بسیار مرتبتر است. مسیرهای برنامه ما اکنون جدا شده و در متد app.routes() کپسوله شدهاند، و مسئولیتهای تابع main() ما محدود به:
- تجزیه تنظیمات پیکربندی زمان اجرا (runtime) برای برنامه؛
- ایجاد وابستگیها برای handlerها؛ و
- اجرای سرور HTTP.