项目作者: nanoninja

项目描述 :
Go HTTP Tool Package
高级语言: Go
项目地址: git://github.com/nanoninja/httptool.git
创建时间: 2020-08-03T14:38:25Z
项目社区:https://github.com/nanoninja/httptool

开源协议:BSD 3-Clause "New" or "Revised" License

下载


HTTPTool

The HTTP tool is a simple extension of the net/http package written in Go.
It is not a Framework and offers additional. This package provides a slightly different handling of the Handler type by
exploiting the return to handle potential errors.

The ResponseWriter type has been increased to retrieve the state of the HTTP response such as
code, length and whether the header has been written.

Golang
Godoc
Build Status
Coverage Status
Go Report Card
Codebeat Badge

Installation

```shell script
go get github.com/nanoninja/httptool

  1. ## Getting Started
  2. ```go
  3. package main
  4. import (
  5. "log"
  6. "net/http"
  7. "os"
  8. "github.com/nanoninja/httptool"
  9. )
  10. func logAccess(next http.Handler, logger *log.Logger) http.Handler {
  11. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  12. next.ServeHTTP(w, r)
  13. ip := httptool.ClientIP(r)
  14. rw := w.(httptool.ResponseWriter)
  15. logger.Printf("[nanoninja] %s %s %s %d\n", ip, r.Method, r.RequestURI, rw.Status())
  16. })
  17. }
  18. func logError(next httptool.HandlerFunc, logger *log.Logger) http.HandlerFunc {
  19. return func(w http.ResponseWriter, r *http.Request) {
  20. if err := next.ServeHTTP(w, r); err != nil {
  21. logger.Println(err)
  22. }
  23. }
  24. }
  25. func greeting(w http.ResponseWriter, _ *http.Request) error {
  26. w.WriteHeader(http.StatusOK)
  27. _, err := w.Write([]byte("Hello, Gophers"))
  28. return err
  29. }
  30. func main() {
  31. errLogger := log.New(os.Stderr, "", log.Lshortfile)
  32. accessLogger := log.New(os.Stdout, "", log.Lshortfile)
  33. mux := http.NewServeMux()
  34. mux.Handle("/", logError(greeting, errLogger))
  35. handler := logAccess(mux, accessLogger)
  36. handler = httptool.ResponseHandler(handler)
  37. handler = httptool.RecoveryHandler(handler, errLogger)
  38. log.Fatalln(http.ListenAndServe(":3000", handler))
  39. }

License

HTTPTool is licensed under the Creative Commons Attribution 3.0 License, and code is licensed under a BSD license.