Skip to content

Commit

Permalink
update
Browse files Browse the repository at this point in the history
  • Loading branch information
novalagung committed Jul 29, 2019
1 parent be58d93 commit 7c22c06
Show file tree
Hide file tree
Showing 3 changed files with 82 additions and 0 deletions.
1 change: 1 addition & 0 deletions README.md
Expand Up @@ -88,6 +88,7 @@ Source Code Praktek [Dasar Pemrograman Golang](https://dasarpemrogramangolang.no
* [B.20. Custom Multiplexer](https://github.com/novalagung/dasarpemrogramangolang/tree/master/chapter-B.20-custom-mux-multiplexer)
* [B.21. HTTP Cookie](https://github.com/novalagung/dasarpemrogramangolang/tree/master/chapter-B.21-cookie)
* [B.22. Configuration File](https://github.com/novalagung/dasarpemrogramangolang/tree/master/chapter-B.22-configuration-file)
* [B.23. Handle Cancelled HTTP Request](https://github.com/novalagung/dasarpemrogramangolang/tree/master/chapter-B.23-handle-cancelled-http-request)
* C. Pemrograman Web Golang Lanjut
* [C.1. Echo Framework & Routing](https://github.com/novalagung/dasarpemrogramangolang/tree/master/chapter-C.1-echo-routing)
* [C.2. Parsing HTTP Request Payload (Echo)](https://github.com/novalagung/dasarpemrogramangolang/tree/master/chapter-C.2-parsing-http-request-payload-echo)
Expand Down
@@ -0,0 +1,38 @@
package main

import (
"fmt"
"log"
"net/http"
"strings"
"time"
)

func handleIndex(w http.ResponseWriter, r *http.Request) {
done := make(chan bool)
go func() {
// do the process here
// simulate a long-time request by putting 10 seconds sleep
time.Sleep(10 * time.Second)

done <- true
}()

select {
case <-r.Context().Done():
if err := r.Context().Err(); err != nil {
if strings.Contains(strings.ToLower(err.Error()), "canceled") {
log.Println("request canceled")
} else {
log.Println("unknown error occured.", err.Error())
}
}
case <-done:
log.Println("done")
}
}

func main() {
http.HandleFunc("/", handleIndex)
http.ListenAndServe(":8080", nil)
}
@@ -0,0 +1,43 @@
package main

import (
"io/ioutil"
"log"
"net/http"
"strings"
"time"
)

func handleIndex(w http.ResponseWriter, r *http.Request) {
done := make(chan bool)
go func() {
// do the process here
// simulate a long-time request by putting 10 seconds sleep

body, err := ioutil.ReadAll(r.Body)
_ = err
_ = body

time.Sleep(10 * time.Second)

done <- true
}()

select {
case <-r.Context().Done():
if err := r.Context().Err(); err != nil {
if strings.Contains(strings.ToLower(err.Error()), "canceled") {
log.Println("request canceled")
} else {
log.Println("unknown error occured.", err.Error())
}
}
case <-done:
log.Println("done")
}
}

func main() {
http.HandleFunc("/", handleIndex)
http.ListenAndServe(":8080", nil)
}

0 comments on commit 7c22c06

Please sign in to comment.