HTTP referer (本来是 referrer 的拼写错误) 是一个可选的 HTTP 头部字段, 用于标记链接到请求资源的网页的地址(即 URI 或者 IRI)。通过检查 referrer,新的网页可以知道请求的来源。

Iris 使用 Shopify's goreferrer 包来实现 Context.GetReferrer() 方法。

GetReferrer 方法提取和返回 Referer 头的信息,Referer 通过 https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Referrer-Policy 或者 URL 的 referer 查询参数(query parameter)指定。

  1. GetReferrer() Referrer

Referrer 是这样的:

  1. type (
  2. Referrer struct {
  3. Type ReferrerType
  4. Label string
  5. URL string
  6. Subdomain string
  7. Domain string
  8. Tld string
  9. Path string
  10. Query string
  11. GoogleType ReferrerGoogleSearchType
  12. }

ReferrerTypeReferrer.Type 值( indirectdirectemailsearchsocial)的枚举。可以的类型有:

  • ReferrerInvalid
  • ReferrerIndirect
  • ReferrerDirect
  • ReferrerEmail
  • ReferrerSearch
  • ReferrerSocial

GoogleType 可以是下列之一:

  • ReferrerNotGoogleSearch
  • ReferrerGoogleOrganicSearch
  • ReferrerGoogleAdwords

示例(Example)

  1. package main
  2. import "github.com/kataras/iris/v12"
  3. func main() {
  4. app := iris.New()
  5. app.Get("/", func(ctx iris.Context) {
  6. r := ctx.GetReferrer()
  7. switch r.Type {
  8. case iris.ReferrerSearch:
  9. ctx.Writef("Search %s: %s\n", r.Label, r.Query)
  10. ctx.Writef("Google: %s\n", r.GoogleType)
  11. case iris.ReferrerSocial:
  12. ctx.Writef("Social %s\n", r.Label)
  13. case iris.ReferrerIndirect:
  14. ctx.Writef("Indirect: %s\n", r.URL)
  15. }
  16. })
  17. app.Run(iris.Addr(":8080"))
  18. }

curl

  1. curl http://localhost:8080?\
  2. referer=https://twitter.com/Xinterio/status/1023566830974251008
  3. curl http://localhost:8080?\
  4. referer=https://www.google.com/search?q=Top+6+golang+web+frameworks\
  5. &oq=Top+6+golang+web+frameworks