context examples

This commit is contained in:
unintendedfraud
2024-03-11 23:11:04 +01:00
parent b638ed612b
commit 731715fa60
3 changed files with 39 additions and 65 deletions
-2
View File
@@ -1,2 +0,0 @@
package main
+37 -34
View File
@@ -3,6 +3,7 @@ package main
import ( import (
"context" "context"
"fmt" "fmt"
"log"
"net/http" "net/http"
"time" "time"
) )
@@ -10,13 +11,9 @@ import (
const PORT = 8080 const PORT = 8080
func main() { func main() {
server := NewServer(1 * time.Second) server := &Server{}
server.Handle( server.Handle("/get-value", addValueToContext, handleGetValue)
"/get-value",
addValueToContext,
handleGetValue,
)
if err := server.Listen(PORT); err != nil { if err := server.Listen(PORT); err != nil {
panic(err) panic(err)
@@ -26,48 +23,50 @@ func main() {
func handleGetValue(next http.Handler) http.Handler { func handleGetValue(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fmt.Println("starting handleGetValue") log.Println("handleGetValue started")
defer fmt.Println("finished executing handleGetNumber") defer log.Println("handleGetNumber ended")
message, err := executeHandleGetValue(r.Context(), r) ctx, cancelCtx := context.WithTimeout(r.Context(), 8*time.Second)
defer cancelCtx()
err := someLongAction(ctx)
if err != nil { if err != nil {
w.Write([]byte(fmt.Sprintf("\nError happened: %s", err.Error()))) w.Write([]byte(fmt.Sprintf("\n%s - Error happened: %s", t(), err.Error())))
fmt.Println("Error happened: ", err) log.Println("Error happened: ", err)
return return
} }
w.Write([]byte(message)) w.Write([]byte(fmt.Sprintf("%s -- operation finished successfully", t())))
}) })
} }
func executeHandleGetValue(ctx context.Context, r *http.Request) (string, error) { func someLongAction(ctx context.Context) error {
log.Println("someLongAction started")
defer log.Println("someLongAction ended")
select {
case err := <-simulatingOperation():
return err
case <-ctx.Done():
return ctx.Err()
}
}
func simulatingOperation() chan error {
log.Println("simlatingOperation started")
defer log.Println("simlatingOperation ended")
chanErr := make(chan error, 1) chanErr := make(chan error, 1)
go func() { go func() {
fmt.Println("executeHandleGetValue started") log.Println("goroutine in simulatingOperation started")
defer log.Println("goroutine in simulatingOperation ended")
time.Sleep(2 * time.Second) time.Sleep(5 * time.Second)
chanErr <- fmt.Errorf("something terrible happened, PLEASE HELP!")
// simulate errors
shouldError := true
if shouldError {
chanErr <- fmt.Errorf("an error happened during goroutine")
} else {
chanErr <- nil
}
fmt.Println("executeHandleGetValue ended")
}() }()
select { return chanErr
case <-ctx.Done():
<-chanErr
return "", ctx.Err()
case err := <-chanErr:
return "finished successfully", err
}
} }
func addValueToContext(next http.Handler) http.Handler { func addValueToContext(next http.Handler) http.Handler {
@@ -93,6 +92,10 @@ func addValueToContext(next http.Handler) http.Handler {
}) })
} }
func t() string {
return time.Now().Format("15:06:05")
}
type ComplexStruct struct { type ComplexStruct struct {
question string question string
possibleAnswers []string possibleAnswers []string
+2 -29
View File
@@ -1,34 +1,16 @@
package main package main
import ( import (
"context"
"fmt" "fmt"
"net/http" "net/http"
"time"
) )
type ServerHandler func(http.Handler) http.Handler type ServerHandler func(http.Handler) http.Handler
type Server struct { type Server struct{}
timeout time.Duration
}
func NewServer(timeout time.Duration) *Server {
return &Server{
timeout,
}
}
func (s *Server) Handle(addr string, handlers ...ServerHandler) { func (s *Server) Handle(addr string, handlers ...ServerHandler) {
var middlewares []ServerHandler http.Handle(addr, handleMiddlewares(handlers))
if s.timeout == 0 {
middlewares = handlers
} else {
middlewares = append([]ServerHandler{s.timeoutMiddleware}, handlers...)
}
http.Handle(addr, handleMiddlewares(middlewares))
} }
func (s *Server) Listen(port int) error { func (s *Server) Listen(port int) error {
@@ -39,15 +21,6 @@ func (s *Server) Listen(port int) error {
return nil return nil
} }
func (s *Server) timeoutMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
ctx, cancel := context.WithTimeout(r.Context(), s.timeout)
defer cancel()
next.ServeHTTP(w, r.WithContext(ctx))
})
}
func handleMiddlewares(handlers []ServerHandler) http.Handler { func handleMiddlewares(handlers []ServerHandler) http.Handler {
var handler http.Handler var handler http.Handler