How to write a plugin for GNU Artanis
Introduction
Since GNU Artanis-1.2.2, we introduced plugins mechanism. It allows you to extend the framework with your own code. In this article, we'll show you how to write a plugin for GNU Artanis.
Simplest plugin named hello
Let's start with a simple plugin named hello. The plugin will provide a handler that returns a string "hello"
when the value is #t, and returns a string with the symbol name when the value is a symbol.
Here's the plugin code, let's put it in the file lib/myproj/hello.scm:
(define-module (myproj hello) #:use-module (ice-9 match) #:export (hello)) (define (hello val rule keys) (match val (#t (lambda (rc . _) "hello")) ((? symbol? sym) (lambda (rc . _) (format #f "~a: hello" sym))) (else (error "wrong mode"))))
Here's the controller code put in app/controllers/hello.scm:
(define-artanis-controller hello) ; DO NOT REMOVE THIS LINE!!! (import (conf plugins)) (get "/hello" #:hello #t (lambda (rc) (:hello rc))) (get "/whello" #:hello 'world (lambda (rc) (:hello rc)))
Since GNU Artanis-1.2.2, there's conf/plugins.scm file in the project root directory. You can enable plugins in this file. Here is an example:
;; This is a plugin configuration file, don't remove it! ;; Uncomment following lines to enable plugins. ;; Make sure you import the plugin modules here. (define-module (conf plugins) #:use-module (artanis oht) #:use-module (myproj hello)) (plugin-enable! hello hello) (plugin-enable! new-alias hello)
After you register the plugin in the name of hello, there'll be a keyword #:hello
as the option of the route. And the value of the option depends on the plugin implementation. In addition, there's also a macro :hello
was generated for you to use in the route handler.
(get "/hello" #:hello #t (lambda (rc) (:hello rc)))
What is the plugin handler?
The plugin handler is a procedure that takes three arguments, the first one is the value passed with #:hello
option, the second one is the rule of the route in string, and the third one is the keys that was bound in the URL.
Let's see an example:
(get "/hello/:who" #:hello #t (lambda (rc) (:hello rc)))
In this case, say, we have a plugin handler like this:
(define (hello val rule keys) (match val (#t (lambda (rc . _) "hello")) ((? symbol? sym) (lambda (rc . _) (format #f "~a: hello" sym))) (else (error "wrong mode"))))
Here're the arguments bound to the plugin handler:
- val is
#t
or any symobl like'world
- rule is
"/hello/:who"
- keys is
(list "who")
Conclusion
We've introduced plugins in GNU Artanis, it's a powerful feature that allows you to extend the framework with your own code. And then you can use it in the route handler by specifying the plugin name in the route option.
Happy hacking!