[][src]Attribute Macro fastly_macros::main

#[main]

Main function attribute for a Compute@Edge program.

Usage

This attribute should be applied to a main function that takes a request and returns a response or an error. For example:

use fastly::{Body, Error, Request, Response, RequestExt, ResponseExt};

#[fastly::main]
fn main(ds_req: Request<Body>) -> Result<impl ResponseExt, Error> {
    ds_req.send("example_backend")
}

You can apply #[fastly::main] to any function that takes Request<Body> as its sole argument, and returns a Result<impl ResponseExt, Error>. The impl ResponseExt syntax means that the function must return a type that implements the fastly::ResponseExt trait, such as Response<Body> or Response<String>.

More Information

This is a convenience to abstract over the common usage of fastly::downstream_request and RequestExt::send_downstream at the beginning and end of a program's main function.

With this macro applied we can write a function that accepts a downstream request as an argument and returns a downstream response, rather than calling fastly::downstream_request ourselves. This is equivalent to the following code:

use fastly::{downstream_request, Error, RequestExt, ResponseExt};

fn main() -> Result<(), Error> {
    let ds_req = downstream_request()?;
    let ds_resp = ds_req.send("example_backend")?;
    ds_resp.send_downstream()?;
    Ok(())
}

Troubleshooting

As described above, [fastly::main] expects a function with a specific signature. While this macro will attempt to provide helpful errors, procedural macros cannot typecheck your code. As a result, you may see "backwards" errors if your argument types are incorrect, like this:

error[E0308]: mismatched types
 --> main.rs:8:1
  |
8 | fn main(downstream_request: Request<u32>) -> Result<impl ResponseExt, Error> {
  | ^^ expected u32, found struct `fastly::body::Body`
  |
  = note: expected type `http::request::Request<u32>`
             found type `http::request::Request<fastly::body::Body>`

In this case, be sure that you should update the signature of your main function, being sure to use the correct Request<Body> type for your function argument.