Contents

gin

Contents

what’s context;

how the gin implement

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
class GinContext {
    // Represents the HTTP request.
    Request HTTPRequest

    // Represents the HTTP response writer.
    Response HTTPResponseWriter

    // A map to store values specific to this context.
    Map[string]any Values

    // Status code to be sent in the response.
    int StatusCode

    // Handlers are the list of middleware + main handler that will be executed.
    List[HandlerFunc] Handlers

    // Index indicates the current position in the middleware chain.
    int Index

    // Context from the standard library, used for handling request cancellations.
    Context context.Context
}

request cancel:

what: user cancel the request; when:

  1. user actively cancel
  2. client reach the timeout

how to detect it: in go server , use request.context;

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
func handleRequest(w http.ResponseWriter, r *http.Request) {
	i := 0
	for {
		select {
		case <-r.Context().Done():
			fmt.Println("Client disconnected")
			w.WriteHeader(http.StatusNoContent)
			return
		default:
			fmt.Println("Working...")
			time.Sleep(1 * time.Second)
			i++
			if i == 5 {
				w.WriteHeader(http.StatusOK)
				w.Write([]byte("ok"))
				return
			}
		}
	}
}

how to response:

  1. not return anything, beacuse the client won’t recevie the message;
  2. can return statsu 204 for logging

gin

  1. how gin work
  2. how gin middleware work
  3. what the gin abort mean?

how gin work?

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
class GinContext {
    // Represents the HTTP request.
    Request HTTPRequest

    // Represents the HTTP response writer.
    Response HTTPResponseWriter
	int Index
	valeus map[]

}

func httpRequest(w http.writer, r http.reader): 
	ginContext := new GinContext;

	handles(ginContext)
	

pass value in gin.Context or gin.Context.request.Context;

gin.Context:

  1. store in a maps

gin.Context.request.Context:

  1. store in context
  2. also have cancel siganl

recommd: pass value in request.context when it also have api and db operation, becaut it can responed the rquest sigal

middleware:

  1. how it work ;
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
handles = [handles1, handle2]

next(gin gin.Context){
	gin.Index++
	gin.handlers[index](gin) // pass control to next handle  

}



use(middleware){
	c.handels.append(handle )
}

the excute order:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10

func 1 
	 1 do sth;
	 next:
	      func 2:
		      2 do sth;
		      next // if next is nothing, just continue
		    2 do sth

	 1 do sth

abort , just stop remianing handles , but current and previous handler is excute

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15

abort:
	gin.index = maxIndex


func 1:
	do sth 1;
	abort()
	next:
		  func2: // not be excuted
			  do sth2

    do sth 3

// do sth1 ; do sth3;