• http请求添加recover错误处理


    package main
    
    import (
    	"io"
    	"log"
    	"net/http"
    )
    
    const form = `<html><body><form action="#" method="post" name="bar">
                        <input type="text" name="in"/>
                        <input type="text" name="in"/>
                         <input type="submit" value="Submit"/>
                 </form></body></html>`
    
    func SimpleServer(w http.ResponseWriter, request *http.Request) {
    	io.WriteString(w, "hello, world")
    	panic("test test")
    }
    
    func FormServer(w http.ResponseWriter, request *http.Request) {
    	w.Header().Set("Content-Type", "text/html")
    	switch request.Method {
    	case "GET":
    		io.WriteString(w, form)
    	case "POST":
    		request.ParseForm()
    		io.WriteString(w, request.Form["in"][1])
    		io.WriteString(w, "\n")
    		io.WriteString(w, request.FormValue("in"))
    	}
    }
    func main() {
    	http.HandleFunc("/test1", logPanics(SimpleServer))
    	http.HandleFunc("/test2", logPanics(FormServer))
    	if err := http.ListenAndServe(":8088", nil); err != nil {
    	}
    }
    
    //logPanics封装了recover,定义一个即可
    func logPanics(handle http.HandlerFunc) http.HandlerFunc {
    	return func(writer http.ResponseWriter, request *http.Request) {
    		defer func() {
    			if x := recover(); x != nil {
    				log.Printf("[%v] caught panic: %v", request.RemoteAddr, x)
    			}
    		}()
    		handle(writer, request)
    	}
    }
    

      

  • 相关阅读:
    博客测试页
    题解 P1420 【最长连号】
    计蒜客T1846AC记
    折腾笔记-计蒜客T1167AC记
    sublimetext使用教程
    北冥'sfish
    折腾笔记-计蒜客T1158-和为给定数AC记
    折腾笔记-计蒜客t1156AC记
    [题解]-整理药名
    python字符串连接的三种方法及其效率、适用场景详解
  • 原文地址:https://www.cnblogs.com/zhaojingyu/p/16314216.html
Copyright © 2020-2023  润新知