当前位置: 首页>>代码示例>>Golang>>正文


Golang Request.RemoteAddr方法代码示例

本文整理汇总了Golang中net/http.Request.RemoteAddr方法的典型用法代码示例。如果您正苦于以下问题:Golang Request.RemoteAddr方法的具体用法?Golang Request.RemoteAddr怎么用?Golang Request.RemoteAddr使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在net/http.Request的用法示例。


在下文中一共展示了Request.RemoteAddr方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。

示例1: readRequest

// Read next request from connection.
func (c *conn) readRequest() (r *request, w *response, err error) {
	if c.hijacked {
		return nil, nil, ErrHijacked
	}
	c.lr.N = int64(c.server.maxHeaderBytes()) + 4096 /* bufio slop */
	var req *http.Request
	if req, err = http.ReadRequest(c.buf.Reader); err != nil {
		if c.lr.N == 0 {
			return nil, nil, errTooLarge
		}
		return nil, nil, err
	}
	c.lr.N = noLimit

	req.RemoteAddr = c.remoteAddr

	w = new(response)
	w.conn = c

	r = new(request)
	r.Request = req
	r.w = w

	w.reqWantsHttp10KeepAlive = r.wantsHttp10KeepAlive()
	w.reqMethod = r.Method
	w.reqProtoAtLeast10 = r.ProtoAtLeast(1, 0)
	w.reqProtoAtLeast11 = r.ProtoAtLeast(1, 1)
	w.reqExpectsContinue = r.expectsContinue()
	w.reqContentLength = r.ContentLength

	w.header = make(http.Header)
	w.contentLength = -1
	return r, w, nil
}
开发者ID:ndzj081221130,项目名称:router-src,代码行数:35,代码来源:server.go

示例2: handleFilteredHTTP

func handleFilteredHTTP(w http.ResponseWriter, r *http.Request) {
	// Patch up RemoteAddr so it looks reasonable.
	if addr := r.Header.Get("X-Appengine-Internal-Remote-Addr"); addr != "" {
		r.RemoteAddr = addr
	} else {
		// Should not normally reach here, but pick
		// a sensible default anyway.
		r.RemoteAddr = "127.0.0.1"
	}

	// Create a private copy of the Request that includes headers that are
	// private to the runtime and strip those headers from the request that the
	// user application sees.
	creq := *r
	r.Header = make(http.Header)
	for name, values := range creq.Header {
		if !strings.HasPrefix(name, "X-Appengine-Internal-") {
			r.Header[name] = values
		}
	}
	ctxsMu.Lock()
	ctxs[r] = &context{req: &creq}
	ctxsMu.Unlock()

	http.DefaultServeMux.ServeHTTP(w, r)

	ctxsMu.Lock()
	delete(ctxs, r)
	ctxsMu.Unlock()
}
开发者ID:LeXa4894,项目名称:test,代码行数:30,代码来源:api_dev.go

示例3: TestBuildEnv

func TestBuildEnv(t *testing.T) {
	testBuildEnv := func(r *http.Request, rule Rule, fpath string, envExpected map[string]string) {
		var h Handler
		env, err := h.buildEnv(r, rule, fpath)
		if err != nil {
			t.Error("Unexpected error:", err.Error())
		}
		for k, v := range envExpected {
			if env[k] != v {
				t.Errorf("Unexpected %v. Got %v, expected %v", k, env[k], v)
			}
		}
	}

	rule := Rule{}
	url, err := url.Parse("http://localhost:2015/fgci_test.php?test=blabla")
	if err != nil {
		t.Error("Unexpected error:", err.Error())
	}

	r := http.Request{
		Method:     "GET",
		URL:        url,
		Proto:      "HTTP/1.1",
		ProtoMajor: 1,
		ProtoMinor: 1,
		Host:       "localhost:2015",
		RemoteAddr: "[2b02:1810:4f2d:9400:70ab:f822:be8a:9093]:51688",
		RequestURI: "/fgci_test.php",
	}

	fpath := "/fgci_test.php"

	var envExpected = map[string]string{
		"REMOTE_ADDR":     "[2b02:1810:4f2d:9400:70ab:f822:be8a:9093]",
		"REMOTE_PORT":     "51688",
		"SERVER_PROTOCOL": "HTTP/1.1",
		"QUERY_STRING":    "test=blabla",
		"REQUEST_METHOD":  "GET",
		"HTTP_HOST":       "localhost:2015",
	}

	// 1. Test for full canonical IPv6 address
	testBuildEnv(&r, rule, fpath, envExpected)

	// 2. Test for shorthand notation of IPv6 address
	r.RemoteAddr = "[::1]:51688"
	envExpected["REMOTE_ADDR"] = "[::1]"
	testBuildEnv(&r, rule, fpath, envExpected)

	// 3. Test for IPv4 address
	r.RemoteAddr = "192.168.0.10:51688"
	envExpected["REMOTE_ADDR"] = "192.168.0.10"
	testBuildEnv(&r, rule, fpath, envExpected)
}
开发者ID:cvvs,项目名称:caddy,代码行数:55,代码来源:fastcgi_test.go

示例4: handleHTTP

func handleHTTP(w http.ResponseWriter, r *http.Request) {
	c := &context{
		req:       r,
		outHeader: w.Header(),
	}
	stopFlushing := make(chan int)

	ctxs.Lock()
	ctxs.m[r] = c
	ctxs.Unlock()
	defer func() {
		ctxs.Lock()
		delete(ctxs.m, r)
		ctxs.Unlock()
	}()

	// Patch up RemoteAddr so it looks reasonable.
	if addr := r.Header.Get(userIPHeader); addr != "" {
		r.RemoteAddr = addr
	} else if addr = r.Header.Get(remoteAddrHeader); addr != "" {
		r.RemoteAddr = addr
	} else {
		// Should not normally reach here, but pick a sensible default anyway.
		r.RemoteAddr = "127.0.0.1"
	}

	// Start goroutine responsible for flushing app logs.
	// This is done after adding c to ctx.m (and stopped before removing it)
	// because flushing logs requires making an API call.
	go c.logFlusher(stopFlushing)

	executeRequestSafely(c, r)
	c.outHeader = nil // make sure header changes aren't respected any more

	stopFlushing <- 1 // any logging beyond this point will be dropped

	// Flush any pending logs asynchronously.
	c.pendingLogs.Lock()
	flushes := c.pendingLogs.flushes
	if len(c.pendingLogs.lines) > 0 {
		flushes++
	}
	c.pendingLogs.Unlock()
	go c.flushLog(false)
	w.Header().Set(logFlushHeader, strconv.Itoa(flushes))

	// Avoid nil Write call if c.Write is never called.
	if c.outCode != 0 {
		w.WriteHeader(c.outCode)
	}
	if c.outBody != nil {
		w.Write(c.outBody)
	}
}
开发者ID:proppy,项目名称:appengine,代码行数:54,代码来源:api.go

示例5: handleFilteredHTTP

func handleFilteredHTTP(w http.ResponseWriter, r *http.Request) {
	// Patch up RemoteAddr so it looks reasonable.
	const remoteAddrHeader = "X-AppEngine-Remote-Addr"
	if addr := r.Header.Get(remoteAddrHeader); addr != "" {
		r.RemoteAddr = addr
		r.Header.Del(remoteAddrHeader)
	} else {
		// Should not normally reach here, but pick
		// a sensible default anyway.
		r.RemoteAddr = "127.0.0.1"
	}

	http.DefaultServeMux.ServeHTTP(w, r)
}
开发者ID:yschu7,项目名称:go_test,代码行数:14,代码来源:api_dev.go

示例6: ServeHTTP

func (m *module) ServeHTTP(w http.ResponseWriter, req *http.Request) (int, error) {
	validSource := false
	host, port, err := net.SplitHostPort(req.RemoteAddr)
	if err != nil {
		if m.Strict {
			return 403, fmt.Errorf("Error reading remote addr: %s", req.RemoteAddr)
		}
		return m.next.ServeHTTP(w, req) // Change nothing and let next deal with it.
	}
	reqIP := net.ParseIP(host)
	if reqIP == nil {
		if m.Strict {
			return 403, fmt.Errorf("Error parsing remote addr: %s", host)
		}
		return m.next.ServeHTTP(w, req)
	}
	for _, from := range m.From {
		if from.Contains(reqIP) {
			validSource = true
			break
		}
	}
	if !validSource && m.Strict {
		return 403, fmt.Errorf("Unrecognized proxy ip address: %s", reqIP)
	}
	if hVal := req.Header.Get(m.Header); validSource && hVal != "" {
		//restore original host:port format
		leftMost := strings.Split(hVal, ",")[0]
		if net.ParseIP(leftMost) != nil {
			req.RemoteAddr = net.JoinHostPort(leftMost, port)
		}
	}
	return m.next.ServeHTTP(w, req)
}
开发者ID:captncraig,项目名称:caddy-realip,代码行数:34,代码来源:module.go

示例7: handleRequest

func handleRequest(w http.ResponseWriter, r *http.Request) {
	if ipHeader != "" {
		r.RemoteAddr = r.Header.Get(ipHeader)
	}
	w.Header().Set("Access-Control-Allow-Origin", "*")
	switch r.Method {
	case "GET":
		if limit(r.RemoteAddr, getLRUCache, getMut, getLimit, getLimitBurst) {
			w.WriteHeader(429)
			return
		}
		handleGetRequest(w, r)
	case "POST":
		if limit(r.RemoteAddr, postLRUCache, postMut, postLimit, postLimitBurst) {
			w.WriteHeader(429)
			return
		}
		handlePostRequest(w, r)
	default:
		if debug {
			log.Println("Unhandled HTTP method", r.Method)
		}
		http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
	}
}
开发者ID:nrm21,项目名称:syncthing,代码行数:25,代码来源:main.go

示例8: runHandler

func runHandler(resp http.ResponseWriter, req *http.Request,
	fn func(resp http.ResponseWriter, req *http.Request) error, errfn httputil.Error) {
	defer func() {
		if rv := recover(); rv != nil {
			err := errors.New("handler panic")
			logError(req, err, rv)
			errfn(resp, req, http.StatusInternalServerError, err)
		}
	}()

	if s := req.Header.Get("X-Real-Ip"); s != "" && httputil.StripPort(req.RemoteAddr) == "127.0.0.1" {
		req.RemoteAddr = s
	}

	req.Body = http.MaxBytesReader(resp, req.Body, 2048)
	req.ParseForm()
	var rb httputil.ResponseBuffer
	err := fn(&rb, req)
	if err == nil {
		rb.WriteTo(resp)
	} else if e, ok := err.(*httpError); ok {
		if e.status >= 500 {
			logError(req, err, nil)
		}
		errfn(resp, req, e.status, e.err)
	} else {
		logError(req, err, nil)
		errfn(resp, req, http.StatusInternalServerError, err)
	}
}
开发者ID:sendgrid-ops,项目名称:gddo,代码行数:30,代码来源:main.go

示例9: TestSessionManagerFree

/**
 *	测试session manager的Free()
 *	测试时间20秒,需要耐心等待
 */
func TestSessionManagerFree(t *testing.T) {
	runtime.GOMAXPROCS(runtime.NumCPU())
	sm := NewSessionManagerAtGCTime(1, true)

	sm.testing = true

	fmt.Println("sm free() testing...:", time.Now(), "\n")

	go func() {

		//	添加http session
		for i := 1; i <= 10; i++ {
			rw := TestImplResponse{}
			req := http.Request{}
			req.RemoteAddr = "128.0.0.1:8212"
			req.Header = make(http.Header, 1)
			req.Form = make(url.Values)
			sm.tempSessMaxlifeTime = int32(i)
			_, err := sm.GetSession(rw, &req, int32(i), false)
			if nil != err {
				fmt.Println("get session error:", err)
			}
		}

		<-time.After(time.Duration(6) * time.Second)
		fmt.Println("session manager start free()...:", time.Now())
		sm.Free()
	}()

	time.Sleep(time.Duration(20) * time.Second)
}
开发者ID:slowfei,项目名称:leafveingo,代码行数:35,代码来源:lv_session_test.go

示例10: NewFastHTTPHandler

// NewFastHTTPHandler wraps net/http handler to fasthttp request handler,
// so it can be passed to fasthttp server.
//
// While this function may be used for easy switching from net/http to fasthttp,
// it has the following drawbacks comparing to using manually written fasthttp
// request handler:
//
//     * A lot of useful functionality provided by fasthttp is missing
//       from net/http handler.
//     * net/http -> fasthttp handler conversion has some overhead,
//       so the returned handler will be always slower than manually written
//       fasthttp handler.
//
// So it is advisable using this function only for quick net/http -> fasthttp
// switching. Then manually convert net/http handlers to fasthttp handlers
// according to https://github.com/valyala/fasthttp#switching-from-nethttp-to-fasthttp .
func NewFastHTTPHandler(h http.Handler) fasthttp.RequestHandler {
	return func(ctx *fasthttp.RequestCtx) {
		var r http.Request

		body := ctx.PostBody()
		r.Method = string(ctx.Method())
		r.Proto = "HTTP/1.1"
		r.ProtoMajor = 1
		r.ProtoMinor = 1
		r.RequestURI = string(ctx.RequestURI())
		r.ContentLength = int64(len(body))
		r.Host = string(ctx.Host())
		r.RemoteAddr = ctx.RemoteAddr().String()

		hdr := make(http.Header)
		ctx.Request.Header.VisitAll(func(k, v []byte) {
			hdr.Set(string(k), string(v))
		})
		r.Header = hdr
		r.Body = &netHTTPBody{body}

		var w netHTTPResponseWriter
		h.ServeHTTP(&w, &r)

		ctx.SetStatusCode(w.StatusCode())
		for k, vv := range w.Header() {
			for _, v := range vv {
				ctx.Response.Header.Set(k, v)
			}
		}
		ctx.Write(w.body)
	}
}
开发者ID:xiaoma20082008,项目名称:fasthttp,代码行数:49,代码来源:adaptor.go

示例11: ServeHTTP

func (h *reverseProxyHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	if ip := r.Header.Get("X-Real-Ip"); len(ip) > 0 {
		r.RemoteAddr = ip
	}
	if host := r.Header.Get("X-Forwarded-Host"); len(host) > 0 {
		r.Host = host
	}
	h.inner.ServeHTTP(w, r)
}
开发者ID:hobinjk,项目名称:livegrep,代码行数:9,代码来源:reverse_proxy.go

示例12: Test_RegistrationFormValidator_valid_registrationForm

func Test_RegistrationFormValidator_valid_registrationForm(t *testing.T) {
	form := &gonews.RegistrationForm{CSRF: "csrf-token", Username: "johnny_doe", Password: "password", PasswordConfirmation: "password", Email: "[email protected]"}
	r := new(http.Request)
	r.RemoteAddr = "some-addr"
	validator := gonews.NewRegistrationFormValidator(r, TestCSRFProvider{}, TestUserFinder{})
	errors := validator.Validate(form)
	if errors != nil {
		t.Fatal("There should be no error got : ", errors)
	}
}
开发者ID:Mparaiso,项目名称:gonews,代码行数:10,代码来源:validators_test.go

示例13: handler

func (s *RpcServer) handler(w http.ResponseWriter, r *http.Request) {
	c := &serverContext{
		req:       &serverRequest{r},
		outHeader: w.Header(),
	}

	ctxs.Lock()
	ctxs.m[r] = c
	ctxs.Unlock()
	defer func() {
		ctxs.Lock()
		delete(ctxs.m, r)
		ctxs.Unlock()
	}()

	// Patch up RemoteAddr so it looks reasonable.
	if addr := r.Header.Get("X-Forwarded-For"); len(addr) > 0 {
		r.RemoteAddr = addr
	} else {
		// Should not normally reach here, but pick a sensible default anyway.
		r.RemoteAddr = "127.0.0.1"
	}
	// The address in the headers will most likely be of these forms:
	//	123.123.123.123
	//	2001:db8::1
	// net/http.Request.RemoteAddr is specified to be in "IP:port" form.
	if _, _, err := net.SplitHostPort(r.RemoteAddr); err != nil {
		// Assume the remote address is only a host; add a default port.
		r.RemoteAddr = net.JoinHostPort(r.RemoteAddr, "80")
	}

	executeRequestSafely(c, r)
	c.outHeader = nil // make sure header changes aren't respected any more

	// Avoid nil Write call if c.Write is never called.
	if c.outCode != 0 {
		w.WriteHeader(c.outCode)
	}
	if c.outBody != nil {
		w.Write(c.outBody)
	}
}
开发者ID:carriercomm,项目名称:go-micro,代码行数:42,代码来源:rpc_server.go

示例14: TestNewId

func TestNewId(t *testing.T) {
	var (
		//engineIO EngineIO
		request http.Request
	)
	request.RemoteAddr = "178.1.2.3:123"
	if id, err := generateId(&request); err != nil {
		t.Error(err)
	} else {
		t.Log(id)
	}
}
开发者ID:alubame001,项目名称:eio,代码行数:12,代码来源:server_test.go

示例15: ServeHTTP

func (handler UnproxyHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	// TODO: Parse this more thoroughly
	if xff, ok := r.Header[XForwardedFor]; ok {
		_, port, err := net.SplitHostPort(r.RemoteAddr)
		if err != nil {
			port = "0"
		}
		xff = strings.Split(strings.Join(xff, ","), ",")
		host := strings.Trim(xff[len(xff)-1], " \t")
		r.RemoteAddr = net.JoinHostPort(host, port)
	}
	handler.H.ServeHTTP(w, r)
}
开发者ID:cloud9-tools,项目名称:cloud9,代码行数:13,代码来源:handler_unproxy.go


注:本文中的net/http.Request.RemoteAddr方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。