Blogs tagged #learn

Creating a basic HTTP server with Go

Go (or Golang) is a powerful and efficient programming language that excels in building scalable and concurrent applications. In this occasion, we'll walk through the process of creating a simple HTTP server using Go. By the end of this guide, you'll have a basic understanding of how to handle HTTP requests and responses. Today, I'm going to share what I've learnt so far about building an HTTP server wiht Go. ## Prerequisites Before we begin, make sure you have Go installed on your machine. You can download it from the official [Go website](https://go.dev/doc/install). ## Project Setup ```bash mkdir go-http-server cd go-http-server ``` Now, create a file named main.go for our Go code. ```go // main.go package main import ( "fmt" "net/http" ) func main() { // Your HTTP server code will go here } ``` ## Handling an HTTP Request To handle HTTP requests, we'll use the `http `package provided by Go. Let's create a simple HTTP handler function that responds to incoming requests. ```go import ( "errors" "fmt" "io" "net/http" "os" ) func get(w http.ResponseWriter, r *http.Request) { fmt.Printf("Responding to GET / /\n") io.WriteString(w, "Hello World!\n") } ``` Now, let's register this handler function in our HTTP server ```go func main() { http.HandleFunc("/", get) err := http.ListenAndServe(":8080", nil) if errors.Is(err, http.ErrServerClosed) { fmt.Printf("Server closed\n") } else if err != nil { fmt.Printf("Error starting server: %s\n", err) os.Exit(1) } } ``` ## Run Your HTTP Server Save the changes applied to main.go, and you can now run your HTTP server. ```bash go run main.go ``` Visit http://localhost:8080 in your web browser, and you should see the message "Hello World!". You can also use the curl command in cmd and you'll also get the same response ```bash curl http://localhost:8080/ ``` And that's it! You have your first HTTP server built with Go. You can expand it a bit further by using `mux` to multiplex a server and http.Handler implementation by `net/http` package, which you can use for a case like this. ```go package main import ( "encoding/json" "errors" "fmt" "math/rand" "net/http" "os" ) type User struct { ID string `json:"id"` Name string `json:"name"` } var users map[string]User var letterRunes = []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ") func generateId(n int) string { b := make([]rune, n) for i := range b { b[i] = letterRunes[rand.Intn(len(letterRunes))] } return string(b) } func getUsers(w http.ResponseWriter, r *http.Request) { fmt.Printf("Responding to GET /\n") usersList := make([]User, 0, len(users)) for _, user := range users { usersList = append(usersList, user) } res, err := json.Marshal(usersList) if err != nil { http.Error(w, "Internal Server Error", http.StatusInternalServerError) return } w.Header().Set("Content-Type", "application/json") w.WriteHeader(http.StatusOK) w.Write(res) } func createUser(w http.ResponseWriter, r *http.Request) { fmt.Printf("Responding to POST /") var newUser User decoder := json.NewDecoder(r.Body) err := decoder.Decode(&newUser) if err != nil { http.Error(w, "Bad Request", http.StatusBadRequest) return } newUser.ID = generateId(12) users[newUser.ID] = newUser res, err := json.Marshal(newUser) if err != nil { http.Error(w, "Internal Server Error", http.StatusInternalServerError) return } w.Header().Set("Content-Type", "application/json") w.WriteHeader(http.StatusOK) w.Write(res) } func main() { users = make(map[string]User) mux := http.NewServeMux() mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { switch r.Method { case http.MethodGet: getUsers(w, r) case http.MethodPost: createUser(w, r) } }) err := http.ListenAndServe(":8080", mux) if errors.Is(err, http.ErrServerClosed) { fmt.Printf("Server closed") } else if err != nil { fmt.Printf("Error starting server: %s\n", err) os.Exit(1) } } ```

Trithemius Cipher in Rust

Hey fellas! Ever heard of "Trithemius Cipher"? You might be wandering, what the heck is a trithemius? Well actually, Trithemius or known as Johannes Trithemius is a german polymath that created this cipher. The Trithemius Cipher is one of the polyalphabetic codes designed to be easier to use. Today, let's embark on a thrilling journey into the world of cryptography with Rust. Our destination? The Trithemius Cipher – a historic encryption technique that adds a dash of mystery to our codes. Our weapon of choice for this cryptographic escapade is Rust, a language known for its speed, safety, and expressiveness. Our code is a humble blend of I/O operations, string manipulation, and a pinch of modular arithmetic. First, you have to install [Rust](https://rust-lang.org/), Then, you create a new project with the cargo in whatever folder you desire. ```bash cargo new trithemius_cipher ``` Now that's done, you can copy (or type if you're not lazy enough) the code below: ```rust use std::io; fn trithemius_cipher(message: &str, shift: u8) -> String { let message_chars: Vec<char> = message.chars().collect(); let mut result: String = String::new(); for &c in message_chars.iter() { if c.is_alphabetic() { let base: u8 = if c.is_lowercase() { 'a' as u8 } else { 'A' as u8 }; let encrypted_char: char = ((((c as u8 - base) + shift) % 26) + base) as char; result.push(encrypted_char); } else { result.push(c); } } result } ``` Wowowowow, wait a second, what the heck was that just now? The Trithemius Cipher is a polyalphabetic substitution cipher, a mouthful that basically means each letter can be replaced by multiple different letters (it is as simple as that). In our Rust code, this is achieved through a clever combination of modular arithmetic and character manipulation. ```rust let base: u8 = if c.is_lowercase() { 'a' as u8 } else { 'A' as u8 }; let encrypted_char: char = ((((c as u8 - base) + shift) % 26) + base) as char; ``` Breaking it down, each alphabetic character takes a journey from its original position in the alphabet to a new destination based on the user-provided shift value. The modular arithmetic ensures that the journey wraps around the alphabet seamlessly. "But why Rust?" you may ask. Rust, with its emphasis on performance, memory safety, and zero-cost abstractions, proves to be an ideal companion in this case. The code gracefully handles user inputs, ensuring a smooth interaction with the cipher. Now to run the code, you'll have to do a bit of command-line interaction. Run this command in the root directory where the `Cargo.toml` are placed at ```bash cargo build ``` Now you just have to run the .exe file in the debug folder at the target folder ```bash .\target\debug\trithemius_cipher ``` That's it! Now you can encrypt a message with the Trithemius Cipher method. But hold on, how do you decrypt one? You just have to reverse the method. ```rust fn trithemius_decipher(message: &str, shift: u8) -> String { let message_chars: Vec<char> = message.chars().collect(); let mut result: String = String::new(); for &c in message_chars.iter() { if c.is_alphabetic() { let base: u8 = if c.is_lowercase() { 'a' as u8 } else { 'A' as u8 }; let decrypted_char: char = ((((c as u8 - base) + 26 - shift) % 26) + base) as char; result.push(decrypted_char); } else { result.push(c); } } result } ``` That's it! We're done, now you can use these methods on your code. Like for example here if you want to decrypt a greeting message to your friend (not sure why'd you do that tho), you can just make a main function and use the methods above: ```rust fn main() { let encrypted_message: String = trithemius_cipher("What's good buddy?", 3); println!("Encrypted message: {}", encrypted_message); } ```