本文整理匯總了Golang中github.com/mssola/user_agent.New函數的典型用法代碼示例。如果您正苦於以下問題:Golang New函數的具體用法?Golang New怎麽用?Golang New使用的例子?那麽, 這裏精選的函數代碼示例或許可以為您提供幫助。
在下文中一共展示了New函數的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。
示例1: ServeHTTP
func (h *HttpHandler) ServeHTTP(rw http.ResponseWriter, r *http.Request) {
url, err := h.getFileUrl(r)
if err != nil {
rw.WriteHeader(http.StatusBadRequest)
return
}
redirect := func() {
http.Redirect(rw, r, url.String(), http.StatusTemporaryRedirect)
}
ua := user_agent.New(r.UserAgent())
name, version := ua.Browser()
if name != "Chrome" || strings.Index(version, "52.") != 0 {
redirect()
return
}
d, err := h.DimensionsCache.Get(url)
if err != nil {
rw.WriteHeader(http.StatusInternalServerError)
return
}
if d.SwapHeightAndWidth == 0 {
redirect()
return
}
h.Proxy.ServeHTTP(rw, r)
}
示例2: Log
func (uap *UADetectionPlugin) Log(req *http.Request, res *http.Response, ctx *apiplexy.APIContext) error {
ua := user_agent.New(req.UserAgent())
ctx.Log["ua_mobile"] = ua.Mobile()
ctx.Log["ua_bot"] = ua.Bot()
browser, version := ua.Browser()
ctx.Log["ua_browser"] = browser
ctx.Log["ua_version"] = version
ctx.Log["ua_os"] = ua.OS()
return nil
}
示例3: insertStatistic
func insertStatistic(r *http.Request) {
// 後台訪問暫不計入統計中
if strings.Contains(r.RequestURI, "/admin") {
return
}
db := openDatabase()
if db == nil {
return
}
defer closeDatabase(db)
//db.execInsert("statistic", "null,?,?,?,?,?,?,?,?,?,?,?", )
tx, err := db.Begin()
if err != nil {
return
}
stmt, err := tx.Prepare("insert into statistic values(null,?,?,?,?,?,?,?,?,?,?,?)")
if err != nil {
fmt.Println(err)
return
}
ua := user_agent.New(r.UserAgent())
/*
id, url, referer, refererhost, refererpath, useragent, time, platform, os, browser, browserver ip,
*/
refererpath := ""
refererhost := ""
referer, err := url.Parse(r.Referer())
if err == nil {
refererhost = referer.Host
refererpath = referer.Path
}
browsername, browserversion := ua.Browser()
if _, err = stmt.Exec(
r.RequestURI, // url
r.Referer(), // referer
refererhost, // refererhost
refererpath, // refererpath
ua.UA(), // useragent
time.Now().Unix(), // time
ua.Platform(), // platform
ua.OS(), // os
browsername, // browser
browserversion, // browserver
getIpAddrByStr(r.RemoteAddr)); err != nil {
fmt.Println(err)
return
}
defer stmt.Close()
tx.Commit()
return
}
示例4: downloadComplianceReport
func downloadComplianceReport(c *Context, w http.ResponseWriter, r *http.Request) {
if !c.HasSystemAdminPermissions("downloadComplianceReport") {
return
}
if !*utils.Cfg.ComplianceSettings.Enable || !utils.IsLicensed || !*utils.License.Features.Compliance || einterfaces.GetComplianceInterface() == nil {
c.Err = model.NewLocAppError("downloadComplianceReport", "ent.compliance.licence_disable.app_error", nil, "")
return
}
params := mux.Vars(r)
id := params["id"]
if len(id) != 26 {
c.SetInvalidParam("downloadComplianceReport", "id")
return
}
if result := <-Srv.Store.Compliance().Get(id); result.Err != nil {
c.Err = result.Err
return
} else {
job := result.Data.(*model.Compliance)
c.LogAudit("downloaded " + job.Desc)
if f, err := ioutil.ReadFile(*utils.Cfg.ComplianceSettings.Directory + "compliance/" + job.JobName() + ".zip"); err != nil {
c.Err = model.NewLocAppError("readFile", "api.file.read_file.reading_local.app_error", nil, err.Error())
return
} else {
w.Header().Set("Cache-Control", "max-age=2592000, public")
w.Header().Set("Content-Length", strconv.Itoa(len(f)))
w.Header().Del("Content-Type") // Content-Type will be set automatically by the http writer
// attach extra headers to trigger a download on IE, Edge, and Safari
ua := user_agent.New(r.UserAgent())
bname, _ := ua.Browser()
w.Header().Set("Content-Disposition", "attachment;filename=\""+job.JobName()+".zip\"")
if bname == "Edge" || bname == "Internet Explorer" || bname == "Safari" {
// trim off anything before the final / so we just get the file's name
w.Header().Set("Content-Type", "application/octet-stream")
}
w.Write(f)
}
}
}
示例5: BySlug
func (this *PostController) BySlug() {
post_slug := this.Ctx.Input.Param(":slug")
post_model := models.NewPostModel()
post, err := post_model.BySlug(post_slug)
if err != nil {
this.Abort("404")
}
this.setPost(post)
ua := user_agent.New(this.Ctx.Request.UserAgent())
if ua.Bot() {
post_model.ViewedBy(post.PostId, "bot")
} else {
post_model.ViewedBy(post.PostId, "human")
}
}
示例6: CheckBrowserCompatability
func CheckBrowserCompatability(c *api.Context, r *http.Request) bool {
ua := user_agent.New(r.UserAgent())
bname, bversion := ua.Browser()
browsers := strings.Split(browsersNotSupported, ";")
for _, browser := range browsers {
version := strings.Split(browser, "/")
if strings.HasPrefix(bname, version[0]) && strings.HasPrefix(bversion, version[1]) {
return false
}
}
return true
}
示例7: CheckBrowserCompatability
func CheckBrowserCompatability(c *api.Context, r *http.Request) bool {
ua := user_agent.New(r.UserAgent())
bname, bversion := ua.Browser()
browsers := strings.Split(browsersNotSupported, ";")
for _, browser := range browsers {
version := strings.Split(browser, "/")
if strings.HasPrefix(bname, version[0]) && strings.HasPrefix(bversion, version[1]) {
c.Err = model.NewAppError("CheckBrowserCompatability", "Your current browser is not supported, please upgrade to one of the following browsers: Google Chrome 21 or higher, Internet Explorer 10 or higher, FireFox 14 or higher", "")
return false
}
}
return true
}
示例8: CheckBrowserCompatability
func CheckBrowserCompatability(c *api.Context, r *http.Request) bool {
ua := user_agent.New(r.UserAgent())
bname, bversion := ua.Browser()
browsers := strings.Split(browsersNotSupported, ";")
for _, browser := range browsers {
version := strings.Split(browser, "/")
if strings.HasPrefix(bname, version[0]) && strings.HasPrefix(bversion, version[1]) {
c.Err = model.NewLocAppError("CheckBrowserCompatability", "web.check_browser_compatibility.app_error", nil, "")
return false
}
}
return true
}
示例9: Handle
func (uae UserAgentExtractor) Handle(c *mv.Context) {
ua := user_agent.New(c.Request.Header["User-Agent"][0])
name, version := ua.Browser()
browserEngine, browserEngineVersion := ua.Engine()
browserInfo := BrowserInfo{
verbose: uae.verbose,
Name: name,
Version: version,
OS: ua.OS(),
Engine: browserEngine,
EngineVersion: browserEngineVersion,
Localization: ua.Localization(),
Platform: ua.Platform(),
Mobile: ua.Mobile(),
}
c.WithValue(browserInfoKey, browserInfo)
c.Next()
}
示例10: testClient
func testClient(client *userAgent) (success bool) {
var crawler bool
switch client.Type {
case "crawlers", "browsers":
crawler = client.Type == "crawlers"
break
default:
return
}
for _, uastr := range client.UserAgents {
ua := user_agent.New(uastr)
if crawler && !ua.Bot() {
glog.Warningf("%s not recognized %q", client.Type, uastr)
} else if !crawler && ua.Bot() {
glog.Warningf("%s recognized as bot %q", client.Type, uastr)
} else {
return true
}
}
return
}
示例11: saveShow
func (self *Server) saveShow(t time.Time, sesUuid string, storeID int, params string, remoteIp string, acceptLanguage string, refererSrc string, userAgent string) {
var zoneId pgx.NullInt32
var uaBrowserVersion pgx.NullInt16
var uaBrowserFamily pgx.NullString
var zoneName pgx.NullString
var referer pgx.NullString
if err := self.DB.QueryRow("getZoneById", storeID).Scan(&zoneId, &zoneName); err != nil {
self.Log.Error("Is not", "zoneId", storeID)
}
ua := user_agent.New(userAgent)
browserFamily, version := ua.Browser()
// fmt.Println("------------ userAgent ------------")
// fmt.Printf("%v", userAgent)
if len(version) > 2 {
// fmt.Println("------------ version ----------")
// fmt.Printf("%v", version)
browserVersion, err := strconv.Atoi(version[0:strings.Index(version, ".")])
if err == nil {
uaBrowserVersion = pgx.NullInt16{Int16: int16(browserVersion), Valid: true}
}
}
if len(browserFamily) > 2 {
uaBrowserFamily = pgx.NullString{String: browserFamily, Valid: true}
}
ip, ipv4, mac := adscore.ParseParams(params)
if len(refererSrc) > 1 {
referer = pgx.NullString{String: refererSrc, Valid: true}
}
if _, err := self.DB.Exec("setShowBanner", t, sesUuid, zoneId, ua.Bot(), mac, ip, ipv4, acceptLanguage, uaBrowserFamily, uaBrowserVersion, ua.OS(), ua.Platform(), ua.Mobile(), userAgent, referer); err != nil {
self.Log.Error("Exec", "setShowBanner", err)
}
}
示例12: Transform
func (event *SnowplowEvent) Transform(request []byte, geo *geoip.GeoIP) error {
event.Body = request
normString, err := strconv.Unquote(`"` + string(request) + `"`)
if err != nil {
return err
}
normString = strings.Replace(normString, "\" ", "", -1)
snowplowRequest := &SnowplowRequest{}
err = json.Unmarshal([]byte(normString), snowplowRequest)
if err != nil {
return err
}
// Binding first level nginx fields
checkStringForNull(snowplowRequest.IPAddress, &event.UserIP)
event.CollectorTstamp = time.Now()
// checkStringForNull(snowplowRequest.Referer, &event.PageReferrer)
checkStringForNull(snowplowRequest.Useragent, &event.Useragent)
// Binding snowplow data
snowplowData := snowplowRequest.RequestBody.Data[0]
// Bind string values
checkStringForNull(snowplowData.Event, &event.Event)
checkStringForNull(snowplowData.PageURL, &event.PageURL)
checkStringForNull(snowplowData.PageTtile, &event.PageTtile)
checkStringForNull(snowplowData.PageReferrer, &event.PageReferrer)
checkStringForNull(snowplowData.VTracker, &event.VTracker)
checkStringForNull(snowplowData.Aid, &event.Aid)
checkStringForNull(snowplowData.Platform, &event.Platform)
checkStringForNull(snowplowData.OsTimezone, &event.OsTimezone)
checkStringForNull(snowplowData.BrLang, &event.BrLang)
checkStringForNull(snowplowData.DocCharset, &event.DocCharset)
checkStringForNull(snowplowData.EventID, &event.EventID)
checkStringForNull(snowplowData.DomainUserID, &event.DomainUserID)
checkStringForNull(snowplowData.UserFingerprint, &event.UserFingerprint)
checkStringForNull(snowplowData.SeCategory, &event.SeCategory)
checkStringForNull(snowplowData.SeAction, &event.SeAction)
checkStringForNull(snowplowData.SeLabel, &event.SeLabel)
checkStringForNull(snowplowData.SeProperty, &event.SeProperty)
checkFloatForNull(snowplowData.SeValue, &event.SeValue)
// Bind integer values
checkIntForNull(snowplowData.BrColorDepth, &event.BrColorDepth)
checkIntForNull(snowplowData.VisitNum, &event.VisitNum)
checkIntForNull(snowplowData.UserID, &event.UserID)
// Bind boolean values
event.BrPDF, _ = strconv.ParseBool(snowplowData.BrPDF)
event.BrQT, _ = strconv.ParseBool(snowplowData.BrQT)
event.BrRealPlayer, _ = strconv.ParseBool(snowplowData.BrRealPlayer)
event.BrWMA, _ = strconv.ParseBool(snowplowData.BrWMA)
event.BrDir, _ = strconv.ParseBool(snowplowData.BrDir)
event.BrFlash, _ = strconv.ParseBool(snowplowData.BrFlash)
event.BrJava, _ = strconv.ParseBool(snowplowData.BrJava)
event.BrGears, _ = strconv.ParseBool(snowplowData.BrGears)
event.BrAg, _ = strconv.ParseBool(snowplowData.BrAg)
event.BrCookies, _ = strconv.ParseBool(snowplowData.BrCookies)
// Bind screen resolutions
event.BrViewWidth = snowplowData.BrView.Width
event.BrViewHeight = snowplowData.BrView.Height
event.DvceScreenWidth = snowplowData.DvceScreen.Width
event.DvceScreenHeight = snowplowData.DvceScreen.Height
event.DocWidth = snowplowData.Doc.Width
event.DocHeight = snowplowData.Doc.Width
// Bind time values
event.DvceTstamp = snowplowData.DvceTstamp.Time
// Bind Geo values
geoIPRecord := geo.GetRecord(snowplowRequest.IPAddress)
if geoIPRecord != nil {
checkStringForNull(geoIPRecord.CountryName, &event.GeoCountry)
checkStringForNull(geoIPRecord.Region, &event.GeoRegion)
checkStringForNull(geoIPRecord.City, &event.GeoCity)
checkStringForNull(geoIPRecord.PostalCode, &event.GeoZipcode)
event.GeoLatitude = geoIPRecord.Latitude
event.GeoLongtitude = geoIPRecord.Longitude
checkStringForNull(geoIPRecord.Region, &event.GeoRegionName)
}
// Bind useragent values
ua := user_agent.New(snowplowRequest.Useragent)
event.DvceIsMobile = ua.Mobile()
checkStringForNull(ua.OS(), &event.OsName)
checkStringForNull(ua.Platform(), &event.DvceType)
name, version := ua.Engine()
checkStringForNull(name+version, &event.BrRndrNgn)
name, version = ua.Browser()
checkStringForNull(name, &event.BrName)
//.........這裏部分代碼省略.........
示例13: send_auditlog_record
func send_auditlog_record(msg jsonMsg) {
//fmt.Println(msg)
params := url.Values{}
/* struct based implementation */
if msg.Action != "" {
params.Set("action", msg.Action)
} else {
action := []string{}
for _, s := range []string{
msg.Study, msg.Subset1, msg.Subset2, msg.Analysis,
msg.Query, msg.FacetQuery, msg.User} {
if s != "0" && s != "" {
action = append(action, s)
}
}
params.Set("action", strings.Join(action, "|"))
}
if msg.Application != "" {
params.Set("application", msg.Application)
}
if msg.AppVersion != "" {
params.Set("appVersion", msg.AppVersion)
}
if msg.User != "" {
params.Set("user", msg.User)
}
if msg.Task != "" {
params.Set("task", msg.Task)
}
if msg.Browser != "" {
browser, version := user_agent.New(msg.Browser).Browser()
params.Set("browser", browser+" "+version)
}
/**/
/* alternative map based implementation
for _, k := range []string{"action", "program", "programVersion", "user", "event"} {
if _, hasKey := msg[k]; !hasKey { continue }
key := k
if outkey, translate := keyMap[k]; translate {
key = outkey
}
params.Set(key, fmt.Sprintf("%v", msg[k]))
}
if _, hasKey := msg["action"]; !hasKey {
action := []string{}
for _, s := range []string{msg["study"], msg["subset1"], msg["subset2"]; msg["analysis"], msg["query"],
msg["facetQuery"], msg["User"]} {
if s != "0" && s != "" {
action = append(action, s)
}
}
params.Set("action", strings.Join(action, "|"))
}
if _, hasKey := msg["userAgent"]; hasKey {
browser, version := user_agent.New(msg["userAgent"]).Browser()
params.Set("browser", browser + " " + version)
}
*/
fullurl := URL + "?" + params.Encode()
//fmt.Println(fullurl)
resp, err := http.PostForm(fullurl, url.Values{})
if err != nil {
error("WARNING: Failed to post message to metrics server: " + err.Error())
} else {
ioutil.ReadAll(resp.Body)
resp.Body.Close()
}
atomicAdd(&requests_in_progress, -1)
wg.Done()
}
示例14: Login
// User MUST be validated before calling Login
func Login(c *Context, w http.ResponseWriter, r *http.Request, user *model.User, deviceId string) {
c.LogAuditWithUserId(user.Id, "attempt")
if !user.EmailVerified && utils.Cfg.EmailSettings.RequireEmailVerification {
c.Err = model.NewAppError("Login", "Login failed because email address has not been verified", "user_id="+user.Id)
c.Err.StatusCode = http.StatusForbidden
return
}
if user.DeleteAt > 0 {
c.Err = model.NewAppError("Login", "Login failed because your account has been set to inactive. Please contact an administrator.", "user_id="+user.Id)
c.Err.StatusCode = http.StatusForbidden
return
}
session := &model.Session{UserId: user.Id, TeamId: user.TeamId, Roles: user.Roles, DeviceId: deviceId, IsOAuth: false}
maxAge := model.SESSION_TIME_WEB_IN_SECS
if len(deviceId) > 0 {
session.SetExpireInDays(model.SESSION_TIME_MOBILE_IN_DAYS)
maxAge = model.SESSION_TIME_MOBILE_IN_SECS
} else {
session.SetExpireInDays(model.SESSION_TIME_WEB_IN_DAYS)
}
ua := user_agent.New(r.UserAgent())
plat := ua.Platform()
if plat == "" {
plat = "unknown"
}
os := ua.OS()
if os == "" {
os = "unknown"
}
bname, bversion := ua.Browser()
if bname == "" {
bname = "unknown"
}
if bversion == "" {
bversion = "0.0"
}
session.AddProp(model.SESSION_PROP_PLATFORM, plat)
session.AddProp(model.SESSION_PROP_OS, os)
session.AddProp(model.SESSION_PROP_BROWSER, fmt.Sprintf("%v/%v", bname, bversion))
if result := <-Srv.Store.Session().Save(session); result.Err != nil {
c.Err = result.Err
c.Err.StatusCode = http.StatusForbidden
return
} else {
session = result.Data.(*model.Session)
AddSessionToCache(session)
}
w.Header().Set(model.HEADER_TOKEN, session.Token)
tokens := GetMultiSessionCookieTokens(r)
multiToken := ""
seen := make(map[string]string)
seen[session.TeamId] = session.TeamId
for _, token := range tokens {
s := GetSession(token)
if s != nil && !s.IsExpired() && seen[s.TeamId] == "" {
multiToken += " " + token
seen[s.TeamId] = s.TeamId
}
}
multiToken = strings.TrimSpace(multiToken + " " + session.Token)
multiSessionCookie := &http.Cookie{
Name: model.SESSION_COOKIE_TOKEN,
Value: multiToken,
Path: "/",
MaxAge: maxAge,
HttpOnly: true,
}
http.SetCookie(w, multiSessionCookie)
c.Session = *session
c.LogAuditWithUserId(user.Id, "success")
}
示例15: ParseUserAgent
func ParseUserAgent(useragent string) (string, string) {
ua := user_agent.New(useragent)
return ua.Browser()
}