github.com/jiasir/deis@v1.12.2/logger/weblog/requesthandler.go (about)

     1  package weblog
     2  
     3  import (
     4  	"fmt"
     5  	"log"
     6  	"net/http"
     7  	"regexp"
     8  	"strconv"
     9  	"strings"
    10  
    11  	"github.com/deis/deis/logger/syslogish"
    12  )
    13  
    14  var getRegex *regexp.Regexp
    15  var deleteRegex *regexp.Regexp
    16  
    17  func init() {
    18  	getRegex = regexp.MustCompile(`^/([-a-z0-9]+)/?(?:\?log_lines=([0-9]+))?$`)
    19  	deleteRegex = regexp.MustCompile(`^/([-a-z0-9]+)/?$`)
    20  }
    21  
    22  type requestHandler struct {
    23  	syslogishServer *syslogish.Server
    24  }
    25  
    26  func (h requestHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
    27  	if r.Method == "GET" {
    28  		h.serveGet(w, r)
    29  	} else if r.Method == "DELETE" {
    30  		h.serveDelete(w, r)
    31  	} else {
    32  		w.WriteHeader(http.StatusBadRequest)
    33  	}
    34  }
    35  
    36  func (h requestHandler) serveGet(w http.ResponseWriter, r *http.Request) {
    37  	match := getRegex.FindStringSubmatch(r.RequestURI)
    38  	if match == nil {
    39  		w.WriteHeader(http.StatusNotFound)
    40  		return
    41  	}
    42  	app := match[1]
    43  	logLines, err := strconv.Atoi(match[2])
    44  	if err != nil || logLines < 1 {
    45  		log.Printf("Invalid number of log lines specified by request for `%s`; defaulting to 100 lines.", r.RequestURI)
    46  		logLines = 100
    47  	}
    48  	logs, err := h.syslogishServer.ReadLogs(app, logLines)
    49  	if err != nil {
    50  		log.Println(err)
    51  		if strings.HasPrefix(err.Error(), "Could not find logs for") {
    52  			w.WriteHeader(http.StatusNoContent)
    53  		} else {
    54  			w.WriteHeader(http.StatusInternalServerError)
    55  		}
    56  		return
    57  	}
    58  	for _, line := range logs {
    59  		fmt.Fprintf(w, "%s\n", line)
    60  	}
    61  }
    62  
    63  func (h requestHandler) serveDelete(w http.ResponseWriter, r *http.Request) {
    64  	match := deleteRegex.FindStringSubmatch(r.RequestURI)
    65  	if match == nil {
    66  		w.WriteHeader(http.StatusNotFound)
    67  		return
    68  	}
    69  	app := match[1]
    70  	if err := h.syslogishServer.DestroyLogs(app); err != nil {
    71  		log.Println(err)
    72  		w.WriteHeader(http.StatusInternalServerError)
    73  	}
    74  }