Last active
October 21, 2018 07:56
-
-
Save anru/e5d60c823ebab775508a029b48a1c7ca to your computer and use it in GitHub Desktop.
http-ehlo
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"net/http" | |
"regexp" | |
) | |
func main() { | |
reg := regexp.MustCompile("^/greeting/([a-z]+)$") | |
http.ListenAndServe(":8080", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { | |
switch r.URL.Path { | |
case "/": | |
fmt.Fprint(w, "Hello World!") | |
default: | |
fmt.Fprintf(w, "Hello, %s", reg.FindStringSubmatch(r.URL.Path)[1]) | |
} | |
})) | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
extern crate hyper; | |
extern crate regex; | |
use std::io::Write; | |
use regex::{Regex, Captures}; | |
use hyper::Server; | |
use hyper::server::{Request, Response}; | |
use hyper::net::Fresh; | |
use hyper::uri::RequestUri::{AbsolutePath}; | |
fn handler(req: Request, res: Response<Fresh>) { | |
let greeting_re = Regex::new(r"^/greeting/([a-z]+)$").unwrap(); | |
match req.uri { | |
AbsolutePath(ref path) => match (&req.method, &path[..]) { | |
(&hyper::Get, "/") => { | |
hello(&req, res); | |
}, | |
_ => { | |
greet(&req, res, greeting_re.captures(path).unwrap()); | |
} | |
}, | |
_ => { | |
not_found(&req, res); | |
} | |
}; | |
} | |
fn hello(_: &Request, res: Response<Fresh>) { | |
let mut r = res.start().unwrap(); | |
r.write_all(b"Hello World!").unwrap(); | |
r.end().unwrap(); | |
} | |
fn greet(_: &Request, res: Response<Fresh>, cap: Captures) { | |
let mut r = res.start().unwrap(); | |
r.write_all(format!("Hello, {}", cap.at(1).unwrap()).as_bytes()).unwrap(); | |
r.end().unwrap(); | |
} | |
fn not_found(_: &Request, mut res: Response<Fresh>) { | |
*res.status_mut() = hyper::NotFound; | |
let mut r = res.start().unwrap(); | |
r.write_all(b"Not Found\n").unwrap(); | |
} | |
fn main() { | |
let _ = Server::http("127.0.0.1:8080").unwrap().handle(handler); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment