mocket

A web framework for MoonBit.

http
server
moon add oboard/mocket@0.7.8
Download zip
Author
Version
0.7.8
License
Apache-2.0
Last updated
2 hours ago
Downloads
2K

Dependencies

README

#oboard/mocket

Version GitHub Workflow Status (with event) License

A web framework for MoonBit.

#Quick Start

fn main {
let app = @mocket.new()
app.get("/", _ => "Hello, Mocket!")
app.serve(port=4000)
}

Mocket supports both js and native backends.

#JavaScript Backend

Set the backend of MoonBit to js in Visual Studio Code

Command: MoonBit: Select Backend -> js

moon run src/example --target js

#Native Backend

Set the backend of MoonBit to native in Visual Studio Code

Command: MoonBit: Select Backend -> native

moon run src/example --target native

Then visit http://localhost:4000

#Usage

Minimum Example: https://github.com/oboard/mocket_example

🙌快来吧!🙌

QQ 群号:949886784

QQ 群

#
HttpHandler

type HttpHandler = async (MocketEvent) -> &Responder noraise

#
Middleware

type Middleware = async (MocketEvent, async () -> &Responder noraise) -> &Responder noraise

#
MiddlewareNext

type MiddlewareNext = async () -> &Responder noraise

#
WebSocketHandler

type WebSocketHandler = (WebSocketEvent) -> Unit

#
BodyReader

pub(open) trait BodyReader {
from_request(req : HttpRequest) -> Self raise
}

impl BodyReader for Bytes
impl BodyReader for Json

#
Responder

pub(open) trait Responder {
options(Self, res : HttpResponse) -> Unit
output(Self, buf :
Buffer
) -> Unit
}

impl Responder for String
impl Responder for Bytes
impl Responder for Json
impl Responder for ToJson

#
ServeStaticProvider

pub(open) trait ServeStaticProvider {
get_meta(Self, id : String) -> StaticAssetMeta?
get_contents(Self, id : String) -> &Responder
get_type(Self, ext : String) -> String?
get_encodings(Self) -> Map[String, String]
get_index_names(Self) -> Array[String]
get_fallthrough(Self) -> Bool
}

#
ExecError

pub suberror ExecError

impl Show for ExecError

#
FetchError

pub suberror FetchError {
RequestFailed(String)
}

impl Show for FetchError

#
IOError

pub suberror IOError

impl Show for IOError

#
NetworkError

pub suberror NetworkError

#
CookieItem

pub(all) struct CookieItem {
name : String
value : String
max_age : Int?
path : String?
domain : String?
secure : Bool?
http_only : Bool?
same_site : SameSiteOption?
}

impl Eq for CookieItem
impl Show for CookieItem

#
FetchCredentials

pub(all) enum FetchCredentials {
Omit
SameOrigin
Include
}

#
FetchCredentials::to_string

fn FetchCredentials::to_string(self : FetchCredentials) -> String

#
FetchMode

pub(all) enum FetchMode {
Cors
NoCors
SameOrigin
Navigate
}

impl Eq for FetchMode
impl Show for FetchMode

#
FetchMode::to_string

fn FetchMode::to_string(self : FetchMode) -> String

#
Html

type Html

impl Responder for Html

#
HttpMethod

pub(all) enum HttpMethod {
GET
POST
PUT
PATCH
DELETE
HEAD
OPTIONS
TRACE
CONNECT
}

impl Eq for HttpMethod
impl Show for HttpMethod

#
HttpRequest

pub(all) struct HttpRequest {
http_method : String
url : String
headers : Map[StringView, StringView]
raw_body : Bytes
}

#
HttpRequest::body

fn[T : BodyReader] HttpRequest::body(self : HttpRequest) -> T raise

fn HttpRequest::get_cookie(self : HttpRequest, name : String) -> CookieItem?

#
HttpRequestInternal

#external
pub type HttpRequestInternal

#
HttpRequestInternal::on_complete

fn HttpRequestInternal::on_complete(self : HttpRequestInternal, cb : FuncRef[() -> Unit]) -> Unit

#
HttpRequestInternal::on_headers

fn HttpRequestInternal::on_headers(self : HttpRequestInternal, cb : FuncRef[(
CStr
) -> Unit]) -> Unit

#
HttpResponse

pub(all) struct HttpResponse {
status_code : StatusCode
headers : Map[StringView, StringView]
cookies : Map[String, CookieItem]
raw_body : Bytes
}

#
HttpResponse::body

fn HttpResponse::body(self : HttpResponse, body : &Responder) -> HttpResponse

fn HttpResponse::delete_cookie(self : HttpResponse, key : String) -> Unit

#
HttpResponse::json

fn HttpResponse::json(self : HttpResponse, obj : &ToJson) -> HttpResponse

#
HttpResponse::new

fn HttpResponse::new(status_code : StatusCode, headers? : Map[StringView, StringView], cookies? : Map[String, CookieItem], raw_body? : Bytes) -> HttpResponse

