github.com/safing/portbase@v0.19.5/api/request.go (about) 1 package api 2 3 import ( 4 "fmt" 5 "net/http" 6 7 "github.com/gorilla/mux" 8 9 "github.com/safing/portbase/log" 10 ) 11 12 // Request is a support struct to pool more request related information. 13 type Request struct { 14 // Request is the http request. 15 *http.Request 16 17 // InputData contains the request body for write operations. 18 InputData []byte 19 20 // Route of this request. 21 Route *mux.Route 22 23 // URLVars contains the URL variables extracted by the gorilla mux. 24 URLVars map[string]string 25 26 // AuthToken is the request-side authentication token assigned. 27 AuthToken *AuthToken 28 29 // ResponseHeader holds the response header. 30 ResponseHeader http.Header 31 32 // HandlerCache can be used by handlers to cache data between handlers within a request. 33 HandlerCache interface{} 34 } 35 36 // apiRequestContextKey is a key used for the context key/value storage. 37 type apiRequestContextKey struct{} 38 39 // RequestContextKey is the key used to add the API request to the context. 40 var RequestContextKey = apiRequestContextKey{} 41 42 // GetAPIRequest returns the API Request of the given http request. 43 func GetAPIRequest(r *http.Request) *Request { 44 ar, ok := r.Context().Value(RequestContextKey).(*Request) 45 if ok { 46 return ar 47 } 48 return nil 49 } 50 51 // TextResponse writes a text response. 52 func TextResponse(w http.ResponseWriter, r *http.Request, text string) { 53 w.Header().Set("Content-Type", "text/plain; charset=utf-8") 54 w.Header().Set("X-Content-Type-Options", "nosniff") 55 w.WriteHeader(http.StatusOK) 56 _, err := fmt.Fprintln(w, text) 57 if err != nil { 58 log.Tracer(r.Context()).Warningf("api: failed to write text response: %s", err) 59 } 60 }