dongqigu0429 2018-10-15 12:19
浏览 79

如何编写处理来自API的响应/错误的golang中间件?

Basically, I want to write one middleware which closes transaction object is created while a request. I am using gorilla mux package. I am familiar with python-Django middlewares and it gives proper handling of error or response. but not able to find anything similar with golang

  • 写回答

1条回答 默认 最新

  • doukuo9116 2018-10-15 13:22
    关注

    In Go lang you can create a middle-ware too, below I've written the process to create handler as validateMiddleware then called it when TestEndpoint API requested.

    func main() {
        router := mux.NewRouter()
    
        router.HandleFunc("/test", ValidateMiddleware(TestEndpoint)).Methods("GET")
        log.Fatal(http.ListenAndServe(":12345", router))
    }
    

    And now you can create your validateMiddleware handler as:

        func ValidateMiddleware(next http.HandlerFunc) http.HandlerFunc {
            return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
                authorizationHeader := req.Header.Get("authorization")
                        if authorizationHeader != "" {
                            // if true, then request for next handler.
                            next(w, req)
                        } else {
                            json.NewEncoder(w).Encode(Exception{Message: "Invalid authorization token"})
                            return
                        }
            })
        }
    

    And finally create original requested handler TestEndpoint

    func TestEndpoint(w http.ResponseWriter, req *http.Request) {
        fmt.Println("Hello Go middleware!!!")
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程
  • ¥30 Eclipse官网打不开,官网首页进不去,显示无法访问此页面,求解决方法
  • ¥15 关于smbclient 库的使用
  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?