example_test.go 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230
  1. package blademaster_test
  2. import (
  3. "io/ioutil"
  4. "log"
  5. "time"
  6. "go-common/library/net/http/blademaster"
  7. "go-common/library/net/http/blademaster/binding"
  8. "go-common/library/net/http/blademaster/middleware/auth"
  9. "go-common/library/net/http/blademaster/middleware/verify"
  10. "go-common/library/net/http/blademaster/tests"
  11. )
  12. // This example start a http server and listen at port 8080,
  13. // it will handle '/ping' and return response in html text
  14. func Example() {
  15. engine := blademaster.Default()
  16. engine.GET("/ping", func(c *blademaster.Context) {
  17. c.String(200, "%s", "pong")
  18. })
  19. engine.Run(":8080")
  20. }
  21. // This example use `RouterGroup` to separate different requests,
  22. // it will handle ('/group1/ping', '/group2/ping') and return response in json
  23. func ExampleRouterGroup() {
  24. engine := blademaster.Default()
  25. group := engine.Group("/group1", blademaster.CORS())
  26. group.GET("/ping", func(c *blademaster.Context) {
  27. c.JSON(map[string]string{"message": "hello"}, nil)
  28. })
  29. group2 := engine.Group("/group2", blademaster.CORS())
  30. group2.GET("/ping", func(c *blademaster.Context) {
  31. c.JSON(map[string]string{"message": "welcome"}, nil)
  32. })
  33. engine.Run(":8080")
  34. }
  35. // This example add two middlewares in the root router by `Use` method,
  36. // it will add CORS headers in response and log total consumed time
  37. func ExampleEngine_Use() {
  38. timeLogger := func() blademaster.HandlerFunc {
  39. return func(c *blademaster.Context) {
  40. start := time.Now()
  41. c.Next()
  42. log.Printf("total consume: %v", time.Since(start))
  43. }
  44. }
  45. engine := blademaster.Default()
  46. engine.Use(blademaster.CORS())
  47. engine.Use(timeLogger())
  48. engine.GET("/ping", func(c *blademaster.Context) {
  49. c.String(200, "%s", "pong")
  50. })
  51. engine.Run(":8080")
  52. }
  53. // This example add two middlewares in the root router by `UseFunc` method,
  54. // it will log total consumed time
  55. func ExampleEngine_UseFunc() {
  56. engine := blademaster.Default()
  57. engine.UseFunc(func(c *blademaster.Context) {
  58. start := time.Now()
  59. c.Next()
  60. log.Printf("total consume: %v", time.Since(start))
  61. })
  62. engine.GET("/ping", func(c *blademaster.Context) {
  63. c.String(200, "%s", "pong")
  64. })
  65. engine.Run(":8080")
  66. }
  67. // This example start a http server through the specified unix socket,
  68. // it will handle '/ping' and return reponse in html text
  69. func ExampleEngine_RunUnix() {
  70. engine := blademaster.Default()
  71. engine.GET("/ping", func(c *blademaster.Context) {
  72. c.String(200, "%s", "pong")
  73. })
  74. unixs, err := ioutil.TempFile("", "engine.sock")
  75. if err != nil {
  76. log.Fatalf("Failed to create temp file: %s", err)
  77. }
  78. if err := engine.RunUnix(unixs.Name()); err != nil {
  79. log.Fatalf("Failed to serve with unix socket: %s", err)
  80. }
  81. }
  82. // This example show how to render response in json format,
  83. // it will render structures as json like: `{"code":0,"message":"0","data":{"Time":"2017-11-14T23:03:22.0523199+08:00"}}`
  84. func ExampleContext_JSON() {
  85. type Data struct {
  86. Time time.Time
  87. }
  88. engine := blademaster.Default()
  89. engine.GET("/ping", func(c *blademaster.Context) {
  90. var d Data
  91. d.Time = time.Now()
  92. c.JSON(d, nil)
  93. })
  94. engine.Run(":8080")
  95. }
  96. // This example show how to render response in protobuf format
  97. // it will marshal whole response content to protobuf
  98. func ExampleContext_Protobuf() {
  99. engine := blademaster.Default()
  100. engine.GET("/ping.pb", func(c *blademaster.Context) {
  101. t := &tests.Time{
  102. Now: time.Now().Unix(),
  103. }
  104. c.Protobuf(t, nil)
  105. })
  106. engine.Run(":8080")
  107. }
  108. // This example show how to render response in XML format,
  109. // it will render structure as XML like: `<Data><Time>2017-11-14T23:03:49.2231458+08:00</Time></Data>`
  110. func ExampleContext_XML() {
  111. type Data struct {
  112. Time time.Time
  113. }
  114. engine := blademaster.Default()
  115. engine.GET("/ping", func(c *blademaster.Context) {
  116. var d Data
  117. d.Time = time.Now()
  118. c.XML(d, nil)
  119. })
  120. engine.Run(":8080")
  121. }
  122. // This example show how to protect your handlers by HTTP basic auth,
  123. // it will validate the baisc auth and abort with status 403 if authentication is invalid
  124. func ExampleContext_Abort() {
  125. engine := blademaster.Default()
  126. engine.UseFunc(func(c *blademaster.Context) {
  127. user, pass, isok := c.Request.BasicAuth()
  128. if !isok || user != "root" || pass != "root" {
  129. c.AbortWithStatus(403)
  130. return
  131. }
  132. })
  133. engine.GET("/auth", func(c *blademaster.Context) {
  134. c.String(200, "%s", "Welcome")
  135. })
  136. engine.Run(":8080")
  137. }
  138. // This example show how to using the default parameter binding to parse the url param from get request,
  139. // it will validate the request and abort with status 400 if params is invalid
  140. func ExampleContext_Bind() {
  141. engine := blademaster.Default()
  142. engine.GET("/bind", func(c *blademaster.Context) {
  143. v := new(struct {
  144. // This mark field `mids` should exist and every element should greater than 1
  145. Mids []int64 `form:"mids" validate:"dive,gt=1,required"`
  146. Title string `form:"title" validate:"required"`
  147. Content string `form:"content"`
  148. // This mark field `cid` should between 1 and 10
  149. Cid int `form:"cid" validate:"min=1,max=10"`
  150. })
  151. err := c.Bind(v)
  152. if err != nil {
  153. // Do not call any write response method in this state,
  154. // the response body is already written in `c.BindWith` method
  155. return
  156. }
  157. c.String(200, "parse params by bind %+v", v)
  158. })
  159. engine.Run(":8080")
  160. }
  161. // This example show how to using the json binding to parse the json param from post request body,
  162. // it will validate the request and abort with status 400 if params is invalid
  163. func ExampleContext_BindWith() {
  164. engine := blademaster.Default()
  165. engine.POST("/bindwith", func(c *blademaster.Context) {
  166. v := new(struct {
  167. // This mark field `mids` should exist and every element should greater than 1
  168. Mids []int64 `json:"mids" validate:"dive,gt=1,required"`
  169. Title string `json:"title" validate:"required"`
  170. Content string `json:"content"`
  171. // This mark field `cid` should between 1 and 10
  172. Cid int `json:"cid" validate:"min=1,max=10"`
  173. })
  174. err := c.BindWith(v, binding.JSON)
  175. if err != nil {
  176. // Do not call any write response method in this state,
  177. // the response body is already written in `c.BindWith` method
  178. return
  179. }
  180. c.String(200, "parse params by bindwith %+v", v)
  181. })
  182. engine.Run(":8080")
  183. }
  184. func ExampleEngine_Inject() {
  185. v := verify.New(nil)
  186. auth := auth.New(nil)
  187. engine := blademaster.Default()
  188. engine.Inject("^/index", v.Verify, auth.User)
  189. engine.POST("/index/hello", func(c *blademaster.Context) {
  190. c.JSON("hello, world", nil)
  191. })
  192. engine.Run(":8080")
  193. }