#
HttpResponse::read_body

fn[T : BodyReader] HttpResponse::read_body(self : HttpResponse) -> T raise

fn HttpResponse::set_cookie(self : HttpResponse, name : String, value : String, max_age? : Int, path? : String, domain? : String, secure? : Bool, http_only? : Bool, same_site? : SameSiteOption) -> Unit

#
HttpResponse::to_responder

fn HttpResponse::to_responder(self : HttpResponse) -> &Responder

#
HttpResponseInternal

#external
pub type HttpResponseInternal

#
HttpServerInternal

#external
pub type HttpServerInternal

#
Mocket

#alias(T)
pub(all) struct Mocket {
base_path : String
mappings : Map[(String, String), async (MocketEvent) -> &Responder noraise]
middlewares : Array[(String, async (MocketEvent, async () -> &Responder noraise) -> &Responder noraise)]
static_routes : Map[String, Map[String, async (MocketEvent) -> &Responder noraise]]
dynamic_routes : Map[String, Array[(String, async (MocketEvent) -> &Responder noraise)]]
ws_static_routes : Map[String, (WebSocketEvent) -> Unit]
ws_dynamic_routes : Array[(String, (WebSocketEvent) -> Unit)]
ws_clients : Map[String, Unit]
ws_channels : Map[String, Map[String, Unit]]
ws_client_port : Map[String, Int]
}

#
Mocket::all

fn Mocket::all(self : Mocket, path : String, handler : async (MocketEvent) -> &Responder noraise) -> Unit

#
Mocket::connect

fn Mocket::connect(self : Mocket, path : String, handler : async (MocketEvent) -> &Responder noraise) -> Unit

#
Mocket::delete

fn Mocket::delete(self : Mocket, path : String, handler : async (MocketEvent) -> &Responder noraise) -> Unit

#
Mocket::get

fn Mocket::get(self : Mocket, path : String, handler : async (MocketEvent) -> &Responder noraise) -> Unit

#
Mocket::group

fn Mocket::group(self : Mocket, base_path : String, configure : (Mocket) -> Unit) -> Unit

#
Mocket::head

fn Mocket::head(self : Mocket, path : String, handler : async (MocketEvent) -> &Responder noraise) -> Unit

#
Mocket::on

fn Mocket::on(self : Mocket, event : String, path : String, handler : async (MocketEvent) -> &Responder noraise) -> Unit

#
Mocket::options

fn Mocket::options(self : Mocket, path : String, handler : async (MocketEvent) -> &Responder noraise) -> Unit

#
Mocket::patch

fn Mocket::patch(self : Mocket, path : String, handler : async (MocketEvent) -> &Responder noraise) -> Unit

#
Mocket::post

fn Mocket::post(self : Mocket, path : String, handler : async (MocketEvent) -> &Responder noraise) -> Unit

#
Mocket::put

fn Mocket::put(self : Mocket, path : String, handler : async (MocketEvent) -> &Responder noraise) -> Unit

#
Mocket::serve

fn Mocket::serve(self : Mocket, port~ : Int) -> Unit

#
Mocket::static_assets

fn Mocket::static_assets(self : Mocket, path : String, provider : &ServeStaticProvider) -> Unit

#
Mocket::trace

fn Mocket::trace(self : Mocket, path : String, handler : async (MocketEvent) -> &Responder noraise) -> Unit

#
Mocket::use_middleware

fn Mocket::use_middleware(self : Mocket, middleware : async (MocketEvent, async () -> &Responder noraise) -> &Responder noraise, base_path? : String) -> Unit

#
Mocket::ws

fn Mocket::ws(self : Mocket, path : String, handler : (WebSocketEvent) -> Unit) -> Unit

#
MocketEvent

pub(all) struct MocketEvent {
req : HttpRequest
res : HttpResponse
params : Map[String, StringView]
}

#
MultipartFormValue

pub(all) struct MultipartFormValue {
filename : String?
content_type : String?
data : BytesView
}

#
SameSiteOption

pub(all) enum SameSiteOption {
Lax
Strict
SameSiteNone
}

#
StaticAssetMeta

pub(all) struct StaticAssetMeta {
asset_type : String?
etag : String?
mtime : Int64?
path : String?
size : Int64?
encoding : String?
}

#
StaticAssetMeta::new

fn StaticAssetMeta::new(asset_type? : String, etag? : String, mtime? : Int64, path? : String, size? : Int64, encoding? : String) -> StaticAssetMeta

#
StatusCode

