util.go 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. // Copyright (c) 2014 Couchbase, Inc.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package http
  15. import (
  16. "encoding/json"
  17. "io"
  18. "io/ioutil"
  19. "log"
  20. "net/http"
  21. )
  22. func showError(w http.ResponseWriter, r *http.Request,
  23. msg string, code int) {
  24. logger.Printf("Reporting error %v/%v", code, msg)
  25. http.Error(w, msg, code)
  26. }
  27. func mustEncode(w io.Writer, i interface{}) {
  28. if headered, ok := w.(http.ResponseWriter); ok {
  29. headered.Header().Set("Cache-Control", "no-cache")
  30. headered.Header().Set("Content-type", "application/json")
  31. }
  32. e := json.NewEncoder(w)
  33. if err := e.Encode(i); err != nil {
  34. panic(err)
  35. }
  36. }
  37. type varLookupFunc func(req *http.Request) string
  38. var logger = log.New(ioutil.Discard, "bleve.http", log.LstdFlags)
  39. // SetLog sets the logger used for logging
  40. // by default log messages are sent to ioutil.Discard
  41. func SetLog(l *log.Logger) {
  42. logger = l
  43. }