本文整理汇总了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
}
示例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()
}
示例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)
}
示例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)
}
}
示例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)
}
示例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)
}
示例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)
}
}
示例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)
}
}
示例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)
}
示例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)
}
}
示例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)
}
示例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)
}
}
示例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)
}
}
示例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)
}
}
示例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)
}