DEV Community

ringabout
ringabout

Posted on

4 1

flask like asynchronous web framework written in Nim

Nim language has great macros supports. Metaprogramming is interesting to play with. Let's look at this asynchronous web framework based on macros route.

https://github.com/planety/starlight

Hello world

import starlight
var app = newApp(newSettings())

proc hello(ctx: Context) {.async, get(app, "/hello").} =
  resp "Hello world!"

app.run()
Enter fullscreen mode Exit fullscreen mode

Vs flask

from flask import Flask
app = Flask(__name__)

@app.route('/')
def hello_world():
    return 'Hello, World!'
Enter fullscreen mode Exit fullscreen mode

Complex example

import starlight except loginPage
import logging
import htmlgen


func loginPage*(): string =
  return html(form(action = "/login",
      `method` = "post",
      "Username: ", input(name = "username", `type` = "text"),
      "Password: ", input(name = "password", `type` = "password"),
      input(value = "login", `type` = "submit")),
      xmlns = "http://www.w3.org/1999/xhtml")


var app = newApp(newSettings())

proc hello*(ctx: Context) {.async,
  get(app, "/"),
  post(app, "/"),
  get(app, "/hello")
  .} =
  resp "<h1>Hello, Prologue!</h1>"

proc home*(ctx: Context) {.async, route(app, "/home", HttpGet).} =
  resp "<h1>Home</h1>"

proc helloName*(ctx: Context) {.async, get(app, "/hello/{name}").} =
  resp "<h1>Hello, " & ctx.getPathParams("name", "Prologue!") & "</h1>"

proc redirectHome*(ctx: Context) {.async, route(app, "/redirect").} =
  resp redirect("/home")

proc loginGet*(ctx: Context) {.async, route(app, "/loginget").} =
  resp loginGetPage()

proc doLoginGet*(ctx: Context) {.async, route(app, "/loginpage", [HttpGet, HttpPost]).} =
  resp redirect("/hello/Nim")

proc login*(ctx: Context) {.async, get(app, "/login").} =
  resp loginPage()

proc doLogin*(ctx: Context) {.async, post(app, "/login").} =
  resp redirect("/hello/Nim")

app.run()
Enter fullscreen mode Exit fullscreen mode

Heroku

Simplify your DevOps and maximize your time.

Since 2007, Heroku has been the go-to platform for developers as it monitors uptime, performance, and infrastructure concerns, allowing you to focus on writing code.

Learn More

Top comments (1)

Collapse
 
jorjun profile image
jorjun •

Nim could really use a decorator syntax seems...

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❀ or a friendly comment on this post if you found it helpful!

Okay