Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

bug: error when using http_client #86

Open
dipankardas011 opened this issue Jun 6, 2023 · 7 comments
Open

bug: error when using http_client #86

dipankardas011 opened this issue Jun 6, 2023 · 7 comments

Comments

@dipankardas011
Copy link

dipankardas011 commented Jun 6, 2023

[package]
name = "http_server"
version = "0.1.0"
authors = ["csh"]
edition = "2018"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
httpcodec = "0.2.3"
bytecodec = "0.4.15"
http_req_wasi  = "0.10"
wasmedge_wasi_socket = "0.5.0"
wasmedge_http_req = "0.9.0"
use bytecodec::DecodeExt;
// use http_req::request;
use wasmedge_http_req::request;

use httpcodec::{HttpVersion, ReasonPhrase, Request, RequestDecoder, Response, StatusCode};
use std::{io::{Read, Write}, println};
use wasmedge_wasi_socket::{Shutdown, TcpListener, TcpStream};

const BOT_URL: &str= "https://dipankardas011-gpt2-bot.hf.space/generate";
const BOT_TEXT_FIELD: &str = "text";

fn handle_http(req: Request<String>) -> bytecodec::Result<Response<String>> {
    println!("Req.reqtarget -> {:?}",req.request_target());
    let request_path = req.request_target().to_string();
    let request_type = req.method().to_string();

    return match (request_type.as_str(), request_path.as_str()) {
        ("GET", "/ping") => {

            println!("request target [{request_path}] method [{request_type}]");
            Ok(Response::new(
                HttpVersion::V1_1,
                StatusCode::new(200)?,
                ReasonPhrase::new("")?,
                format!("Pong!!")))
        }
        ("POST", "/bot") => {

            println!("request target [{request_path}] method [{request_type}]");
            let mod_req: String = req.body().replace(" ", "%20");
            println!("Data in body: {mod_req}");

            

            if mod_req.len() as i32 == 0 {
                Ok(Response::new(
                    HttpVersion::V1_1,
                    StatusCode::new(401)?,
                    ReasonPhrase::new("")?,
                    format!("Invalid request no promppt found!")))
            }else {

                let bot_uri = format!("{BOT_URL}?{BOT_TEXT_FIELD}={mod_req}");
                
                let mut writer = Vec::new(); //container for body of a response
                let res = request::get(bot_uri, &mut writer).unwrap();
                println!("GET");
                println!("Status: {} {}", res.status_code(), res.reason());
                println!("Headers {}", res.headers());
                let bot_response = String::from_utf8_lossy(&writer);



                Ok(Response::new(
                    HttpVersion::V1_1,
                    StatusCode::new(200)?,
                    ReasonPhrase::new("")?,
                    format!("Generated Response {bot_response}")))
            }
        }
        _ => {
            println!("request target [{request_path}] method [{request_type}]");
            Ok(Response::new(
                HttpVersion::V1_1,
                StatusCode::new(403)?,
                ReasonPhrase::new("")?,
                format!("Route path or method is invalid!")))
        }
    };
}

fn handle_client(mut stream: TcpStream) -> std::io::Result<()> {
    let mut buff = [0u8; 1024];
    let mut data = Vec::new();

    loop {
        let n = stream.read(&mut buff)?;
        data.extend_from_slice(&buff[0..n]);
        if n < 1024 {
            break;
        }
    }

    let mut decoder =
        RequestDecoder::<httpcodec::BodyDecoder<bytecodec::bytes::Utf8Decoder>>::default();

    let req = match decoder.decode_from_bytes(data.as_slice()) {
        Ok(req) => handle_http(req),
        Err(e) => Err(e),
    };

    let r = match req {
        Ok(r) => r,
        Err(e) => {
            let err = format!("{:?}", e);
            Response::new(
                HttpVersion::V1_0,
                StatusCode::new(500).unwrap(),
                ReasonPhrase::new(err.as_str()).unwrap(),
                err.clone(),
            )
        }
    };

    let write_buf = r.to_string();
    stream.write(write_buf.as_bytes())?;
    stream.shutdown(Shutdown::Both)?;
    Ok(())
}

fn main() -> std::io::Result<()> {
    let port = std::env::var("PORT").unwrap_or("3000".to_string());
    println!("new connection at {}", port);
    let listener = TcpListener::bind(format!("0.0.0.0:{}", port), false)?;
    loop {
        let _ = handle_client(listener.accept(false)?.0);
    }
}

image

@juntao
Copy link
Member

juntao commented Jun 7, 2023

It sounds like you want to make https calls from your app. It is beyond the scope of "sockets".

You will need to the OpenSSL library and the TLS plugin in WasmEdge.

https://wasmedge.org/docs/develop/rust/http_service/client/#synchronous-client-with-http_req

https://wasmedge.org/docs/develop/build-and-run/install#tls-plugin

@dipankardas011
Copy link
Author

It sounds like you want to make https calls from your app. It is beyond the scope of "sockets".

You will need to the OpenSSL library and the TLS plugin in WasmEdge.

https://wasmedge.org/docs/develop/rust/http_service/client/#synchronous-client-with-http_req

https://wasmedge.org/docs/develop/build-and-run/install#tls-plugin

Got it

@dipankardas011
Copy link
Author

dipankardas011 commented Jun 8, 2023

@juntao can I add missing information in the docs website?

@juntao
Copy link
Member

juntao commented Jun 8, 2023

Sure. Raise a PR here?

https://github.com/WasmEdge/docs/tree/main/docs/develop/rust

Thanks

@dipankardas011
Copy link
Author

Sure. Raise a PR here?

https://github.com/WasmEdge/docs/tree/main/docs/develop/rust

Thanks

creating pr on this https://wasmedge.org/book/en/write_wasm/rust/networking.html
will it be correct?

@alabulei1
Copy link
Member

alabulei1 commented Jun 8, 2023

@dipankardas011

https://github.com/WasmEdge/docs/tree/main/docs/develop/rust is our new docs. We're working on discarding the old book. See the ongoing PR here. WasmEdge/WasmEdge#2541

@dipankardas011
Copy link
Author

@dipankardas011

https://github.com/WasmEdge/docs/tree/main/docs/develop/rust is our new docs. We're working on discarding the old book. See the ongoing PR here. WasmEdge/WasmEdge#2541

Then what to do?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants