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) } }
//EditTaskFunc is used to edit tasks, handles "/edit/" URL func EditTaskFunc(w http.ResponseWriter, r *http.Request) { if r.Method != "GET" { http.Redirect(w, r, "/", http.StatusBadRequest) return } id, err := strconv.Atoi(r.URL.Path[len("/edit/"):]) if err != nil { log.Println(err) http.Redirect(w, r, "/", http.StatusBadRequest) return } redirectURL := utils.GetRedirectUrl(r.Referer()) username := sessions.GetCurrentUserName(r) task, err := db.GetTaskByID(username, id) categories := db.GetCategories(username) task.Categories = categories task.Referer = redirectURL if err != nil { task.Message = "Error fetching Tasks" } editTemplate.Execute(w, task) }
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 Handle(w http.ResponseWriter, r *http.Request) { context := appengine.NewContext(r) now := time.Now() expire := now.AddDate(30, 0, 0) zcookie, _ := r.Cookie("z") if zcookie == nil { zcookie = &http.Cookie{} zcookie.Name = "z" zcookie.Value = make_hash("127.0.0.1", r.RemoteAddr, now.UnixNano()) zcookie.Expires = expire zcookie.Path = "/" zcookie.Domain = config.DOMAIN http.SetCookie(w, zcookie) } context.Infof("%s", zcookie.Value) w.Header().Set("Content-type", "image/gif") w.Header().Set("Cache-control", "no-cache, must-revalidate") w.Header().Set("Expires", "Sat, 26 Jul 1997 05:00:00 GMT") fmt.Fprintf(w, "%s", GIF) channel.Send(context, "pi", zcookie.Value+"\n"+r.RemoteAddr+"\n"+r.Referer()+"\n"+r.FormValue("r")+"\n"+r.UserAgent()) }
func Login(session sessions.Session, re render.Render, r *http.Request) { client_id := common.Config.OAuth2Client_ID letters := []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ") b := make([]rune, 10) for i := range b { b[i] = letters[rand.Intn(len(letters))] } session.AddFlash(string(b), "state") redirectBack := r.URL.Query().Get("redirect_back") ref := r.Referer() if redirectBack == "true" && ref != "" { session.Set("redirect_to", ref) } else { session.Set("redirect_to", nil) } query := url.Values{} query.Set("client_id", client_id) query.Set("state", string(b)) query.Set("scope", "repo") dest := url.URL{ Scheme: "https", Host: "github.com", Path: "/login/oauth/authorize", RawQuery: query.Encode(), } re.Redirect(dest.String()) }
func RedirectBack(w http.ResponseWriter, r *http.Request) { url := r.Referer() if url == "" { url = "/" } http.Redirect(w, r, url, http.StatusSeeOther) }
func loginPage(page *page, req *http.Request) { page.SetField("redirect", "/") page.SetField("success", false) switch req.Method { case "POST": page.SetField("redirect", req.FormValue("redirect")) if req.FormValue("password") != page.main.conf.Password() { page.AddMessage("Feil passord.") } else { err := page.main.auth.NewSession() if err != nil { page.Fatalf("Failed to create new session: %s", err.Error()) } http.SetCookie(page, &http.Cookie{ Name: "session-id", Value: page.main.auth.SessionID(), HttpOnly: true, }) page.AddMessage("Innloggin vellykket.") page.SetField("success", true) } case "GET": referrer := req.URL.Query().Get("redirect") if referrer == "" { referrer = req.Referer() } if referrer != "" { page.SetField("redirect", referrer) } } page.ExecuteTemplate("login") }
func UserLoginHandler(ctx context.Context, rw http.ResponseWriter, r *http.Request) { if !cas.IsAuthenticated(r) { // save the referrer sessionmw.Set(ctx, CASReferrer, r.Referer()) // shut off rendering dataRenderer := data.FromContext(ctx) dataRenderer.Type = data.DataNoRender // and redirect cas.RedirectToLogin(rw, r) } else { // get the referrer referrer, has := sessionmw.Get(ctx, CASReferrer) sessionmw.Delete(ctx, CASReferrer) // shut off rendering dataRenderer := data.FromContext(ctx) dataRenderer.Type = data.DataNoRender // and redirect if !has { http.Redirect(rw, r, render.ConvertURL("/"), http.StatusTemporaryRedirect) } else { http.Redirect(rw, r, referrer.(string), http.StatusTemporaryRedirect) } } }
func (p *post) processForm(r *http.Request) error { p.Date = time.Now() p.Subject = "Message submitted through " + r.Referer() if r.Form.Get("email") != "" { p.Replyto = r.Form.Get("email") } for k, v := range r.Form { if k == "_replyto" { p.Replyto = v[0] continue } if k == "_next" { p.Next = v[0] continue } if k == "_subject" { p.Subject = v[0] continue } if k == "_cc" { p.CC = v continue } p.Content[k] = v } return nil }
func LoginHandler(w http.ResponseWriter, r *http.Request) { ref := r.Referer() if ref == "" { ref = "localhost" } service := service.NewMembershipService() service.Init(ref) m := r.Method if m != "POST" { server.JsonErr(w, errors.New("must POST when logging in")) } dec := json.NewDecoder(r.Body) var reg models.Registration err := dec.Decode(reg) if err != nil { server.JsonErr(w, err) return } reg, err = service.Login(reg) if err != nil { server.JsonErr(w, err) } server.Json(w, reg) return }
// 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()) }
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) } }
func NewContext(req *http.Request) (*Context, error) { sess, err := store.Get(req, Settings.Session.Name) sess.Options.Domain = Settings.Session.Domain sess.Options.HttpOnly = true var ( lastUid string user *User ) if v, ok := sess.Values[kLastUid]; ok { lastUid = v.(string) } if v, ok := sess.Values[kUserOL]; ok { user = v.(*User) } referer := req.FormValue("referer") if referer == "" { referer = req.Referer() } ctx := &Context{ Vars: mux.Vars(req), Session: sess, ResUrl: Settings.ResUrl, Referer: referer, Version: VERSION, LastUid: lastUid, User: user, } if err != nil { log.Printf("new context error: %s", err) return ctx, err } return ctx, err }
func NewContext(app *App, res http.ResponseWriter, req *http.Request) *Context { c := new(Context) c.app = app c.IsSend = false c.IsEnd = false c.Request = req c.Url = req.URL.Path c.RequestUrl = req.RequestURI c.Method = req.Method c.Host = req.Host c.Ip = strings.Split(req.RemoteAddr, ":")[0] c.IsAjax = req.Header.Get("X-Requested-With") == "XMLHttpRequest" c.IsSSH = req.TLS == nil c.UserAgent = req.UserAgent() c.Referer = req.Referer() c.eventsFunc = make(map[string][]reflect.Value) c.BaseUrl = "://" + c.Host + "/" if c.IsSSH { c.BaseUrl = "https" + c.BaseUrl } else { c.BaseUrl = "http" + c.BaseUrl } c.Response = res c.Status = 200 c.Header = make(map[string]string) c.Header["Content-Type"] = "text/html;charset=UTF-8" req.ParseForm() return c }
// assetView handles the requested assets. // request /doc/gopher/pkg.png // referer http://localhost:8000/?view=https://golang.org/pkg/ // returns https://golang.org/doc/gopher/pkg.png func assetView(r *http.Request) (v string) { referer := r.Referer() if referer == "" { return } refererURL, err := url.Parse(referer) if err != nil { return } if refererURL.Host != r.Host { return } view := refererURL.Query().Get("view") if view == "" { return } baseView, err := url.Parse(view) if err != nil { return } nextView, err := baseView.Parse(r.URL.Path) if err != nil { return } v = nextView.String() return }
func (controller *ShawtyJSController) ServeHTTP(w http.ResponseWriter, r *http.Request) { defer closeReqBody(r) var u = r.FormValue("url") if u == "" { u = r.Referer() if u != "" { // if it's in the referer then we don't want the browser to cache this w.Header().Set("Cache-Control", "no-cache") http.Redirect(w, r, "shawty.js?url="+url.QueryEscape(u), http.StatusTemporaryRedirect) return } else { http.NotFound(w, r) return } } res := controller.GetJSResponse(u, utils.HttpRemoteIP(r), r.FormValue("bm") == "1") tpl := getShawtyJs() w.Header().Set("Content-Type", "application/javascript") if err := tpl.Execute(w, res); err != nil { log.Error("Cannot execute shawty javascript template") log.Error(err) http.Error(w, "Error", http.StatusInternalServerError) } }
//TrashTaskFunc is used to populate the trash tasks func TrashTaskFunc(w http.ResponseWriter, r *http.Request) { //for best UX we want the user to be returned to the page making //the delete transaction, we use the r.Referer() function to get the link var redirectUrl string redirect := strings.Split(r.Referer(), "/") index := len(redirect) - 1 if len(redirect) == 4 { redirectUrl = "/" } else { redirectUrl = redirect[index] } if r.Method == "GET" { id, err := strconv.Atoi(r.URL.Path[len("/trash/"):]) if err != nil { log.Println("TrashTaskFunc", err) http.Redirect(w, r, redirectUrl, http.StatusBadRequest) } else { err = db.TrashTask(id) if err != nil { message = "Error trashing task" } else { message = "Task trashed" } http.Redirect(w, r, redirectUrl, http.StatusFound) } } else { message = "Method not allowed" http.Redirect(w, r, redirectUrl, http.StatusFound) } }
// 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(), )) }
// 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 (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) }
func Shorten(w http.ResponseWriter, r *http.Request) { u := url.URL{ Scheme: "https", Host: "www.googleapis.com", Path: "/urlshortener/v1/url", } if schedule.Conf.ShortURLKey != "" { u.RawQuery = "key=" + schedule.Conf.ShortURLKey } j, err := json.Marshal(struct { LongURL string `json:"longUrl"` }{ r.Referer(), }) if err != nil { serveError(w, err) return } req, err := http.Post(u.String(), "application/json", bytes.NewBuffer(j)) if err != nil { serveError(w, err) return } io.Copy(w, req.Body) req.Body.Close() }
func Api(w http.ResponseWriter, r *http.Request) (*models.Page, int) { err := r.ParseMultipartForm(1000) if err != nil { fmt.Println("Error when parse POST data: " + err.Error()) } user_cookie, err := r.Cookie("UserID") if err != nil { fmt.Println("Trying to save data with API from non-user. Error: " + err.Error()) return nil, 404 } user_id, _ := strconv.Atoi(user_cookie.Value) user, _ := models.GetUserByID(user_id) if user.Role != "admin" { fmt.Println("Trying to save data with API from not admin user. Error: " + err.Error()) return nil, 404 } url_parts := strings.Split(strings.Trim(r.Referer(), "/"), "/") post, _ := models.GetPageByUrl(url_parts[len(url_parts)-1]) post.Content = r.MultipartForm.Value["content"][0] post.Title = r.MultipartForm.Value["title"][0] post.Description = r.MultipartForm.Value["description"][0] post.Save() return nil, 200 }
// 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, ) }
// Create a customer for a // given shop. func AddAccount(w http.ResponseWriter, req *http.Request, params martini.Params, enc encoding.Encoder, shop *cart.Shop) string { var c cart.Customer defer req.Body.Close() data, err := ioutil.ReadAll(req.Body) if err != nil { apierror.GenerateError(err.Error(), err, w, req) return "" } if err = json.Unmarshal(data, &c); err != nil { apierror.GenerateError(err.Error(), err, w, req) return "" } c.ShopId = shop.Id if err = c.Insert(req.Referer()); err != nil { apierror.GenerateError(err.Error(), err, w, req) return "" } return encoding.Must(enc.Encode(c)) }
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 }
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) }
// 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, " ") }
func (b *Brog) setLangCookie(req *http.Request, rw http.ResponseWriter) { lang := req.URL.RawQuery _, err := req.Cookie("lang") if lang != "" && (err != nil || strings.HasSuffix(req.Referer(), "/changelang")) { rw.Header().Add("Set-Cookie", "lang="+lang) } }
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: ×tamp.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) } }
func handler(w http.ResponseWriter, r *http.Request) { fmt.Fprintf(w, "URL: %s\n", r.URL.Path) fmt.Fprintf(w, "Method: %s\n", r.Method) fmt.Fprintf(w, "Protocol: %s, Major: %v, Minor: %v\n", r.Proto, r.ProtoMajor, r.ProtoMinor) fmt.Fprintf(w, "Host: %s\n", r.Host) fmt.Fprintf(w, "Remote Address: %s\n", r.RemoteAddr) // Remote Address that sent this request (IP:port) fmt.Fprintf(w, "Headers: %v\n", r.Header) fmt.Fprintf(w, "User Agent: %s\n", r.UserAgent()) // As set in the header fmt.Fprintf(w, "Referrer: %s\n", r.Referer()) // As set in the header // Form data (GET, POST) r.ParseForm() // r.Form will be filled by this function // r.Form contain GET, POST, PUT paramters all combined fmt.Fprintf(w, "URL Parameters: %v\n", r.Form) // Parsed Form data // Try this: http://localhost:8080/?test=asdasd&test=qwerty // NOTE: The duplicate parameters are appended instead of overwritten to Form.. // However, FormValue() returns the 1st found value, which is generally preferable fmt.Fprintf(w, "Test Parameters: %v, %v\n", r.Form["test"], r.FormValue("test")) // TODO: To distinguish GET and POST parameters, @see http://code.google.com/p/go/issues/detail?id=3630 // Reading cookie fmt.Fprintf(w, "All cookies: %v\n", r.Cookies()) // Get all cookies testCookie, err := r.Cookie("test") // Get cookie with the given name. err = ErrNoCookie, if cookie not found fmt.Fprintf(w, "Cookie with name test: %v, err = %v, isErrNoCookie=%v\n", testCookie, err, err == http.ErrNoCookie) }