本文整理汇总了Golang中net/http.Request.URL方法的典型用法代码示例。如果您正苦于以下问题:Golang Request.URL方法的具体用法?Golang Request.URL怎么用?Golang Request.URL使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类net/http.Request
的用法示例。
在下文中一共展示了Request.URL方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: TestThreadList
func TestThreadList(t *testing.T) {
ctl := gomock.NewController(t)
defer ctl.Finish()
threadServiceMock := service.NewMockThread(ctl)
threadServiceMock.
EXPECT().
FindThreads(dao.Paging{Limit: 5, Offset: 0, OrderBy: "updated_at desc"}).
Return(model.ThreadSlice{}, nil).
Times(1)
threadHandler := NewThread(threadServiceMock)
ctx := context.Background()
{
r := http.Request{}
url, err := url.Parse("http://localhost?limit=a&offset=0")
if err != nil {
t.Fatal(err)
}
r.URL = url
res := threadHandler.List(ctx, &r)
assert.Equal(t, response.BadRequest, res, "")
}
{
r := http.Request{}
url, err := url.Parse("http://localhost?limit=5&offset=0")
if err != nil {
t.Fatal(err)
}
r.URL = url
threadHandler.List(ctx, &r)
}
}
示例2: MapRequest
func (c *Config) MapRequest(r *http.Request) {
if mapped, err := c.MapURL(r.URL); err != nil {
r.URL = &url.URL{Host: r.Host, Path: "/404", Scheme: "http"}
} else {
r.URL = &mapped
}
}
示例3: makeRequest
func makeRequest(params map[string]string) (*http.Request, error) {
r := new(http.Request)
r.Method = params["METHOD"]
if r.Method == "" {
return nil, errors.New("mongrel2: no METHOD")
}
r.Proto = params["VERSION"]
var ok bool
r.ProtoMajor, r.ProtoMinor, ok = http.ParseHTTPVersion(r.Proto)
if !ok {
return nil, errors.New("mongrel2: invalid protocol version")
}
r.Trailer = http.Header{}
r.Header = http.Header{}
r.Host = params["Host"]
r.Header.Set("Referer", params["Referer"])
r.Header.Set("User-Agent", params["User-Agent"])
if lenstr := params["Content-Length"]; lenstr != "" {
clen, err := strconv.ParseInt(lenstr, 10, 64)
if err != nil {
return nil, errors.New("mongrel2: bad Content-Length")
}
r.ContentLength = clen
}
for k, v := range params {
if !skipHeader[k] {
r.Header.Add(k, v)
}
}
// TODO: cookies
if r.Host != "" {
url_, err := url.Parse("http://" + r.Host + params["URI"])
if err != nil {
return nil, errors.New("mongrel2: failed to parse host and URI into a URL")
}
r.URL = url_
}
if r.URL == nil {
url_, err := url.Parse(params["URI"])
if err != nil {
return nil, errors.New("mongrel2: failed to parse URI into a URL")
}
r.URL = url_
}
// TODO: how do we know if we're using HTTPS?
// TODO: fill in r.RemoteAddr
return r, nil
}
示例4: Proxy
func (p *WebsocketProxy) Proxy(w http.ResponseWriter, r *http.Request) {
hj, ok := w.(http.Hijacker)
if !ok {
log.Println("hijack assertion failed", r.Host, r.URL.Path)
p.handler.ServeHTTP(w, r) // last-ditch effort as plain http
return
}
conn, rw, err := hj.Hijack()
if err != nil {
log.Println("hijack failed", r.Host, r.URL.Path, err)
p.handler.ServeHTTP(w, r) // last-ditch effort as plain http
return
}
defer conn.Close()
rw.Flush()
wrapreq := new(http.Request)
wrapreq.Proto = "HTTP/1.1"
wrapreq.ProtoMajor, wrapreq.ProtoMinor = 1, 1
wrapreq.Method = "WEBSOCKET"
wrapreq.Host = r.Host
const dummy = "/"
wrapreq.URL = &url.URL{Path: dummy}
var buf bytes.Buffer
r.Write(&buf)
wrapreq.Body = ioutil.NopCloser(io.MultiReader(&buf, conn))
resp, err := p.transport.RoundTrip(wrapreq)
if err != nil || resp.StatusCode != 200 {
io.WriteString(conn, "HTTP/1.0 503 Gateway Failed\r\n")
io.WriteString(conn, "Connection: close\r\n\r\n")
return
}
defer resp.Body.Close()
io.Copy(conn, resp.Body)
}
示例5: TestGetFormatForRequest
func TestGetFormatForRequest(t *testing.T) {
var request *http.Request
request = new(http.Request)
request.URL, _ = url.Parse(testDomain + "/people/123/groups/456.json")
if getFormatForRequest(request) != JSON_FORMAT {
t.Errorf("getFormatForRequest should be 'JSON' not '%s'", getFormatForRequest(request))
}
request.URL, _ = url.Parse(testDomain + "/people/123/groups/456.xml")
if getFormatForRequest(request) != XML_FORMAT {
t.Errorf("getFormatForRequest should be 'XML' not '%s'", getFormatForRequest(request))
}
request.URL, _ = url.Parse(testDomain + "/people/123/groups/456")
if getFormatForRequest(request) != DEFAULT_FORMAT {
t.Errorf("getFormatForRequest should be '%s' not '%s'", DEFAULT_FORMAT, getFormatForRequest(request))
}
request.URL, _ = url.Parse(testDomain + "/people/123/groups/456.html")
if getFormatForRequest(request) != HTML_FORMAT {
t.Errorf("getFormatForRequest should be '%s' not '%s'", HTML_FORMAT, getFormatForRequest(request))
}
request.URL, _ = url.Parse(testDomain + "/people/123/groups/456.htm")
if getFormatForRequest(request) != HTML_FORMAT {
t.Errorf("getFormatForRequest should be '%s' not '%s'", HTML_FORMAT, getFormatForRequest(request))
}
request.URL = nil
if getFormatForRequest(request) != DEFAULT_FORMAT {
t.Errorf("getFormatForRequest should be 'JSON' not '%s'", getFormatForRequest(request))
}
}
示例6: Do
func (r Client) Do(l Logger, req *http.Request) (resp *http.Response, err error) {
//check bind remote ip
if r.BindRemoteIp != "" {
oldReqUrl := req.URL.String()
oldReqUri, _ := url.Parse(oldReqUrl)
newUrlStr := fmt.Sprintf("%s://%s%s", oldReqUri.Scheme, r.BindRemoteIp, oldReqUri.RequestURI())
newUrl, _ := url.Parse(newUrlStr)
req.URL = newUrl
req.Header.Set("Host", oldReqUri.Host)
}
if l != nil {
req.Header.Set("X-Reqid", l.ReqId())
}
req.Header.Set("User-Agent", UserAgent)
resp, err = r.Client.Do(req)
if err != nil {
return
}
if l != nil {
details := resp.Header["X-Log"]
if len(details) > 0 {
l.Xput(details)
}
}
return
}
示例7: ProcessRequest
// ProcessRequest will run any checks on the request on the way through the system, return an error to have the chain fail
func (m *URLRewriteMiddleware) ProcessRequest(w http.ResponseWriter, r *http.Request, configuration interface{}) (error, int) {
_, versionPaths, _, _ := m.TykMiddleware.Spec.GetVersionData(r)
found, meta := m.TykMiddleware.Spec.CheckSpecMatchesStatus(r.URL.Path, r.Method, versionPaths, URLRewrite)
if found {
log.Debug("Rewriter active")
thisMeta := meta.(*tykcommon.URLRewriteMeta)
log.Debug(r.URL)
oldPath := r.URL.String()
p, pErr := m.Rewriter.Rewrite(thisMeta, r.URL.String(), true, r)
if pErr != nil {
return pErr, 500
}
m.CheckHostRewrite(oldPath, p, r)
newURL, uErr := url.Parse(p)
if uErr != nil {
log.Error("URL Rewrite failed, could not parse: ", p)
} else {
r.URL = newURL
}
}
return nil, 200
}
示例8: send
func send(url *url.URL, addr string) result {
var req http.Request
req.URL = url
now := time.Now()
conn, err := net.Dial("tcp", addr)
if err != nil {
return result{0, err}
}
defer conn.Close()
err = req.Write(conn)
if err != nil {
return result{0, err}
}
ch := make(chan respErr, 1)
go func() {
reader := bufio.NewReader(conn)
response, err := http.ReadResponse(reader, &req)
ch <- respErr{response, err}
}()
var res result
select {
case <-time.After(time.Duration(*timeout * 1e6)):
res = result{time.Now().Sub(now), errors.New("Timeout!")}
case rerr := <-ch:
res = result{time.Now().Sub(now), rerr.err}
rerr.resp.Body.Close()
}
return res
}
示例9: Target
func (e Post) Target(r *http.Request) {
r.Body = ioutil.NopCloser(bytes.NewBuffer(e.Body))
r.ContentLength = int64(len(e.Body))
r.Header.Set("Content-Type", e.ContentType)
r.Method = "POST"
r.URL = e.URL
}
示例10: ServeHTTP
func (rrlb *RoundRobinLoadBalancer) ServeHTTP(response http.ResponseWriter, request *http.Request) {
_, endpoint, _ := rrlb.NextEndpoint()
fmt.Println("Next Endpoint => " + net.JoinHostPort(endpoint.host.String(), endpoint.port))
request.Header.Add("X-FORWARDED-FOR", request.RemoteAddr)
request.Header.Add("Server", "Go Load Balancer")
fmt.Println(request.Proto)
client := &http.Client{}
newRequest := new(http.Request)
*newRequest = *request
fmt.Println("Request URI => " + request.RequestURI)
uri, _ := url.ParseRequestURI(request.RequestURI)
if len(uri.Scheme) == 0 {
uri.Scheme = "http"
}
newRequest.URL = uri
newRequest.URL.Host = net.JoinHostPort(endpoint.host.String(), endpoint.port)
newRequest.URL.User = request.URL.User
newRequest.RequestURI = ""
clientResponse, _ := client.Do(newRequest)
clientResponse.Write(response)
}
示例11: RoundTrip
func (st *supervisorTransport) RoundTrip(req *http.Request) (*http.Response, error) {
if req.URL == nil {
return nil, errors.New("unix: nil Request.URL")
}
if req.Header == nil {
return nil, errors.New("unix: nil Request.Header")
}
if req.URL.Scheme != "unix" {
panic("unix: unsupported protocol scheme")
}
sock, err := net.Dial("unix", req.URL.Path)
if err != nil {
return nil, err
}
defer sock.Close()
//create shallow copy of request object
newReq := new(http.Request)
*newReq = *req
newReq.URL = supervisorURL
newReq.Write(sock)
return http.ReadResponse(bufio.NewReader(sock), req)
}
示例12: ServeHTTP
// ServeHTTP handles the response
func (s *Server) ServeHTTP(w http.ResponseWriter, req *http.Request) {
if ProxyPath != "" && strings.HasPrefix(req.URL.Path, "/"+ProxyPath) {
uri, err := url.Parse(req.FormValue("uri"))
if err != nil {
s.debug.Println(req.RequestURI, err.Error())
}
req.URL = uri
req.Host = uri.Host
req.RequestURI = uri.RequestURI()
proxy.ServeHTTP(w, req)
return
}
if websocketUpgrade(req) {
websocketServe(w, req)
return
}
defer func() {
req.Body.Close()
}()
r := s.handle(w, &httpRequest{req, s})
for key := range r.headers {
w.Header().Set(key, r.headers.Get(key))
}
if r.status > 0 {
w.WriteHeader(r.status)
}
if len(r.argv) > 0 {
fmt.Fprint(w, r.argv...)
}
}
示例13: ApplyTo
// ApplyTo sets the requests Method to PUT, URL and Body
func (p Put) ApplyTo(req *http.Request) {
req.Method = "PUT"
req.URL = p.URL
req.Body = ioutil.NopCloser(bytes.NewBuffer(p.Body))
req.ContentLength = int64(len(p.Body))
req.Header.Set("Content-Type", p.ContentType)
}
示例14: createRequest
func createRequest() *http.Request {
r := new(http.Request)
url := new(url.URL)
url.Path = "/station/9530"
r.URL = url
return r
}
示例15: forwardRequest
func forwardRequest(r *http.Request, ip string, destport int, client http.Client, requesturl string, responseChannel chan int, wg *sync.WaitGroup) {
defer wg.Done()
r.Host = ip
r.RequestURI = ""
newURL, err := url.Parse(fmt.Sprintf("http://%v:%d%v", ip, destport, requesturl))
if err != nil {
log.Printf("Error parsing URL: %s\n", err)
if *debug {
log.Printf("For URL: %s\n", fmt.Sprintf("http://%v:%d%v", ip, destport, requesturl))
}
responseChannel <- 500
return
}
r.URL = newURL
response, err := client.Do(r)
if err != nil {
log.Printf("Error sending request: %s\n", err)
if *debug {
log.Printf("For URL: %s\n", r.URL)
}
responseChannel <- 500
return
}
io.Copy(ioutil.Discard, response.Body)
defer response.Body.Close()
return
}