Skip to content

Instantly share code, notes, and snippets.

@ka2n
Created March 9, 2023 20:50
Show Gist options
  • Save ka2n/61b3f706d0e254b5056535708e40c491 to your computer and use it in GitHub Desktop.
Save ka2n/61b3f706d0e254b5056535708e40c491 to your computer and use it in GitHub Desktop.
echo server
package main
import (
"fmt"
"log"
"net/http"
"os"
)
func main() {
port := os.Getenv("PORT")
if port == "" {
port = "8080"
}
if err := http.ListenAndServe(":" + port, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, "OK")
})); err != nil {
log.Fatal(err)
}
}
use std::net::{TcpStream, TcpListener};
use std::io::{Write};
use std::thread;
use std::env;
fn handle_write(mut stream: TcpStream) {
let response = b"HTTP/1.1 200 OK\r\nContent-Type: text/html; charset=UTF-8\r\n\r\n<html><body>Hello world</body></html>\r\n";
match stream.write(response) {
Ok(_) => println!("Response sent"),
Err(e) => println!("Failed sending response: {}", e),
}
}
fn handle_client(stream: TcpStream) {
handle_write(stream);
}
fn main() {
let port = env::var("PORT").unwrap_or_else(|_| "8080".to_string());
let listener = TcpListener::bind(format!("127.0.0.1:{}", port)).unwrap();
println!("Listening for connections on port {}", port);
for stream in listener.incoming() {
match stream {
Ok(stream) => {
thread::spawn(|| {
handle_client(stream)
});
}
Err(e) => {
println!("Unable to connect: {}", e);
}
}
}
}
const std = @import("std");
const net = std.net;
const mem = std.mem;
const fs = std.fs;
const io = std.io;
pub fn main() anyerror!void {
var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
defer arena.deinit();
const env_map = try arena.allocator().create(std.process.EnvMap);
env_map.* = try std.process.getEnvMap(arena.allocator());
defer env_map.deinit(); // technically unnecessary when using ArenaAllocator
const port = try std.fmt.parseInt(u16, env_map.get("PORT") orelse "8080", 10);
const addr = try net.Address.resolveIp("0.0.0.0", port);
try server(addr);
}
pub fn server(addr: net.Address) anyerror!void {
var s = net.StreamServer.init(.{});
defer s.deinit();
std.debug.print("Listening on {s}\n", .{addr});
try s.listen(addr);
defer s.close();
while (s.accept()) |conn| {
try handleConn(conn);
} else |err| {
return err;
}
}
pub fn handleConn(conn: net.StreamServer.Connection) anyerror!void {
const s = &conn.stream;
defer s.close();
_ = try s.write("HTTP/1.1 200 OK\r\nContent-Type: text/html; charset=UTF-8\r\n\r\n<html><body>Hello world</body></html>\r\n");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment