Skip to content

Instantly share code, notes, and snippets.

@mayankchoubey
Created July 11, 2021 05:32
Show Gist options
  • Save mayankchoubey/ca3b641df50e3b53b5111fb050d7ca12 to your computer and use it in GitHub Desktop.
Save mayankchoubey/ca3b641df50e3b53b5111fb050d7ca12 to your computer and use it in GitHub Desktop.
Deno native HTTP v/s Go native HTTP
const listener = Deno.listen({ port: 3000 });
for await(const conn of listener)
handleNewConnection(conn);
async function handleNewConnection(conn: Deno.Conn) {
for await(const { request, respondWith } of Deno.serveHttp(conn)) {
const reqBody=await request.json();
if(reqBody) {
respondWith(new Response(JSON.stringify({ name: reqBody.name }), {
headers: { 'content-type': 'application/json'}
}));
} else
respondWith(new Response(undefined, {status: 400}));
}
}
package main
import (
"encoding/json"
"net/http"
)
type ReqBody struct {
Name string `json:"name"`
}
func main() {
http.HandleFunc("/", HelloServer)
http.ListenAndServe(":3000", nil)
}
func HelloServer(w http.ResponseWriter, r *http.Request) {
var reqBody ReqBody
json.NewDecoder(r.Body).Decode(&reqBody)
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(reqBody)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment