sysapihandler.go 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. package api
  2. import (
  3. "log"
  4. "net/http"
  5. "strings"
  6. )
  7. // APIKeyHeader in this header thr right api key should be inserted
  8. const APIKeyHeader = "X-mcs-apikey"
  9. /*
  10. SysAPIKey defining a handler for checking system id and api key
  11. */
  12. type SysAPIKey struct {
  13. log *log.Logger
  14. Apikey string
  15. }
  16. /*
  17. NewSysAPIHandler creates a new SysApikeyHandler
  18. */
  19. func NewSysAPIHandler(apikey string) *SysAPIKey {
  20. c := &SysAPIKey{
  21. Apikey: apikey,
  22. }
  23. return c
  24. }
  25. /*
  26. Handler the handler checks systemid and apikey headers
  27. */
  28. func (s *SysAPIKey) Handler(next http.Handler) http.Handler {
  29. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  30. path := strings.TrimSuffix(r.URL.Path, "/")
  31. if !strings.HasPrefix(path, "/health") {
  32. if s.Apikey != strings.ToLower(r.Header.Get(APIKeyHeader)) {
  33. Msg(w, http.StatusBadRequest, "either system id or apikey not correct")
  34. return
  35. }
  36. }
  37. next.ServeHTTP(w, r)
  38. })
  39. }
  40. /*
  41. AddHeader adding gefault header for system and apikey
  42. */
  43. func AddHeader(response http.ResponseWriter, apikey string, system string) {
  44. response.Header().Add(APIKeyHeader, apikey)
  45. }