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() }
func (session *Session) SetCookie(w http.ResponseWriter, context appengine.Context) { cookie := &http.Cookie{ Name: "session", Value: session.Key, } w.Header().Add("Set-Cookie", cookie.String()) }
func handle(w http.ResponseWriter, r *http.Request) { c := appengine.NewContext(r) item, err := memcache.Get(c, r.URL.Path) if err != nil && err != memcache.ErrCacheMiss { serveError(c, w, err) return } n := 0 if err == nil { n, err = strconv.Atoi(string(item.Value)) if err != nil { serveError(c, w, err) return } } n++ item = &memcache.Item{ Key: r.URL.Path, Value: []byte(strconv.Itoa(n)), } err = memcache.Set(c, item) if err != nil { serveError(c, w, err) return } w.Header().Set("Content-Type", "text/plain") fmt.Fprintf(w, "%q has been visited %d times", r.URL.Path, n) }
func (v *jsonView) handle(w http.ResponseWriter, req *http.Request, s *session) { if v.checkUniqueURL != "" && req.URL.Path != v.checkUniqueURL { w.WriteHeader(http.StatusNotFound) fmt.Fprintf(w, "<pre>404 page not found</pre>") return } d := func() (ret interface{}) { defer func() { if e := recover(); e != nil { if gde, ok := e.(getDataError); ok { ret = gde } else if ose, ok := e.(os.Error); ok { ret = getDataError{http.StatusInternalServerError, ose} } else { ret = getDataError{http.StatusInternalServerError, os.NewError(fmt.Sprintf("%v", e))} } } }() return v.getData(req, s) }() dd, e := json.Marshal(d) if e != nil { fmt.Fprintf(w, "{Code: 500, Error: %#v}", e.String()) } else { w.Write(dd) } }
func evServer(w http.ResponseWriter, r *http.Request) { wevs := make(chan store.Event) path := r.URL.Path[len("/$events"):] glob, err := store.CompileGlob(path + "**") if err != nil { w.WriteHeader(400) return } rev, _ := Store.Snap() go func() { walk(path, Store, wevs) for { ch, err := Store.Wait(glob, rev+1) if err != nil { break } ev, ok := <-ch if !ok { break } wevs <- ev rev = ev.Rev } close(wevs) }() websocket.Handler(func(ws *websocket.Conn) { send(ws, path, wevs) ws.Close() }).ServeHTTP(w, r) }
func handle(w http.ResponseWriter, r *http.Request) { params, err := url.ParseQuery(r.URL.RawQuery) check(err) w.Header().Add("Access-Control-Allow-Origin", "*") w.Header().Add( "Access-Control-Allow-Methods", "OPTIONS, HEAD, GET, POST, PUT, DELETE", ) switch r.Method { case "OPTIONS": case "HEAD": case "GET": get(w, r) case "POST": if len(params["_method"]) > 0 && params["_method"][0] == "DELETE" { delete(w, r) } else { post(w, r) } case "DELETE": delete(w, r) default: http.Error(w, "501 Not Implemented", http.StatusNotImplemented) } }
func ServeDataItemPage(writer http.ResponseWriter, request *http.Request) { if strings.Contains(request.Header.Get("Accept"), "application/json") { writer.Header().Set("Content-Type", "applicaton/json") } else { writer.Header().Set("Content-Type", "text/plain") } stream := StreamByName("ranger") log.Printf("Serving full data for '%s'", request.FormValue("q")) data := stream.LookupData(request.FormValue("q")) if data == nil { log.Printf("Failed to find %s", request.FormValue("q")) writer.WriteHeader(http.StatusNotFound) return } outputBytes, err := json.MarshalIndent(data, "", " ") if err != nil { log.Printf("Failed to format data") writer.WriteHeader(http.StatusInternalServerError) return } writer.Write(outputBytes) }
func handleIndex(w http.ResponseWriter, r *http.Request) { w.Write([]byte(`<html> <head> <title>Json RPC</title> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script> <script type="text/javascript"> $(function(){ $('#button').click(function(){ var a = $('#a').val(); var b = $('#b').val(); var body = '{"jsonrpc": "2.0", "method":"Service.Add","params":['+a+', '+b+'],"id":0}'; $.post("/json", body ,function(data){ $('#output').html(data.result); }, "json"); }); }); </script> </head> <body> <h1>Go Ajax Example</h1> <input id="a" type="text" name="a" style="width: 50px;" value="5" /> <span>+</span> <input id="b" type="text" name="b" style="width: 50px;" value="7" /> <input id="button" type="button" value="="/> <span id="output"></span> </body> </html>`)) }
func InsertTweet(w http.ResponseWriter, r *http.Request) { query, _ := http.ParseQuery(r.URL.RawQuery) signature := Sign([]byte(query["message"][0])) tweet := &Tweet{Name: query["name"][0], Message: query["message"][0], Timestamp: query["date"][0], Sig: signature} TweetWrite <- tweet w.Write([]byte(`"looks good"`)) }
func uploadUser(w http.ResponseWriter, r *http.Request) { if r.Method != "POST" { // No upload; show the upload form. uploadUserTemplate.Execute(w, nil) return } f, _, err := r.FormFile("image") errors.Check(err) defer f.Close() // Grab the image data i, _, err := image.Decode(f) errors.Check(err) var key string = keyOf() // store image i = picstore.Store(key, i, 320, "userimg") i = picstore.Store(key, i, 180, "userthumb") // generate result w.Header().Set("Content-Type", "application/json") w.Header().Set("cache-control", "no-cache") w.Header().Set("Expires", "-1") fmt.Fprintf(w, "{\"profilePicUrl\":\"uimg?id="+key+"\",\"profileThumbUrl\":\"utmb?id="+key+"\"}") }
// 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.Header().Set("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 } } }
func authCallback(w http.ResponseWriter, r *http.Request, oldSession *Session) { // We cheat here -- font-end has direct access to the oauth data code := r.FormValue("code") context := appengine.NewContext(r) var userKey datastore.Key _, err := memcache.Gob.Get(context, "oauth-code-"+code, &userKey) if err != nil { w.Write([]byte("Invalid code")) } else { /* auth := model.NewOAuth2(&userKey) if _, err = datastore.Put(context, datastore.NewIncompleteKey(context, "Authentication", nil), auth); err != nil { context.Errorf("Error saving: %v", err) w.Write([]byte("Error saving: " + err.String())) return } // replace session cookie oldKey := datastore.NewKey(context, "Session", oldSession.Key, 0, nil) datastore.Delete(context, oldKey) session := NewSession(context) oldSession.Key = session.Key oldSession.Token = auth.Token oldSession.SetCookie(w, context) // redirect */ } }
func serveObject(val reflect.Value, w http.ResponseWriter, r *http.Request) os.Error { switch r.Method { case "HEAD", "GET", "PUT": default: return nil return &BadMethod{r.URL.Path, r.Method, val.Interface()} } ctype := "application/json" // TODO(kevlar): Content type negotiation w.Header().Set("Content-Type", ctype) if r.Method == "HEAD" { return nil } js, err := json.Marshal(val.Interface()) if err != nil { return &FailedEncode{err, ctype, val.Interface()} } if _, err := w.Write(js); err != nil { return err } return nil }
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) }
func handleVerify(conn http.ResponseWriter, req *http.Request) { if !(req.Method == "POST" && req.URL.Path == "/camli/sig/verify") { httputil.BadRequestError(conn, "Inconfigured handler.") return } req.ParseForm() sjson := req.FormValue("sjson") if sjson == "" { httputil.BadRequestError(conn, "Missing sjson parameter.") return } m := make(map[string]interface{}) vreq := jsonsign.NewVerificationRequest(sjson, pubKeyFetcher) if vreq.Verify() { m["signatureValid"] = 1 m["verifiedData"] = vreq.PayloadMap } else { errStr := vreq.Err.String() m["signatureValid"] = 0 m["errorMessage"] = errStr } conn.WriteHeader(http.StatusOK) // no HTTP response code fun, error info in JSON httputil.ReturnJson(conn, m) }
// 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 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.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, ok := req.Header["Origin"]; ok { 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 join(w http.ResponseWriter, r *http.Request) { c := appengine.NewContext(r) u := user.Current(c) if u == nil { url, err := user.LoginURL(c, r.URL.String()) if err != nil { http.Error(w, err.String(), http.StatusInternalServerError) return } w.Header().Set("Location", url) w.WriteHeader(http.StatusFound) return } r.ParseForm() // TODO check table arg state, err := joinTable(c, r.Form["table"][0], u.String()) if err != nil { http.Error(w, err.String(), http.StatusInternalServerError) return } var b []byte b, err = json.Marshal(state) if err != nil { http.Error(w, err.String(), http.StatusInternalServerError) return } fmt.Fprintf(w, "%s", b) }
func StartTiling(w http.ResponseWriter, req *http.Request) { if reset != nil { select { case <-reset: reset <- 1 case reset <- 1: } } tilingType := req.FormValue("type") tileSymmetry := req.FormValue("symmetry") if tilingType == "skeleton" { skeleton := req.FormValue("skeleton") showIntermediate, ok := strconv.Atob(req.FormValue("intermediate")) if ok != nil || skeleton == "" { w.WriteHeader(http.StatusNotFound) } ZellijTilings, reset = zellij.TileSkeleton(skeleton, tileSymmetry, showIntermediate) w.WriteHeader(http.StatusOK) return } else if tilingType == "plane" { maxtiles, okm := strconv.Atoi(req.FormValue("maxtiles")) showIntermediate, oks := strconv.Atob(req.FormValue("intermediate")) if okm != nil || oks != nil || maxtiles == 0 { w.WriteHeader(http.StatusNotFound) } ZellijTilings, reset = zellij.TilePlane(maxtiles, tileSymmetry, showIntermediate) w.WriteHeader(http.StatusOK) return } w.WriteHeader(http.StatusNotFound) }
// 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 }
func serveHTMLDoc(w http.ResponseWriter, r *http.Request, abspath, relpath string) { // get HTML body contents src, err := fs.ReadFile(abspath) if err != nil { log.Printf("ReadFile: %s", err) serveError(w, r, relpath, err) return } // if it begins with "<!DOCTYPE " assume it is standalone // html that doesn't need the template wrapping. if bytes.HasPrefix(src, []byte("<!DOCTYPE ")) { w.Write(src) return } // if it's the language spec, add tags to EBNF productions if strings.HasSuffix(abspath, "go_spec.html") { var buf bytes.Buffer linkify(&buf, src) src = buf.Bytes() } // get title and subtitle, if any title := extractString(src, titleRx) if title == "" { // no title found; try first comment for backward-compatibility title = extractString(src, firstCommentRx) } subtitle := extractString(src, subtitleRx) servePage(w, title, subtitle, "", src) }
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) }
// hello world, the web server func PageExecuteJS(w http.ResponseWriter, req *http.Request) { url := req.FormValue("url") js := req.FormValue("js") header := w.Header() if url == "" { log.Printf("ERROR: url is required. (%s)\n", url) w.WriteHeader(http.StatusInternalServerError) header.Set("Content-Type", "text/plian;charset=UTF-8;") io.WriteString(w, "Internal Server Error: please input url.\n") return } if strings.Index(url, "http") != 0 { log.Printf("ERROR: url is invalid. (%s)\n", url) w.WriteHeader(http.StatusInternalServerError) header.Set("Content-Type", "text/plian;charset=UTF-8;") io.WriteString(w, "Internal Server Error: please input valid url.\n") return } if js == "" { log.Printf("ERROR: js is required. (%s)\n", url) w.WriteHeader(http.StatusInternalServerError) header.Set("Content-Type", "text/plian;charset=UTF-8;") io.WriteString(w, "Internal Server Error: please input js.\n") return } json := ExecuteJS(url, js) if len(json) == 0 { log.Printf("ERROR: failed to execute. (%s)\n", url) json = []byte("{}") } header.Set("Content-Type", "application/json;charset=UTF-8;") w.Write(json) }
func (v *redirectView) handle(w http.ResponseWriter, req *http.Request, s *session) { if v.checkUniqueURL != "" && req.URL.Path != v.checkUniqueURL { w.WriteHeader(http.StatusNotFound) fmt.Fprintf(w, "<pre>404 page not found</pre>") return } defer func() { if e := recover(); e != nil { fmt.Fprintf(w, "%v", e) log.Printf("Error in handling %v : %v", req.RawURL, e) gde, ok := e.(getDataError) if !ok { if ose, ok := e.(os.Error); ok { gde = getDataError{http.StatusInternalServerError, ose} } else { gde = getDataError{http.StatusInternalServerError, os.NewError(fmt.Sprintf("%v", e))} } } w.WriteHeader(gde.Code) e2 := tpl["error"].Execute(w, giveTplData{"Sess": s, "Error": gde, "Request": req}) if e2 != nil { w.Write([]byte(e2.String())) } } }() rurl := v.process(req, s) if rurl == "" { rurl = "/" } w.Header().Add("Location", rurl) w.WriteHeader(http.StatusFound) }
func PageInternalUpdateJson(w http.ResponseWriter, req *http.Request) { id := req.FormValue("id") updateJson := req.FormValue("json") header := w.Header() conn, err := GetConnection() c := GetExecuteCollection(conn) var ( rs ExecuteRs jsonb []byte ) execId, err := mongo.NewObjectIdHex(id) log.Printf("Search ExecuteId=%s", execId) err = c.Find(map[string]interface{}{"_id": execId}).One(&rs) if err != nil { jsonb = []byte(`{error: "Not found."}`) } else { rs.Json = updateJson err = c.Update(mongo.M{"_id": execId}, rs) if err != nil { jsonb = []byte(`{result: "failed"}`) } else { jsonb = []byte(`{result: "success"}`) } } conn.Close() header.Set("Access-Control-Allow-Origin", "*") header.Set("Content-Type", "application/json") w.Write(jsonb) }
func homeHandler(w http.ResponseWriter, r *http.Request) { w.Header().Add("Content-Type", "text/html") url1 := router.NamedRoutes["hello"].URL("salutation", "hello", "name", "world") url2 := router.NamedRoutes["datastore-session"].URL() url3 := router.NamedRoutes["memcache-session"].URL() fmt.Fprintf(w, "Try a <a href='%s'>hello</a>. Or a <a href='%s'>datastore</a> or <a href='%s'>memcache</a> session.", url1, url2, url3) }
func c1LoginHandler(w http.ResponseWriter, r *http.Request) { c := appengine.NewContext(r) if l, err := c1IsLoggedIn(c); err != nil { http.Error(w, err.String(), http.StatusInternalServerError) return } else if l { /// http.Redirect(w, r, "/", http.StatusFound) http.Redirect(w, r, "/index", http.StatusFound) return } if r.Method == "GET" { w.Write([]byte( "<html><body><form action='/c1Login' method='POST'>" + "<input type='text' name='usr'></input>" + "<input type='password' name='pwd'></input>" + "<input type='submit' value='Submit'></input>" + "</form></body></html>")) return } else if r.Method == "POST" { usr := r.FormValue("usr") pwd := r.FormValue("pwd") _, err := C1Login(c, usr, pwd) if err == C1AuthError { http.Error(w, err.String(), http.StatusUnauthorized) return } http.Redirect(w, r, "/index", http.StatusFound) /// http.Redirect(w, r, "/", http.StatusFound) } }
func handle(w http.ResponseWriter, r *http.Request) { // If root, show the link registration page. if r.URL.Path == "/" { switch r.Method { case "GET": w.Write([]byte(registration)) case "POST": // Get input key := r.FormValue("key") url := r.FormValue("url") // Write to db resp := make(chan bool) save <- SaveRequest{key, url, resp} _ = <-resp w.Write([]byte("ok")) } return } // Redirect user based on the path. resp := make(chan string) code := r.URL.Path[1:] lookup <- LookupRequest{code, resp} url := <-resp if url == "" { http.Error(w, "Key not found", http.StatusNotFound) return } http.Redirect(w, r, <-resp, http.StatusFound) }
// 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 } }
func (h *Handler) handleInternalRedirect(rw http.ResponseWriter, req *http.Request, path string) { url, err := req.URL.ParseURL(path) if err != nil { rw.WriteHeader(http.StatusInternalServerError) h.printf("cgi: error resolving local URI path %q: %v", path, err) return } // TODO: RFC 3875 isn't clear if only GET is supported, but it // suggests so: "Note that any message-body attached to the // request (such as for a POST request) may not be available // to the resource that is the target of the redirect." We // should do some tests against Apache to see how it handles // POST, HEAD, etc. Does the internal redirect get the same // method or just GET? What about incoming headers? // (e.g. Cookies) Which headers, if any, are copied into the // second request? newReq := &http.Request{ Method: "GET", URL: url, RawURL: path, Proto: "HTTP/1.1", ProtoMajor: 1, ProtoMinor: 1, Header: make(http.Header), Host: url.Host, RemoteAddr: req.RemoteAddr, TLS: req.TLS, } h.PathLocationHandler.ServeHTTP(rw, newReq) }
func myWidgets(w http.ResponseWriter, r *http.Request) { var err os.Error ctx := appengine.NewContext(r) page, err := template.Parse(myWidgetTemplate, nil) if err != nil { http.Error(w, err.String(), http.StatusInternalServerError) return } data := myWidgetData{ CSS: commonCSS(), Header: header(ctx), } data.Widget, err = LoadWidgets(ctx) if err != nil { http.Error(w, err.String(), http.StatusInternalServerError) return } if len(r.FormValue("ids_only")) > 0 { w.Header().Set("Content-Type", "text/plain") for _, widget := range data.Widget { fmt.Fprintln(w, widget.ID) } return } page.Execute(w, data) }