zoukankan      html  css  js  c++  java
  • 7.8 http redirected

    
    
    package main
    
    import (
    	"fmt"
    	"net/http"
    )
    
    const addr = "localhost:7070"
    
    type RedirecServer struct {
    	redirectCount int
    }
    
    func (s *RedirecServer) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
    	s.redirectCount++
    	fmt.Println("Received header: " + req.Header.Get("Known-redirects"))
    	http.Redirect(rw, req, fmt.Sprintf("/redirect%d", s.redirectCount), http.StatusTemporaryRedirect)
    }
    
    func main() {
    	s := http.Server{
    		Addr:    addr,
    		Handler: &RedirecServer{0},
    	}
    	go s.ListenAndServe()
    
    	client := http.Client{}
    	redirectCount := 0
    
    	// If the count of redirects is reached
    	// than return error.
    	client.CheckRedirect = func(req *http.Request, via []*http.Request) error {
    		fmt.Println("Redirected")
    		if redirectCount > 2 {
    			return fmt.Errorf("Too many redirects")
    		}
    		req.Header.Set("Known-redirects", fmt.Sprintf("%d", redirectCount))
    		redirectCount++
    		for _, prReq := range via {
    			fmt.Printf("Previous request: %v
    ", prReq.URL)
    		}
    		return nil
    	}
    
    	_, err := client.Get("http://" + addr)
    	if err != nil {
    		panic(err)
    	}
    }
    
    /*
    
    Received header: 
    Redirected
    Previous request: http://localhost:7070
    Received header: 0
    Redirected
    Previous request: http://localhost:7070
    Previous request: http://localhost:7070/redirect1
    Received header: 1
    Redirected
    Previous request: http://localhost:7070
    Previous request: http://localhost:7070/redirect1
    Previous request: http://localhost:7070/redirect2
    Received header: 2
    Redirected
    panic: Get /redirect4: Too many redirects
    
    goroutine 1 [running]:
    main.main()
    	/Users/zrd/Desktop/go/go_path/src/go_web/xml.go:47 +0x238
     */
    
    
  • 相关阅读:
    css添加方法
    node + vue 实现服务端单向推送消息,利用EventSource
    获取公众号openid,通过unionid 和小程序用户绑定起来
    小程序 构建npm
    powershell禁止系统运行脚本
    mongoose 删除
    mongoose 查询
    moogoose 更新
    小程序,用户授权手机号,node需要检验和解析
    小程序:支付的时候缺少参数:total_fee,支付失败
  • 原文地址:https://www.cnblogs.com/zrdpy/p/8635875.html
Copyright © 2011-2022 走看看