Skip to content

Commit

Permalink
Simplify example further
Browse files Browse the repository at this point in the history
  • Loading branch information
felixge committed Jun 24, 2020
1 parent 09ccaa8 commit a660750
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 12 deletions.
14 changes: 11 additions & 3 deletions example/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import (
"fmt"
"log"
"net/http"
"os"
"time"

_ "net/http/pprof"
Expand All @@ -18,12 +17,22 @@ const (
networkTime = 60 * time.Millisecond
)

// sleepURL is the url for the sleep server used by slowNetworkRequest. It's
// a global variable to keep the cute simplicitly of main's loop.
var sleepURL string

func main() {
// Run http endpoints for both pprof and gprof.
http.DefaultServeMux.Handle("/debug/gprof", gprof.Handler())
go func() {
log.Println(http.ListenAndServe("localhost:6060", nil))
}()

// Start a sleep server to help with simulating slow network requests.
var stop func()
sleepURL, stop = StartSleepServer()
defer stop()

for {
// Http request to a web service that might be slow.
slowNetworkRequest()
Expand All @@ -35,8 +44,7 @@ func main() {
}

func slowNetworkRequest() {
addr := os.Getenv("SLEEPD_ADDR")
res, err := http.Get("http://" + addr + "/?sleep=" + networkTime.String())
res, err := http.Get(sleepURL + "/?sleep=" + networkTime.String())
if err != nil {
panic(err)
}
Expand Down
16 changes: 7 additions & 9 deletions example/sleepd/main.go → example/sleep_server.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,19 +2,17 @@ package main

import (
"fmt"
"log"
"net/http"
"os"
"net/http/httptest"
"time"
)

func main() {
h := http.HandlerFunc(sleepHandler)
addr := os.Getenv("SLEEPD_ADDR")
if addr == "" {
addr = "localhost:6061"
}
log.Println(http.ListenAndServe(addr, h))
// StartSleepServer starts a server that supports a ?sleep parameter to
// simulate slow http responses. It returns the url of that server and a
// function to stop it.
func StartSleepServer() (url string, stop func()) {
server := httptest.NewServer(http.HandlerFunc(sleepHandler))
return server.URL, server.Close
}

func sleepHandler(w http.ResponseWriter, r *http.Request) {
Expand Down

0 comments on commit a660750

Please sign in to comment.