github.com/wangkui503/aero@v1.0.0/docs/API.md (about)

     1  # API
     2  
     3  Unless specified otherwise, the API is considered to be stable.
     4  
     5  ## Creating an app
     6  
     7  ```go
     8  app := aero.New()
     9  ```
    10  
    11  ## Routing
    12  
    13  ```go
    14  app.Get("/hello", func(ctx *aero.Context) string {
    15  	return ctx.Text("Hello World")
    16  })
    17  ```
    18  
    19  ## Routing with parameters
    20  
    21  ```go
    22  app.Get("/hello/:person", func(ctx *aero.Context) string {
    23  	return ctx.Text("Hello " + ctx.Get("person"))
    24  })
    25  ```
    26  
    27  ## Shortcuts for different content types
    28  
    29  ```go
    30  app.Get("/", func(ctx *aero.Context) string {
    31  	// Choose one:
    32  	return ctx.HTML("<html></html>")
    33  	return ctx.CSS("body{}")
    34  	return ctx.JavaScript("console.log(42)")
    35  	return ctx.JSON(app.Config)
    36  	return ctx.Text("just some plain text")
    37  })
    38  ```
    39  
    40  ## Middleware
    41  
    42  You can run middleware functions that are executed after the routing phase and before the final request handler.
    43  
    44  ```go
    45  app.Use(func(ctx *aero.Context, next func()) {
    46  	start := time.Now()
    47  	next()
    48  	responseTime := time.Since(start)
    49  	fmt.Println(responseTime)
    50  })
    51  ```
    52  
    53  It is possible to implement a firewall by filtering requests and denying the `next()` call as the final request handler is also part of the middleware chain. Not calling `next()` means the request will not be handled.
    54  
    55  It is also possible to create a request / access log that includes performance timings as shown in the code example above. `ctx.URI()` will retrieve the URI of the request. Note that the actual logging happens **after** the request has been dealt with (`next()` call) which makes it efficient.
    56  
    57  ## Multiple middleware
    58  
    59  You can use multiple `Use()` calls or combine them into a single call:
    60  
    61  ```go
    62  app.Use(
    63  	First(),
    64  	Second(),
    65  	Third(),
    66  )
    67  ```
    68  
    69  ## Starting server
    70  
    71  This will start the server and block until a termination signal arrives.
    72  
    73  ```go
    74  app.Run()
    75  ```
    76  
    77  ## Layout
    78  
    79  The server package by itself does **not** concern itself with the implementation of your layout system but you can add [aerogo/layout](https://github.com/aerogo/layout) to register full-page and content-only routes at once.
    80  
    81  ```go
    82  // Create a new aerogo/layout
    83  l := layout.New(app)
    84  
    85  // Specify the page frame
    86  l.Render = func(ctx *aero.Context, content string) string {
    87  	return "<html><head></head><body>" + content + "</body></html>"
    88  }
    89  
    90  // Register the /hello page.
    91  // The page without the page frame will be available under /_/hello
    92  l.Page("/hello", func(ctx *aero.Context) string {
    93  	return ctx.HTML("<h1>Hello</h1>")
    94  })
    95  ```
    96  
    97  ## Rewrite
    98  
    99  Rewrites the internal URI before routing happens:
   100  
   101  ```go
   102  app.Rewrite(func(ctx *aero.RewriteContext) {
   103  	uri := ctx.URI()
   104  
   105  	if uri == "/old" {
   106  		ctx.SetURI("/new")
   107  		return
   108  	}
   109  })
   110  ```
   111  
   112  Only one rewrite function can be active in an Application. Multiple calls will overwrite the previously registered function.
   113  
   114  ## OnStart
   115  
   116  Schedules the function to be called when the server has started. Calling `OnStart` multiple times will register multiple callbacks.
   117  
   118  ```go
   119  app.OnStart(func() {
   120  	// Do something.
   121  })
   122  ```
   123  
   124  ## OnEnd
   125  
   126  In case the server is terminated by outside factors such as a kill signal sent by the operating system, you can specify a function to be called in that event. Calling `OnEnd` multiple times will register multiple callbacks.
   127  
   128  ```go
   129  app.OnEnd(func() {
   130  	// Free up resources.
   131  })
   132  ```
   133  
   134  ## Sessions
   135  
   136  ```go
   137  app.Get("/", func(ctx *aero.Context) string {
   138  	// Load number of views
   139  	views := 0
   140  	storedViews := ctx.Session().Get("views")
   141  
   142  	if storedViews != nil {
   143  		views = storedViews.(int)
   144  	}
   145  
   146  	// Increment
   147  	views++
   148  
   149  	// Store number of views
   150  	ctx.Session().Set("views", views)
   151  
   152  	// Display current number of views
   153  	return ctx.Text(fmt.Sprintf("%d views", views))
   154  })
   155  ```
   156  
   157  ## EventStream
   158  
   159  *SSE (server sent events) have recently been added as an experimental feature. The API is subject to change.*
   160  
   161  Using an event stream, you can push data from your server at any time to your client.
   162  
   163  ```go
   164  app.Get("/events/live", func(ctx *aero.Context) string {
   165  	stream := aero.NewEventStream()
   166  
   167  	go func() {
   168  		defer println("disconnected")
   169  
   170  		for {
   171  			select {
   172  			case <-stream.Closed:
   173  				return
   174  
   175  			case <-time.After(1 * time.Second):
   176  				stream.Events <- &aero.Event{
   177  					Name: "ping",
   178  					Data: "Hello World",
   179  				}
   180  			}
   181  		}
   182  	}()
   183  
   184  	return ctx.EventStream(stream)
   185  })
   186  ```
   187  
   188  On the client side, use [EventSource](https://developer.mozilla.org/en-US/docs/Web/API/EventSource#Examples) to receive events.
   189  
   190  ## AddPushCondition
   191  
   192  By default, HTTP/2 push will only trigger on `text/html` responses. You can add more conditions via:
   193  
   194  ```go
   195  // Do not use HTTP/2 push on service worker requests
   196  app.AddPushCondition(func(ctx *aero.Context) bool {
   197  	return ctx.Request().Header().Get("X-Source") != "service-worker"
   198  })
   199  ```
   200  
   201  Returning `true` for a given request will allow the push of resources while returning `false` will cancel the push immediately in the given request.