Golang Request.UserAgent Examples

Golang Request.UserAgent - 30 examples found. These are the top rated real world Golang examples of net/http.Request.UserAgent extracted from open source projects. You can rate examples to help us improve the quality of examples.
Example #1
0
func (c *Client) logInternal(ctx context.Context, r *http.Request, isPanic bool, msg string) {
	payload := map[string]interface{}{
		"eventTime": time.Now().In(time.UTC).Format(time.RFC3339Nano),
	}
	// limit the stack trace to 16k.
	var buf [16384]byte
	stack := buf[0:runtime.Stack(buf[:], false)]
	payload["message"] = msg + "\n" + chopStack(stack, isPanic)
	if r != nil {
		payload["context"] = map[string]interface{}{
			"httpRequest": map[string]interface{}{
				"method":    r.Method,
				"url":       r.Host + r.RequestURI,
				"userAgent": r.UserAgent(),
				"referrer":  r.Referer(),
				"remoteIp":  r.RemoteAddr,
			},
		}
	}
	if c == nil {
		log.Println("Error report used nil client:", payload)
		return
	}
	payload["serviceContext"] = c.serviceContext
	e := logging.Entry{
		Level:   logging.Error,
		Payload: payload,
	}
	err := c.loggingClient.LogSync(e)
	if err != nil {
		log.Println("Error writing error report:", err, "report:", payload)
	}
}
Example #2
0
// buildLogLine creates a common log format
// in addittion to the common fields, we also append referrer, user agent and request ID
func buildLogLine(l *responseLogger, r *http.Request, start time.Time) string {
	username := parseUsername(r)

	host, _, err := net.SplitHostPort(r.RemoteAddr)

	if err != nil {
		host = r.RemoteAddr
	}

	uri := r.URL.RequestURI()

	referer := r.Referer()

	userAgent := r.UserAgent()

	fields := []string{
		host,
		"-",
		detect(username, "-"),
		fmt.Sprintf("[%s]", start.Format("02/Jan/2006:15:04:05 -0700")),
		r.Method,
		uri,
		r.Proto,
		detect(strconv.Itoa(l.Status()), "-"),
		strconv.Itoa(l.Size()),
		detect(referer, "-"),
		detect(userAgent, "-"),
		r.Header.Get("Request-Id"),
	}

	return strings.Join(fields, " ")
}
Example #3
0
func (s *loggingSender) send(ctx context.Context, r *http.Request, message string) {
	payload := map[string]interface{}{
		"eventTime":      time.Now().In(time.UTC).Format(time.RFC3339Nano),
		"message":        message,
		"serviceContext": s.serviceContext,
	}
	if r != nil {
		payload["context"] = map[string]interface{}{
			"httpRequest": map[string]interface{}{
				"method":    r.Method,
				"url":       r.Host + r.RequestURI,
				"userAgent": r.UserAgent(),
				"referrer":  r.Referer(),
				"remoteIp":  r.RemoteAddr,
			},
		}
	}
	e := logging.Entry{
		Severity: logging.Error,
		Payload:  payload,
	}
	err := s.logger.LogSync(ctx, e)
	if err != nil {
		log.Println("Error writing error report:", err, "report:", payload)
	}
}
Example #4
0
func (b *BouncerHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
	reqParams := BouncerParamsFromValues(req.URL.Query())

	if reqParams.Product == "" {
		http.Redirect(w, req, "http://www.mozilla.org/", 302)
		return
	}

	if reqParams.OS == "" {
		reqParams.OS = DefaultOS
	}
	if reqParams.Lang == "" {
		reqParams.Lang = DefaultLang
	}

	isWinXpClient := isWindowsXPUserAgent(req.UserAgent())

	// If the client is not WinXP and attribution_code is set, redirect to the stub service
	if b.StubRootURL != "" &&
		reqParams.AttributionCode != "" &&
		reqParams.AttributionSig != "" &&
		!isWinXpClient {

		stubURL := b.stubAttributionURL(reqParams)
		http.Redirect(w, req, stubURL, 302)
		return
	}

	// HACKS
	// If the user is coming from windows xp or vista, send a sha1
	// signed product
	// HACKS
	if reqParams.OS == "win" && isWinXpClient {
		reqParams.Product = sha1Product(reqParams.Product)
	}

	url, err := b.URL(reqParams.Lang, reqParams.OS, reqParams.Product)
	if err != nil {
		http.Error(w, "Internal Server Error.", http.StatusInternalServerError)
		log.Println(err)
		return
	}
	if url == "" {
		http.NotFound(w, req)
		return
	}

	if b.CacheTime > 0 {
		w.Header().Set("Cache-Control", fmt.Sprintf("max-age=%d", b.CacheTime/time.Second))
	}

	// If ?print=yes, print the resulting URL instead of 302ing
	if reqParams.PrintOnly {
		w.Header().Set("Content-Type", "text/plain")
		w.Write([]byte(url))
		return
	}

	http.Redirect(w, req, url, 302)
}
Example #5
0
func (handler *Handler) ServeHTTP(writer http.ResponseWriter, request *http.Request) {
	logMsg := &RequestLog{actualResponseWriter: writer}
	logMsg.RequestHeaders = request.Header
	logMsg.Method = request.Method
	logMsg.Url = request.URL.String()
	logMsg.Host = request.Host
	logMsg.RemoteAddr = request.RemoteAddr
	logMsg.Referer = request.Referer()
	logMsg.UserAgent = request.UserAgent()
	handler.wrappedHandler.ServeHTTP(logMsg, request)
	// Get the resulting values
	if logMsg.ResponseCode == 0 {
		logMsg.ResponseCode = http.StatusOK
	}
	logMsg.ResponseHeaders = writer.Header()
	// Fire off the event to Forest Bus
	jsonMsg, err := json.Marshal(logMsg)
	if err == nil {
		sendErr := handler.msgBatcher.AsyncSendMessage(jsonMsg, nil, nil, handler.blockIfFull)
		if sendErr != nil {
			log.Printf("Warning: Error from AsyncSendMessage: %v\n", sendErr)
		}
	} else {
		log.Printf("Warning: Unable to marshal request information to JSON: %v\n", err)
	}
}
Example #6
0
func HandlerEiffageQueryPost(w http.ResponseWriter, r *http.Request) {
	log.Printf("Content-Type %s & Content-Length %d \n", r.Header.Get("Content-Type"), r.ContentLength)
	if r.Method == "POST" {
		b, err := ioutil.ReadAll(r.Body)
		if err != nil {
			log.Fatal("error handler: ", err)
		}
		//dont' write until you have read all the elements in the request
		log.Printf("User-Agent %s\n", r.UserAgent())
		log.Printf("Body %s\n", string(b))
		defer r.Body.Close()

		var resultFakeXml []byte
		if strings.Contains(string(b), "FROM Opportunity") {
			resultFakeXml = []byte(`
<result><records><sf:Id>123456</sf:Id><sf:OpportunityNumber__c>789012</sf:OpportunityNumber__c><sf:VP_ID__c>C3587C35-AFE8-4434-AD69-104C84025163</sf:VP_ID__c><sf:Name>Golang Salesforce Affaire</sf:Name></records></result>
				`)
		} else if strings.Contains(string(b), "FROM Ville__c") {
			resultFakeXml = []byte(`
<result><records><sf:Id>555666</sf:Id><sf:Name>NANTES</sf:Name><sf:Departement__c>44 - Loire-Atlantique</sf:Departement__c></records></result>
				`)
		}

		w.Write(resultFakeXml)
		log.Printf("xml_data %s\n", resultFakeXml)
		return
	}
}