github.com/blend/go-sdk@v1.20220411.3/examples/webutil/httplogged/main.go (about) 1 /* 2 3 Copyright (c) 2022 - Present. Blend Labs, Inc. All rights reserved 4 Use of this source code is governed by a MIT license that can be found in the LICENSE file. 5 6 */ 7 8 package main 9 10 import ( 11 "log" 12 "net/http" 13 _ "net/http/pprof" 14 "os" 15 16 "github.com/blend/go-sdk/logger" 17 "github.com/blend/go-sdk/webutil" 18 ) 19 20 func indexHandler(res http.ResponseWriter, req *http.Request) { 21 res.WriteHeader(http.StatusOK) 22 res.Write([]byte(`{"status":"ok!"}`)) 23 } 24 25 func fatalErrorHandler(res http.ResponseWriter, req *http.Request) { 26 res.WriteHeader(http.StatusInternalServerError) 27 res.Write([]byte(`{"status":"not ok."}`)) 28 } 29 30 func errorHandler(res http.ResponseWriter, req *http.Request) { 31 res.WriteHeader(http.StatusInternalServerError) 32 res.Write([]byte(`{"status":"not ok."}`)) 33 } 34 35 func warningHandler(res http.ResponseWriter, req *http.Request) { 36 res.WriteHeader(http.StatusBadRequest) 37 res.Write([]byte(`{"status":"not ok."}`)) 38 } 39 40 func subScopeHandler(res http.ResponseWriter, req *http.Request) { 41 res.WriteHeader(http.StatusOK) 42 res.Write([]byte(`{"status":"did sub-context things"}`)) 43 } 44 45 func scopeMetaHandler(res http.ResponseWriter, req *http.Request) { 46 *req = *req.WithContext(logger.WithLabels(req.Context(), logger.Labels{"foo": "bar"})) 47 res.WriteHeader(http.StatusOK) 48 res.Write([]byte(`{"status":"ok!"}`)) 49 } 50 51 func auditHandler(res http.ResponseWriter, req *http.Request) { 52 res.WriteHeader(http.StatusOK) 53 res.Write([]byte(`{"status":"audit logged!"}`)) 54 } 55 56 func port() string { 57 envPort := os.Getenv("PORT") 58 if len(envPort) > 0 { 59 return envPort 60 } 61 return "8888" 62 } 63 64 func main() { 65 go func() { 66 log.Println(http.ListenAndServe("localhost:6060", nil)) 67 }() 68 69 log := logger.Prod() 70 71 http.HandleFunc("/", webutil.HTTPLogged(log)(indexHandler)) 72 73 http.HandleFunc("/fatalerror", webutil.HTTPLogged(log)(fatalErrorHandler)) 74 http.HandleFunc("/error", webutil.HTTPLogged(log)(errorHandler)) 75 http.HandleFunc("/warning", webutil.HTTPLogged(log)(warningHandler)) 76 http.HandleFunc("/audit", webutil.HTTPLogged(log)(auditHandler)) 77 78 http.HandleFunc("/subscope", webutil.HTTPLogged(log.WithPath("a sub scope"))(subScopeHandler)) 79 http.HandleFunc("/scopemeta", webutil.HTTPLogged(log)(scopeMetaHandler)) 80 81 http.HandleFunc("/bench/logged", webutil.HTTPLogged(log)(indexHandler)) 82 83 log.Infof("Listening on :%s", port()) 84 log.Infof("Events %s", log.Flags.String()) 85 86 log.Fatal(http.ListenAndServe(":"+port(), nil)) 87 }