웹 사이트에서 예제와 연습을 시작하십시오!
문서를 읽을 시간이 없습니까? 체크 아웃
✅ 안정적인 실행 ✅ ✅ 빠르게 실행
선적 서류 비치
Thruster는 개발자가 프로젝트 및 팀 전체에서 생산적이고 일관되게하는 것을 목표로하는 웹 프레임 워크입니다. 목표는 다음과 같습니다.
스러스터도 마찬가지입니다
unsafe 사용하지 않습니다스러 스터는 다른 서버 백엔드로 실행할 수 있으며 그 위에 멋진 패키지 레이어를 나타냅니다. 이는 집에서 자란 HTTP 엔진 인 Hyper, Actix 또는 심지어 Thrusterserver와 같은 최신의 가장 큰 변화를 따라갈 수 있음을 의미합니다.
KOA 및 Express와 같은 프레임 워크를 기반으로 스러스터는 발전하는 즐거움을 목표로합니다.
예제 cargo run --example <example-name> . 예를 들어, cargo run --example hello_world 및 Open http : // localhost : 4321/
새로운 비스듬한 코드 작업을하는 핵심 부분은 #[middleware_fn] 속성 (중간웨어를 표시하여 스러스터가 구축 한 안정적인 선물 버전과 호환되도록 m! 실제 경로에서 매크로.
비동기를 기다리는 간단한 예는 다음과 같습니다.
use std :: boxed :: Box ;
use std :: future :: Future ;
use std :: pin :: Pin ;
use std :: time :: Instant ;
use thruster :: { App , BasicContext as Ctx , Request } ;
use thruster :: { m , middleware_fn , MiddlewareNext , MiddlewareResult , Server , ThrusterServer } ;
# [ middleware_fn ]
async fn profile ( context : Ctx , next : MiddlewareNext < Ctx > ) -> MiddlewareResult < Ctx > {
let start_time = Instant :: now ( ) ;
context = next ( context ) . await ;
let elapsed_time = start_time . elapsed ( ) ;
println ! (
"[{}μs] {} -- {}" ,
elapsed_time . as_micros ( ) ,
context . request . method ( ) ,
context . request . path ( )
) ;
Ok ( context )
}
# [ middleware_fn ]
async fn plaintext ( mut context : Ctx , _next : MiddlewareNext < Ctx > ) -> MiddlewareResult < Ctx > {
let val = "Hello, World!" ;
context . body ( val ) ;
Ok ( context )
}
# [ middleware_fn ]
async fn four_oh_four ( mut context : Ctx , _next : MiddlewareNext < Ctx > ) -> MiddlewareResult < Ctx > {
context . status ( 404 ) ;
context . body ( "Whoops! That route doesn't exist!" ) ;
Ok ( context )
}
# [ tokio :: main ]
fn main ( ) {
println ! ( "Starting server..." ) ;
let mut app = App :: < Request , Ctx , ( ) > :: new_basic ( ) ;
app . get ( "/plaintext" , m ! [ profile , plaintext ] ) ;
app . set404 ( m ! [ four_oh_four ] ) ;
let server = Server :: new ( app ) ;
server . build ( "0.0.0.0" , 4321 ) . await ;
}다음은 좋은 예입니다
use thruster :: errors :: ThrusterError as Error ;
use thruster :: proc :: { m , middleware_fn } ;
use thruster :: { map_try , App , BasicContext as Ctx , Request } ;
use thruster :: { MiddlewareNext , MiddlewareResult , MiddlewareReturnValue , Server , ThrusterServer } ;
# [ middleware_fn ]
async fn plaintext ( mut context : Ctx , _next : MiddlewareNext < Ctx > ) -> MiddlewareResult < Ctx > {
let val = "Hello, World!" ;
context . body ( val ) ;
Ok ( context )
}
# [ middleware_fn ]
async fn error ( mut context : Ctx , _next : MiddlewareNext < Ctx > ) -> MiddlewareResult < Ctx > {
let res = "Hello, world" . parse :: < u32 > ( )
. map_err ( |_| {
let mut context = Ctx :: default ( ) ;
context . status ( 400 ) ;
ThrusterError {
context ,
message : "Custom error message" . to_string ( ) ,
cause : None ,
}
} ? ;
context . body ( & format ! ( "{}" , non_existent_param ) ) ;
Ok ( context )
}
# [ tokio :: main ]
fn main ( ) {
println ! ( "Starting server..." ) ;
let app = App :: < Request , Ctx , ( ) > :: new_basic ( )
. get ( "/plaintext" , m ! [ plaintext ] )
. get ( "/error" , m ! [ error ] ) ;
let server = Server :: new ( app ) ;
server . build ( "0.0.0.0" , 4321 ) . await ;
} Thruster는 엔드 포인트를 테스트 할 수있는 쉬운 테스트 스위트를 제공합니다. 다음과 같이 testing 모듈을 포함시킵니다.
let mut app = App :: < Request , Ctx , ( ) > :: new_basic ( ) ;
.. .
app . get ( "/plaintext" , m ! [ plaintext ] ) ;
.. .
let result = testing :: get ( app , "/plaintext" ) ;
assert ! ( result . body == "Hello, World!" ) ; 미들웨어는 매우 쉽게 만들 수 있습니다! 단순히 함수를 작성하고 모듈 수준에서 내보내십시오. 아래에는 요청을 프로파일 링 할 수있는 미들웨어가 표시됩니다.
# [ middleware_fn ]
async fn profiling < C : ' static + Context + Send > (
mut context : C ,
next : MiddlewareNext < C > ,
) -> MiddlewareResult < C > {
let start_time = Instant :: now ( ) ;
context = next ( context ) . await ? ;
let elapsed_time = start_time . elapsed ( ) ;
info ! ( "[{}μs] {}" , elapsed_time . as_micros ( ) , context . route ( ) ) ;
Ok ( context )
}예를 들어, 컨텍스트에 저장된보다 특정한 데이터를 허용하고 싶을 수도 있습니다. 예를 들어, 다른 중간 전쟁에서 나중에 사용하기 위해 쿼리 매개 변수를 해시 맵으로 수화 할 수 있기를 원할 것입니다. 이를 위해, 당신은 하류 하류가 준수 해야하는 맥락에 대한 추가 특성을 만들 수 있습니다. 제공된 query_params 미들웨어를 확인하십시오.
Thruster는 위의 하이퍼 스 니펫에서 어떤 종류의 서버 위에 라우팅 레이어를 제공 할 수 있습니다. 서버가 ThrusterServer 구현하는 한 이것은 모든 백엔드에 광범위하게 적용될 수 있습니다.
use async_trait :: async_trait ;
# [ async_trait ]
pub trait ThrusterServer {
type Context : Context + Send ;
type Response : Send ;
type Request : RequestWithParams + Send ;
fn new ( App < Self :: Request , Self :: Context > ) -> Self ;
async fn build ( self , host : & str , port : u16 ) ;
}다음이 필요합니다.
build 기능 내에서 서버 구현은 다음과 같습니다.
let matched = app.resolve_from_method_and_path(<some method>, <some path>); (이것은 실제 라우팅을 제공합니다.)app.resolve(<incoming request>, matched) 호출하십시오 (이로 인해 체인 미들웨어가 실행됩니다.) fn ip_guard ( head : & RequestHead ) -> bool {
// Check for the cloudflare IP header
let ip = if let Some ( val ) = head . headers ( ) . get ( CF_IP_HEADER ) {
val . to_str ( ) . unwrap_or ( "" ) . to_owned ( )
} else if let Some ( val ) = head . peer_addr {
val . to_string ( )
} else {
return false ;
} ;
"1.2.3.4" . contains ( & ip )
}
# [ actix_web :: post ( "/ping" ) ]
async fn ping ( ) -> Result < HttpResponse , UserPersonalError > {
Ok ( HttpResponse :: Ok ( ) . body ( "pong" ) )
}
.. .
web :: scope ( "/*" )
// This is confusing, but we catch all routes that _aren't_
// ip guarded and return an error.
. guard ( guard :: Not ( ip_guard ) )
. route ( "/*" , web :: to ( HttpResponse :: Forbidden ) ) ,
)
. service ( ping ) ;
.. .여기서 스러 스터입니다.
# [ middleware_fn ]
async fn ip_guard ( mut context : Ctx , next : MiddlewareNext < Ctx > ) -> MiddlewareResult < Ctx > {
if "1.2.3.4" . contains ( & context . headers ( ) . get ( "Auth-Token" ) . unwrap_or ( "" ) ) {
context = next ( context ) . await ? ;
Ok ( context )
} else {
Err ( Error :: unauthorized_error ( context ) )
}
}
# [ middleware_fn ]
async fn ping ( mut context : Ctx , _next : MiddlewareNext < Ctx > ) -> MiddlewareResult < Ctx > {
context . body ( "pong" ) ;
Ok ( context )
}
.. .
app . get ( "/ping" , m ! [ ip_guard , plaintext ] ) ;
.. .조금 더 직접적인 것은 좋습니다!
멀리 있다면 읽어 주셔서 감사합니다! 항상 자유롭게 연락하십시오.