example_test.go 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. package proxy_test
  2. import (
  3. "go-common/library/net/http/blademaster"
  4. "go-common/library/net/http/blademaster/middleware/proxy"
  5. )
  6. // This example create several reverse proxy to show how to use proxy middleware.
  7. // We proxy three path to `api.bilibili.com` and return response without any changes.
  8. func Example() {
  9. proxies := map[string]string{
  10. "/index": "http://api.bilibili.com/html/index",
  11. "/ping": "http://api.bilibili.com/api/ping",
  12. "/api/versions": "http://api.bilibili.com/api/web/versions",
  13. }
  14. engine := blademaster.Default()
  15. for path, ep := range proxies {
  16. engine.GET(path, proxy.NewAlways(ep))
  17. }
  18. engine.Run(":18080")
  19. }
  20. // This example create several reverse proxy to show how to use jd proxy middleware.
  21. // The request will be proxied to destination only when request is from specified datacenter.
  22. func ExampleNewZoneProxy() {
  23. proxies := map[string]string{
  24. "/index": "http://api.bilibili.com/html/index",
  25. "/ping": "http://api.bilibili.com/api/ping",
  26. "/api/versions": "http://api.bilibili.com/api/web/versions",
  27. }
  28. engine := blademaster.Default()
  29. // proxy to specified destination
  30. for path, ep := range proxies {
  31. engine.GET(path, proxy.NewZoneProxy("sh004", ep), func(ctx *blademaster.Context) {
  32. ctx.String(200, "Origin")
  33. })
  34. }
  35. // proxy with request path
  36. ug := engine.Group("/update", proxy.NewZoneProxy("sh004", "http://sh001-api.bilibili.com"))
  37. ug.POST("/name", func(ctx *blademaster.Context) {
  38. ctx.String(500, "Should not be accessed")
  39. })
  40. ug.POST("/sign", func(ctx *blademaster.Context) {
  41. ctx.String(500, "Should not be accessed")
  42. })
  43. engine.Run(":18080")
  44. }