View : 0

12/04/2026 18:17pm

JS2GO EP.30 Handling HTTP Requests and Responses: JavaScript (Fetch/Express) vs Go (net/http)

JS2GO EP.30 Handling HTTP Requests and Responses: JavaScript (Fetch/Express) vs Go (net/http)

#HTTP Requests

#HTTP Responses

#JavaScript Fetch

#Go net/http

#Golang

#JavaScript

HTTP is a core protocol for communication between clients and servers, essential for building APIs and web applications. In this article, we compare handling HTTP requests and responses in JavaScript (Node.js + Fetch/Express) and Go (net/http), with clear examples and best practices for production-ready applications.

 

1. HTTP Requests in JavaScript

 

Client-side: Fetch API

// GET request
fetch('https://jsonplaceholder.typicode.com/posts/1')
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(err => console.error('Error:', err));

// POST request
fetch('https://jsonplaceholder.typicode.com/posts', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({ title: 'Hello', body: 'World' })
})
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(err => console.error('Error:', err));

 

Advantages:
✔️ Concise syntax, compatible with async/await
✔️ Built-in JSON support, flexible headers and HTTP methods

 

Server-side: Express

const express = require('express');
const app = express();
app.use(express.json());

app.get('/api/posts/:id', (req, res) => {
  res.json({ id: req.params.id, title: 'Hello', body: 'World' });
});

app.post('/api/posts', (req, res) => {
  const { title, body } = req.body;
  res.status(201).json({ id: 1, title, body });
});

app.listen(3000, () => console.log('Server running on port 3000'));

 

Advantages:
✔️ Easy routing and middleware
✔️ Automatic JSON parsing, supports authentication, logging

 

2. HTTP Requests in Go

 

Client-side: HTTP GET / POST

package main

import (
    "bytes"
    "encoding/json"
    "fmt"
    "io/ioutil"
    "net/http"
)

func main() {
    // GET request
    resp, err := http.Get("https://jsonplaceholder.typicode.com/posts/1")
    if err != nil {
        fmt.Println("Error:", err)
        return
    }
    defer resp.Body.Close()
    body, _ := ioutil.ReadAll(resp.Body)
    fmt.Println(string(body))

    // POST request
    data := map[string]string{"title": "Hello", "body": "World"}
    jsonData, _ := json.Marshal(data)
    resp, err = http.Post("https://jsonplaceholder.typicode.com/posts", "application/json", bytes.NewBuffer(jsonData))
    if err != nil {
        fmt.Println("Error:", err)
        return
    }
    defer resp.Body.Close()
    body, _ = ioutil.ReadAll(resp.Body)
    fmt.Println(string(body))
}

 

Server-side: net/http

package main

import (
    "encoding/json"
    "fmt"
    "net/http"
)

type Post struct {
    ID    int    `json:"id"`
    Title string `json:"title"`
    Body  string `json:"body"`
}

func getPostHandler(w http.ResponseWriter, r *http.Request) {
    post := Post{ID: 1, Title: "Hello", Body: "World"}
    w.Header().Set("Content-Type", "application/json")
    json.NewEncoder(w).Encode(post)
}

func postPostHandler(w http.ResponseWriter, r *http.Request) {
    var post Post
    json.NewDecoder(r.Body).Decode(&post)
    post.ID = 1
    w.Header().Set("Content-Type", "application/json")
    w.WriteHeader(http.StatusCreated)
    json.NewEncoder(w).Encode(post)
}

func main() {
    http.HandleFunc("/api/posts", postPostHandler)
    http.HandleFunc("/api/posts/1", getPostHandler)
    fmt.Println("Server running on port 3000")
    http.ListenAndServe(":3000", nil)
}

 

Advantages:
✔️ Type-safe, compile-time checking
✔️ Efficient and lightweight
✔️ Built-in JSON support and HTTP server

 

3. Best Practices

 

✔️ Use JSON as the standard data format
✔️ Always check errors and HTTP response status
✔️ Manage headers properly (Content-Type, Authorization)
✔️ Use async/await in JS or Goroutines in Go for concurrent requests
✔️ Separate client and server logic clearly

 

4. Comparison: JavaScript vs Go HTTP

 

FeatureJavaScript (Fetch/Express)Go (net/http)
Clientfetch / axioshttp.Get / http.Post
ServerExpressnet/http
JSONAuto parsing / stringifyjson.Marshal / json.Unmarshal
Concurrencyasync/await / PromisesGoroutines
Type SafetyDynamicStatic
MiddlewareExpress supports middlewarenet/http handlers, optional middleware

 

Recommendations:
✔️ Frontend & lightweight APIs → JavaScript Fetch + Express
✔️ High-performance backend / type-safe APIs → Go net/http

 


 

Next Episode

 

In EP.31 of the JS2GO series, we will explore Queues and Stacks in JavaScript and Go to understand linear data structures and how to use them efficiently in real-world applications.

 

Read more

🔵 Facebook: Superdev Academy

🔴 YouTube: Superdev Academy

📸 Instagram: Superdev Academy

🎬 TikTok: https://www.tiktok.com/@superdevacademy?lang=th-TH

🌐 Website: https://www.superdevacademy.com/en