Skip to content

Commit a154d10

Browse files
committed
Http context
1 parent c66a5ef commit a154d10

File tree

6 files changed

+177
-0
lines changed

6 files changed

+177
-0
lines changed

17-Http/06-Context/api/result.go

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
package api
2+
3+
import (
4+
"encoding/json"
5+
"net/http"
6+
)
7+
8+
type ApiResult struct {
9+
Success bool `json:"success"`
10+
Result interface{} `json:"result"`
11+
Error string `json:"error"`
12+
}
13+
14+
func SetResult(statusCode int, result interface{}, errorInfo error, w http.ResponseWriter) {
15+
w.Header().Add("Web-Server", "NGINX")
16+
w.Header().Set("Content-Type", "application/json")
17+
18+
apiResult := &ApiResult{}
19+
if statusCode == http.StatusOK {
20+
apiResult.Success = true
21+
} else {
22+
apiResult.Success = false
23+
}
24+
25+
apiResult.Result = result
26+
27+
if errorInfo != nil {
28+
apiResult.Error = errorInfo.Error()
29+
}
30+
31+
jsonResponse, err := json.Marshal(apiResult)
32+
if err != nil {
33+
apiResult.Success = false
34+
apiResult.Error = err.Error()
35+
w.WriteHeader(http.StatusInternalServerError)
36+
}
37+
38+
w.WriteHeader(statusCode)
39+
_, err = w.Write(jsonResponse)
40+
if err != nil {
41+
panic(err)
42+
}
43+
44+
}
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
package examples
2+
3+
import (
4+
"context"
5+
"time"
6+
)
7+
8+
func InternalCancellationExample() {
9+
ctx := context.Background()
10+
ctx, cancel := context.WithCancel(ctx)
11+
12+
//Timeout
13+
//ctx, cancel = context.WithTimeout(ctx, time.Second * 3)
14+
15+
//Deadline
16+
//ctx, cancel = context.WithDeadline(ctx, time.Date(2022, time.February, 13, 23, 30, 0, 0, time.UTC))
17+
18+
defer cancel()
19+
20+
go func() {
21+
for {
22+
if time.Now().Second()%12 == 0 {
23+
cancel()
24+
}
25+
}
26+
}()
27+
28+
Processor(ctx, 0)
29+
}
30+
31+
func Processor(ctx context.Context, num int) {
32+
for {
33+
num++
34+
select {
35+
case <-ctx.Done():
36+
println("Canceled...")
37+
return
38+
default:
39+
println("processing", num)
40+
}
41+
time.Sleep(time.Millisecond * 500)
42+
}
43+
}
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
package examples
2+
3+
import "context"
4+
5+
func SendValueExample() {
6+
ctx := context.Background()
7+
8+
ctx = context.WithValue(ctx, "api-key", "1234567890")
9+
ctx = context.WithValue(ctx, "api-key", "1234567891")
10+
ctx = context.WithValue(ctx, "validation-code", "1020304050")
11+
12+
Print(ctx)
13+
14+
}
15+
16+
func Print(ctx context.Context) {
17+
var apiKey = ctx.Value("api-key")
18+
var validationCode = ctx.Value("validation-code")
19+
20+
println(apiKey.(string), validationCode.(string))
21+
}

17-Http/06-Context/go.mod

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
module context-examples
2+
3+
go 1.18

17-Http/06-Context/main.go

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
package main
2+
3+
import (
4+
"context-examples/examples"
5+
"context-examples/management"
6+
)
7+
8+
/*
9+
Context
10+
Creation
11+
Send value
12+
Cancellation from request
13+
Internal cancellation
14+
timeout
15+
Deadline
16+
17+
*/
18+
func main() {
19+
// Creation
20+
examples.SendValueExample()
21+
22+
//External Cancellation
23+
management.Run()
24+
25+
// Internal Cancellation
26+
examples.InternalCancellationExample()
27+
28+
}
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
package management
2+
3+
import (
4+
"fmt"
5+
"net/http"
6+
"time"
7+
)
8+
9+
func Run() {
10+
mux := http.NewServeMux()
11+
mux.HandleFunc("/test/", TestHandler)
12+
13+
server := &http.Server{
14+
Addr: ":8080",
15+
ReadTimeout: time.Second * 10,
16+
WriteTimeout: time.Second * 10,
17+
Handler: mux,
18+
}
19+
20+
err := server.ListenAndServe()
21+
22+
if err != nil {
23+
panic(err)
24+
}
25+
}
26+
27+
func TestHandler(w http.ResponseWriter, r *http.Request) {
28+
ctx := r.Context()
29+
30+
select {
31+
case <-time.After(time.Second * 5):
32+
fmt.Println("processing request")
33+
fmt.Fprintf(w, "Response")
34+
case <-ctx.Done():
35+
fmt.Println("cancel request")
36+
return
37+
}
38+
}

0 commit comments

Comments
 (0)