pub(all) enum StatusCode {
Continue
SwitchingProtocols
Processing
EarlyHints
OK
Created
Accepted
NonAuthoritativeInfo
NoContent
ResetContent
PartialContent
MultiStatus
AlreadyReported
IMUsed
MultipleChoices
MovedPermanently
Found
SeeOther
NotModified
UseProxy
TemporaryRedirect
PermanentRedirect
BadRequest
Unauthorized
PaymentRequired
Forbidden
NotFound
MethodNotAllowed
NotAcceptable
ProxyAuthRequired
RequestTimeout
Conflict
Gone
LengthRequired
PreconditionFailed
RequestEntityTooLarge
RequestUriTooLong
UnsupportedMediaType
RequestedRangeNotSatisfiable
ExpectationFailed
Teapot
MisdirectedRequest
UnprocessableEntity
Locked
FailedDependency
TooEarly
UpgradeRequired
PreconditionRequired
TooManyRequests
RequestHeaderFieldsTooLarge
UnavailableForLegalReasons
InternalServerError
NotImplemented
BadGateway
ServiceUnavailable
GatewayTimeout
HttpVersionNotSupported
VariantAlsoNegotiates
InsufficientStorage
LoopDetected
NotExtended
NetworkAuthenticationRequired
Custom(Int)
}

HTTP status codes as registered with IANA. See: https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml
impl Eq for StatusCode
impl Show for StatusCode

#
StatusCode::from_int

fn StatusCode::from_int(i : Int) -> StatusCode

#
StatusCode::to_int

fn StatusCode::to_int(self : StatusCode) -> Int

#
WebSocketAggregatedMessage

pub enum WebSocketAggregatedMessage {
Text(String)
Binary(Bytes)
Ping
}

#
WebSocketEvent

pub enum WebSocketEvent {
Open(WebSocketPeer)
Message(WebSocketPeer, WebSocketAggregatedMessage)
Close(WebSocketPeer)
}

#
WebSocketPeer

pub(all) struct WebSocketPeer {
connection_id : String
subscribed_channels : Array[String]
}

#
WebSocketPeer::binary

fn WebSocketPeer::binary(self : WebSocketPeer, message : Bytes) -> Unit

#
WebSocketPeer::pong

fn WebSocketPeer::pong(self : WebSocketPeer) -> Unit

#
WebSocketPeer::publish

fn WebSocketPeer::publish(channel : String, message : String) -> Unit

#
WebSocketPeer::subscribe

fn WebSocketPeer::subscribe(self : WebSocketPeer, channel : String) -> Unit

#
WebSocketPeer::text

fn WebSocketPeer::text(self : WebSocketPeer, message : String) -> Unit

#
WebSocketPeer::to_string

fn WebSocketPeer::to_string(self : WebSocketPeer) -> String

#
WebSocketPeer::unsubscribe

fn WebSocketPeer::unsubscribe(self : WebSocketPeer, channel : String) -> Unit

#
__ws_emit

fn __ws_emit(event_type :
CStr
, connection_id :
CStr
, payload :
CStr
) -> Unit

#
async_run

fn async_run(f : async () -> Unit noraise) -> Unit

fn cookie_to_string(cookie : Array[CookieItem]) -> String

#
execute_middlewares

async fn execute_middlewares(middlewares : Array[(String, async (MocketEvent, async () -> &Responder noraise) -> &Responder noraise)], event : MocketEvent, final_handler : async (MocketEvent) -> &Responder noraise) -> &Responder noraise

#
fetch

async fn fetch(url : String, body? : String, http_method : HttpMethod, data? : &Responder, headers? : Map[String, String], credentials? : FetchCredentials, mode? : FetchMode) -> HttpResponse

#
form_encode

fn form_encode(map : Map[String, String]) -> String

#
handle_not_found

fn handle_not_found() -> (async (MocketEvent) -> &Responder noraise)

#
html

fn html(html : &Show) -> &Responder

#
new

fn new(base_path? : String) -> Mocket

fn parse_cookie(cookie : StringView) -> Map[String, CookieItem]

#
parse_form_data

fn parse_form_data(bytes : BytesView) -> Map[String, String]

#
parse_multipart

fn parse_multipart(bytes : BytesView, boundary : String) -> Map[String, MultipartFormValue]

#
register_ws_handler

fn register_ws_handler(mocket : Mocket, port : Int) -> Unit

#
serve_ffi

fn serve_ffi(mocket : Mocket, port~ : Int) -> Unit

#
suspend

async fn[T, E : Error] suspend(f : ((T) -> Unit, (E) -> Unit) -> Unit) -> T raise E

suspend 会中断当前协程的运行。 suspend 会接受一个回调函数,并让这个回调函数来操作中断的协程

#
text

fn text(text : &Show) -> &Responder

#
url_decode

fn url_decode(bytes : BytesView) -> String

#
url_encode

fn url_encode(s : String) -> String

#
ws_pong

fn ws_pong(id : String) -> Unit

#
ws_publish

fn ws_publish(channel : String, msg : String) -> Unit

#
ws_send

fn ws_send(id : String, msg : String) -> Unit

#
ws_send_bytes

fn ws_send_bytes(id : String, msg : Bytes) -> Unit

#
ws_subscribe

fn ws_subscribe(id : String, channel : String) -> Unit

#
ws_unsubscribe

fn ws_unsubscribe(id : String, channel : String) -> Unit