Created
February 24, 2021 09:23
-
-
Save 2hamed/b87b8ba83f9e70e952d19bd4e2839bcf to your computer and use it in GitHub Desktop.
http server/client to showcase timeout
This file contains hidden or 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" | |
"io/ioutil" | |
"net/http" | |
"time" | |
) | |
type rt struct { | |
roundTripper func(req *http.Request) (*http.Response, error) | |
} | |
func (r rt) RoundTrip(req *http.Request) (*http.Response, error) { | |
return r.roundTripper(req) | |
} | |
func main() { | |
c := http.Client{ | |
Timeout: 3 * time.Second, | |
Transport: rt{RoundTripper(http.DefaultTransport)}, | |
} | |
resp, err := c.Get("http://127.0.0.1:9000") | |
if err != nil { | |
fmt.Println("err:", err) | |
} else { | |
body, err := ioutil.ReadAll(resp.Body) | |
resp.Body.Close() | |
fmt.Println(string(body), err) | |
} | |
} | |
func RoundTripper(next http.RoundTripper) func(req *http.Request) (*http.Response, error) { | |
return func(req *http.Request) (*http.Response, error) { | |
resp, err := next.RoundTrip(req) | |
if err != nil { | |
return nil, fmt.Errorf("err: %w", err) | |
} | |
return resp, nil | |
} | |
} |
This file contains hidden or 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" | |
"net/http" | |
"time" | |
) | |
func main() { | |
router := http.NewServeMux() | |
router.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { | |
fmt.Println("HTTP Request received!") | |
time.Sleep(10 * time.Second) | |
fmt.Println("HTTP response sent!") | |
w.WriteHeader(200) | |
w.Write([]byte("OK")) | |
}) | |
server := http.Server{ | |
Handler: router, | |
} | |
l, err := net.Listen("tcp", ":9000") | |
if err != nil { | |
panic(err) | |
} | |
if err := server.Serve(l); err != nil { | |
panic(err) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment