Last active
April 26, 2016 07:19
-
-
Save hsinhoyeh/e8d4a6c43d1033c24a1b0e3b3bb97a54 to your computer and use it in GitHub Desktop.
golang restful logcontainer
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
```go | |
package api | |
import ( | |
"fmt" | |
"hash/fnv" | |
"net/http" | |
"net/http/httptest" | |
"net/http/httputil" | |
"github.com/emicklei/go-restful" | |
"github.com/satori/go.uuid" | |
) | |
type LogContainer struct { | |
container *restful.Container | |
} | |
func NewLogContainer(c *restful.Container) *LogContainer { | |
return &LogContainer{container: c} | |
} | |
func (l *LogContainer) ServeHTTP(httpwriter http.ResponseWriter, httpRequest *http.Request) { | |
rid := requestID() | |
log.Infof("[log-container](%s) method:%v, url:%v", rid, httpRequest.Method, httpRequest.URL) | |
dump, _ := httputil.DumpRequest(httpRequest, true) | |
log.Infof("[log-container](%s) request dump: %v", rid, string(dump)) | |
rec := httptest.NewRecorder() | |
l.container.ServeHTTP(rec, httpRequest) | |
log.Infof("[log-container](%s) response dump: code:%d, body: %v", rid, rec.Code, rec.Body.String()) | |
// copy from w to httpwriter | |
// NOTE: we need to write header first | |
for k, v := range rec.Header() { | |
httpwriter.Header()[k] = v | |
} | |
httpwriter.WriteHeader(rec.Code) | |
httpwriter.Write(rec.Body.Bytes()) | |
} | |
func requestID() string { | |
h := fnv.New32() | |
h.Write(uuid.NewV4().Bytes()) | |
return fmt.Sprintf("%010d", h.Sum32()) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment