func handleEntries(w http.ResponseWriter, r *http.Request) {
	ctx := context.Background()
	filter := fmt.Sprintf(`logName = "projects/%s/logs/testlog"`, *projectID)
	it := client.Entries(ctx, logadmin.Filter(filter))
	var entries []*logging.Entry
	nextTok, err := iterator.NewPager(it, 5, r.URL.Query().Get("pageToken")).NextPage(&entries)
	if err != nil {
		http.Error(w, fmt.Sprintf("problem getting the next page: %v", err), http.StatusInternalServerError)
		return
	}
	data := struct {
		Entries []*logging.Entry
		Next    string
	}{
		entries,
		nextTok,
	}
	var buf bytes.Buffer
	if err := pageTemplate.Execute(&buf, data); err != nil {
		http.Error(w, fmt.Sprintf("problem executing page template: %v", err), http.StatusInternalServerError)
	}
	if _, err := buf.WriteTo(w); err != nil {
		log.Printf("writing response: %v", err)
	}
}
Example #2
0
func (mdb *Mdb) debugWrite(w io.Writer) error {
	b, _ := json.Marshal(mdb)
	var out bytes.Buffer
	json.Indent(&out, b, "", "    ")
	_, err := out.WriteTo(w)
	return err
}
Example #3
0
func ExampleIndent() {
	type Road struct {
		Name   string
		Number int
	}
	roads := []Road{
		{"Diamond Fork", 29},
		{"Sheep Creek", 51},
	}

	b, err := json.Marshal(roads)
	if err != nil {
		log.Fatal(err)
	}

	var out bytes.Buffer
	json.Indent(&out, b, "=", "\t")
	out.WriteTo(os.Stdout)
	// Output:
	// [
	// =	{
	// =		"Name": "Diamond Fork",
	// =		"Number": 29
	// =	},
	// =	{
	// =		"Name": "Sheep Creek",
	// =		"Number": 51
	// =	}
	// =]
}
Example #4
0
// tryFlushResponse flushes the response buffer (if not empty); returns true if flush succeeded
func (d *httpDecoder) tryFlushResponse(out *bytes.Buffer) {
	log.V(2).Infof(d.idtag+"try-flush-responses: %d bytes to flush", out.Len())
	// set a write deadline here so that we don't block for very long.
	err := d.setWriteTimeout()
	if err != nil {
		// this is a problem because if we can't set the timeout then we can't guarantee
		// how long a write op might block for. Log the error and skip this response.
		log.Errorln("failed to set write deadline, aborting response:", err.Error())
	} else {
		_, err = out.WriteTo(d.rw.Writer)
		if err != nil {
			if neterr, ok := err.(net.Error); ok && neterr.Timeout() && out.Len() > 0 {
				// we couldn't fully write before timing out, return rch and hope that
				// we have better luck next time.
				return
			}
			// we don't really know how to deal with other kinds of errors, so
			// log it and skip the rest of the response.
			log.Errorln("failed to write response buffer:", err.Error())
		}
		err = d.rw.Flush()
		if err != nil {
			if neterr, ok := err.(net.Error); ok && neterr.Timeout() && out.Len() > 0 {
				return
			}
			log.Errorln("failed to flush response buffer:", err.Error())
		}
	}
}
Example #5
0
// marshal an SNMP message
func (packet *SnmpPacket) marshalMsg(oids []string, requestid uint32) ([]byte, error) {
	buf := new(bytes.Buffer)

	// version
	buf.Write([]byte{2, 1, byte(packet.Version)})

	// community
	buf.Write([]byte{4, uint8(len(packet.Community))})
	buf.WriteString(packet.Community)

	// pdu
	pdu, err := packet.marshalPDU(oids, requestid)
	if err != nil {
		return nil, err
	}
	buf.Write(pdu)

	// build up resulting msg - sequence, length then the tail (buf)
	msg := new(bytes.Buffer)
	msg.WriteByte(byte(Sequence))

	buf_length_bytes, err2 := marshalLength(buf.Len())
	if err2 != nil {
		return nil, err2
	}
	msg.Write(buf_length_bytes)

	buf.WriteTo(msg) // reverse logic - want to do msg.Write(buf)
	return msg.Bytes(), nil
}
Example #6
0
File: web.go Project: jmj/bosun
func JSON(h func(miniprofiler.Timer, http.ResponseWriter, *http.Request) (interface{}, error)) http.Handler {
	return miniprofiler.NewHandler(func(t miniprofiler.Timer, w http.ResponseWriter, r *http.Request) {
		d, err := h(t, w, r)
		if err != nil {
			serveError(w, err)
			return
		}
		if d == nil {
			return
		}
		buf := new(bytes.Buffer)
		if err := json.NewEncoder(buf).Encode(d); err != nil {
			log.Println(err)
			serveError(w, err)
			return
		}
		var tw io.Writer = w
		if strings.Contains(r.Header.Get("Accept-Encoding"), "gzip") {
			w.Header().Set("Content-Encoding", "gzip")
			gz := gzip.NewWriter(w)
			defer gz.Close()
			tw = gz
		}
		if cb := r.FormValue("callback"); cb != "" {
			w.Header().Add("Content-Type", "application/javascript")
			tw.Write([]byte(cb + "("))
			buf.WriteTo(tw)
			tw.Write([]byte(")"))
			return
		}
		w.Header().Add("Content-Type", "application/json")
		buf.WriteTo(tw)
	})
}
Example #7
0
func main() {
	args := flag.Args()
	if len(args) < 1 {
		lerr.Fatal("Prettifies json")
	}
	filename := args[0]

	unformattedJson, err := ioutil.ReadFile(filename)
	if err != nil {
		lerr.Fatal(err)
	}

	var out bytes.Buffer
	err = json.Indent(&out, unformattedJson, "", "  ")
	if err != nil {
		lerr.Fatal(err)
	}

	if write {
		ioutil.WriteFile(filename, out.Bytes(), 0777)
	} else {
		out.WriteTo(os.Stdout)
	}

}
Example #8
0
// ServeError serves the appropriate error message in the error template
// depending on the value of displayErrors. If displayErrors is true then
// the given message is shown, otherwise the default error message is shown.
func (h *ErrorHandler) ServeError(w http.ResponseWriter, message string) {

	var (
		templateData *ErrorMessage
		buffer       bytes.Buffer
	)

	if h.displayErrors {

		templateData = &ErrorMessage{message}

	} else {

		templateData = &ErrorMessage{h.defaultMessage}
	}

	// Execute template into buffer
	err := h.template.Execute(&buffer, templateData)

	// If template execution fails, fall back to the built-in http error
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	// Otherwise serve the error in the error template
	w.WriteHeader(http.StatusInternalServerError)
	buffer.WriteTo(w)
	return
}
Example #9
0
func (bt BTree) Draw() string {
	var bufGraph, bufLinks, bufLabels bytes.Buffer
	fmt.Fprintln(&bufGraph, "digraph {\n\tsplines=line\n\tnode [shape=record];")
	if bt.Root != nil {
		visited := make(map[*node]bool)
		q := list.New()
		visited[bt.Root] = true
		q.PushFront(bt.Root)
		for q.Len() > 0 {
			n := q.Remove(q.Front()).(*node)
			// Process labels.
			fmt.Fprintf(&bufLabels, "\t\"%p\" [label=\"", n)
			for i := 0; i < n.N; i++ {
				fmt.Fprintf(&bufLabels, "<f%d> | %d | ", i, n.Keys[i])
			}
			fmt.Fprintf(&bufLabels, "<f%d>\"];\n", n.N)
			// Process links (there are N+1 links).
			for i := 0; i <= n.N; i++ {
				if !n.Leaf {
					if !visited[n.C[i]] {
						fmt.Fprintf(&bufLinks, "\t\"%p\":f%d -> \"%p\";\n", n, i, n.C[i])
						visited[n.C[i]] = true
						q.PushFront(n.C[i])
					}
				}
			}
		}
	}
	bufLinks.WriteTo(&bufGraph)
	bufLabels.WriteTo(&bufGraph)
	fmt.Fprintln(&bufGraph, "}")
	return bufGraph.String()
}
Example #10
0
func main() {
	printArticleFl := flag.Bool("p", false, "Print articles")
	flag.Parse()

	var b bytes.Buffer

	rd := bufio.NewReader(os.Stdin)
	for {
		line, err := rd.ReadString('\n')
		if err != nil {
			return
		}
		line = strings.TrimSpace(line)
		if len(line) == 0 {
			continue
		}
		resp, err := http.Get(line)
		if err != nil {
			log.Printf("cannot GET %s: %s", line, err)
		}

		b.Reset()
		err = article.Parse(io.LimitReader(resp.Body, 1000000), &b)
		resp.Body.Close()
		if *printArticleFl {
			b.WriteTo(os.Stdout)
		} else {
			fmt.Printf("%6v %s\n", err == nil, line)
		}
	}
}
Example #11
0
// returns items resulting from supplied query. Use getQuery() to get the query
func getIssues(query string, config *Config) (result []JiraIssue, e error) {

	// get credentials
	credentials, err := config.GetCredentials()
	if err != nil {
		return result, err
	}

	// send the request
	//client := http.Client{Timeout: time.Duration(10*time.Millisecond)}
	client := http.Client{}
	req, _ := http.NewRequest("GET", query, nil)
	req.Header.Set("Accept", "application/json")
	req.Header.Set("Authorization", "Basic "+credentials)
	var resp *http.Response
	if resp, err = client.Do(req); err != nil {
		return nil, fmt.Errorf("No such host: %v", err)
	}
	defer resp.Body.Close()

	// process the response
	if resp.StatusCode == 200 { // OK

		if PRINT_JSON {
			var indented bytes.Buffer
			bodyBytes, _ := ioutil.ReadAll(resp.Body)
			json.Indent(&indented, bodyBytes, "", "\t")
			indented.WriteTo(os.Stdout)
		}

		// decode json
		var list JiraIssueList
		json.NewDecoder(resp.Body).Decode(&list)
		result = list.Issues

	} else {
		name := ""
		info := ""
		switch resp.StatusCode {
		case 400:
			name = "400 (Bad Request)"
			info = "Possible causes:\n" +
				" - A project doesn't exist\n" +
				" - A filter doesn't exist\n" +
				" - Nested comma, quote, or backslash"
		case 401:
			name = "401 (Not Authorized)"
			info = "Possible causes:\n" +
				" - Incorrect username or password\n" +
				" - Your server doesn't support basic authentication\n" +
				" - You are trying to use OAuth"
		case 404:
			name = "404 (Not Found)"
			info = "Perhaps your Jira instance is configured differently?"
		}
		e = fmt.Errorf("Response Status Code %s\n%s\nQuery: %s\n", name, info, query)
	}

	return result, e
}
Example #12
0
// uiHandler draws the build status page.
func uiHandler(w http.ResponseWriter, r *http.Request) {
	d := dashboardForRequest(r)
	c := d.Context(appengine.NewContext(r))
	now := cache.Now(c)
	const key = "build-ui"

	page, _ := strconv.Atoi(r.FormValue("page"))
	if page < 0 {
		page = 0
	}

	// Used cached version of front page, if available.
	if page == 0 {
		var b []byte
		if cache.Get(r, now, key, &b) {
			w.Write(b)
			return
		}
	}

	commits, err := dashCommits(c, page)
	if err != nil {
		logErr(w, r, err)
		return
	}
	builders := commitBuilders(commits, "")

	var tipState *TagState
	if page == 0 {
		// only show sub-repo state on first page
		tipState, err = TagStateByName(c, "tip")
		if err != nil {
			logErr(w, r, err)
			return
		}
	}

	p := &Pagination{}
	if len(commits) == commitsPerPage {
		p.Next = page + 1
	}
	if page > 0 {
		p.Prev = page - 1
		p.HasPrev = true
	}
	data := &uiTemplateData{d, commits, builders, tipState, p}

	var buf bytes.Buffer
	if err := uiTemplate.Execute(&buf, data); err != nil {
		logErr(w, r, err)
		return
	}

	// Cache the front page.
	if page == 0 {
		cache.Set(r, now, key, buf.Bytes())
	}

	buf.WriteTo(w)
}
Example #13
0
func (w *MirrorListRenderer) Write(ctx *Context, results *Results) (statusCode int, err error) {
	if ctx.Templates().mirrorlist == nil {
		// No templates found for the mirrorlist
		return http.StatusInternalServerError, TemplatesNotFound
	}
	// Sort the exclude reasons by message so they appear grouped
	sort.Sort(ByExcludeReason{results.ExcludedList})

	// Create a temporary output buffer to render the page
	var buf bytes.Buffer

	// Generate the URL to the map
	results.MapURL = getMirrorMapUrl(results.MirrorList, results.ClientInfo)
	ctx.ResponseWriter().Header().Set("Content-Type", "text/html; charset=utf-8")

	// Render the page into the buffer
	err = ctx.Templates().mirrorlist.ExecuteTemplate(&buf, "base", results)
	if err != nil {
		// Something went wrong, discard the buffer
		return http.StatusInternalServerError, err
	}

	// Write the buffer to the socket
	buf.WriteTo(ctx.ResponseWriter())
	return http.StatusOK, nil
}
Example #14
0
func (p *Project) WriteTo(w io.Writer) (int64, error) {
	var b bytes.Buffer
	if err := projectTemplate.Execute(&b, p); err != nil {
		return 0, err
	}
	return b.WriteTo(w)
}
// Accepts a http connection & request pair. It hijacks the connection, sends headers and calls
// proceed if succesfull.
func (s *htmlfileSocket) accept(w http.ResponseWriter, req *http.Request, proceed func()) (err os.Error) {
	if s.connected {
		return ErrConnected
	}

	rwc, _, err := w.Hijack()

	if err == nil {
		rwc.(*net.TCPConn).SetReadTimeout(s.t.rtimeout)
		rwc.(*net.TCPConn).SetWriteTimeout(s.t.wtimeout)

		buf := new(bytes.Buffer)
		buf.WriteString("HTTP/1.1 200 OK\r\n")
		buf.WriteString("Content-Type: text/html\r\n")
		buf.WriteString("Connection: keep-alive\r\n")
		buf.WriteString("Transfer-Encoding: chunked\r\n\r\n")
		if _, err = buf.WriteTo(rwc); err != nil {
			rwc.Close()
			return
		}
		if _, err = fmt.Fprintf(rwc, "%x\r\n%s\r\n", len(htmlfileHeader), htmlfileHeader); err != nil {
			rwc.Close()
			return
		}

		s.rwc = rwc
		s.connected = true
		proceed()
	}

	return
}
Example #16
0
func (r *RenderTemplateResult) Apply(req *Request, resp *Response) {
	// Handle panics when rendering templates.
	defer func() {
		if err := recover(); err != nil {
			ERROR.Println(err)
			PlaintextErrorResult{fmt.Errorf("Template Execution Panic in %s:\n%s",
				r.Template.Name(), err)}.Apply(req, resp)
		}
	}()

	chunked := Config.BoolDefault("results.chunked", false)

	// In a prod mode, write the status, render, and hope for the best.
	// (In a dev mode, always render to a temporary buffer first to avoid having
	// error pages distorted by HTML already written)
	if chunked && !DevMode {
		resp.WriteHeader(http.StatusOK, "text/html")
		r.render(req, resp, resp.Out)
		return
	}

	// Render the template into a temporary buffer, to see if there was an error
	// rendering the template.  If not, then copy it into the response buffer.
	// Otherwise, template render errors may result in unpredictable HTML (and
	// would carry a 200 status code)
	var b bytes.Buffer
	r.render(req, resp, &b)
	if !chunked {
		resp.Out.Header().Set("Content-Length", strconv.Itoa(b.Len()))
	}
	resp.WriteHeader(http.StatusOK, "text/html")
	b.WriteTo(resp.Out)
}
Example #17
0
func writeEvent(ev *Event, writer io.Writer) error {
	if len(ev.raw) > 0 {
		_, err := writer.Write(ev.raw)
		return err
	}
	var buf bytes.Buffer
	dataBuf, err := proto.Marshal(ev.Msg)
	if nil != err {
		return err
	}
	msgtype := proto.MessageName(ev.Msg)
	ev.MsgType = &msgtype
	headbuf, _ := proto.Marshal(ev)
	headerLen := uint32(len(headbuf))

	// length = msglength(3byte) + headerlen(1byte)
	length := uint32(len(dataBuf))
	length = (length << 8) + headerLen
	buf.Write(MAGIC_EVENT_HEADER)
	binary.Write(&buf, binary.LittleEndian, length)

	buf.Write(headbuf)
	buf.Write(dataBuf)
	_, err = buf.WriteTo(writer)

	return err
}
// Accepts a http connection & request pair. It hijacks the connection, sends headers and calls
// proceed if succesfull.
func (s *xhrMultipartSocket) accept(w http.ResponseWriter, req *http.Request, proceed func()) (err error) {
	if s.connected {
		return ErrConnected
	}

	rwc, _, err := w.(http.Hijacker).Hijack()

	if err == nil {
		//		rwc.(*net.TCPConn).SetReadTimeout(s.t.rtimeout)
		//		rwc.(*net.TCPConn).SetWriteTimeout(s.t.wtimeout)

		buf := new(bytes.Buffer)
		buf.WriteString("HTTP/1.0 200 OK\r\n")
		buf.WriteString("Content-Type: multipart/x-mixed-replace; boundary=\"socketio\"\r\n")
		buf.WriteString("Connection: keep-alive\r\n")
		if origin := req.Header.Get("Origin"); origin != "" {
			fmt.Fprintf(buf,
				"Access-Control-Allow-Origin: %s\r\nAccess-Control-Allow-Credentials: true\r\n",
				origin)
		}
		buf.WriteString("\r\n--socketio\r\n")

		if _, err = buf.WriteTo(rwc); err != nil {
			rwc.Close()
			return
		}

		s.rwc = rwc
		s.connected = true
		proceed()
	}

	return
}
func writeout(decodeOnFly bool, fullpath string, fileName string, w http.ResponseWriter, r *http.Request) {
	var b []byte
	var err error
	if decodeOnFly {
		// decode the file
		b, err = vc.Decode(fullpath)
		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
	} else {
		// read the entire png file to a byte array
		b, err = ioutil.ReadFile(fullpath)
		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
	}
	w.Header().Set("Content-Disposition", "attachment; filename="+fileName)
	w.Header().Set("Content-Type", "image/png")

	var buff bytes.Buffer
	buff.Write(b)
	buff.WriteTo(w)
}
Example #20
0
// Save saves the config in a configuration file.
// If it already exists, it removes it and writes it freshly.
// Make sure you lock and unlock the config while calling Save.
func (c *Config) Save() error {
	if fileutil.Exists(configPath) {
		if err := os.Remove(configPath); err != nil {
			return err
		}
	}

	f, err := os.Create(configPath)
	if err != nil {
		return err
	}
	// Brad Fitzpatrick:
	// Never defer a file Close when the file was opened for writing.
	// Many filesystems do their real work (and thus their real failures) on close.
	// You can defer a file.Close for Read, but not for write.

	var out bytes.Buffer
	b, err := json.MarshalIndent(c, "", "  ")
	if err != nil {
		return err
	}
	out.Write(b)
	out.WriteTo(f)

	if err := f.Close(); err != nil {
		return err
	}

	return nil
}
Example #21
0
File: main.go Project: rollcat/json
func json_dump(o any) {
	b, err := json.Marshal(o)
	assert(err)
	var out bytes.Buffer
	json.Indent(&out, b, "", "\t")
	out.WriteTo(os.Stdout)
}
Example #22
0
// serveFile delivers an HTML fragment of a Go source file with
// highlighted comments and an (optional) highlighted selection.
// The request parameters are:
//
//   path: "/path/to/file.go"
//   s: optional selection range like "line.col-line.col", e.g. "24.4-25.10"
//
// Returns a "403 Forbidden" status code if the requested file
// is not within the import scope, or a "404 Not Found" if the
// file can't be read.
func serveFile(w http.ResponseWriter, req *http.Request) {
	path := req.FormValue("path")
	if isForbidden(path) {
		errorForbidden(w)
		return
	}
	content, err := ioutil.ReadFile(path)
	if err != nil {
		log.Println(req.RemoteAddr, err)
		http.NotFound(w, req)
		return
	}

	var sel godoc.Selection
	s, err := parseSelection(req.FormValue("s"))
	if err == nil {
		offsets := s.byteOffsetsIn(content)
		sel = godoc.RangeSelection(offsets)
	}

	var buf bytes.Buffer
	godoc.FormatText(&buf, content, -1, true, "", sel)

	buf.WriteTo(w)
}
Example #23
0
func main() {
	if len(os.Args) < 2 {
		fmt.Printf("Usage: %s file.ffindex\n", os.Args[0])
		return
	}

	f, err := os.Open(os.Args[1])
	if err != nil {
		log.Fatalf("Can't open %s.", os.Args[1])
	}
	defer f.Close()

	idx, err := ffmsindex.ReadIndex(f)
	if err != nil {
		log.Fatalf(err.Error())
	}

	out, err := json.Marshal(idx)
	if err != nil {
		log.Fatalf(err.Error())
	}

	var b bytes.Buffer
	err = json.Indent(&b, out, "", "    ")
	if err != nil {
		log.Fatalf(err.Error())
	}

	b.WriteTo(os.Stdout)
}
Example #24
0
func PrettyJsonWriter(thing interface{}, w http.ResponseWriter) {
	var out bytes.Buffer
	b, err := json.MarshalIndent(thing, "", "  ")
	checkError(err)
	out.Write(b)
	out.WriteTo(w)
}
Example #25
0
// Bulk Reply
func (s *session) replyBulk(bulk interface{}) (err error) {
	// NULL Bulk Reply
	isnil := bulk == nil
	if !isnil {
		b, ok := bulk.([]byte)
		isnil = ok && b == nil
	}
	if isnil {
		_, err = s.Write([]byte("$-1\r\n"))
		return
	}
	buf := bytes.Buffer{}
	buf.WriteString("$")
	switch bulk.(type) {
	case []byte:
		b := bulk.([]byte)
		buf.WriteString(utils.ItoaQuick(len(b)))
		buf.WriteString(CRLF)
		buf.Write(b)
	default:
		b := []byte(bulk.(string))
		buf.WriteString(utils.ItoaQuick(len(b)))
		buf.WriteString(CRLF)
		buf.Write(b)
	}
	buf.WriteString(CRLF)
	_, err = buf.WriteTo(s)
	return
}
Example #26
0
func (r region) WriteOpensimINI(configs []mgm.ConfigOption) error {
	opensimINI := path.Join(r.dir, "OpenSim.ini")

	cfgs := make(map[string]map[string]string)
	for _, cfg := range configs {
		if _, ok := cfgs[cfg.Section]; !ok {
			cfgs[cfg.Section] = make(map[string]string)
		}
		cfgs[cfg.Section][cfg.Item] = cfg.Content
	}

	//write the configuration into a buffer
	var buffer bytes.Buffer

	for section, m := range cfgs {
		buffer.WriteString(fmt.Sprintf("[%s]\n", section))
		for item, content := range m {
			buffer.WriteString(fmt.Sprintf("  %s = \"%s\"\n", item, content))
		}
	}

	f, err := os.Create(opensimINI)
	if err != nil {
		return err
	}
	defer f.Close()

	_, err = buffer.WriteTo(f)

	return err
}
Example #27
0
func ExampleBuffer() {
	var b bytes.Buffer // A Buffer needs no initialization.
	b.Write([]byte("Hello "))
	fmt.Fprintf(&b, "world!")
	b.WriteTo(os.Stdout)
	// Output: Hello world!
}
func (nego *d5SNegotiation) verifyThenDHExchange(conn net.Conn, credBuf []byte) (key []byte, err error) {
	userIdentity, err := RSADecrypt(credBuf, nego.RSAKeys.priv)
	ThrowErr(err)
	clientIdentity := string(userIdentity)
	if log.V(2) {
		log.Infoln("Auth clientIdentity:", clientIdentity)
	}
	allow, ex := nego.AuthSys.Authenticate(userIdentity)
	cDHPub, err := ReadFullByLen(2, conn)
	if !allow {
		log.Warningf("Auth %s failed: %v\n", clientIdentity, ex)
		conn.Write([]byte{0, 1, 0xff})
		return nil, ex
	}
	nego.clientIdentity = clientIdentity
	key = takeSharedKey(nego.dhKeys, cDHPub)
	//	if log.V(5) {
	//		dumpHex("Sharedkey", key)
	//	}
	buf := new(bytes.Buffer)
	buf.Write(nego.dhKeys.pubLen)
	buf.Write(nego.dhKeys.pub)
	_, err = buf.WriteTo(conn)
	return
}
Example #29
0
func handleRootHealthz(w http.ResponseWriter, r *http.Request) {
	lock.RLock()
	defer lock.RUnlock()
	failed := false
	var verboseOut bytes.Buffer
	for _, name := range names {
		check, found := checks[name]
		if !found {
			// this should not happen
			http.Error(w, fmt.Sprintf("Internal server error: check \"%q\" not registered", name), http.StatusInternalServerError)
			return
		}
		err := check.check(r)
		if err != nil {
			fmt.Fprintf(&verboseOut, "[-]%v failed: %v\n", check.name, err)
			failed = true
		} else {
			fmt.Fprintf(&verboseOut, "[+]%v ok\n", check.name)
		}
	}
	// always be verbose on failure
	if failed {
		http.Error(w, fmt.Sprintf("%vhealthz check failed", verboseOut.String()), http.StatusInternalServerError)
		return
	}

	if _, found := r.URL.Query()["verbose"]; !found {
		fmt.Fprint(w, "ok")
		return
	} else {
		verboseOut.WriteTo(w)
		fmt.Fprint(w, "healthz check passed\n")
	}
}
Example #30
0
func (s *Service) writeMetaStore(conn net.Conn) error {
	// Retrieve and serialize the current meta data.
	buf, err := s.MetaClient.MarshalBinary()
	if err != nil {
		return fmt.Errorf("marshal meta: %s", err)
	}

	var b bytes.Buffer
	enc := json.NewEncoder(&b)
	if err := enc.Encode(s.Node); err != nil {
		return err
	}

	if _, err := conn.Write(u64tob(BackupMagicHeader)); err != nil {
		return err
	}

	if _, err := conn.Write(u64tob(uint64(len(buf)))); err != nil {
		return err
	}

	if _, err := conn.Write(buf); err != nil {
		return err
	}

	if _, err := conn.Write(u64tob(uint64(b.Len()))); err != nil {
		return err
	}

	if _, err := b.WriteTo(conn); err != nil {
		return err
	}
	return nil
}