This code snippet is part of my local repository for demo and simple applications. I wanted to see a difference between Go and Rust code for the given task.
There are many ways to implement a simple HTTP Get in each language. Since I already have Golang experience, the code in Go took me a few minutes.
My initial goal for the Rust code was to write an HTTP Get using only the standard library. But surprisingly, the Rust code took me at least one hour, where at the end, I just took the code from the reqwest
package and just simplified it for the text response.
Go implementation
package main
import (
"io/ioutil"
"log"
"net/http"
)
func main() {
log.Println("mycurl")
url := "https://kenanbek.github.io/"
resp, err := http.Get(url)
if err != nil {
log.Fatalf("Error fetching url %s: %v", url, err)
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
log.Fatalf("Error fetching url %s: %v", url, err)
}
log.Println("Response: ")
log.Println(string(body))
}
Rust implementation
For the Rust implementation, I am going to use reqwest
package. That’s why we need to initialize a project environment using the following commands:
cargo init
Then edit content of the Cargo.toml
and add reqwest
dependency:
[dependencies]
reqwest = { version = "0.11", features = ["blocking", "json"] }
I will use blocking call api.
Here is the actual Rust code for fetching webpage's content via HTTP GET request:
fn main() -> Result<(), Box<dyn std::error::Error>> {
let resp = reqwest::blocking::get("https://kenanbek.github.io/")?
.text()?;
println!("{:#?}", resp);
Ok(())
}
If you are also a newbie in Rust as myself, you can run this code by executing the following command:
cargo run
Top comments (4)
Really educational about updates about investment planning and the experts are having pretty wise suggestions for the public. I need to do my assignment and would like to avail here trusted material. Please keep going to share such updated material on your blog.
One of the most important items for nurses to carry is a stethoscope. Stethoscopes are used to listen to a patient’s heart, lungs, and other body sounds. They’re also essential for assessing a patient’s blood pressure and other vital signs. A good quality one should have a comfortable earpiece and a clear sound. Tom Parling
Thanks for these article, as a Golang Developer why you decide to learn Rust?
Will Rust be a technology in demand?
Glad that you liked it.
I always wanted to know more about system programming and tried to keep myself updated on C and C++. But Rust is something new (relatively) in the field and introduces improvements. So I thought it would be nice to have a look.
About demand, I believe it already has specific use cases. Also, the community around it is quite active, so I think yes it will be needed (if it is not already).