Skip to content

Instantly share code, notes, and snippets.

@ydm
Last active June 14, 2024 19:47
Show Gist options
  • Save ydm/cb564a38e2590788137a4d24ce118f65 to your computer and use it in GitHub Desktop.
Save ydm/cb564a38e2590788137a4d24ce118f65 to your computer and use it in GitHub Desktop.
package main
import (
"context"
"errors"
"fmt"
"io"
"net/http"
"time"
)
var errHTTPErrorResponse = errors.New("HTTP error response")
func httpClientDisallowRedirects(_ *http.Request, _ []*http.Request) error {
return http.ErrUseLastResponse
}
func makeClient() http.Client {
return http.Client{
Timeout: time.Second,
CheckRedirect: httpClientDisallowRedirects,
}
}
func main() {
client := makeClient()
// client := http.DefaultClient
ctx := context.Background()
// ctx = context.WithTimeout(ctx, time.Second)
req, err := http.NewRequestWithContext(ctx, "GET", "http://127.0.0.1:8080/", nil)
if err != nil {
panic(err)
}
resp, err := client.Do(req)
fmt.Println("RESPONSE ERROR:", err)
fmt.Println("CONTEXT ERROR:", ctx.Err())
if resp != nil {
fmt.Println("RESPONSE:", resp.Status)
if resp.StatusCode < 400 {
bodyBytes, err := io.ReadAll(resp.Body)
if err != nil {
panic(fmt.Errorf("could not read error response body for status code %d: %w", resp.StatusCode, err))
}
fmt.Println(string(bodyBytes))
} else {
panic(fmt.Errorf("%w: %d", errHTTPErrorResponse, resp.StatusCode))
}
}
}
#!/usr/bin/env python
import time
from http.server import BaseHTTPRequestHandler, HTTPServer
class SimpleDelayedHTTPRequestHandler(BaseHTTPRequestHandler):
def do_GET(self):
time.sleep(1.2)
self.send_response(200)
self.send_header('Content-type', 'text/html')
self.end_headers()
response_message = "<html><body><h1>Hello, World!</h1></body></html>"
self.wfile.write(response_message.encode('utf-8'))
def run(server_class=HTTPServer, handler_class=SimpleDelayedHTTPRequestHandler, port=8080):
server_address = ('', port)
httpd = server_class(server_address, handler_class)
print(f'Starting http server on port {port}...')
httpd.serve_forever()
if __name__ == '__main__':
run()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment