0

I'm a college student, currently trying to rewrite a toy Django website using Actix-web, and I'm facing problems.

The original Python code looks like this(irrelevant parts removed). It receives a request as the parameter, extract the 'title' and 'content' field, and get the user name from cookies.

def message(request):
    def gen_response(code: int, data: str):
        return JsonResponse({
            'code': code,
            'data': data
        }, status=code)
    if request.method == 'POST':
        name = request.COOKIES['user'] if 'user' in request.COOKIES else 'Unknown'
        user = User.objects.filter(name=name).first()
        try:
            request_body = json.loads(request.body)
        except JSONDecodeError as e:
            return gen_response(400, "Json Parse Error: {}".format(e))
        return gen_response(201, "message was sent successfully")
    else:
        return gen_response(405, 'method {} not allowed'.format(request.method))

Now I want my Rust code to run just like that. If I use web:Json<PostData> as the parameter, I don't know how to read the cookies. And if I use the raw HttpRequest, I can't see how I should extract the request body

1 Answers1

0

HttpRequest have a method called cookie.And Cookie exist in HttpHeader.So you can use headers() get cookie.


/// cookie = "0.14"

use cookie::Cookie;

#[post("/cookie")]
async fn test_cookie(post: Json<HashMap<String, String>>, request: HttpRequest) -> HttpResponse {

    let x:Cookie = request.cookie("prov").unwrap();
    println!("{:?}", x.value());

    let head = request.headers().get("cookie").unwrap();
    println!("{}", head.to_str().unwrap());

    HttpResponse::Ok().body("")
}

will
  • 111
  • 1
  • 5