Exemple #1
4
func writeFileResponse(filename string, bytes []byte, w http.ResponseWriter, r *http.Request) *model.AppError {
	w.Header().Set("Cache-Control", "max-age=2592000, public")
	w.Header().Set("Content-Length", strconv.Itoa(len(bytes)))
	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()

	parts := strings.Split(filename, "/")
	filePart := strings.Split(parts[len(parts)-1], "?")[0]
	w.Header().Set("Content-Disposition", "attachment;filename=\""+filePart+"\"")

	if bname == "Edge" || bname == "Internet Explorer" || bname == "Safari" {
		w.Header().Set("Content-Type", "application/octet-stream")
	}

	// prevent file links from being embedded in iframes
	w.Header().Set("X-Frame-Options", "DENY")
	w.Header().Set("Content-Security-Policy", "Frame-ancestors 'none'")

	w.Write(bytes)

	return nil
}
Exemple #2
1
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)
	}
}
Exemple #3
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)
	}
}
Exemple #4
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, " ")
}
Exemple #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)
	}
}
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)
}
Exemple #7
0
// ServeHTTP wraps the http.Request and http.ResponseWriter to log to standard
// output and pass through to the underlying http.Handler.
func (al *ApacheLogger) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	aw := &apacheLoggerResponseWriter{ResponseWriter: w}
	al.handler.ServeHTTP(aw, r)
	remoteAddr := r.RemoteAddr
	if index := strings.LastIndex(remoteAddr, ":"); index != -1 {
		remoteAddr = remoteAddr[:index]
	}
	referer := r.Referer()
	if "" == referer {
		referer = "-"
	}
	userAgent := r.UserAgent()
	if "" == userAgent {
		userAgent = "-"
	}
	username, _, _ := httpBasicAuth(r.Header)
	if "" == username {
		username = "******"
	}
	al.Printf(
		"%s %s %s [%v] \"%s %s %s\" %d %d \"%s\" \"%s\"\n",
		remoteAddr,
		"-", // We're not supporting identd, sorry.
		username,
		time.Now().Format("02/Jan/2006:15:04:05 -0700"),
		r.Method,
		r.RequestURI,
		r.Proto,
		aw.StatusCode,
		aw.Size,
		referer,
		userAgent,
	)
}
Exemple #8
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
	}
}
Exemple #9
0
func (h *ApacheLoggingHandler) ServeHTTP(rw http.ResponseWriter, r *http.Request) {
	clientIP := r.RemoteAddr
	if colon := strings.LastIndex(clientIP, ":"); colon != -1 {
		clientIP = clientIP[:colon]
	}

	record := &ApacheLogRecord{
		ResponseWriter: rw,
		ip:             clientIP,
		time:           time.Time{},
		method:         r.Method,
		uri:            r.RequestURI,
		protocol:       r.Proto,
		status:         http.StatusOK,
		referrer:       r.Referer(),
		userAgent:      r.UserAgent(),
		elapsedTime:    time.Duration(0),
	}

	startTime := time.Now()
	h.handler.ServeHTTP(record, r)
	finishTime := time.Now()

	record.time = finishTime.UTC()
	record.elapsedTime = finishTime.Sub(startTime)

	record.Log(h.out)
}
Exemple #10
0
func IsMobile(r *http.Request) bool {
	ua := r.UserAgent()
	if strings.Index(ua, "Mobile") != -1 || strings.Index(ua, "Android") != -1 {
		return true
	}
	return false
}
Exemple #11
0
func (n *Notice) SetValueFromRequest(req *http.Request) {
	if n.Request == nil {
		n.Request = &Request{}
	}
	n.Request.Url = req.URL.String()
	n.Request.AddCgiKeyValue("SERVER_SOFTWARE", "go")
	n.Request.AddCgiKeyValue("PATH_INFO", req.URL.Path)
	n.Request.AddCgiKeyValue("HTTP_HOST", req.Host)
	n.Request.AddCgiKeyValue("GATEWAY_INTERFACE", "CGI/1.1")
	n.Request.AddCgiKeyValue("REQUEST_METHOD", req.Method)
	n.Request.AddCgiKeyValue("QUERY_STRING", req.URL.RawQuery)
	n.Request.AddCgiKeyValue("REQUEST_URI", req.URL.RequestURI())
	n.Request.AddCgiKeyValue("REMOTE_ADDR", req.RemoteAddr)
	n.Request.AddCgiKeyValue("REMOTE_HOST", req.RemoteAddr)
	n.Request.AddCgiKeyValue("HTTP_ACCEPT", req.Header.Get("Accept-Encoding"))
	n.Request.AddCgiKeyValue("HTTP_USER_AGENT", req.UserAgent())
	env := os.Environ()
	for _, val := range env {
		pair := strings.Split(val, "=")
		if len(pair) < 2 {
			continue
		}
		if strings.Index(pair[0], "_KEY") >= 0 {
			continue
		}
		n.Request.AddCgiKeyValue(pair[0], pair[1])
	}
}
Exemple #12
0
func isBanned(r *http.Request) bool {
	ctx := req2ctx(r)
	cdb := complaintdb.NewDB(ctx)
	u := user.Current(cdb.Ctx())
	userWhitelist := map[string]int{
		"*****@*****.**":    1,
		"*****@*****.**": 1,
		"*****@*****.**":  1,
		"*****@*****.**": 1,
	}

	reqBytes, _ := httputil.DumpRequest(r, true)

	cdb.Infof("remoteAddr: '%v'", r.RemoteAddr)
	cdb.Infof("user: '******' (%s)", u, u.Email)
	cdb.Infof("inbound IP determined as: '%v'", getIP(r))
	cdb.Infof("HTTP req:-\n%s", string(reqBytes))

	if strings.HasPrefix(r.UserAgent(), "python") {
		cdb.Infof("User-Agent rejected")
		return true
	}
	if _, exists := userWhitelist[u.Email]; !exists {
		cdb.Infof("user not found in whitelist")
		return true
	}
	return false
}
Exemple #13
0
func (h handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	// From https://en.wikipedia.org/wiki/Common_Log_Format
	//
	// 127.0.0.1 user-identifier frank [10/Oct/2000:13:55:36 -0700] "GET /apache_pb.gif HTTP/1.0" 200 2326
	const format = "%s - - [%s] \"%s %s %s\" %d %d \"%s\" \"%s\""
	const layout = "2/Jan/2006:15:04:05 -0700"

	userAgent := "-"
	if agent := r.UserAgent(); agent != "" {
		userAgent = agent
	}
	referer := "-"
	if ref := r.Referer(); ref != "" {
		referer = ref
	}

	shim := responseWriter{ResponseWriter: w}

	//start := time.Now()
	h.handler.ServeHTTP(&shim, r)
	end := time.Now()

	h.logf(format,
		strings.Split(r.RemoteAddr, ":")[0],
		end.Format(layout),
		r.Method,
		r.URL.RequestURI(),
		r.Proto,
		shim.status,
		shim.n,
		referer,
		userAgent)
}
Exemple #14
0
// LoggerMiddleware log each request using
// comman log format
func LoggerMiddleware(c *Container, rw http.ResponseWriter, r *http.Request, next func()) {
	rw.(ResponseWriterExtra).SetLogger(c.MustGetLogger())
	start := time.Now()
	next()

	// @see https://en.wikipedia.org/wiki/Common_Log_Format for log format
	// @see http://httpd.apache.org/docs/1.3/logs.html#combined
	c.MustGetLogger().Info(
		fmt.Sprintf("%s %s %s [%s] \"%s %s %s\" %d %d \"%s\" \"%s\"",
			r.RemoteAddr,
			func() string {
				if c.CurrentUser() != nil {
					return fmt.Sprintf("%d", c.CurrentUser().ID)
				}
				return "-"
			}(),
			func() string {
				if c.CurrentUser() != nil {
					return c.CurrentUser().Username
				}
				return "-"
			}(),
			start.Format("Jan/02/2006:15:04:05 -0700 MST"),
			r.Method,
			r.RequestURI,
			r.Proto,
			c.ResponseWriter().Status(),
			rw.(ResponseWriterExtra).GetCurrentSize(),
			r.Referer(),
			r.UserAgent(),
		))

}
Exemple #15
0
// Log is show viwer log.
func Log(req *http.Request) {
	var userIP string
	if userIP = req.Header.Get("X-FORWARDED-FOR"); userIP == "" {
		userIP = req.RemoteAddr
	}
	log.Println(req.URL, userIP, req.UserAgent(), req.Form, req.Referer())
}
Exemple #16
0
// PrefersHTML returns true if the request was made by something that looks like a browser, or can receive HTML
func PrefersHTML(req *http.Request) bool {
	accepts := goautoneg.ParseAccept(req.Header.Get("Accept"))
	acceptsHTML := false
	acceptsJSON := false
	for _, accept := range accepts {
		if accept.Type == "text" && accept.SubType == "html" {
			acceptsHTML = true
		} else if accept.Type == "application" && accept.SubType == "json" {
			acceptsJSON = true
		}
	}

	// If HTML is accepted, return true
	if acceptsHTML {
		return true
	}

	// If JSON was specifically requested, return false
	// This gives browsers a way to make requests and add an "Accept" header to request JSON
	if acceptsJSON {
		return false
	}

	// In Intranet/Compatibility mode, IE sends an Accept header that does not contain "text/html".
	if strings.HasPrefix(req.UserAgent(), "Mozilla") {
		return true
	}

	return false
}
Exemple #17
0
// Creates a new session
func (store *BASessionStore) New(w http.ResponseWriter, r *http.Request) *BASession {

	random := make([]byte, 16)
	rand.Read(random)
	currentTime := strconv.FormatInt(time.Now().UnixNano(), 10)
	ip := net.ParseIP(r.Header["X-Real-Ip"][0]).String()
	userAgent := r.UserAgent()

	plaintext := []byte(cfg.HTTPServer.SessionIDSalt + "|" + fmt.Sprintf("%x", string(random[:])) + "|" + currentTime + "|" + ip + "|" + userAgent)
	sessionID := fmt.Sprintf("%x", sha1.Sum(plaintext))

	//log.Printf("BASessionStore New(): generated session ID: %s", sessionID)

	cookie := &http.Cookie{
		Name:    SESSION_ID_COOKIE_NAME,
		Value:   sessionID,
		Domain:  SESSION_ID_COOKIE_DOMAIN,
		Path:    "/",
		Expires: time.Now().Add(24 * time.Hour),
	}
	http.SetCookie(w, cookie)

	return &BASession{
		MemcachedClient: store.MemcachedClient,
		Id:              sessionID,
	}
}
Exemple #18
0
func HomeHandler(w http.ResponseWriter, r *http.Request) {
	log.Println("Responsing to home request")
	log.Println(r.UserAgent())

	w.WriteHeader(http.StatusOK)
	fmt.Fprintln(w, "Hello:")
}
Exemple #19
0
// respond builds a Collection+JSON body and sends it to the client
func respond(code int, response interface{}, respWriter http.ResponseWriter, r *http.Request) (err error) {
	defer func() {
		if e := recover(); e != nil {
			ctx.Channels.Log <- mig.Log{OpID: getOpID(r), Desc: fmt.Sprintf("%v", e)}.Err()
		}
		ctx.Channels.Log <- mig.Log{OpID: getOpID(r), Desc: "leaving respond()"}.Debug()
	}()
	var body []byte
	// if the response is a cljs resource, marshal it, other treat it as a slice of bytes
	if _, ok := response.(*cljs.Resource); ok {
		body, err = response.(*cljs.Resource).Marshal()
		if err != nil {
			panic(err)
		}
	} else {
		body = []byte(response.([]byte))
	}

	respWriter.Header().Set("Content-Type", "application/json")
	respWriter.Header().Set("Cache-Control", "no-cache")
	respWriter.WriteHeader(code)
	respWriter.Write(body)

	ctx.Channels.Log <- mig.Log{
		OpID: getOpID(r),
		Desc: fmt.Sprintf("src=%s auth=[%s %.0f] %s %s %s resp_code=%d resp_size=%d user-agent=%s",
			remoteAddresses(r), getInvName(r), getInvID(r), r.Method, r.Proto,
			r.URL.String(), code, len(body), r.UserAgent()),
	}
	return
}
Exemple #20
0
func DeleteHandler(w http.ResponseWriter, r *http.Request) {
	n := new(storage.Needle)
	vid, fid, _ := parseURLPath(r.URL.Path)
	volumeId, _ := strconv.ParseUint(vid, 10, 64)
	n.ParsePath(fid)

	if *IsDebug {
		log.Info("deleting", n)
	}

	cookie := n.Cookie
	count, ok := store.Read(volumeId, n)

	if ok != nil {
		m := make(map[string]uint32)
		m["size"] = 0
		writeJson(w, r, m)
		return
	}

	if n.Cookie != cookie {
		log.Info("delete with unmaching cookie from ", r.RemoteAddr, "agent", r.UserAgent())
		return
	}

	n.Size = 0
	store.Delete(volumeId, n)
	m := make(map[string]uint32)
	m["size"] = uint32(count)
	writeJson(w, r, m)
}
Exemple #21
0
func debugHandler(w http.ResponseWriter, r *http.Request) {
	var (
		err        error
		debug_info *DebugInfo
	)

	debug := r.PostFormValue("debug")

	if len(debug) == 0 {
		http.Error(w, "No debug information received.", http.StatusBadRequest)
		return
	}

	debug_info = &DebugInfo{}

	err = json.Unmarshal([]byte(debug), debug_info)
	if err != nil {
		http.Error(w, "Invalid debug information.", http.StatusBadRequest)
		return
	}

	//set current time
	debug_info.ReceivedAt = time.Now()
	debug_info.UserAgent = r.UserAgent()

	err = debug_collection.Insert(debug_info)
	if err != nil {
		log.Println(err)
	}

	//No need to return any content
	http.Error(w, "No content", http.StatusNoContent)
}
Exemple #22
0
func NewHttpStart(req *http.Request, peerType events.PeerType, requestId *uuid.UUID) *events.HttpStart {
	httpStart := &events.HttpStart{
		Timestamp:     proto.Int64(time.Now().UnixNano()),
		RequestId:     NewUUID(requestId),
		PeerType:      &peerType,
		Method:        events.HttpStart_Method(events.HttpStart_Method_value[req.Method]).Enum(),
		Uri:           proto.String(fmt.Sprintf("%s%s", req.Host, req.URL.Path)),
		RemoteAddress: proto.String(req.RemoteAddr),
		UserAgent:     proto.String(req.UserAgent()),
	}

	if applicationId, err := uuid.ParseHex(req.Header.Get("X-CF-ApplicationID")); err == nil {
		httpStart.ApplicationId = NewUUID(applicationId)
	}

	if instanceIndex, err := strconv.Atoi(req.Header.Get("X-CF-InstanceIndex")); err == nil {
		httpStart.InstanceIndex = proto.Int(instanceIndex)
	}

	if instanceId := req.Header.Get("X-CF-InstanceID"); instanceId != "" {
		httpStart.InstanceId = &instanceId
	}

	return httpStart
}
Exemple #23
0
func newRequest(hr *http.Request, hc http.ResponseWriter) *Request {

	remoteAddr, _ := net.ResolveTCPAddr("tcp", hr.RemoteAddr)

	maps := make(map[string]string)
	for _, v := range hr.Cookies() {
		maps[v.Name] = v.Value
	}

	req := Request{
		Method:     hr.Method,
		URL:        hr.URL,
		Proto:      hr.Proto,
		ProtoMajor: hr.ProtoMajor,
		ProtoMinor: hr.ProtoMinor,
		Headers:    hr.Header,
		Body:       hr.Body,
		Close:      hr.Close,
		Host:       hr.Host,
		Referer:    hr.Referer(),
		UserAgent:  hr.UserAgent(),
		FullParams: hr.Form,
		Cookie:     hr.Cookies(),
		Cookies:    maps,
		RemoteAddr: remoteAddr.IP.String(),
		RemotePort: remoteAddr.Port,
	}
	return &req
}
Exemple #24
0
func (c *AccountCtrl) Signin(w http.ResponseWriter, r *http.Request, _ map[string]string) {
	var credentials Credentials

	err := json.NewDecoder(r.Body).Decode(&credentials)
	if err != nil {
		c.render.JSONError(w, http.StatusBadRequest, apierrors.BodyDecodingError, err)
		return
	}

	if credentials.Password == "" {
		c.render.JSONError(w, http.StatusBadRequest, apierrors.BlankParam("password"), err)
		return
	}

	if credentials.Email == "" {
		c.render.JSONError(w, http.StatusBadRequest, apierrors.BlankParam("email"), err)
		return
	}

	session, err := c.guestInter.Signin(r.RemoteAddr, r.UserAgent(), &credentials)
	if err != nil {
		c.render.JSONError(w, http.StatusUnauthorized, apierrors.InvalidCredentials, err)
		return
	}

	cookie := http.Cookie{Name: "authToken", Value: session.AuthToken, Expires: session.ValidTo, Path: "/"}
	http.SetCookie(w, &cookie)

	session.BeforeRender()
	c.render.JSON(w, http.StatusCreated, session)
}
func StatusHandler(w http.ResponseWriter, r *http.Request) {
	var m = map[string]interface{}{
		"status":  "ok",
		"ts":      time.Now().UnixNano() / 1000000,
		"version": "1.0",
		"webStatus": map[string]interface{}{
			"version":         version,
			"pid":             os.Getpid(),
			"proto":           r.Proto,
			"host":            r.Host,
			"path":            r.URL.Path,
			"agent":           r.UserAgent(),
			"remoteAddr":      r.RemoteAddr,
			"xForwardedFor":   r.Header.Get("X-Forwarded-For"),
			"xForwardedProto": r.Header.Get("X-Forwarded-Proto"),
		},
	}

	json, err := json.Marshal(m)

	if err != nil {
		fmt.Fprintf(w, "json error\r\n")
	} else {
		headers := w.Header()
		headers.Set("Content-Type", "application/json")
		log.Debug("headers: %v", headers)

		w.Write(json)
		w.Write([]byte("\r\n"))
	}
}
Exemple #26
0
// buildLogLine creates a common log format
// in addition to the common fields, we also append referrer, user agent,
// request ID and response time (microseconds)
//  ie, in apache mod_log_config terms:
//     %h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-agent}i\"" %L %D
func buildLogLine(l *responseLogger, r *http.Request, start time.Time) string {

	redactPassword(r)

	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()

	return fmt.Sprintf(`%s - %s [%s] "%s %s %s" %s %s "%s" "%s" %s %d`,
		host,
		detect(username, "-"),
		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"),
		// response time, report in microseconds because this is consistent
		// with apache's %D parameter in mod_log_config
		int64(time.Since(start)/time.Microsecond))
}
func NewHttpStartStop(req *http.Request, statusCode int, contentLength int64, peerType events.PeerType, requestId *uuid.UUID) *events.HttpStartStop {
	now := proto.Int64(time.Now().UnixNano())
	httpStartStop := &events.HttpStartStop{
		StartTimestamp: now,
		StopTimestamp:  now,
		RequestId:      NewUUID(requestId),
		PeerType:       &peerType,
		Method:         events.Method(events.Method_value[req.Method]).Enum(),
		Uri:            proto.String(fmt.Sprintf("%s://%s%s", scheme(req), req.Host, req.URL.Path)),
		RemoteAddress:  proto.String(req.RemoteAddr),
		UserAgent:      proto.String(req.UserAgent()),
		StatusCode:     proto.Int(statusCode),
		ContentLength:  proto.Int64(contentLength),
	}

	if applicationId, err := uuid.ParseHex(req.Header.Get("X-CF-ApplicationID")); err == nil {
		httpStartStop.ApplicationId = NewUUID(applicationId)
	}

	if instanceIndex, err := strconv.Atoi(req.Header.Get("X-CF-InstanceIndex")); err == nil {
		httpStartStop.InstanceIndex = proto.Int(instanceIndex)
	}

	if instanceId := req.Header.Get("X-CF-InstanceID"); instanceId != "" {
		httpStartStop.InstanceId = proto.String(instanceId)
	}

	allForwards := req.Header[http.CanonicalHeaderKey("X-Forwarded-For")]
	for _, forwarded := range allForwards {
		httpStartStop.Forwarded = append(httpStartStop.Forwarded, parseXForwarded(forwarded)...)
	}

	return httpStartStop
}
Exemple #28
0
func (h *TestHandler) ServeHTTP(w http.ResponseWriter, hr *http.Request) {
	h.hit()
	w.Header().Set("Access-Control-Allow-Origin", "*")
	w.Header().Set("Access-Control-Request-Method", "GET")

	fmt.Println("\n=== TestHandler : Requete reçue ====================")
	fmt.Println(" Method : " + hr.Method)
	//~ fmt.Println(" URL : " + hr.RawURL)
	fmt.Println(" Proto : " + hr.Proto)
	fmt.Printf(" ContentLength : %d\n", hr.ContentLength)
	fmt.Println(" UserAgent : " + hr.UserAgent())
	fmt.Println(" Header :")
	for key, value := range hr.Header {
		fmt.Printf("  %s=%v\n", key, value)
	}

	b, e := ioutil.ReadAll(hr.Body)
	if e != nil {
		fmt.Println("Erreur lecture :")
		fmt.Println(e)
	}
	s := string(b)
	fmt.Print(s)

	fmt.Fprint(w, "Bien reçu")
}
Exemple #29
0
func (s *errorApiSender) send(ctx context.Context, r *http.Request, message string) {
	time := time.Now()
	var errorContext *erpb.ErrorContext
	if r != nil {
		errorContext = &erpb.ErrorContext{
			HttpRequest: &erpb.HttpRequestContext{
				Method:    r.Method,
				Url:       r.Host + r.RequestURI,
				UserAgent: r.UserAgent(),
				Referrer:  r.Referer(),
				RemoteIp:  r.RemoteAddr,
			},
		}
	}
	req := erpb.ReportErrorEventRequest{
		ProjectName: s.projectID,
		Event: &erpb.ReportedErrorEvent{
			EventTime: &timestamp.Timestamp{
				Seconds: time.Unix(),
				Nanos:   int32(time.Nanosecond()),
			},
			ServiceContext: &s.serviceContext,
			Message:        message,
			Context:        errorContext,
		},
	}
	_, err := s.apiClient.ReportErrorEvent(ctx, &req)
	if err != nil {
		log.Println("Error writing error report:", err, "report:", message)
	}
}
Exemple #30
0
func rootFunc(w http.ResponseWriter, r *http.Request) {

	g := Load()

	l := log551.New(&g.config.Framework.SystemLog)
	l.Open()
	defer l.Close()

	cookie := cookie551.New(w, r)

	sid := g.sid(cookie)
	l.Debugf("%s SID: %s", sid[:10], sid)
	session := memcache551.New(&g.config.Framework.Session.Server, sid)

	route := g.router.FindRouteByPathMatch(r.Method, r.URL.Path)
	response551.UrlFunction = g.router.Url

	var data interface{} = nil
	if route != nil {
		mysql := mysql551.New(&g.config.Framework.Database)
		mysql.Open()
		defer mysql.Close()

		l.Debugf("%s --[ Routing ]--", sid[:10])
		l.Debugf("%s Path: %s", sid[:10], r.URL.Path)
		l.Debugf("%s Neme: %s", sid[:10], route.Name())

		c := container551.New()
		c.SetSID(sid)
		c.SetResponseWriter(w)
		c.SetRequest(r)
		c.SetLogger(l)
		c.SetCookie(cookie)
		c.SetDb(mysql)
		c.SetSession(session)
		c.SetModel(g.modelManager)
		c.SetAuth(g.auth)
		c.SetUrlFunc(g.router.Url)

		baseUrl := "https://" + g.config.Framework.WebServerSSL.Host
		if g.config.Framework.WebServerSSL.Port != "443" {
			baseUrl = baseUrl + ":" + g.config.Framework.WebServerSSL.Port
		}
		c.SetBaseURL(baseUrl)
		response551.BaseUrl = baseUrl

		action := route.Action()
		data = action(c)
		response551.Response(w, r, data, route.PackageName(), route.Name(), c.User(), g.config.Application)
	} else {
		l.Errorf("%s --[ Route not found ]--", sid[:10])
		l.Errorf("%s UA:     %s", sid[:10], r.UserAgent())
		l.Errorf("%s Method: %s", sid[:10], r.Method)
		l.Errorf("%s Path:   %s", sid[:10], r.URL.Path)
		l.Errorf("%s --[/Route not found ]--", sid[:10])
		data = response551.Error(404, "Route not found.")
		response551.Response(w, r, data, "", "", nil, g.config.Application)
	}

}