Skip to content

Commit

Permalink
Upload exercise files for 03_06
Browse files Browse the repository at this point in the history
  • Loading branch information
TomPughe authored Jun 18, 2024
1 parent f391ed7 commit 8f88b4a
Show file tree
Hide file tree
Showing 2 changed files with 72 additions and 0 deletions.
62 changes: 62 additions & 0 deletions hello-server.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
// Credits:
// https://yourbasic.org/golang/http-server-example/
// https://stackoverflow.com/a/42533360/2308522
// https://www.digitalocean.com/community/tutorials/how-to-build-go-executables-for-multiple-platforms-on-ubuntu-16-04
package main

import (
"context"
"fmt"
"log"
"net/http"
"sync"
"time"
)

func startHttpServer(wg *sync.WaitGroup) *http.Server {
srv := &http.Server{Addr: ":11000"}

http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hello, %s!", r.URL.Path[1:])
})

go func() {
defer wg.Done() // let main know we are done cleaning up

// always returns error. ErrServerClosed on graceful close
if err := srv.ListenAndServe(); err != http.ErrServerClosed {
// unexpected error. port in use?
log.Fatalf("ListenAndServe(): %v", err)
}
}()

// returning reference so caller can call Shutdown()
return srv
}

func main() {
log.Printf("main: starting HTTP server")

httpServerExitDone := &sync.WaitGroup{}

httpServerExitDone.Add(1)
srv := startHttpServer(httpServerExitDone)

log.Printf("main: serving for 10 seconds")

time.Sleep(10 * time.Second)

log.Printf("main: stopping HTTP server")

// now close the server gracefully ("shutdown")
// timeout could be given with a proper context
// (in real world you shouldn't use TODO()).
if err := srv.Shutdown(context.TODO()); err != nil {
panic(err) // failure/timeout shutting down the server gracefully
}

// wait for goroutine started in startHttpServer() to stop
httpServerExitDone.Wait()

log.Printf("main: done. exiting")
}
10 changes: 10 additions & 0 deletions test.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
chmod +x ./linux/hello-server

./linux/hello-server &

sleep 3

for i in Anakin Luke Leia Kylo Rey;
do
echo "$(date): $(curl -s http://localhost:11000/${i})"
done

0 comments on commit 8f88b4a

Please sign in to comment.