You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

README.md 20 KiB

5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649
  1. # gorilla/mux
  2. [![GoDoc](https://godoc.org/github.com/gorilla/mux?status.svg)](https://godoc.org/github.com/gorilla/mux)
  3. [![Build Status](https://travis-ci.org/gorilla/mux.svg?branch=master)](https://travis-ci.org/gorilla/mux)
  4. [![Sourcegraph](https://sourcegraph.com/github.com/gorilla/mux/-/badge.svg)](https://sourcegraph.com/github.com/gorilla/mux?badge)
  5. ![Gorilla Logo](http://www.gorillatoolkit.org/static/images/gorilla-icon-64.png)
  6. https://www.gorillatoolkit.org/pkg/mux
  7. Package `gorilla/mux` implements a request router and dispatcher for matching incoming requests to
  8. their respective handler.
  9. The name mux stands for "HTTP request multiplexer". Like the standard `http.ServeMux`, `mux.Router` matches incoming requests against a list of registered routes and calls a handler for the route that matches the URL or other conditions. The main features are:
  10. * It implements the `http.Handler` interface so it is compatible with the standard `http.ServeMux`.
  11. * Requests can be matched based on URL host, path, path prefix, schemes, header and query values, HTTP methods or using custom matchers.
  12. * URL hosts, paths and query values can have variables with an optional regular expression.
  13. * Registered URLs can be built, or "reversed", which helps maintaining references to resources.
  14. * Routes can be used as subrouters: nested routes are only tested if the parent route matches. This is useful to define groups of routes that share common conditions like a host, a path prefix or other repeated attributes. As a bonus, this optimizes request matching.
  15. ---
  16. * [Install](#install)
  17. * [Examples](#examples)
  18. * [Matching Routes](#matching-routes)
  19. * [Static Files](#static-files)
  20. * [Registered URLs](#registered-urls)
  21. * [Walking Routes](#walking-routes)
  22. * [Graceful Shutdown](#graceful-shutdown)
  23. * [Middleware](#middleware)
  24. * [Testing Handlers](#testing-handlers)
  25. * [Full Example](#full-example)
  26. ---
  27. ## Install
  28. With a [correctly configured](https://golang.org/doc/install#testing) Go toolchain:
  29. ```sh
  30. go get -u github.com/gorilla/mux
  31. ```
  32. ## Examples
  33. Let's start registering a couple of URL paths and handlers:
  34. ```go
  35. func main() {
  36. r := mux.NewRouter()
  37. r.HandleFunc("/", HomeHandler)
  38. r.HandleFunc("/products", ProductsHandler)
  39. r.HandleFunc("/articles", ArticlesHandler)
  40. http.Handle("/", r)
  41. }
  42. ```
  43. Here we register three routes mapping URL paths to handlers. This is equivalent to how `http.HandleFunc()` works: if an incoming request URL matches one of the paths, the corresponding handler is called passing (`http.ResponseWriter`, `*http.Request`) as parameters.
  44. Paths can have variables. They are defined using the format `{name}` or `{name:pattern}`. If a regular expression pattern is not defined, the matched variable will be anything until the next slash. For example:
  45. ```go
  46. r := mux.NewRouter()
  47. r.HandleFunc("/products/{key}", ProductHandler)
  48. r.HandleFunc("/articles/{category}/", ArticlesCategoryHandler)
  49. r.HandleFunc("/articles/{category}/{id:[0-9]+}", ArticleHandler)
  50. ```
  51. The names are used to create a map of route variables which can be retrieved calling `mux.Vars()`:
  52. ```go
  53. func ArticlesCategoryHandler(w http.ResponseWriter, r *http.Request) {
  54. vars := mux.Vars(r)
  55. w.WriteHeader(http.StatusOK)
  56. fmt.Fprintf(w, "Category: %v\n", vars["category"])
  57. }
  58. ```
  59. And this is all you need to know about the basic usage. More advanced options are explained below.
  60. ### Matching Routes
  61. Routes can also be restricted to a domain or subdomain. Just define a host pattern to be matched. They can also have variables:
  62. ```go
  63. r := mux.NewRouter()
  64. // Only matches if domain is "www.example.com".
  65. r.Host("www.example.com")
  66. // Matches a dynamic subdomain.
  67. r.Host("{subdomain:[a-z]+}.example.com")
  68. ```
  69. There are several other matchers that can be added. To match path prefixes:
  70. ```go
  71. r.PathPrefix("/products/")
  72. ```
  73. ...or HTTP methods:
  74. ```go
  75. r.Methods("GET", "POST")
  76. ```
  77. ...or URL schemes:
  78. ```go
  79. r.Schemes("https")
  80. ```
  81. ...or header values:
  82. ```go
  83. r.Headers("X-Requested-With", "XMLHttpRequest")
  84. ```
  85. ...or query values:
  86. ```go
  87. r.Queries("key", "value")
  88. ```
  89. ...or to use a custom matcher function:
  90. ```go
  91. r.MatcherFunc(func(r *http.Request, rm *RouteMatch) bool {
  92. return r.ProtoMajor == 0
  93. })
  94. ```
  95. ...and finally, it is possible to combine several matchers in a single route:
  96. ```go
  97. r.HandleFunc("/products", ProductsHandler).
  98. Host("www.example.com").
  99. Methods("GET").
  100. Schemes("http")
  101. ```
  102. Routes are tested in the order they were added to the router. If two routes match, the first one wins:
  103. ```go
  104. r := mux.NewRouter()
  105. r.HandleFunc("/specific", specificHandler)
  106. r.PathPrefix("/").Handler(catchAllHandler)
  107. ```
  108. Setting the same matching conditions again and again can be boring, so we have a way to group several routes that share the same requirements. We call it "subrouting".
  109. For example, let's say we have several URLs that should only match when the host is `www.example.com`. Create a route for that host and get a "subrouter" from it:
  110. ```go
  111. r := mux.NewRouter()
  112. s := r.Host("www.example.com").Subrouter()
  113. ```
  114. Then register routes in the subrouter:
  115. ```go
  116. s.HandleFunc("/products/", ProductsHandler)
  117. s.HandleFunc("/products/{key}", ProductHandler)
  118. s.HandleFunc("/articles/{category}/{id:[0-9]+}", ArticleHandler)
  119. ```
  120. The three URL paths we registered above will only be tested if the domain is `www.example.com`, because the subrouter is tested first. This is not only convenient, but also optimizes request matching. You can create subrouters combining any attribute matchers accepted by a route.
  121. Subrouters can be used to create domain or path "namespaces": you define subrouters in a central place and then parts of the app can register its paths relatively to a given subrouter.
  122. There's one more thing about subroutes. When a subrouter has a path prefix, the inner routes use it as base for their paths:
  123. ```go
  124. r := mux.NewRouter()
  125. s := r.PathPrefix("/products").Subrouter()
  126. // "/products/"
  127. s.HandleFunc("/", ProductsHandler)
  128. // "/products/{key}/"
  129. s.HandleFunc("/{key}/", ProductHandler)
  130. // "/products/{key}/details"
  131. s.HandleFunc("/{key}/details", ProductDetailsHandler)
  132. ```
  133. ### Static Files
  134. Note that the path provided to `PathPrefix()` represents a "wildcard": calling
  135. `PathPrefix("/static/").Handler(...)` means that the handler will be passed any
  136. request that matches "/static/\*". This makes it easy to serve static files with mux:
  137. ```go
  138. func main() {
  139. var dir string
  140. flag.StringVar(&dir, "dir", ".", "the directory to serve files from. Defaults to the current dir")
  141. flag.Parse()
  142. r := mux.NewRouter()
  143. // This will serve files under http://localhost:8000/static/<filename>
  144. r.PathPrefix("/static/").Handler(http.StripPrefix("/static/", http.FileServer(http.Dir(dir))))
  145. srv := &http.Server{
  146. Handler: r,
  147. Addr: "127.0.0.1:8000",
  148. // Good practice: enforce timeouts for servers you create!
  149. WriteTimeout: 15 * time.Second,
  150. ReadTimeout: 15 * time.Second,
  151. }
  152. log.Fatal(srv.ListenAndServe())
  153. }
  154. ```
  155. ### Registered URLs
  156. Now let's see how to build registered URLs.
  157. Routes can be named. All routes that define a name can have their URLs built, or "reversed". We define a name calling `Name()` on a route. For example:
  158. ```go
  159. r := mux.NewRouter()
  160. r.HandleFunc("/articles/{category}/{id:[0-9]+}", ArticleHandler).
  161. Name("article")
  162. ```
  163. To build a URL, get the route and call the `URL()` method, passing a sequence of key/value pairs for the route variables. For the previous route, we would do:
  164. ```go
  165. url, err := r.Get("article").URL("category", "technology", "id", "42")
  166. ```
  167. ...and the result will be a `url.URL` with the following path:
  168. ```
  169. "/articles/technology/42"
  170. ```
  171. This also works for host and query value variables:
  172. ```go
  173. r := mux.NewRouter()
  174. r.Host("{subdomain}.example.com").
  175. Path("/articles/{category}/{id:[0-9]+}").
  176. Queries("filter", "{filter}").
  177. HandlerFunc(ArticleHandler).
  178. Name("article")
  179. // url.String() will be "http://news.example.com/articles/technology/42?filter=gorilla"
  180. url, err := r.Get("article").URL("subdomain", "news",
  181. "category", "technology",
  182. "id", "42",
  183. "filter", "gorilla")
  184. ```
  185. All variables defined in the route are required, and their values must conform to the corresponding patterns. These requirements guarantee that a generated URL will always match a registered route -- the only exception is for explicitly defined "build-only" routes which never match.
  186. Regex support also exists for matching Headers within a route. For example, we could do:
  187. ```go
  188. r.HeadersRegexp("Content-Type", "application/(text|json)")
  189. ```
  190. ...and the route will match both requests with a Content-Type of `application/json` as well as `application/text`
  191. There's also a way to build only the URL host or path for a route: use the methods `URLHost()` or `URLPath()` instead. For the previous route, we would do:
  192. ```go
  193. // "http://news.example.com/"
  194. host, err := r.Get("article").URLHost("subdomain", "news")
  195. // "/articles/technology/42"
  196. path, err := r.Get("article").URLPath("category", "technology", "id", "42")
  197. ```
  198. And if you use subrouters, host and path defined separately can be built as well:
  199. ```go
  200. r := mux.NewRouter()
  201. s := r.Host("{subdomain}.example.com").Subrouter()
  202. s.Path("/articles/{category}/{id:[0-9]+}").
  203. HandlerFunc(ArticleHandler).
  204. Name("article")
  205. // "http://news.example.com/articles/technology/42"
  206. url, err := r.Get("article").URL("subdomain", "news",
  207. "category", "technology",
  208. "id", "42")
  209. ```
  210. ### Walking Routes
  211. The `Walk` function on `mux.Router` can be used to visit all of the routes that are registered on a router. For example,
  212. the following prints all of the registered routes:
  213. ```go
  214. package main
  215. import (
  216. "fmt"
  217. "net/http"
  218. "strings"
  219. "github.com/gorilla/mux"
  220. )
  221. func handler(w http.ResponseWriter, r *http.Request) {
  222. return
  223. }
  224. func main() {
  225. r := mux.NewRouter()
  226. r.HandleFunc("/", handler)
  227. r.HandleFunc("/products", handler).Methods("POST")
  228. r.HandleFunc("/articles", handler).Methods("GET")
  229. r.HandleFunc("/articles/{id}", handler).Methods("GET", "PUT")
  230. r.HandleFunc("/authors", handler).Queries("surname", "{surname}")
  231. err := r.Walk(func(route *mux.Route, router *mux.Router, ancestors []*mux.Route) error {
  232. pathTemplate, err := route.GetPathTemplate()
  233. if err == nil {
  234. fmt.Println("ROUTE:", pathTemplate)
  235. }
  236. pathRegexp, err := route.GetPathRegexp()
  237. if err == nil {
  238. fmt.Println("Path regexp:", pathRegexp)
  239. }
  240. queriesTemplates, err := route.GetQueriesTemplates()
  241. if err == nil {
  242. fmt.Println("Queries templates:", strings.Join(queriesTemplates, ","))
  243. }
  244. queriesRegexps, err := route.GetQueriesRegexp()
  245. if err == nil {
  246. fmt.Println("Queries regexps:", strings.Join(queriesRegexps, ","))
  247. }
  248. methods, err := route.GetMethods()
  249. if err == nil {
  250. fmt.Println("Methods:", strings.Join(methods, ","))
  251. }
  252. fmt.Println()
  253. return nil
  254. })
  255. if err != nil {
  256. fmt.Println(err)
  257. }
  258. http.Handle("/", r)
  259. }
  260. ```
  261. ### Graceful Shutdown
  262. Go 1.8 introduced the ability to [gracefully shutdown](https://golang.org/doc/go1.8#http_shutdown) a `*http.Server`. Here's how to do that alongside `mux`:
  263. ```go
  264. package main
  265. import (
  266. "context"
  267. "flag"
  268. "log"
  269. "net/http"
  270. "os"
  271. "os/signal"
  272. "time"
  273. "github.com/gorilla/mux"
  274. )
  275. func main() {
  276. var wait time.Duration
  277. flag.DurationVar(&wait, "graceful-timeout", time.Second * 15, "the duration for which the server gracefully wait for existing connections to finish - e.g. 15s or 1m")
  278. flag.Parse()
  279. r := mux.NewRouter()
  280. // Add your routes as needed
  281. srv := &http.Server{
  282. Addr: "0.0.0.0:8080",
  283. // Good practice to set timeouts to avoid Slowloris attacks.
  284. WriteTimeout: time.Second * 15,
  285. ReadTimeout: time.Second * 15,
  286. IdleTimeout: time.Second * 60,
  287. Handler: r, // Pass our instance of gorilla/mux in.
  288. }
  289. // Run our server in a goroutine so that it doesn't block.
  290. go func() {
  291. if err := srv.ListenAndServe(); err != nil {
  292. log.Println(err)
  293. }
  294. }()
  295. c := make(chan os.Signal, 1)
  296. // We'll accept graceful shutdowns when quit via SIGINT (Ctrl+C)
  297. // SIGKILL, SIGQUIT or SIGTERM (Ctrl+/) will not be caught.
  298. signal.Notify(c, os.Interrupt)
  299. // Block until we receive our signal.
  300. <-c
  301. // Create a deadline to wait for.
  302. ctx, cancel := context.WithTimeout(context.Background(), wait)
  303. defer cancel()
  304. // Doesn't block if no connections, but will otherwise wait
  305. // until the timeout deadline.
  306. srv.Shutdown(ctx)
  307. // Optionally, you could run srv.Shutdown in a goroutine and block on
  308. // <-ctx.Done() if your application should wait for other services
  309. // to finalize based on context cancellation.
  310. log.Println("shutting down")
  311. os.Exit(0)
  312. }
  313. ```
  314. ### Middleware
  315. Mux supports the addition of middlewares to a [Router](https://godoc.org/github.com/gorilla/mux#Router), which are executed in the order they are added if a match is found, including its subrouters.
  316. Middlewares are (typically) small pieces of code which take one request, do something with it, and pass it down to another middleware or the final handler. Some common use cases for middleware are request logging, header manipulation, or `ResponseWriter` hijacking.
  317. Mux middlewares are defined using the de facto standard type:
  318. ```go
  319. type MiddlewareFunc func(http.Handler) http.Handler
  320. ```
  321. Typically, the returned handler is a closure which does something with the http.ResponseWriter and http.Request passed to it, and then calls the handler passed as parameter to the MiddlewareFunc. This takes advantage of closures being able access variables from the context where they are created, while retaining the signature enforced by the receivers.
  322. A very basic middleware which logs the URI of the request being handled could be written as:
  323. ```go
  324. func loggingMiddleware(next http.Handler) http.Handler {
  325. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  326. // Do stuff here
  327. log.Println(r.RequestURI)
  328. // Call the next handler, which can be another middleware in the chain, or the final handler.
  329. next.ServeHTTP(w, r)
  330. })
  331. }
  332. ```
  333. Middlewares can be added to a router using `Router.Use()`:
  334. ```go
  335. r := mux.NewRouter()
  336. r.HandleFunc("/", handler)
  337. r.Use(loggingMiddleware)
  338. ```
  339. A more complex authentication middleware, which maps session token to users, could be written as:
  340. ```go
  341. // Define our struct
  342. type authenticationMiddleware struct {
  343. tokenUsers map[string]string
  344. }
  345. // Initialize it somewhere
  346. func (amw *authenticationMiddleware) Populate() {
  347. amw.tokenUsers["00000000"] = "user0"
  348. amw.tokenUsers["aaaaaaaa"] = "userA"
  349. amw.tokenUsers["05f717e5"] = "randomUser"
  350. amw.tokenUsers["deadbeef"] = "user0"
  351. }
  352. // Middleware function, which will be called for each request
  353. func (amw *authenticationMiddleware) Middleware(next http.Handler) http.Handler {
  354. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  355. token := r.Header.Get("X-Session-Token")
  356. if user, found := amw.tokenUsers[token]; found {
  357. // We found the token in our map
  358. log.Printf("Authenticated user %s\n", user)
  359. // Pass down the request to the next middleware (or final handler)
  360. next.ServeHTTP(w, r)
  361. } else {
  362. // Write an error and stop the handler chain
  363. http.Error(w, "Forbidden", http.StatusForbidden)
  364. }
  365. })
  366. }
  367. ```
  368. ```go
  369. r := mux.NewRouter()
  370. r.HandleFunc("/", handler)
  371. amw := authenticationMiddleware{}
  372. amw.Populate()
  373. r.Use(amw.Middleware)
  374. ```
  375. Note: The handler chain will be stopped if your middleware doesn't call `next.ServeHTTP()` with the corresponding parameters. This can be used to abort a request if the middleware writer wants to. Middlewares _should_ write to `ResponseWriter` if they _are_ going to terminate the request, and they _should not_ write to `ResponseWriter` if they _are not_ going to terminate it.
  376. ### Testing Handlers
  377. Testing handlers in a Go web application is straightforward, and _mux_ doesn't complicate this any further. Given two files: `endpoints.go` and `endpoints_test.go`, here's how we'd test an application using _mux_.
  378. First, our simple HTTP handler:
  379. ```go
  380. // endpoints.go
  381. package main
  382. func HealthCheckHandler(w http.ResponseWriter, r *http.Request) {
  383. // A very simple health check.
  384. w.Header().Set("Content-Type", "application/json")
  385. w.WriteHeader(http.StatusOK)
  386. // In the future we could report back on the status of our DB, or our cache
  387. // (e.g. Redis) by performing a simple PING, and include them in the response.
  388. io.WriteString(w, `{"alive": true}`)
  389. }
  390. func main() {
  391. r := mux.NewRouter()
  392. r.HandleFunc("/health", HealthCheckHandler)
  393. log.Fatal(http.ListenAndServe("localhost:8080", r))
  394. }
  395. ```
  396. Our test code:
  397. ```go
  398. // endpoints_test.go
  399. package main
  400. import (
  401. "net/http"
  402. "net/http/httptest"
  403. "testing"
  404. )
  405. func TestHealthCheckHandler(t *testing.T) {
  406. // Create a request to pass to our handler. We don't have any query parameters for now, so we'll
  407. // pass 'nil' as the third parameter.
  408. req, err := http.NewRequest("GET", "/health", nil)
  409. if err != nil {
  410. t.Fatal(err)
  411. }
  412. // We create a ResponseRecorder (which satisfies http.ResponseWriter) to record the response.
  413. rr := httptest.NewRecorder()
  414. handler := http.HandlerFunc(HealthCheckHandler)
  415. // Our handlers satisfy http.Handler, so we can call their ServeHTTP method
  416. // directly and pass in our Request and ResponseRecorder.
  417. handler.ServeHTTP(rr, req)
  418. // Check the status code is what we expect.
  419. if status := rr.Code; status != http.StatusOK {
  420. t.Errorf("handler returned wrong status code: got %v want %v",
  421. status, http.StatusOK)
  422. }
  423. // Check the response body is what we expect.
  424. expected := `{"alive": true}`
  425. if rr.Body.String() != expected {
  426. t.Errorf("handler returned unexpected body: got %v want %v",
  427. rr.Body.String(), expected)
  428. }
  429. }
  430. ```
  431. In the case that our routes have [variables](#examples), we can pass those in the request. We could write
  432. [table-driven tests](https://dave.cheney.net/2013/06/09/writing-table-driven-tests-in-go) to test multiple
  433. possible route variables as needed.
  434. ```go
  435. // endpoints.go
  436. func main() {
  437. r := mux.NewRouter()
  438. // A route with a route variable:
  439. r.HandleFunc("/metrics/{type}", MetricsHandler)
  440. log.Fatal(http.ListenAndServe("localhost:8080", r))
  441. }
  442. ```
  443. Our test file, with a table-driven test of `routeVariables`:
  444. ```go
  445. // endpoints_test.go
  446. func TestMetricsHandler(t *testing.T) {
  447. tt := []struct{
  448. routeVariable string
  449. shouldPass bool
  450. }{
  451. {"goroutines", true},
  452. {"heap", true},
  453. {"counters", true},
  454. {"queries", true},
  455. {"adhadaeqm3k", false},
  456. }
  457. for _, tc := range tt {
  458. path := fmt.Sprintf("/metrics/%s", tc.routeVariable)
  459. req, err := http.NewRequest("GET", path, nil)
  460. if err != nil {
  461. t.Fatal(err)
  462. }
  463. rr := httptest.NewRecorder()
  464. // Need to create a router that we can pass the request through so that the vars will be added to the context
  465. router := mux.NewRouter()
  466. router.HandleFunc("/metrics/{type}", MetricsHandler)
  467. router.ServeHTTP(rr, req)
  468. // In this case, our MetricsHandler returns a non-200 response
  469. // for a route variable it doesn't know about.
  470. if rr.Code == http.StatusOK && !tc.shouldPass {
  471. t.Errorf("handler should have failed on routeVariable %s: got %v want %v",
  472. tc.routeVariable, rr.Code, http.StatusOK)
  473. }
  474. }
  475. }
  476. ```
  477. ## Full Example
  478. Here's a complete, runnable example of a small `mux` based server:
  479. ```go
  480. package main
  481. import (
  482. "net/http"
  483. "log"
  484. "github.com/gorilla/mux"
  485. )
  486. func YourHandler(w http.ResponseWriter, r *http.Request) {
  487. w.Write([]byte("Gorilla!\n"))
  488. }
  489. func main() {
  490. r := mux.NewRouter()
  491. // Routes consist of a path and a handler function.
  492. r.HandleFunc("/", YourHandler)
  493. // Bind to a port and pass our router in
  494. log.Fatal(http.ListenAndServe(":8000", r))
  495. }
  496. ```
  497. ## License
  498. BSD licensed. See the LICENSE file for details.