Exemplo n.º 1
1
func Get(w http.ResponseWriter, r *http.Request) {
	w.SetHeader("Content-Type", "application/json")
	lock.Lock()
	e := json.NewEncoder(w)
	e.Encode(server)
	lock.Unlock()
}
Exemplo n.º 2
1
/*
 * @return information about this session
 */
func (self *Session) InfoHandler(w http.ResponseWriter, r *http.Request) os.Error {
	// Find the user of this session
	user, err := self.sessionDatabase.server.UserAccountDatabase.FindUser(self.Username)
	if err != nil {
		makeErrorResponse(w, err.String())
		return err
	}

	result := make(map[string]string)
	result["sid"] = self.Id
	result["user"] = self.Username
	result["displayName"] = user.DisplayName
	result["domain"] = self.sessionDatabase.server.Capabilities().Domain
	json, err := json.Marshal(result)
	if err != nil {
		log.Println("Failed marshaling to json")
		makeErrorResponse(w, "Failed marshaling to json")
		return err
	}
	w.SetHeader("Content-Type", "application/json")
	_, err = w.Write(json)
	if err != nil {
		log.Println("Failed writing HTTP response")
		makeErrorResponse(w, "Failed writing HTTP response")
		return err
	}
	return nil
}
Exemplo n.º 3
0
// exec a program, redirecting output
func DateServer(rw http.ResponseWriter, req *http.Request) {
	rw.SetHeader("content-type", "text/plain; charset=utf-8")
	r, w, err := os.Pipe()
	if err != nil {
		fmt.Fprintf(rw, "pipe: %s\n", err)
		return
	}
	pid, err := os.ForkExec("/bin/date", []string{"date"}, os.Environ(), "", []*os.File{nil, w, w})
	defer r.Close()
	w.Close()
	if err != nil {
		fmt.Fprintf(rw, "fork/exec: %s\n", err)
		return
	}
	io.Copy(rw, r)
	wait, err := os.Wait(pid, 0)
	if err != nil {
		fmt.Fprintf(rw, "wait: %s\n", err)
		return
	}
	if !wait.Exited() || wait.ExitStatus() != 0 {
		fmt.Fprintf(rw, "date: %v\n", wait)
		return
	}
}
Exemplo n.º 4
0
func ProxyServer(w http.ResponseWriter, req *http.Request) {
	log.Printf("%#v", req)
	addr, err := net.ResolveIPAddr(req.URL.Host)
	if err != nil {
		io.WriteString(w, err.String())
		return
	}
	conn, err := net.DialTCP("tcp4", nil, &net.TCPAddr{IP: addr.IP, Port: 80})
	if err != nil {
		io.WriteString(w, err.String())
		return
	}
	defer conn.Close()
	client := http.NewClientConn(conn, nil)
	err = client.Write(req)
	if err != nil {
		io.WriteString(w, err.String())
		return
	}
	resp, err := client.Read()
	if err != nil {
		io.WriteString(w, err.String())
		return
	}
	for k, v := range resp.Header {
		w.SetHeader(k, v)
	}
	io.Copy(w, resp.Body)
	w.Flush()
}
Exemplo n.º 5
0
// Symbol looks up the program counters listed in the request,
// responding with a table mapping program counters to function names.
// The package initialization registers it as /debug/pprof/symbol.
func Symbol(w http.ResponseWriter, r *http.Request) {
	w.SetHeader("content-type", "text/plain; charset=utf-8")

	// We don't know how many symbols we have, but we
	// do have symbol information.  Pprof only cares whether
	// this number is 0 (no symbols available) or > 0.
	fmt.Fprintf(w, "num_symbols: 1\n")

	var b *bufio.Reader
	if r.Method == "POST" {
		b = bufio.NewReader(r.Body)
	} else {
		b = bufio.NewReader(strings.NewReader(r.URL.RawQuery))
	}

	for {
		word, err := b.ReadSlice('+')
		if err == nil {
			word = word[0 : len(word)-1] // trim +
		}
		pc, _ := strconv.Btoui64(string(word), 0)
		if pc != 0 {
			f := runtime.FuncForPC(uintptr(pc))
			if f != nil {
				fmt.Fprintf(w, "%#x %s\n", pc, f.Name())
			}
		}

		// Wait until here to check for err; the last
		// symbol will have an err because it doesn't end in +.
		if err != nil {
			break
		}
	}
}
Exemplo n.º 6
0
func handleAudit(w http.ResponseWriter, r *http.Request) {
	_, kind := path.Split(r.URL.Path)
	ip := r.FormValue("IP")
	ser := DefaultMaster.delegator.Delegate(kind)
	keys := ser.Keys()
	n := ser.Init()
	for _, v := range keys {
		ss := ser.At(v).(SerialSender)
		host := ss.Host()
		if host == ip || host == "" {
			n = n.Insert(ss)
		}
	}
	if len(n.Keys()) != 0 {
		w.SetHeader("Content-Encoding", "gzip")
		w.SetHeader("Content-Type", "application/octet-stream")
		err := DefaultMaster.SaveKind(w, n)
		if err != nil {
			DefaultMaster.Logger.Printf("Problem: Audit Typ %s mit Server %s fehlgeschlagen", n.Kind(), ip)
			w.WriteHeader(500)
		}
		return
	}
	w.WriteHeader(404)
}
Exemplo n.º 7
0
func handleReplaceForm(w http.ResponseWriter, r *http.Request) {
	r.ParseForm()
	_, kind := path.Split(r.URL.Path)
	ser := DefaultMaster.delegator.Delegate(kind).(SerializerFormParser)
	s := ser.NewFromForm(r.Form)
	if s == nil {
		r.Form = nil
		w.SetHeader("Location", r.Referer)
		w.WriteHeader(302)
		return
	}
	ser.Replace(s)
	DefaultMaster.Save(s)
	out := bytes.NewBufferString("")
	host := s.Host()
	if host != "" {
		DefaultMaster.save(out, s)
		http.Post("http://"+host+DefaultMaster.replacePattern+kind, "application/octet-stream", out)
	} else {
		bc := DefaultMaster.delegator.(DelegatorBroadcaster)
		for _, h := range bc.Hosts() {
			out = bytes.NewBufferString("")
			DefaultMaster.save(out, s)
			http.Post("http://"+h+DefaultMaster.replacePattern+kind, "application/octet-stream", out)
		}
	}
	DefaultMaster.Logger.Printf("%v erfolgreich modifiziert", s.Log())
	redir := "http://" + r.Host + r.FormValue("Redir")
	w.SetHeader("Location", redir)
	w.WriteHeader(302)
}
Exemplo n.º 8
0
func handleDeleteForm(w http.ResponseWriter, r *http.Request) {
	r.ParseForm()
	_, kind := path.Split(r.URL.Path)
	key := DefaultMaster.delegator.(DelegatorBroadcaster).KeyFromForm(r.Form)
	ser := DefaultMaster.delegator.Delegate(kind)
	keys := ser.Keys()
	n := ser.Init()
	for _, v := range keys {
		if v != key {
			n = n.Insert(ser.At(v))
		}
	}
	ser.All(n)
	s := ser.At(key).(SerialSender)
	DefaultMaster.Delete(s)
	out := bytes.NewBufferString("")
	host := s.Host()
	if host != "" {
		DefaultMaster.save(out, s)
		http.Post("http://"+host+DefaultMaster.deletePattern+kind, "application/octet-stream", out)
	} else {
		bc := DefaultMaster.delegator.(DelegatorBroadcaster)
		for _, h := range bc.Hosts() {
			out = bytes.NewBufferString("")
			DefaultMaster.save(out, s)
			http.Post("http://"+h+DefaultMaster.deletePattern+kind, "application/octet-stream", out)
		}
	}
	DefaultMaster.Logger.Printf("%v erfolgreich gelöscht", s.Log())
	redir := "http://" + r.Host + r.FormValue("Redir")
	w.SetHeader("Location", redir)
	w.WriteHeader(302)
}
Exemplo n.º 9
0
func Dispatch(w http.ResponseWriter) os.Error {
	t := View.Themes.Current()
	if t == nil {
		se := &ServerError{404, "Not Found"}
		se.Write(w)
		return os.ENOENT
	}
	w.SetHeader("Content-Type", "text/html; charset=utf-8")
	w.SetHeader("Content-Encoding", "gzip")

	templ, err := template.Parse(t.Index, nil)
	if err != nil {
		return err
	}
	gz, err := gzip.NewWriter(w)
	if err != nil {
		return err
	}
	err = templ.Execute(gz, View)
	if err != nil {
		return err
	}

	gz.Close()
	return nil
}
Exemplo n.º 10
0
func Images(w http.ResponseWriter, r *http.Request) {

	imagePath := path.Base(r.URL.Path)
	mimeType := mime.TypeByExtension(path.Ext(imagePath))

	w.SetHeader("Content-Type", mimeType)
	w.SetHeader("Cache-Control", "max-age=31104000, public")
	current := View.Themes.Current()
	if current == nil {
		se := &ServerError{404, "Not Found"}
		se.Write(w)
		return
	}
	for _, v := range View.Resources {
		if v.Template == current.ID {
			if v.Name == imagePath {
				w.Write(v.Data)
				w.Flush()
				return
			}
		}
	}
	se := &ServerError{404, "Not Found"}
	se.Write(w)
	return
}
Exemplo n.º 11
0
func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	s.mu.Lock()
	defer s.mu.Unlock()
	w.SetHeader("Content-Type", "application/json")
	e := json.NewEncoder(w)
	e.Encode(s.series)
}
Exemplo n.º 12
0
func SetSecureCookie(rw http.ResponseWriter, name, val, path string, timeout int64) {
	var buf bytes.Buffer

	e := base64.NewEncoder(base64.StdEncoding, &buf)
	e.Write([]byte(val))
	e.Close()

	ts := strconv.Itoa64(time.Seconds())
	data := strings.Join([]string{buf.String(), ts, getCookieSig(buf.Bytes(), ts)}, "|")

	var cookie string

	// Timeout of -1 is a special case that omits the entire 'expires' bit.
	// This is used for cookies which expire as soon as a user's session ends.
	if timeout != -1 {
		t := time.UTC()
		t = time.SecondsToUTC(t.Seconds() + timeout)
		ts = t.Format(time.RFC1123)
		ts = ts[0:len(ts)-3] + "GMT"
		cookie = fmt.Sprintf("%s=%s; expires=%s; path=%s", name, data, ts, path)
	} else {
		cookie = fmt.Sprintf("%s=%s; path=%s", name, data, path)
	}

	if context.Config().Secure {
		cookie += "; secure"
	}

	rw.SetHeader("Set-Cookie", cookie)
}
Exemplo n.º 13
0
// Creates a HTTP error response
func makeHtmlErrorResponse(res http.ResponseWriter, errorText string) {
	log.Println(errorText)
	res.SetHeader("Content-Type", "text/html")
	_, err := res.Write([]byte(errorText))
	if err != nil {
		log.Println("Failed writing HTTP response")
	}
}
Exemplo n.º 14
0
func Css(w http.ResponseWriter, r *http.Request) {
	w.SetHeader("Content-Encoding", "gzip")
	w.SetHeader("Content-Type", "text/css")

	gz, _ := gzip.NewWriter(w)
	gz.Write([]byte(View.Themes.Current().Style))
	gz.Close()
}
Exemplo n.º 15
0
func (proxy *Proxy) ServeHTTP(conn http.ResponseWriter, req *http.Request) {

	// Open a connection to the Hub.
	hubconn, err := net.Dial("tcp", "", remoteAddr)
	if err != nil {
		if debugMode {
			fmt.Printf("Couldn't connect to remote %s: %v\n", remoteHost, err)
		}
		return
	}

	hub := tls.Client(hubconn, tlsconf.Config)
	defer hub.Close()

	// Modify the request Host: header.
	req.Host = remoteHost

	// Send the request to the Hub.
	err = req.Write(hub)
	if err != nil {
		if debugMode {
			fmt.Printf("Error writing to the hub: %v\n", err)
		}
		return
	}

	// Parse the response from the Hub.
	resp, err := http.ReadResponse(bufio.NewReader(hub), req.Method)
	if err != nil {
		if debugMode {
			fmt.Printf("Error parsing response from the hub: %v\n", err)
		}
		return
	}

	// Set the received headers back to the initial connection.
	for k, v := range resp.Header {
		conn.SetHeader(k, v)
	}

	// Read the full response body.
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		if debugMode {
			fmt.Printf("Error reading response from the hub: %v\n", err)
		}
		resp.Body.Close()
		return
	}

	// Write the response body back to the initial connection.
	resp.Body.Close()
	conn.WriteHeader(resp.StatusCode)
	conn.Write(body)

}
Exemplo n.º 16
0
func FileHelper(w http.ResponseWriter, r *http.Request) {
	mimeType := mime.TypeByExtension(path.Ext(r.URL.Path))
	w.SetHeader("Content-Encoding", "gzip")
	w.SetHeader("Content-Type", mimeType)
	//w.SetHeader("Expires", "Fri, 30 Oct 2013 14:19:41 GMT")
	b, _ := ioutil.ReadFile("." + r.URL.Path)
	gz, _ := gzip.NewWriter(w)
	gz.Write(b)
	gz.Close()
}
Exemplo n.º 17
0
func (s *Settings) Set(c http.ResponseWriter) {
	if s.WhichCard != s.Card().Name {
		c := s.Card()
		s.Cards[s.WhichCard] = nil, false
		s.WhichCard = c.Name
		s.Cards[s.WhichCard] = c
	}
	bytes, _ := json.Marshal(*s)
	c.SetHeader("Set-Cookie", string(bytes))
}
Exemplo n.º 18
0
func viewHtml(w http.ResponseWriter, r *http.Request) {
	if !strings.HasSuffix(r.URL.Path, "/") {
		w.WriteHeader(404)
		return
	}
	var x info
	x.Path = r.URL.Path[len("/view"):]
	w.SetHeader("content-type", "text/html")
	mainTpl.Execute(x, w)
}
Exemplo n.º 19
0
func GlobalController(w http.ResponseWriter, r *http.Request) {
	imagePath := path.Base(r.URL.Path)
	mimeType := mime.TypeByExtension(path.Ext(imagePath))
	w.SetHeader("Content-Type", mimeType)
	for _, v := range View.Globals {
		if v.Name == imagePath {
			w.Write(v.Data)
			w.Flush()
		}
	}
}
Exemplo n.º 20
0
func writeWorld(w http.ResponseWriter, req *http.Request) {
	world := JsonWorld{World: &World, CurrentTime: time.Nanoseconds()}
	bytes, err := json.Marshal(world)
	if err != nil {
		log.Fatalf("Error writing JSON: %s", err)
	}

	w.SetHeader("Access-Control-Allow-Origin", "*")
	w.SetHeader("Access-Control-Max-Age", "3600")
	w.Write(bytes)
}
Exemplo n.º 21
0
func FlagServer(w http.ResponseWriter, req *http.Request) {
	w.SetHeader("content-type", "text/plain; charset=utf-8")
	fmt.Fprint(w, "Flags:\n")
	flag.VisitAll(func(f *flag.Flag) {
		if f.Value.String() != f.DefValue {
			fmt.Fprintf(w, "%s = %s [default = %s]\n", f.Name, f.Value.String(), f.DefValue)
		} else {
			fmt.Fprintf(w, "%s = %s\n", f.Name, f.Value.String())
		}
	})
}
Exemplo n.º 22
0
func ReturnJson(conn http.ResponseWriter, data interface{}) {
	conn.SetHeader("Content-Type", "text/javascript")
	bytes, err := json.MarshalIndent(data, "", "  ")
	if err != nil {
		BadRequestError(conn, fmt.Sprintf(
			"JSON serialization error: %v", err))
		return
	}
	conn.Write(bytes)
	conn.Write([]byte("\n"))
}
Exemplo n.º 23
0
Arquivo: web.go Projeto: kr/doozerd
func viewHtml(w http.ResponseWriter, r *http.Request) {
	if !strings.HasSuffix(r.URL.Path, "/") {
		w.WriteHeader(404)
		return
	}
	var x info
	x.Name = ClusterName
	x.Path = r.URL.Path
	w.SetHeader("content-type", "text/html")
	mainTpl.Execute(w, x)
}
Exemplo n.º 24
0
func expvarHandler(w http.ResponseWriter, r *http.Request) {
	w.SetHeader("content-type", "application/json; charset=utf-8")
	fmt.Fprintf(w, "{\n")
	first := true
	for name, value := range vars {
		if !first {
			fmt.Fprintf(w, ",\n")
		}
		first = false
		fmt.Fprintf(w, "%q: %s", name, value)
	}
	fmt.Fprintf(w, "\n}\n")
}
Exemplo n.º 25
0
func wavServer(c http.ResponseWriter, req *http.Request) {
	c.SetHeader("Content-Type", "audio/x-wav")
	text := req.URL.Path[:len(req.URL.Path)-4]
	if len(text) > 8 {
		text = text[8:]
	}
	x, err := speech.Speak(text)
	if err == nil {
		fmt.Fprint(c, x)
	} else {
		fmt.Println("Error speaking:", err)
	}
}
Exemplo n.º 26
0
func wavServer(c http.ResponseWriter, req *http.Request) {
	c.SetHeader("Content-Type", "audio/x-wav")
	dat := getTransitoryData(req)
	text := dat.Url[:len(dat.Url)-4]
	if len(text) > 8 {
		text = text[8:]
	}
	x, err := speech.Speak(text)
	if err == nil {
		fmt.Fprint(c, x)
	} else {
		fmt.Println("Error speaking:", err)
	}
}
Exemplo n.º 27
0
// ServeHTTP implements an http.Handler that answers RPC requests.
func (server *Server) ServeHTTP(w http.ResponseWriter, req *http.Request) {
	if req.Method != "CONNECT" {
		w.SetHeader("Content-Type", "text/plain; charset=utf-8")
		w.WriteHeader(http.StatusMethodNotAllowed)
		io.WriteString(w, "405 must CONNECT\n")
		return
	}
	conn, _, err := w.Hijack()
	if err != nil {
		log.Print("rpc hijacking ", w.RemoteAddr(), ": ", err.String())
		return
	}
	io.WriteString(conn, "HTTP/1.0 "+connected+"\n\n")
	server.ServeConn(conn)
}
Exemplo n.º 28
0
// Creates a HTTP error response
func makeErrorResponse(res http.ResponseWriter, errorText string) {
	log.Println(errorText)
	m := make(map[string]interface{})
	m["ok"] = false
	m["error"] = errorText
	json, err := json.Marshal(m)
	if err != nil {
		panic("Failed marshaling to json")
	}
	res.SetHeader("Content-Type", "application/json")
	_, err = res.Write(json)
	if err != nil {
		log.Println("Failed writing HTTP response")
	}
}
Exemplo n.º 29
0
func makeClientErrorResponse(res http.ResponseWriter, errorText string) {
	log.Println(errorText)
	response := &ClientSubmitResponse{}
	response.OperationsApplied = proto.Int(0)
	response.ErrorMessage = proto.String(errorText)
	var buffer bytes.Buffer
	err := Marshal(response, &buffer)
	if err != nil {
		panic("Failed marshaling")
	}
	res.SetHeader("Content-Type", "application/json")
	_, err = res.Write(buffer.Bytes())
	if err != nil {
		log.Println("Failed writing HTTP response")
	}
}
Exemplo n.º 30
0
func (h *handler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
	var response *http.Response
	var err os.Error
	// get the next available responder
	responder := <-h.responders
	// send the request to the FastCGI responder
	reqid, err := responder.WriteRequest(w, req)
	if err != nil {
		panic("error writing request " + err.String())
		Log("Handler: Failed to write request to", responder, "disabling (error:", err, ")")
		w.WriteHeader(http.StatusInternalServerError)
		io.WriteString(w, err.String())
		responder.Close()
		return
	}
	// a multiplexing responder is available again immediately
	if responder.multiplex {
		h.responders <- responder
	}
	// read the response (blocking)
	if response, err = responder.ReadResponse(reqid, req.Method); err != nil {
		panic("Reading failed")
		Log("Handler: Failed to read response from", responder, "error:", err)
		w.WriteHeader(http.StatusInternalServerError)
		io.WriteString(w, err.String())
		return
	}
	// a non-multiplexing responder has to wait until the response is fully read
	// before it is available
	if !responder.multiplex {
		h.responders <- responder
	}
	// once response is ready, write it out to the real connection
	for k, v := range response.Header {
		w.SetHeader(k, v)
	}
	w.WriteHeader(response.StatusCode)
	if _, err = io.Copy(w, response.Body); err != nil {
		body, _ := ioutil.ReadAll(response.Body)
		Log("Handler: Error reading response.Body from", responder, "(error:", err, ")")
		io.WriteString(w, err.String())
		panic("Bad body in handler! " + err.String() + "\n" + string(body))
		return
	}
}