• 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
     */
    
    
  • 相关阅读:
    JavaScript语法
    C#拼接string字符串
    C#字母替换
    C#timer控件用法
    C#字体选择框和颜色对话框
    C#保存文件
    C#认识对话框
    C#TextBox文本框
    C#Button窗体常用属性及事件
    C#Form窗体常用属性及事件
  • 原文地址:https://www.cnblogs.com/zrdpy/p/8635875.html
Copyright © 2020-2023  润新知