Skip to content

Instantly share code, notes, and snippets.

@unixsurfer
Created September 23, 2023 11:36
Show Gist options
  • Save unixsurfer/34a14c5241c4fb6b09f56aa27c4d4483 to your computer and use it in GitHub Desktop.
Save unixsurfer/34a14c5241c4fb6b09f56aa27c4d4483 to your computer and use it in GitHub Desktop.
//
// main.go
// Copyright (C) 2023 pavlos <pavlos.parissis@gmail.com>
//
// Distributed under terms of the MIT license.
//
package main
import (
"bytes"
"context"
"errors"
"fmt"
"io/ioutil"
"net"
"net/http"
"os"
"strings"
"time"
)
const serverPort = 5555
func main() {
go func() {
mux := http.NewServeMux()
mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
fmt.Printf("server: %s /\n", r.Method)
fmt.Printf("server: query id: %s\n", r.URL.Query().Get("id"))
fmt.Printf("server: content-type: %s\n", r.Header.Get("content-type"))
fmt.Printf("server: remote add: %s\n", r.RemoteAddr)
fmt.Printf("server: headers:\n")
for headerName, headerValue := range r.Header {
fmt.Printf("\t%s = %s\n", headerName, strings.Join(headerValue, ", "))
}
reqBody, err := ioutil.ReadAll(r.Body)
if err != nil {
fmt.Printf("server: could not read request %s\n", err)
}
fmt.Printf("server: request body: %s\n", reqBody)
fmt.Fprintf(w, `{"message": "hello!"}`)
})
server := http.Server{
Addr: fmt.Sprintf(":%d", serverPort),
Handler: mux,
}
server.SetKeepAlivesEnabled(true)
if err := server.ListenAndServe(); err != nil {
if !errors.Is(err, http.ErrServerClosed) {
fmt.Printf("error running http server: %s\n", err)
}
}
}()
time.Sleep(100 * time.Millisecond)
jsonBody := []byte(`{"client_message": "hello server!"}`)
bodyReader := bytes.NewReader(jsonBody)
requestURL := fmt.Sprintf("http://localhost:%d?id=1234", serverPort)
for i := 0; i < 1; i++ {
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()
req, err := http.NewRequestWithContext(ctx, http.MethodPost, requestURL, bodyReader)
if err != nil {
fmt.Printf("client: could not create request: %s\n", err)
os.Exit(1)
}
req.Header.Set("Content-Type", "application/json")
t := http.DefaultTransport.(*http.Transport).Clone()
t.MaxIdleConns = 100
t.MaxConnsPerHost = 100
t.MaxIdleConnsPerHost = 100
client := http.Client{
Timeout: 30 * time.Second,
Transport: t,
}
res, err := client.Do(req)
if err != nil {
fmt.Printf("error making the request %s\n", err)
os.Exit(1)
}
fmt.Printf("client: got response!\n")
fmt.Printf("client: status code : %d\n", res.StatusCode)
addr := req.Context().Value(http.LocalAddrContextKey).(net.Addr)
fmt.Printf("client: ip %s\n", addr.String())
resBody, err := ioutil.ReadAll(res.Body)
if err != nil {
fmt.Printf("client: could not read response body: %s\n", err)
os.Exit(1)
}
fmt.Printf("client: response body: %s\n", resBody)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment