/usr/share/perl5/Dancer2/Manual.pod is in libdancer2-perl 0.204002+dfsg-1.
This file is owned by root:root, with mode 0o644.
The actual contents of the file can be viewed below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 | # ABSTRACT: A gentle introduction to Dancer2
package Dancer2::Manual;
__END__
=pod
=encoding UTF-8
=head1 NAME
Dancer2::Manual - A gentle introduction to Dancer2
=head1 VERSION
version 0.204002
=head1 DESCRIPTION
Dancer2 is a free and open source web application framework written in Perl.
It's a complete rewrite of L<Dancer>, based on L<Moo> and using a more
robust and extensible fully-OO design.
It's designed to be powerful and flexible, but also easy to use - getting up
and running with your web app is trivial, and an ecosystem of adaptors for
common template engines, session storage, logging methods, serializers, and
plugins to make common tasks easy means you can do what you want to do, your
way, easily.
=head1 INSTALL
Installation of Dancer2 is simple:
perl -MCPAN -e 'install Dancer2'
Thanks to the magic of cpanminus, if you do not have CPAN.pm configured, or
just want a quickfire way to get running, the following should work, at
least on Unix-like systems:
wget -O - http://cpanmin.us | sudo perl - Dancer2
(If you don't have root access, omit the 'sudo', and cpanminus will install
Dancer2 and prereqs into C<~/perl5>.)
=head1 BOOTSTRAPPING A NEW APP
Create a web application using the dancer script:
$ dancer2 -a MyApp && cd MyApp
+ MyApp
+ MyApp/config.yml
+ MyApp/Makefile.PL
+ MyApp/MANIFEST.SKIP
+ MyApp/.dancer
+ MyApp/cpanfile
+ MyApp/bin
+ MyApp/bin/app.psgi
+ MyApp/environments
+ MyApp/environments/development.yml
+ MyApp/environments/production.yml
+ MyApp/lib
+ MyApp/lib/MyApp.pm
+ MyApp/public
+ MyApp/public/favicon.ico
+ MyApp/public/500.html
+ MyApp/public/dispatch.cgi
+ MyApp/public/404.html
+ MyApp/public/dispatch.fcgi
+ MyApp/public/css
+ MyApp/public/css/error.css
+ MyApp/public/css/style.css
+ MyApp/public/images
+ MyApp/public/images/perldancer.jpg
+ MyApp/public/images/perldancer-bg.jpg
+ MyApp/public/javascripts
+ MyApp/public/javascripts/jquery.js
+ MyApp/t
+ MyApp/t/001_base.t
+ MyApp/t/002_index_route.t
+ MyApp/views
+ MyApp/views/index.tt
+ MyApp/views/layouts
+ MyApp/views/layouts/main.tt
It creates a directory named after the name of the app, along with a
configuration file, a views directory (where your templates and layouts
will live), an environments directory (where environment-specific
settings live), a module containing the actual guts of your application, and
a script to start it. A default skeleton is used to bootstrap the new
application, but you can use the C<-s> option to provide another skeleton.
For example:
$ dancer2 -a MyApp -s ~/mydancerskel
For an example of a skeleton directory check the default one available in
the C<share/> directory of your Dancer2 distribution.
(In what follows we will refer to the directory in which you have created your
Dancer2 application -- I<e.g.,> what C<MyApp> was above -- as the
C<appdir>.)
Because Dancer2 is a L<PSGI> web application framework, you can use the
C<plackup> tool (provided by L<Plack>) for launching the application:
plackup -p 5000 bin/app.psgi
View the web application at:
http://localhost:5000
=head1 USAGE
When Dancer2 is imported to a script, that script becomes a webapp, and at
this point, all the script has to do is declare a list of B<routes>. A
route handler is composed by an HTTP method, a path pattern and a code
block. C<strict>, C<warnings> and C<utf8> pragmas are also imported with
Dancer2.
The code block given to the route handler has to return a string which will
be used as the content to render to the client.
Routes are defined for a given HTTP method. For each method supported, a
keyword is exported by the module.
=head2 HTTP Methods
Here are some of the standard HTTP methods which you can use to define your
route handlers.
=over 4
=item * B<GET> The GET method retrieves information, and is the most common
GET requests should be used for typical "fetch" requests - retrieving
information. They should not be used for requests which change data on the
server or have other effects.
When defining a route handler for the GET method, Dancer2 automatically
defines a route handler for the HEAD method (in order to honour HEAD
requests for each of your GET route handlers).
To define a GET action, use the L<get|Dancer2::Manual/get> keyword.
=item * B<POST> The POST method is used to create a resource on the server.
To define a POST action, use the L<post|Dancer2::Manual/post> keyword.
=item * B<PUT> The PUT method is used to replace an existing resource.
To define a PUT action, use the L<put|Dancer2::Manual/put> keyword.
a PUT request should replace the existing resource with that specified - for
instance - if you wanted to just update an email address for a user, you'd
have to specify all attributes of the user again; to make a partial update,
a PATCH request is used.
=item * B<PATCH> The PATCH method updates some attributes of an existing resource.
To define a PATCH action, use the L<patch|Dancer2::Manual/patch> keyword.
=item * B<DELETE> The DELETE method requests that the origin server delete the
resource identified by the Request-URI.
To define a DELETE action, use the L<del|Dancer2::Manual/del> keyword.
=back
=head3 Handling multiple HTTP request methods
Routes can use C<any> to match all, or a specified list of HTTP methods.
The following will match any HTTP request to the path C</myaction>:
any '/myaction' => sub {
# code
}
The following will match GET or POST requests to C</myaction>:
any ['get', 'post'] => '/myaction' => sub {
# code
};
For convenience, any route which matches GET requests will also match HEAD
requests.
=head2 Route Handlers
The route action is the code reference declared. It can access parameters
through the specific C<route_parameters>, C<query_parameters>, and
C<body_parameters> keywords, which return a L<Hash::MultiValue> object.
This hashref is a merge of the route pattern matches and the request params.
You can have more details about how params are built and how to access them
in the L<Dancer2::Core::Request> documentation.
=head3 Declaring Routes
To control what happens when a web request is received by your webapp,
you'll need to declare C<routes>. A route declaration indicates which HTTP
method(s) it is valid for, the path it matches (e.g. C</foo/bar>), and a
coderef to execute, which returns the response.
get '/hello/:name' => sub {
return "Hi there " . route_parameters->get('name');
};
The above route specifies that, for GET requests to C</hello/...>, the code
block provided should be executed.
=head3 Retrieving request parameters
The L<query_parameters|Dancer2::Manual/query_parameters>,
L<route_parameters|Dancer2::Manual/route_parameters>, and
L<body_parameters|Dancer2::Manual/body_parameters> keywords provide
a L<Hash::MultiValue> result from the three different parameters.
=head3 Named matching
A route pattern can contain one or more tokens (a word prefixed with ':').
Each token found in a route pattern is used as a named-pattern match. Any
match will be set in the route parameters.
get '/hello/:name' => sub {
"Hey " . route_parameters->get('name') . ", welcome here!";
};
Tokens can be optional, for example:
get '/hello/:name?' => sub {
"Hello there, " .
(defined route_parameters->get('name') ? route_parameters->get('name') : "whoever you are!");
};
=head3 Wildcard Matching
A route can contain a wildcard (represented by a C<*>). Each wildcard match
will be placed in a list, which the C<splat> keyword returns.
get '/download/*.*' => sub {
my ($file, $ext) = splat;
# do something with $file.$ext here
};
An extensive, greedier wildcard represented by C<**> (A.K.A. "megasplat") can be
used to define a route. The additional path is broken down and returned as an
arrayref:
get '/entry/*/tags/**' => sub {
my ( $entry_id, $tags ) = splat;
my @tags = @{$tags};
};
The C<splat> keyword in the above example for the route F</entry/1/tags/one/two>
would set C<$entry_id> to C<1> and C<$tags> to C<['one', 'two']>.
=head3 Mixed named and wildcard matching
A route can combine named (token) matching and wildcard matching.
This is useful when chaining actions:
get '/team/:team/**' => sub {
var team => route_parameters->get('team');
pass;
};
prefix '/team/:team';
get '/player/*' => sub {
my ($player) = splat;
# etc...
};
get '/score' => sub {
return score_for( vars->{'team'} );
};
=head3 Regular Expression Matching
A route can be defined with a Perl regular expression.
In order to tell Dancer2 to consider the route as a real regexp, the route
must be defined explicitly with C<qr{}>, like the following:
get qr{/hello/([\w]+)} => sub {
my ($name) = splat;
return "Hello $name";
};
For Perl 5.10+, a route regex may use named capture groups. The C<captures>
keyword will return a reference to a copy of C<%+>.
=head3 Conditional Matching
Routes may include some matching conditions (on content_type, agent,
user_agent, content_length and path_info):
get '/foo', {agent => 'Songbird (\d\.\d)[\d\/]*?'} => sub {
'foo method for songbird'
}
get '/foo' => sub {
'all browsers except songbird'
}
=head2 Prefix
A prefix can be defined for each route handler, like this:
prefix '/home';
From here, any route handler is defined to /home/*
get '/page1' => sub {}; # will match '/home/page1'
You can unset the prefix value
prefix '/'; # or: prefix undef;
get '/page1' => sub {}; # will match /page1
Alternatively, to prevent you from ever forgetting to undef the prefix, you
can use lexical prefix like this:
prefix '/home' => sub {
get '/page1' => sub {}; # will match '/home/page1'
}; ## prefix reset to previous value on exit
get '/page1' => sub {}; # will match /page1
=head2 Delayed responses (Async/Streaming)
L<Dancer2> can provide delayed (otherwise known as I<asynchronous>) responses
using the C<delayed> keyword. These responses are streamed, although you can
set the content all at once, if you prefer.
get '/status' => sub {
delayed {
response_header 'X-Foo' => 'Bar';
# flush headers (in case of streaming)
flush;
# send content to the user
content 'Hello, world!';
# you can write more content
# all streaming
content 'Hello, again!';
# when done, close the connection
done;
# do whatever you want else, asynchronously
# the user socket closed by now
...
};
};
If you are streaming (calling C<content> several times), you must call
C<flush> first. If you're sending only once, you don't need to call C<flush>.
Here is an example of using delayed responses with L<AnyEvent>:
use Dancer2;
use AnyEvent;
my %timers;
my $count = 5;
get '/drums' => sub {
delayed {
print "Stretching...\n";
flush; # necessary, since we're streaming
$timers{'Snare'} = AE::timer 1, 1, delayed {
$timers{'HiHat'} ||= AE::timer 0, 0.5, delayed {
content "Tss...\n";
};
content "Bap!\n";
if ( $count-- == 0 ) {
%timers = ();
content "Tugu tugu tugu dum!\n";
done;
print "<enter sound of applause>\n\n";
$timers{'Applause'} = AE::timer 3, 0, sub {
# the DSL will not available here
# because we didn't call the "delayed" keyword
print "<applause dies out>\n";
};
}
};
};
};
If an error happens during a write operation, a warning will be issued
to the logger.
You can handle the error yourself by providing an C<on_error> handler:
get '/' => sub {
delayed {
flush;
content "works";
# ... user disconnected here ...
content "fails";
# ... error triggered ...
done; # doesn't even get run
} on_error => sub {
# delayed{} not needed, DSL already available
my ($error) = @_;
# do something with $error
};
};
=head2 Action Skipping
An action can choose not to serve the current request and ask Dancer2 to
process the request with the next matching route.
This is done with the B<pass> keyword, like in the following example
get '/say/:word' => sub {
return pass if (route_parameters->get('word') =~ /^\d+$/);
"I say a word: " . route_parameters->get('word');
};
get '/say/:number' => sub {
"I say a number: " . route_parameters->get('number');
};
=head1 HOOKS
Hooks are code references (or anonymous subroutines) that are triggered at
specific moments during the resolution of a request.
Many of them are supported by the core but plugins and engines can also
define their own.
=over 4
=item * C<before> hooks
C<before> hooks are evaluated before each request within the context of the
request and receives as argument the app (a L<Dancer2::Core::App> object).
It's possible to define variables which will be accessible in the action
blocks with the keyword C<var>.
hook before => sub {
var note => 'Hi there';
};
get '/foo/*' => sub {
my ($match) = splat; # 'oversee';
vars->{note}; # 'Hi there'
};
For another example, this can be used along with session support to easily
give non-logged-in users a login page:
hook before => sub {
if (!session('user') && request->dispatch_path !~ m{^/login}) {
# Pass the original path requested along to the handler:
forward '/login', { requested_path => request->dispatch_path };
}
};
The request keyword returns the current L<Dancer2::Core::Request> object
representing the incoming request.
=item * C<after> hooks
C<after> hooks are evaluated after the response has been built by a route
handler, and can alter the response itself, just before it's sent to the
client.
This hook runs after a request has been processed, but before the response
is sent.
It receives a L<Dancer2::Core::Response> object, which it can modify if it
needs to make changes to the response which is about to be sent.
The hook can use other keywords in order to do whatever it wants.
hook after => sub {
response->content(
q{The "after" hook can alter the response's content here!}
);
};
=back
=head2 Templates
=over 4
=item * C<before_template_render>
C<before_template_render> hooks are called whenever a template is going to
be processed, they are passed the tokens hash which they can alter.
hook before_template_render => sub {
my $tokens = shift;
$tokens->{foo} = 'bar';
};
The tokens hash will then be passed to the template with all the
modifications performed by the hook. This is a good way to setup some
global vars you like to have in all your templates, like the name of the
user logged in or a section name.
=item * C<after_template_render>
C<after_template_render> hooks are called after the view has been rendered.
They receive as their first argument the reference to the content that has
been produced. This can be used to post-process the content rendered by the
template engine.
hook after_template_render => sub {
my $ref_content = shift;
my $content = ${$ref_content};
# do something with $content
${$ref_content} = $content;
};
=item * C<before_layout_render>
C<before_layout_render> hooks are called whenever the layout is going to be
applied to the current content. The arguments received by the hook are the
current tokens hashref and a reference to the current content.
hook before_layout_render => sub {
my ($tokens, $ref_content) = @_;
$tokens->{new_stuff} = 42;
$ref_content = \"new content";
};
=item * C<after_layout_render>
C<after_layout_render> hooks are called once the complete content of the
view has been produced, after the layout has been applied to the content.
The argument received by the hook is a reference to the complete content
string.
hook after_layout_render => sub {
my $ref_content = shift;
# do something with ${ $ref_content }, which reflects directly
# in the caller
};
=back
=head2 Error Handling
Refer to L<Error Handling|Dancer2::Manual/error-handling-1>
for details about the following hooks:
=over 4
=item * C<init_error>
=item * C<before_error>
=item * C<after_error>
=item * C<on_route_exception>
=back
=head2 File Rendering
Refer to L<File Rendering|Dancer2::Manual/file-handler>
for details on the following hooks:
=over 4
=item * C<before_file_render>
=item * C<after_file_render>
=back
=head2 Serializers
=over 4
=item * C<before_serializer> is called before serializing the content, and receives
the content to serialize as an argument.
hook before_serializer => sub {
my $content = shift;
...
};
=item * C<after_serializer> is called after the payload has been serialized, and
receives the serialized content as an argument.
hook after_serializer => sub {
my $serialized_content = shift;
...
};
=back
=head1 HANDLERS
=head2 File Handler
Whenever a content is produced out of the parsing of a static file, the
L<Dancer2::Handler::File> component is used. This component provides two
hooks, C<before_file_render> and C<after_file_render>.
C<before_file_render> hooks are called just before starting to parse the
file, the hook receives as its first argument the file path that is going to
be processed.
hook before_file_render => sub {
my $path = shift;
};
C<after_file_render> hooks are called after the file has been parsed and the
response content produced. It receives the response object
(L<Dancer2::Core::Response>) produced.
hook after_file_render => sub {
my $response = shift;
};
=head2 Auto page
Whenever a page that matches an existing template needs to be served, the
L<Dancer2::Handler::AutoPage> component is used.
=head2 Writing your own
A route handler is a class that consumes the L<Dancer2::Core::Role::Handler>
role. The class must implement a set of methods: C<methods>, C<regexp> and
C<code> which will be used to declare the route.
Let's look at L<Dancer2::Handler::AutoPage> for example.
First, the matching methods are C<get> and C<head>:
sub methods { qw(head get) }
Then, the C<regexp> or the I<path> we want to match:
sub regexp { '/:page' }
Anything will be matched by this route, since we want to check if there's
a view named with the value of the C<page> token. If not, the route needs
to C<pass>, letting the dispatching flow to proceed further.
sub code {
sub {
my $app = shift;
my $prefix = shift;
my $template = $app->template_engine;
if ( !defined $template ) {
$app->response->has_passed(1);
return;
}
my $page = $app->request->path;
my $layout_dir = $template->layout_dir;
if ( $page =~ m{^/\Q$layout_dir\E/} ) {
$app->response->has_passed(1);
return;
}
# remove leading '/', ensuring paths relative to the view
$page =~ s{^/}{};
my $view_path = $template->view_pathname($page);
if ( ! $template->pathname_exists( $view_path ) ) {
$app->response->has_passed(1);
return;
}
my $ct = $template->process( $page );
return ( $app->request->method eq 'GET' ) ? $ct : '';
};
}
The C<code> method passed the L<Dancer2::Core::App> object which provides
access to anything needed to process the request.
A C<register> is then implemented to add the route to the registry and if
the C<auto_page setting> is off, it does nothing.
sub register {
my ($self, $app) = @_;
return unless $app->config->{auto_page};
$app->add_route(
method => $_,
regexp => $self->regexp,
code => $self->code,
) for $self->methods;
}
The config parser looks for a C<route_handlers> section and any handler defined
there is loaded. Thus, any random handler can be added to your app.
For example, the default config file for any Dancer2 application is as follows:
route_handlers:
File:
public_dir: /path/to/public
AutoPage: 1
=head1 ERRORS
=head2 Error Pages
When an HTTP error occurs (the action responds with a status code other
than 200), Dancer2 first looks in the public directory for a corresponding
HTML file matching the error code (eg: 500.html or 404.html).
If such a file exists, it's used to report the error, otherwise, a default
error page will be rendered on the fly.
Note that in order to provide more informative diagnostics, the default
error page will override the error-code HTML files for errors with a C<5xx>
status when B<show_errors> is set to true. For more information see
L<Dancer2::Config>.
=head2 Execution Errors
When an error occurs during the route execution, Dancer2 will render an
error page with the HTTP status code 500.
It's possible either to display the content of the error message or to hide
it with a generic error page.
This is a choice left to the end-user and can be set with the B<show_errors>
setting.
Note that you can also choose to consider all warnings in your route
handlers as errors when the setting B<warnings> is set to 1.
=head2 Error handling
When an error is caught by Dancer2's core, an exception object is built (of
the class L<Dancer2::Core::Error>). This class provides a hook to let the
user alter the error workflow if needed.
C<init_error> hooks are called whenever an error object is built, the object
is passed to the hook.
hook init_error => sub {
my $error = shift;
# do something with $error
};
I<This hook was named B<before_error_init> in Dancer, both names currently
are synonyms for backward-compatibility.>
C<before_error> hooks are called whenever an error is going to be thrown, it
receives the error object as its sole argument.
hook before_error => sub {
my $error = shift;
# do something with $error
};
I<This hook was named B<before_error_render> in Dancer, both names currently
are synonyms for backward-compatibility.>
C<after_error> hooks are called whenever an error object has been thrown, it
receives a L<Dancer2::Core::Response> object as its sole argument.
hook after_error => sub {
my $response = shift;
};
I<This hook was named B<after_error_render> in Dancer, both names currently
are synonyms for backward-compatibility.>
C<on_route_exception> is called when an exception has been caught, at the
route level, just before rethrowing it higher. This hook receives a
L<Dancer2::Core::App> and the error as arguments.
hook on_route_exception => sub {
my ($app, $error) = @_;
};
=head1 SESSIONS
=head2 Handling sessions
It's common to want to use sessions to give your web applications state; for
instance, allowing a user to log in, creating a session, and checking that
session on subsequent requests.
By default Dancer 2 has L<Simple|Dancer2::Session::Simple> sessions enabled.
It implements a very simple in-memory session storage. This will be fast and
useful for testing, but such sessions will not persist between restarts of
your app.
If you'd like to use a different session engine you must declare it in the
configuration file.
For example to use YAML file base sessions you need to add the following
to your F<config.yml>:
session: YAML
Or, to enable session support from within your code,
set session => 'YAML';
(However, controlling settings is best done from your config file.)
The L<Dancer2::Session::YAML> backend implements a file-based YAML session
storage to help with debugging, but shouldn't be used on production systems.
There are other session backends, such as L<Dancer2::Session::Memcached>,
which are recommended for production use.
You can then use the L<session|Dancer2/session> keyword to manipulate the
session:
=head3 Storing data in the session
Storing data in the session is as easy as:
session varname => 'value';
=head3 Retrieving data from the session
Retrieving data from the session is as easy as:
session('varname')
Or, alternatively,
session->read("varname")
=head3 Controlling where sessions are stored
For disc-based session backends like L<Dancer2::Session::YAML>,
L<Dancer2::Session::Storable> etc., session files are written to the session
dir specified by the C<session_dir> setting, which defaults to C<./sessions>
if not specifically set.
If you need to control where session files are created, you can do so
quickly and easily within your config file, for example:
session: YAML
engines:
session:
YAML:
session_dir: /tmp/dancer-sessions
If the directory you specify does not exist, Dancer2 will attempt to create
it for you.
=head3 Changing session ID
If you wish to change the session ID (for example on privilege level change):
my $new_session_id = app->change_session_id
=head3 Destroying a session
When you're done with your session, you can destroy it:
app->destroy_session
=head2 Sessions and logging in
A common requirement is to check the user is logged in, and, if not, require
them to log in before continuing.
This can easily be handled using a before hook to check their session:
use Dancer2;
set session => "Simple";
hook before => sub {
if (!session('user') && request->dispatch_path !~ m{^/login}) {
forward '/login', { requested_path => request->dispatch_path };
}
};
get '/' => sub { return "Home Page"; };
get '/secret' => sub { return "Top Secret Stuff here"; };
get '/login' => sub {
# Display a login page; the original URL they requested is available as
# query_parameters->get('requested_path'), so could be put in a hidden field in the form
template 'login', { path => query_parameters->get('requested_path') };
};
post '/login' => sub {
# Validate the username and password they supplied
if (body_parameters->get('user') eq 'bob' && body_parameters->get('pass') eq 'letmein') {
session user => body_parameters->get('user');
redirect body_parameters->get('path') || '/';
} else {
redirect '/login?failed=1';
}
};
dance();
Here is what the corresponding C<login.tt> file should look like. You should
place it in a directory called C<views/>:
<html>
<head>
<title>Session and logging in</title>
</head>
<body>
<form action='/login' method='POST'>
User Name : <input type='text' name='user'/>
Password: <input type='password' name='pass' />
<!-- Put the original path requested into a hidden
field so it's sent back in the POST and can be
used to redirect to the right page after login -->
<input type='hidden' name='path' value='<% path %>'/>
<input type='submit' value='Login' />
</form>
</body>
</html>
Of course, you'll probably want to validate your users against a database
table, or maybe via IMAP/LDAP/SSH/POP3/local system accounts via PAM etc.
L<Authen::Simple> is probably a good starting point here!
A simple working example of handling authentication against a database table
yourself (using L<Dancer2::Plugin::Database> which provides the C<database>
keyword, and L<Crypt::SaltedHash> to handle salted hashed passwords (well,
you wouldn't store your users passwords in the clear, would you?)) follows:
post '/login' => sub {
my $user_value = body_parameters->get('user');
my $pass_value = body_parameters->get('pass');
my $user = database->quick_select('users',
{ username => $user_value }
);
if (!$user) {
warning "Failed login for unrecognised user $user_value";
redirect '/login?failed=1';
} else {
if (Crypt::SaltedHash->validate($user->{password}, $pass_value))
{
debug "Password correct";
# Logged in successfully
session user => $user;
redirect body_parameters->get('path') || '/';
} else {
debug("Login failed - password incorrect for " . $user_value);
redirect '/login?failed=1';
}
}
};
=head3 Retrieve complete hash stored in session
Get complete hash stored in session:
my $hash = session;
=head2 Writing a session engine
In Dancer 2, a session backend consumes the role
L<Dancer2::Core::Role::SessionFactory>.
The following example using the Reddis session demonstrates how session
engines are written in Dancer 2.
First thing to do is to create the class for the session engine,
we'll name it C<Dancer2::Session::Redis>:
package Dancer2::Session::Redis;
use Moo;
with 'Dancer2::Core::Role::SessionFactory';
we want our backend to have a handle over a Redis connection.
To do that, we'll create an attribute C<redis>
use JSON;
use Redis;
use Dancer2::Core::Types; # brings helper for types
has redis => (
is => 'rw',
isa => InstanceOf['Redis'],
lazy => 1,
builder => '_build_redis',
);
The lazy attribute says to Moo that this attribute will be
built (initialized) only when called the first time. It means that
the connection to Redis won't be opened until necessary.
sub _build_redis {
my ($self) = @_;
Redis->new(
server => $self->server,
password => $self->password,
encoding => undef,
);
}
Two more attributes, C<server> and C<password> need to be created.
We do this by defining them in the config file. Dancer2 passes anything
defined in the config to the engine creation.
# config.yml
...
engines:
session:
Redis:
server: foo.mydomain.com
password: S3Cr3t
The server and password entries are now passed to the constructor
of the Redis session engine and can be accessed from there.
has server => (is => 'ro', required => 1);
has password => (is => 'ro');
Next, we define the subroutine C<_retrieve> which will return a session
object for a session ID it has passed. Since in this case, sessions are
going to be stored in Redis, the session ID will be the key, the session the value.
So retrieving is as easy as doing a get and decoding the JSON string returned:
sub _retrieve {
my ($self, $session_id) = @_;
my $json = $self->redis->get($session_id);
my $hash = from_json( $json );
return bless $hash, 'Dancer2::Core::Session';
}
The C<_flush> method is called by Dancer when the session needs to be stored in
the backend. That is actually a write to Redis. The method receives a C<Dancer2::Core::Session>
object and is supposed to store it.
sub _flush {
my ($self, $session) = @_;
my $json = encode_json( { %{ $session } } );
$self->redis->set($session->id, $json);
}
For the C<_destroy> method which is supposed to remove a session from the backend,
deleting the key from Redis is enough.
sub _destroy {
my ($self, $session_id) = @_;
$self->redis->del($session_id);
}
The C<_sessions> method which is supposed to list all the session IDs currently
stored in the backend is done by listing all the keys that Redis has.
sub _sessions {
my ($self) = @_;
my @keys = $self->redis->keys('*');
return \@keys;
}
The session engine is now ready.
=head3 The Session keyword
Dancer2 maintains two session layers.
The first layer, L<Dancer2::Core::Session> provides a session object
which represents the current session. You can read from it as many
times as you want, and write to it as many times as you want.
The second layer is the session engine (L<Dancer2::Session::Simple>
is one example), which is used in order to implement the reading and
writing from the actual storage. This is read only once, when a request
comes in (using a cookie whose value is C<dancer.session> by default).
At the end of a request, all the data you've written will be flushed
to the engine itself, which will do the actual write to the storage
(whether it's in a hash in memory, in Memcache, or in a database).
=head1 TEMPLATES
Returning plain content is all well and good for examples or trivial apps,
but soon you'll want to use templates to maintain separation between your
code and your content. Dancer2 makes this easy.
Your route handlers can use the L<template|Dancer2::Manual/template> keyword
to render templates.
=head2 Views
In Dancer2, a file which holds a template is called a I<view>. Views are
located in the C<appdir/views> directory.
You can change this location by changing the setting 'views'. For instance
if your templates are located in the 'templates' directory, do the
following:
set views => path( app->location , 'templates' );
By default, the internal template engine L<Dancer2::Template::Simple> is
used, but you may want to upgrade to L<Template
Toolkit|http://www.template-toolkit.org/>. If you do so, you have to enable
this engine in your settings as explained in
L<Dancer2::Template::TemplateToolkit> and you'll also have to install the
L<Template> module.
In order to render a view, just call the
L<template|Dancer2::Manual/template> keyword at the end of the action by
giving the view name and the HASHREF of tokens to interpolate in the view
(note that for convenience, the request, session, params and vars are
automatically accessible in the view, named C<request>, C<session>, C<params>,
and C<vars>) - for example:
hook before => sub { var time => scalar(localtime) };
get '/hello/:name' => sub {
my $name = route_parameters->get('name');
template 'hello.tt', { name => $name };
};
The template C<hello.tt> could contain, for example:
<p>Hi there, [% name %]!</p>
<p>You're using [% request.user_agent %]</p>
[% IF session.username %]
<p>You're logged in as [% session.username %]</p>
[% END %]
It's currently [% vars.time %]
For a full list of the tokens automatically added to your template (like
C<session>, C<request>, and C<vars>, refer to
L<Dancer2::Core::Role::Template>).
By default, views use a F<.tt> extension. This can be overridden by setting
the C<extension> attribute in the template engine configuration:
set engines => {
template => {
template_toolkit => {
extension => 'foo',
},
},
};
=head2 Layouts
A layout is a special view, located in the F<layouts> directory (inside the
views directory) which must have a token named C<content>. That token marks
the place where to render the action view. This lets you define a global
layout for your actions, and have each individual view contain only
specific content. This is a good thing and helps avoid lots of needless
duplication of HTML. :)
For example, the layout F<views/layouts/main.tt>:
<html>
<head>...</head>
<body>
<div id="header">
...
</div>
<div id="content">
[% content %]
</div>
</body>
</html>
You can tell your app which layout to use with C<layout: name> in the config
file, or within your code:
set layout => 'main';
You can control which layout to use (or whether to use a layout at all) for
a specific request without altering the layout setting by passing an options
hashref as the third param to the template keyword:
template 'index.tt', {}, { layout => undef };
If your application is not mounted under root (C</>), you can use a
C<before_template_render> hook instead of hardcoding the path into your
application for your CSS, images and JavaScript:
hook before_template_render => sub {
my $tokens = shift;
$tokens->{uri_base} = request->base->path;
};
Then in your layout, modify your CSS inclusion as follows:
<link rel="stylesheet" href="[% uri_base %]/css/style.css" />
From now on you can mount your application wherever you want, without any
further modification of the CSS inclusion.
=head2 Encoding
If you use L<Plack> and have a Unicode problem with your Dancer2
application, don't forget to check if you have set your template engine to
use Unicode, and set the default charset to UTF-8. So, if you are using
template toolkit, your config file will look like this:
charset: UTF-8
engines:
template:
template_toolkit:
ENCODING: utf8
=head1 STATIC FILES
=head2 Static Directory
Static files are served from the F<./public> directory. You can specify a
different location by setting the C<public_dir> option:
set public_dir => path( app->location , 'static' );
When you modify default public_dir you have to set C<static_handler> option.
set static_handler => true;
Note that the public directory name is not included in the URL. A file
F<./public/css/style.css> is made available as
L<http://example.com/css/style.css>.
=head2 Static File from a Route Handler
It's possible for a route handler to send a static file, as follows:
get '/download/*' => sub {
my ($file) = splat;
send_file $file;
};
Or even if you want your index page to be a plain old F<index.html> file,
just do:
get '/' => sub {
send_file '/index.html'
};
=head1 FILE UPLOADS
Files are uploaded in Dancer2 using the class L<Dancer2::Core::Request::Upload>.
The objects are accessible within the route handlers using the C<upload>
keyword:
post '/upload' => sub {
my $upload_dir = "MyApp/UPLOADS";
my $upload = upload('file_input_name'); # upload object
$upload->copy_to('Uploads/');
};
=head1 CONFIGURATION
=head2 Configuration and environments
Configuring a Dancer2 application can be done in many ways. The easiest one
(and maybe the dirtiest) is to put all your settings statements at the top
of your script, before calling the C<dance()> method.
Other ways are possible: for example, you can define all your settings in the file
C<appdir/config.yml>. For this, you must have installed the L<YAML> module, and
of course, write the config file in YAML.
That's better than the first option, but it's still not perfect as you can't
switch easily from an environment to another without rewriting the config
file.
A better solution is to have one F<config.yml> file with default global
settings, like the following:
# appdir/config.yml
logger: 'file'
layout: 'main'
And then write as many environment files as you like in
C<appdir/environments>. That way, the appropriate environment config file
will be loaded according to the running environment (if none is specified,
it will be 'development').
Note that you can change the running environment using the C<--environment>
command line switch.
Typically, you'll want to set the following values in a development config
file:
# appdir/environments/development.yml
log: 'debug'
startup_info: 1
show_errors: 1
And in a production one:
# appdir/environments/production.yml
log: 'warning'
startup_info: 0
show_errors: 0
Please note that you are not limited to writing configuration files in YAML.
Dancer2 supports any file format that is supported by L<Config::Any>, such
as JSON, XML, INI files, and Apache-style config files.
=head2 Accessing configuration information
A Dancer2 application can use the C<config> keyword to easily access the
settings within its config file, for instance:
get '/appname' => sub {
return "This is " . config->{appname};
};
This makes keeping your application's settings all in one place simple and
easy - you shouldn't need to worry about implementing all that yourself. :)
=head2 Settings
It's possible to change almost every parameter of the application via the
settings mechanism.
A setting is a key/value pair assigned by the keyword B<set>:
set setting_name => 'setting_value';
More usefully, settings can be defined in a configuration file.
Environment-specific settings can also be defined in environment-specific
files (for instance, you do not want to show error stacktraces in
production, and might want extra logging in development).
=head2 Serializers
When writing a webservice, data serialization/deserialization is a common
issue to deal with. Dancer2 can automatically handle that for you, via a
serializer.
When setting up a serializer, a new behaviour is authorized for any route
handler you define: any non-scalar response will be rendered as a serialized
string, via the current serializer.
Here is an example of a route handler that will return a hashref:
use Dancer2;
set serializer => 'JSON';
get '/user/:id/' => sub {
{ foo => 42,
number => 100234,
list => [qw(one two three)],
}
};
Dancer2 will render the response via the current serializer.
Hence, with the JSON serializer set, the route handler above would result in
a content like the following:
{"number":100234,"foo":42,"list":["one","two","three"]}
If you send a value which is validated serialized data, but is not in the
form a key and value pair (such as a serialized string or a JSON array), the
data will not be available in C<params> but will be available in
C<< request->data >>.
The following serializers are available, be aware they dynamically depend on
Perl modules you may not have on your system.
=over 4
=item * B<JSON>
Requires L<JSON>.
=item * B<YAML>
Requires L<YAML>,
=item * B<XML>
Requires L<XML::Simple>.
=item * B<Mutable>
Will try to find the appropriate serializer using the B<Content-Type> and
B<Accept-type> header of the request.
=back
=head2 Importing using Appname
An app in Dancer2 uses the class name (defined by the C<package> function) to
define the App name. Thus separating the App to multiple files, actually means
creating multiple applications. This means that any engine defined in an application,
because the application is a complete separate scope, will not be available to a
different application:
package MyApp::User {
use Dancer2;
set serializer => 'JSON';
get '/view' => sub {...};
}
package MyApp::User::Edit {
use Dancer2;
get '/edit' => sub {...};
}
These are two different Dancer2 Apps. They have different scopes, contexts,
and thus different engines. While C<MyApp::User> has a serializer defined,
C<MyApp::User::Edit> will not have that configuration.
By using the import option C<appname>, we can ask Dancer2 to extend an
App without creating a new one:
package MyApp::User {
use Dancer2;
set serializer => 'JSON';
get '/view' => sub {...};
}
package MyApp::User::Edit {
use Dancer2 appname => 'MyApp::User'; # extending MyApp::User
get '/edit' => sub {...};
}
The import option C<appname> allows you to seamlessly extend Dancer2 Apps
without creating unnecessary additional applications or repeat any definitions.
This allows you to spread your application routes across multiple files and allow
ease of mind when developing it, and accommodate multiple developers working
on the same codebase.
# app.pl
use MyApp::User;
use MyApp::User::Edit;
# single application composed of routes provided in multiple files
MyApp::User->to_app;
This way only one class needs to be loaded while creating an app:
# app.pl:
use MyApp::User;
MyApp::User->to_app;
=head1 LOGGING
=head2 Configuring logging
It's possible to log messages generated by the application and by Dancer2
itself.
To start logging, select the logging engine you wish to use with the
C<logger> setting; Dancer2 includes built-in log engines named C<file> and
C<console>, which log to a logfile and to the console respectively.
To enable logging to a file, add the following to your config file:
logger: 'file'
Then you can choose which kind of messages you want to actually log:
log: 'core' # will log debug, info, warnings, errors,
# and messages from Dancer2 itself
log: 'debug' # will log debug, info, warning and errors
log: 'info' # will log info, warning and errors
log: 'warning' # will log warning and errors
log: 'error' # will log only errors
If you're using the C<file> logging engine, a directory C<appdir/logs> will
be created and will host one logfile per environment. The log message
contains the time it was written, the PID of the current process, the
message and the caller information (file and line).
=head2 Logging your own messages
Just call L<debug|https://metacpan.org/pod/Dancer2::Manual#debug>,
L<info|https://metacpan.org/pod/Dancer2::Manual#info>,
L<warning|https://metacpan.org/pod/Dancer2::Manual#warning> or
L<error|https://metacpan.org/pod/Dancer2::Manual#error> with your message:
debug "This is a debug message from my app.";
=head1 TESTING
=head2 Using Plack::Test
L<Plack::Test> receives a common web request (using standard L<HTTP::Request>
objects), fakes a web server in order to create a proper PSGI request, and sends it
to the web application. When the web application returns a PSGI response
(which Dancer applications do), it will then convert it to a common web response
(as a standard L<HTTP::Response> object).
This allows you to then create requests in your test, create the code reference
for your web application, call them, and receive a response object, which can
then be tested.
=head3 Basic Example
Assuming there is a web application:
# MyApp.pm
package MyApp;
use Dancer2;
get '/' => sub {'OK'};
1;
The following test I<base.t> is created:
# base.t
use strict;
use warnings;
use Test::More tests => 2;
use Plack::Test;
use HTTP::Request;
use MyApp;
Creating a coderef for the application using the C<to_app> keyword:
my $app = MyApp->to_app;
Creating a test object from L<Plack::Test> for the application:
my $test = Plack::Test->create($app);
Creating the first request object and sending it to the test object
to receive a response:
my $request = HTTP::Request->new( GET => '/' );
my $response = $test->request($request);
It can now be tested:
ok( $response->is_success, '[GET /] Successful request' );
is( $response->content, 'OK', '[GET /] Correct content' );
=head3 Putting it together
# base.t
use strict;
use warnings;
use Test::More;
use Plack::Test;
use HTTP::Request::Common;
use MyApp;
my $test = Plack::Test->create( MyApp->to_app );
my $response = $test->request( GET '/' );
ok( $response->is_success, '[GET /] Successful request' );
is( $response->content, 'OK', '[GET /] Correct content' );
done_testing();
=head3 Subtests
Tests can be separated using L<Test::More>'s C<subtest> functionality,
thus creating multiple self-contained tests that don't overwrite each other.
Assuming we have a different app that has two states we want to test:
# MyApp.pm
package MyApp;
use Dancer2;
set serializer => 'JSON';
get '/' => sub {
my $user = route_parameters->get('user');
$user and return { user => $user };
return {};
};
1;
This is a contrived example of a route that checks for a user
parameter. If it exists, it returns it in a hash with the key
'user'. If not, it returns an empty hash
# param.t
use strict;
use warnings;
use Test::More;
use Plack::Test;
use HTTP::Request::Common;
use MyApp;
my $test = Plack::Test->create( MyApp->to_app );
subtest 'A empty request' => sub {
my $res = $test->request( GET '/' );
ok( $res->is_success, 'Successful request' );
is( $res->content '{}', 'Empty response back' );
};
subtest 'Request with user' => sub {
my $res = $test->request( GET '/?user=sawyer_x' );
ok( $res->is_success, 'Successful request' );
is( $res->content '{"user":"sawyer_x"}', 'Empty response back' );
};
done_testing();
=head3 Cookies
To handle cookies, which are mostly used for maintaining sessions,
the following modules can be used:
=over 4
=item * L<Test::WWW::Mechanize::PSGI>
=item * L<LWP::Protocol::PSGI>
=item * L<HTTP::Cookies>
=back
Taking the previous test, assuming it actually creates and uses
cookies for sessions:
# ... all the use statements
use HTTP::Cookies;
my $jar = HTTP::Cookies->new;
my $test = Plack::Test->create( MyApp->to_app );
subtest 'A empty request' => sub {
my $res = $test->request( GET '/' );
ok( $res->is_success, 'Successful request' );
is( $res->content '{}', 'Empty response back' );
$jar->extract_cookies($res);
ok( $jar->as_string, 'We have cookies!' );
};
subtest 'Request with user' => sub {
my $req = GET '/?user=sawyer_x';
$jar->add_cookie_header($req);
my $res = $test->request($req);
ok( $res->is_success, 'Successful request' );
is( $res->content '{"user":"sawyer_x"}', 'Empty response back' );
$jar->extract_cookies($res);
ok( ! $jar->as_string, 'All cookies deleted' );
};
done_testing();
Here a cookie jar is created, all requests and responses, existing
cookies, as well as cookies that were deleted by the response, are checked.
=head3 Accessing the configuration file
By importing Dancer2 in the command line scripts, there is full
access to the configuration using the imported keywords:
use strict;
use warnings;
use Test::More;
use Plack::Test;
use HTTP::Request::Common;
use MyApp;
use Dancer2;
my $appname = config->{'appname'};
diag "Testing $appname";
# ...
=head1 PACKAGING
=head2 Carton
=head3 What it does
L<Carton> sets up a local copy of your project prerequisites. You only
need to define them in a file and ask Carton to download all of them
and set them up.
When you want to deploy your app, you just carry the git clone and ask
Carton to set up the environment again and you will then be able to run it.
The benefits are multifold:
=over 4
=item * Local Directory copy
By putting all the dependencies in a local directory, you can make
sure they aren't updated by someone else by accident and their versions
locked to the version you picked.
=item * Sync versions
Deciding which versions of the dependent modules your project needs
allows you to sync this with other developers as well. Now you're all
using the same version and they don't change unless you want update the
versions you want. When updated everyone again uses the same new version
of everything.
=item * Carry only the requirement, not bundled modules
Instead of bundling the modules, you only actually bundle the requirements.
Carton builds them for you when you need it.
=back
=head3 Setting it up
First set up a new app:
$ dancer2 -a MyApp
...
Delete the files that are not needed:
$ rm -f Makefile.PL MANIFEST MANIFEST.SKIP
Create a git repo:
$ git init && git add . && git commit -m "initial commit"
Add a requirement using the L<cpanfile> format:
$ cat > cpanfile
requires 'Dancer2' => 0.155000;
requires 'Template' => 0;
recommends 'URL::Encode::XS' => 0;
recommends 'CGI::Deurl::XS' => 0;
recommends 'HTTP::Parser::XS' => 0;
Ask carton to set it up:
$ carton install
Installing modules using [...]
Successfully installed [...]
...
Complete! Modules were install into [...]/local
Now we have two files: I<cpanfile> and I<cpanfile.snapshot>. We
add both of them to our Git repository and we make sure we don't
accidentally add the I<local/> directory Carton created which holds
the modules it installed:
$ echo local/ >> .gitignore
$ git add .gitignore cpanfile cpanfile.snapshot
$ git commit -m "Start using carton"
When we want to update the versions on the production machine,
we simply call:
$ carton install --deployment
By using --deployment we make sure we only install the modules
we have in our cpanfile.snapshot file and do not fallback to querying
the CPAN.
=head2 FatPacker
L<App::FatPacker> (using its command line interface, L<fatpack>) packs
dependencies into a single file, allowing you to carry a single file
instead of a directory tree.
As long as your application is pure-Perl, you could create a single
file with your application and all of Dancer2 in it.
The following example will demonstrate how this can be done:
Assuming we have an application in I<lib/MyApp.pm>:
package MyApp;
use Dancer2;
get '/' => sub {'OK'};
1;
And we have a handler in I<bin/app.pl>:
use strict;
use warnings;
use FindBin;
use lib "$FindBin::Bin/../lib";
use MyApp;
MyApp->to_app;
To fatpack it, we begin by tracing the script:
$ fatpack trace bin/app.pl
This creates a I<fatpacker.trace> file. From this we create the packlists:
$ fatpack packlists-for `cat fatpacker.trace` > packlists
The packlists are stored in a file called I<packlists>.
Now we create the tree using the following command:
$ fatpack tree `cat packlists`
The tree is created under the directory I<fatlib>.
Now we create a file containing the dependency tree, and add our script to it,
using the following command:
$ (fatpack file; cat bin/app.pl) > myapp.pl
This creates a file called I<myapp.pl> with everything in it. Dancer2 uses
L<MIME::Types> which has a database of all MIME types and helps translate those.
The small database file containing all of these types is a binary and therefore
cannot be fatpacked. Hence, it needs to be copied to the current directory so our
script can find it:
$ cp fatlib/MIME/types.db .
=head1 MIDDLEWARES
=head2 Plack middlewares
If you want to use Plack middlewares, you need to enable them using
L<Plack::Builder> as such:
# in app.psgi or any other handler
use Dancer2;
use MyApp;
use Plack::Builder;
builder {
enable 'Deflater';
enable 'Session', store => 'File';
enable 'Debug', panels => [ qw<DBITrace Memory Timer> ];
dance;
};
The nice thing about this setup is that it will work seamlessly through
Plack or through the internal web server.
# load dev web server (without middlewares)
perl -Ilib app.psgi
# load plack web server (with middlewares)
plackup -I lib app.psgi
You do not need to provide different files for either server.
=head3 Path-based middlewares
If you want to set up a middleware for a specific path, you can do that using
L<Plack::Builder> which uses L<Plack::App::URLMap>:
# in your app.psgi or any other handler
use Dancer2;
use MyApp;
use Plack::Builder;
my $special_handler = sub { ... };
builder {
mount '/' => dance;
mount '/special' => $special_handler;
};
=head3 Running on Perl web servers with plackup
A number of Perl web servers supporting PSGI are available on CPAN:
=over 4
=item * L<Starman|http://search.cpan.org/dist/Starman/>
C<Starman> is a high performance web server, with support for preforking,
signals, multiple interfaces, graceful restarts and dynamic worker pool
configuration.
=item * L<Twiggy|http://search.cpan.org/dist/Twiggy/>
C<Twiggy> is an C<AnyEvent> web server, it's light and fast.
=item * L<Corona|http://search.cpan.org/dist/Corona/>
C<Corona> is a C<Coro> based web server.
=back
To start your application, just run plackup (see L<Plack> and specific
servers above for all available options):
$ plackup bin/app.psgi
$ plackup -E deployment -s Starman --workers=10 -p 5001 -a bin/app.psgi
As you can see, the scaffolded Perl script for your app can be used as a
PSGI startup file.
=head4 Enabling content compression
Content compression (gzip, deflate) can be easily enabled via a Plack
middleware (see L<Plack/Plack::Middleware>): L<Plack::Middleware::Deflater>.
It's a middleware to encode the response body in gzip or deflate, based on the
C<Accept-Encoding> HTTP request header.
Enable it as you would enable any Plack middleware. First you need to
install L<Plack::Middleware::Deflater>, then in the handler (usually
F<app.psgi>) edit it to use L<Plack::Builder>, as described above:
use Dancer2;
use MyApp;
use Plack::Builder;
builder {
enable 'Deflater';
dance;
};
To test if content compression works, trace the HTTP request and response
before and after enabling this middleware. Among other things, you should
notice that the response is gzip or deflate encoded, and contains a header
C<Content-Encoding> set to C<gzip> or C<deflate>.
=head3 Running multiple apps with Plack::Builder
You can use L<Plack::Builder> to mount multiple Dancer2 applications on a
L<PSGI> webserver like L<Starman>.
Start by creating a simple app.psgi file:
use OurWiki; # first app
use OurForum; # second app
use Plack::Builder;
builder {
mount '/wiki' => OurWiki->to_app;
mount '/forum' => OurForum->to_app;
};
and now use L<Starman>
plackup -a app.psgi -s Starman
Currently this still demands the same appdir for both (default circumstance)
but in a future version this will be easier to change while staying very
simple to mount.
=head3 Running from Apache with Plack
You can run your app from Apache using PSGI (Plack), with a config like the
following:
<VirtualHost myapp.example.com>
ServerName www.myapp.example.com
ServerAlias myapp.example.com
DocumentRoot /websites/myapp.example.com
<Directory /home/myapp/myapp>
AllowOverride None
Order allow,deny
Allow from all
</Directory>
<Location />
SetHandler perl-script
PerlResponseHandler Plack::Handler::Apache2
PerlSetVar psgi_app /websites/myapp.example.com/app.psgi
</Location>
ErrorLog /websites/myapp.example.com/logs/error_log
CustomLog /websites/myapp.example.com/logs/access_log common
</VirtualHost>
To set the environment you want to use for your application (production or
development), you can set it this way:
<VirtualHost>
...
SetEnv DANCER_ENVIRONMENT "production"
...
</VirtualHost>
=head1 PLUGINS
=head2 Writing a plugin
See L<Dancer2::Plugin/Writing the plugin> for information on how to author
a new plugin for Dancer2.
=head1 EXPORTS
By default, C<use Dancer2> exports all the DSL keywords and sets up the
webapp under the name of the current package. The following tags control
exports and webapp namespace.
=over 4
=item * B<!keyword>
If you want to prevent Dancer2 from exporting specific keywords (perhaps you
plan to implement them yourself in a different way, or they clash with
another module you're loading), you can simply exclude them:
use Test::More;
use Dancer2 qw(!pass);
The above would import all keywords as usual, with the exception of C<pass>.
=item * B<appname>
A larger application may split its source between several packages to aid
maintainability. Dancer2 will create a separate application for each
package, each having separate hooks, config and/or engines. You can force
Dancer2 to collect the route and hooks into a single application with the
C<appname> tag; e.g.
package MyApp;
use Dancer2;
get '/foo' => sub {...};
package MyApp::Private;
use Dancer2 appname => MyApp;
get '/bar' => sub {...};
The above would add the C<bar> route to the MyApp application. Dancer2 will
I<not> create an application with the name C<MyApp::Private>.
=item * B<:nopragmas>
By default L<Dancer2> will import three pragmas: L<strict>, L<warnings>,
and L<utf8>. If you require control over the imported pragmas, you can add
B<:nopragmas> to the importing flags, in which case Dancer2 will not import
any pragmas:
use strict;
use warnings;
no warnings 'experimental::smartmatch'; # for example...
use Dancer2 ':nopragmas'; # do not touch the existing pragmas
This way importing C<Dancer2> does not change the existing pragmas setup
you have.
=back
When you C<use Dancer2>, you get an C<import> method added into the current
package. This B<will> override previously declared import methods from other
sources, such as L<Exporter>. Dancer2 applications support the following
tags on import:
=over 4
=item * B<with>
The C<with> tag allows an app to pass one or more config entries to another
app, when it C<use>s it.
package MyApp;
use Dancer2;
BEGIN { set session => 'YAML' };
use Blog with => { session => engine('session') };
In this example, the session engine is passed to the C<Blog> app. That way,
anything done in the session will be shared between both apps.
Anything that is defined in the config entry can be passed that way. If we
want to pass the whole config object, it can be done like so:
use SomeApp with => { %{config()} };
=back
=head1 DSL KEYWORDS
Dancer2 provides you with a DSL (Domain-Specific Language) which makes
implementing your web application trivial.
For example, take the following example:
use Dancer2;
get '/hello/:name' => sub {
my $name = route_parameters->get('name');
};
dance;
C<get> and C<route_parameters> are keywords provided by Dancer2.
This document lists all keywords provided by Dancer2. It does not cover
additional keywords which may be provided by loaded plugins; see the
documentation for plugins you use to see which additional keywords they make
available to you.
=head2 any
Defines a route for multiple HTTP methods at once:
any ['get', 'post'] => '/myaction' => sub {
# code
};
Or even, a route handler that would match any HTTP methods:
any '/myaction' => sub {
# code
};
=head2 cookies
Accesses cookies values, it returns a hashref of L<Dancer2::Core::Cookie>
objects:
get '/some_action' => sub {
my $cookie = cookies->{name};
return $cookie->value;
};
In case you have stored something other than a scalar in your cookie:
get '/some_action' => sub {
my $cookie = cookies->{oauth};
my %values = $cookie->value;
return ($values{token}, $values{token_secret});
};
=head2 cookie
Accesses a cookie value (or sets it). Note that this method will eventually
be preferred over C<set_cookie>.
cookie lang => "fr-FR"; # set a cookie and return its value
cookie lang => "fr-FR", expires => "2 hours"; # extra cookie info
cookie "lang" # return a cookie value
If your cookie value is a key/value URI string, like
token=ABC&user=foo
C<cookie> will only return the first part (C<token=ABC>) if called in scalar
context. Use list context to fetch them all:
my @values = cookie "name";
=head2 config
Accesses the configuration of the application:
get '/appname' => sub {
return "This is " . config->{appname};
};
=head2 content
Sets the content for the response. This B<only> works within a delayed
response.
This will crash:
get '/' => sub {
# THIS WILL CRASH
content 'Hello, world!';
};
But this will work just fine:
get '/' => sub {
delayed {
content 'Hello, world!';
...
};
};
=head2 content_type
Sets the B<content-type> rendered, for the current route handler:
get '/cat/:txtfile' => sub {
content_type 'text/plain';
# here we can dump the contents of route_parameters->get('txtfile')
};
You can use abbreviations for content types. For instance:
get '/svg/:id' => sub {
content_type 'svg';
# here we can dump the image with id route_parameters->get('id')
};
Note that if you want to change the default content-type for every route,
it is easier to change the C<content_type> setting instead.
=head2 dance
Alias for the C<start> keyword.
=head2 dancer_version
Returns the version of Dancer. If you need the major version, do something
like:
int(dancer_version);
=head2 debug
Logs a message of debug level:
debug "This is a debug message";
See L<Dancer2::Core::Role::Logger> for details on how to configure where log
messages go.
=head2 decode_json ($string)
Deserializes a JSON structure from an UTF-8 binary string.
=head2 dirname
Returns the dirname of the path given:
my $dir = dirname($some_path);
=head2 encode_json ($structure)
Serializes a structure to a UTF-8 binary JSON string.
Calling this function will B<not> trigger the serialization's hooks.
=head2 engine
Given a namespace, returns the current engine object
my $template_engine = engine 'template';
my $html = $template_engine->apply_renderer(...);
$template_engine->apply_layout($html);
=head2 error
Logs a message of error level:
error "This is an error message";
See L<Dancer2::Core::Role::Logger> for details on how to configure where log
messages go.
=head2 false
Constant that returns a false value (0).
=head2 forward
Runs an "internal redirect" of the current route to another route. More
formally; when C<forward> is executed, the current dispatch of the route is
aborted, the request is modified (altering query params or request method),
and the modified request following a new route is dispatched again. Any
remaining code (route and hooks) from the current dispatch will never be run
and the modified route's dispatch will execute hooks for the new route normally.
It effectively lets you chain routes together in a clean manner.
get '/demo/articles/:article_id' => sub {
# you'll have to implement this next sub yourself :)
change_the_main_database_to_demo();
forward "/articles/" . route_parameters->get('article_id');
};
In the above example, the users that reach I</demo/articles/30> will
actually reach I</articles/30> but we've changed the database to demo
before.
This is pretty cool because it lets us retain our paths and offer a demo
database by merely going to I</demo/...>.
You'll notice that in the example we didn't indicate whether it was B<GET>
or B<POST>. That is because C<forward> chains the same type of route the
user reached. If it was a B<GET>, it will remain a B<GET> (but if you do
need to change the method, you can do so; read on below for details.)
Also notice that C<forward> only redirects to a new route. It does not redirect
the requests involving static files. This is because static files are handled
before L<Dancer2> tries to match the request to a route - static files take
higher precedence.
This means that you will not be able to C<forward> to a static file. If you
wish to do so, you have two options: either redirect (asking the browser to
make another request, but to a file path instead) or use C<send_file> to
provide a file.
B<WARNING:> Any code after a C<forward> is ignored, until the end of the
route. It's not necessary to use C<return> with C<forward> anymore.
get '/foo/:article_id' => sub {
if ($condition) {
forward "/articles/" . route_parameters->get('article_id');
# The following code WILL NOT BE executed
do_stuff();
}
more_stuff();
};
Note that C<forward> doesn't parse GET arguments. So, you can't use
something like:
forward '/home?authorized=1';
But C<forward> supports an optional hashref with parameters to be added to
the actual parameters:
forward '/home', { authorized => 1 };
Finally, you can add some more options to the C<forward> method, in a third
argument, also as a hashref. That option is currently only used to change
the method of your request. Use with caution.
forward '/home', { auth => 1 }, { method => 'POST' };
=head2 from_dumper ($structure)
Deserializes a Data::Dumper structure.
=head2 from_json ($string, \%options)
Deserializes a JSON structure from a string. You should probably use
C<decode_json> which expects a UTF-8 encoded binary string and
handles decoding it for you.
=head2 from_yaml ($structure)
Deserializes a YAML structure.
=head2 get
Defines a route for HTTP B<GET> requests to the given path:
get '/' => sub {
return "Hello world";
}
Note that a route to match B<HEAD> requests is automatically created as well.
=head2 halt
Sets a response object with the content given.
When used as a return value from a hook, this breaks the execution flow and
renders the response immediately:
hook before => sub {
if ($some_condition) {
halt("Unauthorized");
# this code is not executed
do_stuff();
}
};
get '/' => sub {
"hello there";
};
B<WARNING:> Issuing a halt immediately exits the current route, and performs
the halt. Thus, any code after a halt is ignored, until the end of the route.
Hence, it's not necessary anymore to use C<return> with halt.
=head2 response_headers
Adds custom headers to response:
get '/send/headers', sub {
response_headers 'X-Foo' => 'bar', 'X-Bar' => 'foo';
}
=head2 response_header
Adds a custom header to response:
get '/send/header', sub {
response_header 'x-my-header' => 'shazam!';
}
Note that it will overwrite the old value of the header, if any. To avoid
that, see L</push_response_header>.
=head2 push_response_header
Do the same as C<response_header>, but allow for multiple headers with the same
name.
get '/send/header', sub {
push_response_header 'x-my-header' => '1';
push_response_header 'x-my-header' => '2';
# will result in two headers "x-my-header" in the response
}
=head2 hook
Adds a hook at some position. For example :
hook before_serializer => sub {
my $content = shift;
...
};
There can be multiple hooks assigned to a given position, and each will be
executed in order.
=head2 info
Logs a message of C<info> level:
info "This is an info message";
See L<Dancer2::Core::Role::Logger> for details on how to configure where log
messages go.
=head2 mime
Shortcut to access the instance object of L<Dancer2::Core::MIME>. You should
read the L<Dancer2::Core::MIME> documentation for full details, but the most
commonly-used methods are summarized below:
# set a new mime type
mime->add_type( foo => 'text/foo' );
# set a mime type alias
mime->add_alias( f => 'foo' );
# get mime type for an alias
my $m = mime->for_name( 'f' );
# get mime type for a file (based on extension)
my $m = mime->for_file( "foo.bar" );
# get current defined default mime type
my $d = mime->default;
# set the default mime type using config.yml
# or using the set keyword
set default_mime_type => 'text/plain';
=head2 params
I<This method should be called from a route handler>.
It's an alias for the L<Dancer2::Core::Request params
accessor|Dancer2::Core::Request/"params($source)">. It returns a hash (in
list context) or a hash reference (in scalar context) to all defined
parameters. Check C<param> below to access quickly to a single parameter
value.
post '/login' => sub {
// get all parameters as a single hash
my %all_parameters = params;
// request all parmameters from a specific source: body, query, route
my %body_parameters = params('body');
my %route_parameters = params('route');
my %query_parameters = params('query');
// any $source that is not body, query, or route generates an exception
params('fake_source'); // Unknown source params "fake_source"
};
We now recommend using one of the specific keywords for parameters
(C<route_parameters>, C<query_parameters>, and C<body_parameters>)
instead of C<params> or C<param>.
=head2 param
I<This method should be called from a route handler>.
This method is an accessor to the parameters hash table.
post '/login' => sub {
my $username = param "user";
my $password = param "pass";
# ...
};
We now recommend using one of the specific keywords for parameters
(C<route_parameters>, C<query_parameters>, and C<body_parameters>)
instead of C<params> or C<param>.
=head2 route_parameters
Returns a L<Hash::MultiValue> object from the route parameters.
# /hello
get '/:foo' => sub {
my $foo = route_parameters->get('foo');
};
=head2 query_parameters
Returns a L<Hash::MultiValue> object from the request parameters.
/?foo=hello
get '/' => sub {
my $name = query_parameters->get('foo');
};
/?name=Alice&name=Bob
get '/' => sub {
my @names = query_parameters->get_all('name');
};
=head2 body_parameters
Returns a L<Hash::MultiValue> object from the body parameters.
post '/' => sub {
my $last_name = body_parameters->get('name');
my @all_names = body_parameters->get_all('name');
};
=head2 pass
I<This method should be called from a route handler>.
Tells Dancer2 to pass the processing of the request to the next matching
route.
B<WARNING:> Issuing a pass immediately exits the current route, and performs
the pass. Thus, any code after a pass is ignored, until the end of the
route. Hence, it's not necessary anymore to use C<return> with pass.
get '/some/route' => sub {
if (...) {
# we want to let the next matching route handler process this one
pass(...);
# this code will be ignored
do_stuff();
}
};
B<WARNING:> You cannot set the content before passing and have it remain,
even if you use the C<content> keyword or set it directly in the response
object.
=head2 patch
Defines a route for HTTP B<PATCH> requests to the given URL:
patch '/resource' => sub { ... };
(C<PATCH> is a relatively new and not-yet-common HTTP verb, which is
intended to work as a "partial-PUT", transferring just the changes; please
see L<RFC5789|http://tools.ietf.org/html/rfc5789> for further details.)
=head2 path
Concatenates multiple paths together, without worrying about the underlying
operating system:
my $path = path(dirname($0), 'lib', 'File.pm');
It also normalizes (cleans) the path aesthetically. It does not verify whether
the path exists, though.
=head2 post
Defines a route for HTTP B<POST> requests to the given URL:
post '/' => sub {
return "Hello world";
}
=head2 prefix
Defines a prefix for each route handler, like this:
prefix '/home';
From here, any route handler is defined to /home/*:
get '/page1' => sub {}; # will match '/home/page1'
You can unset the prefix value:
prefix undef;
get '/page1' => sub {}; # will match /page1
For a safer alternative you can use lexical prefix like this:
prefix '/home' => sub {
## Prefix is set to '/home' here
get ...;
get ...;
};
## prefix reset to the previous version here
This makes it possible to nest prefixes:
prefix '/home' => sub {
## some routes
prefix '/private' => sub {
## here we are under /home/private...
## some more routes
};
## back to /home
};
## back to the root
B<Notice:> Once you have a prefix set, do not add a caret to the regex:
prefix '/foo';
get qr{^/bar} => sub { ... } # BAD BAD BAD
get qr{/bar} => sub { ... } # Good!
=head2 del
Defines a route for HTTP B<DELETE> requests to the given URL:
del '/resource' => sub { ... };
=head2 options
Defines a route for HTTP B<OPTIONS> requests to the given URL:
options '/resource' => sub { ... };
=head2 put
Defines a route for HTTP B<PUT> requests to the given URL:
put '/resource' => sub { ... };
=head2 redirect
Generates a HTTP redirect (302). You can either redirect to a complete
different site or within the application:
get '/twitter', sub {
redirect 'http://twitter.com/me';
# Any code after the redirect will not be executed.
};
B<WARNING:> Issuing a C<redirect> immediately exits the current route.
Thus, any code after a C<redirect> is ignored, until the end of the route.
Hence, it's not necessary anymore to use C<return> with C<redirect>.
You can also force Dancer to return a specific 300-ish HTTP response code:
get '/old/:resource', sub {
redirect '/new/' . route_parameters->get('resource'), 301;
};
=head2 request
Returns a L<Dancer2::Core::Request> object representing the current request.
See the L<Dancer2::Core::Request> documentation for the methods you can
call, for example:
request->referer; # value of the HTTP referer header
request->remote_address; # user's IP address
request->user_agent; # User-Agent header value
=head2 request_header
Returns request header(s).
get '/get/headers' => sub {
my $xfoo = request_header 'X-Foo';
...
};
=head2 send_as
Allows the current route handler to return specific content types to the
client using either a specified serializer or as html.
Any Dancer2 serializer may be used. The specified serializer class will
be loaded if required, or an error generated if the class can not be found.
Serializer configuration may be added to your apps C<engines> configuration.
If C<html> is specified, the content will be returned assuming it is HTML with
appropriate C<Content-Type> headers and encoded using the apps configured
C<charset> (or UTF-8).
set serializer => 'YAML';
set template => 'TemplateToolkit';
# returns html (not YAML)
get '/' => sub { send_as html => template 'welcome.tt' };
# return json (not YAML)
get '/json' => sub {
send_as JSON => [ some => { data => 'structure' } ];
};
C<send_as> uses L<send_file> to return the content immediately. You may
pass any option C<send_file> supports as an extra option. For example:
# return json with a custom content_type header
get '/json' => sub {
send_as JSON => [ some => { data => 'structure' } ],
{ content_type => 'application/json; charset=UTF-8' },
};
B<WARNING:> Issuing a send_as immediately exits the current route, and
performs the C<send_as>. Thus, any code after a C<send_as> is ignored,
until the end of the route. Hence, it's not necessary to use C<return>
with C<send_as>.
get '/some/route' => sub {
if (...) {
send_as JSON => $some_data;
# this code will be ignored
do_stuff();
}
};
=head2 send_error
Returns a HTTP error. By default the HTTP code returned is 500:
get '/photo/:id' => sub {
if (...) {
send_error("Not allowed", 403);
} else {
# return content
}
}
B<WARNING:> Issuing a send_error immediately exits the current route, and
performs the C<send_error>. Thus, any code after a C<send_error> is ignored,
until the end of the route. Hence, it's not necessary anymore to use C<return>
with C<send_error>.
get '/some/route' => sub {
if (...) {
# Something bad happened, stop immediately!
send_error(..);
# this code will be ignored
do_stuff();
}
};
=head2 send_file
Lets the current route handler send a file to the client. Note that the path
of the file must be relative to the B<public> directory unless you use the
C<system_path> option (see below).
get '/download/:file' => sub {
return send_file(route_parameters->get('file'));
}
B<WARNING:> Issuing a C<send_file> immediately exits the current route, and
performs the C<send_file>. Thus, any code after a C<send_file> is ignored,
until the end of the route. Hence, it's not necessary anymore to use C<return>
with C<send_file>.
get '/some/route' => sub {
if (...) {
# OK, send her what she wants...
send_file(...);
# this code will be ignored
do_stuff();
}
};
C<send_file> will use PSGI streaming if the server supports it (most, if
not all, do). You can explicitly disable streaming by passing
C<streaming =E<gt> 0> as an option to C<send_file>.
get '/download/:file' => sub {
send_file( route_parameters->get('file'), streaming => 0 );
}
The content-type will be set depending on the current MIME types definition
(see C<mime> if you want to define your own).
If your filename does not have an extension, you are passing in a filehandle,
or you need to force a specific mime type, you can pass it to C<send_file>
as follows:
send_file(route_parameters->get('file'), content_type => 'image/png');
send_file($fh, content_type => 'image/png');
Also, you can use your aliases or file extension names on C<content_type>,
like this:
send_file(route_parameters->get('file'), content_type => 'png');
The encoding of the file or filehandle may be specified by passing both
the C<content_type> and C<charset> options. For example:
send_file($fh, content_type => 'text/csv', charset => 'utf-8' );
For files outside your B<public> folder, you can use the C<system_path>
switch. Just bear in mind that its use needs caution as it can be dangerous.
send_file('/etc/passwd', system_path => 1);
If you have your data in a scalar variable, C<send_file> can be useful as
well. Pass a reference to that scalar, and C<send_file> will behave as if
there was a file with that contents:
send_file( \$data, content_type => 'image/png' );
Note that Dancer is unable to guess the content type from the data contents.
Therefore you might need to set the C<content_type> properly. For this kind
of usage an attribute named C<filename> can be useful. It is used as the
Content-Disposition header, to hint the browser about the filename it should
use.
send_file( \$data, content_type => 'image/png'
filename => 'onion.png' );
=head2 set
Defines a setting:
set something => 'value';
You can set more than one value at once:
set something => 'value', otherthing => 'othervalue';
=head2 setting
Returns the value of a given setting:
setting('something'); # 'value'
=head2 session
Provides access to all data stored in the user's session (if any).
It can also be used as a setter to store data in the session:
# getter example
get '/user' => sub {
if (session('user')) {
return "Hello, ".session('user')->name;
}
};
# setter example
post '/user/login' => sub {
...
if ($logged_in) {
session user => $user;
}
...
};
You may also need to clear a session:
# destroy session
get '/logout' => sub {
...
app->destroy_session;
...
};
If you need to fetch the session ID being used for any reason:
my $id = session->id;
=head2 splat
Returns the list of captures made from a route handler with a route pattern
which includes wildcards:
get '/file/*.*' => sub {
my ($file, $extension) = splat;
...
};
There is also the extensive splat (A.K.A. "megasplat"), which allows
extensive greedier matching, available using two asterisks. The additional
path is broken down and returned as an arrayref:
get '/entry/*/tags/**' => sub {
my ( $entry_id, $tags ) = splat;
my @tags = @{$tags};
};
The C<splat> keyword in the above example for the route F</entry/1/tags/one/two>
would set C<$entry_id> to C<1> and C<$tags> to C<['one', 'two']>.
=head2 start
Starts the application or the standalone server (depending on the deployment
choices).
This keyword should be called at the very end of the script, once all routes
are defined. At this point, Dancer2 takes over.
=head2 to_app
Returns the PSGI coderef for the current (and only the current) application.
You can call it as a method on the class or as a DSL:
my $app = MyApp->to_app;
# or
my $app = to_app;
There is a
L<Dancer Advent Calendar article|http://advent.perldancer.org/2014/9> covering
this keyword and its usage further.
=head2 psgi_app
Provides the same functionality as C<to_app> but uses the deprecated
Dispatcher engine. You should use C<to_app> instead.
=head2 status
Changes the status code provided by an action. By default, an action will
produce an C<HTTP 200 OK> status code, meaning everything is OK:
get '/download/:file' => {
if (! -f route_parameters->get('file')) {
status 'not_found';
return "File does not exist, unable to download";
}
# serving the file...
};
In that example, Dancer will notice that the status has changed, and will
render the response accordingly.
The C<status> keyword receives either a numeric status code or its name in
lower case, with underscores as a separator for blanks - see the list in
L<Dancer2::Core::HTTP/"HTTP CODES">. As an example, The above call translates
to setting the code to C<404>.
=head2 template
Returns the response of processing the given template with the given
parameters (and optional settings), wrapping it in the default or specified
layout too, if layouts are in use.
An example of a route handler which returns the result of using template to
build a response with the current template engine:
get '/' => sub {
...
return template 'some_view', { token => 'value'};
};
Note that C<template> simply returns the content, so when you use it in a
route handler, if execution of the route handler should stop at that point,
make sure you use C<return> to ensure your route handler returns the content.
Since C<template> just returns the result of rendering the template, you can
also use it to perform other templating tasks, e.g. generating emails:
post '/some/route' => sub {
if (...) {
email {
to => 'someone@example.com',
from => 'foo@example.com',
subject => 'Hello there',
msg => template('emails/foo', { name => body_parameters->get('name') }),
};
return template 'message_sent';
} else {
return template 'error';
}
};
Compatibility notice: C<template> was changed in version 1.3090 to
immediately interrupt execution of a route handler and return the content,
as it's typically used at the end of a route handler to return content.
However, this caused issues for some people who were using C<template> to
generate emails etc, rather than accessing the template engine directly, so
this change has been reverted in 1.3091.
The first parameter should be a template available in the views directory,
the second one (optional) is a hashref of tokens to interpolate, and the
third (again optional) is a hashref of options.
For example, to disable the layout for a specific request:
get '/' => sub {
template 'index', {}, { layout => undef };
};
Or to request a specific layout, of course:
get '/user' => sub {
template 'user', {}, { layout => 'user' };
};
Some tokens are automatically added to your template (C<perl_version>,
C<dancer_version>, C<settings>, C<request>, C<query_parameters>, C<body_parameters>, C<route_parameters>, C<vars> and, if you
have sessions enabled, C<session>). Check L<Dancer2::Core::Role::Template>
for further details.
=head2 to_dumper ($structure)
Serializes a structure with Data::Dumper.
Calling this function will B<not> trigger the serialization's hooks.
=head2 to_json ($structure, \%options)
Serializes a structure to JSON. You should probably use C<encode_json> instead
which handles encoding the result for you.
=head2 to_yaml ($structure)
Serializes a structure to YAML.
Calling this function will B<not> trigger the serialization's hooks.
=head2 true
Constant that returns a true value (1).
=head2 upload
Provides access to file uploads. Any uploaded file is accessible as a
L<Dancer2::Core::Request::Upload> object. You can access all parsed uploads
via:
post '/some/route' => sub {
my $file = upload('file_input_foo');
# $file is a Dancer2::Core::Request::Upload object
};
If you named multiple inputs of type "file" with the same name, the C<upload>
keyword would return an Array of L<Dancer2::Core::Request::Upload> objects:
post '/some/route' => sub {
my ($file1, $file2) = upload('files_input');
# $file1 and $file2 are Dancer2::Core::Request::Upload objects
};
You can also access the raw hashref of parsed uploads via the current
C<request> object:
post '/some/route' => sub {
my $all_uploads = request->uploads;
# $all_uploads->{'file_input_foo'} is a Dancer2::Core::Request::Upload object
# $all_uploads->{'files_input'} is an arrayref of Dancer2::Core::Request::Upload objects
};
Note that you can also access the filename of the upload received via the
C<body_parameters> keyword:
post '/some/route' => sub {
# body_parameters->get('files_input') is the filename of the file uploaded
};
See L<Dancer2::Core::Request::Upload> for details about the interface provided.
=head2 uri_for
Returns a fully-qualified URI for the given path:
get '/' => sub {
redirect uri_for('/path');
# can be something like: http://localhost:3000/path
};
=head2 captures
Returns a reference to a copy of C<%+>, if there are named captures in the
route's regular expression.
Named captures are a feature of Perl 5.10, and are not supported in earlier
versions:
get qr{
/ (?<object> user | ticket | comment )
/ (?<action> delete | find )
/ (?<id> \d+ )
/?$
}x
, sub {
my $value_for = captures;
"i don't want to $$value_for{action} the $$value_for{object} $$value_for{id} !"
};
=head2 var
Provides an accessor for variables shared between hooks and route
handlers. Given a key/value pair, it sets a variable:
hook before => sub {
var foo => 42;
};
Later, route handlers and other hooks will be able to read that variable:
get '/path' => sub {
my $foo = var 'foo';
...
};
=head2 vars
Returns the hashref of all shared variables set during the hook/route
chain with the C<var> keyword:
get '/path' => sub {
if (vars->{foo} eq 42) {
...
}
};
=head2 warning
Logs a warning message through the current logger engine:
warning "This is a warning";
See L<Dancer2::Core::Role::Logger> for details on how to configure where log
messages go.
=head1 AUTHOR
Dancer Core Developers
=head1 COPYRIGHT AND LICENSE
This software is copyright (c) 2016 by Alexis Sukrieh.
This is free software; you can redistribute it and/or modify it under
the same terms as the Perl 5 programming language system itself.
=cut
|