/* * @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 }
func (authData *validatorImpl) LoginHandler(w http.ResponseWriter, r *http.Request) { client := r.FormValue("client") token := r.FormValue("token") if client == "" || token == "" { w.Write([]byte(loginHtml)) return } existingToken, found := authData.tokenMap[client] if !found { http.Error(w, "Invalid auth token", http.StatusForbidden) return } if token != existingToken { log.Printf("Invalid token: %s != %s", token, existingToken) http.Error(w, "Invalid auth token", http.StatusForbidden) return } // Set cookies. clientCookie := &http.Cookie{Name: "client", Value: client, Secure: true} http.SetCookie(w, clientCookie) tokenCookie := &http.Cookie{Name: "token", Value: token, Secure: true} http.SetCookie(w, tokenCookie) w.Write([]byte("Login successful")) }
func (ui *UIHandler) serveDiscovery(rw http.ResponseWriter, req *http.Request) { rw.Header().Set("Content-Type", "text/javascript") inCb := false if cb := req.FormValue("cb"); identPattern.MatchString(cb) { fmt.Fprintf(rw, "%s(", cb) inCb = true } pubRoots := map[string]interface{}{} for key, pubh := range ui.PublishRoots { pubRoots[key] = map[string]interface{}{ "name": pubh.RootName, // TODO: include gpg key id } } bytes, _ := json.Marshal(map[string]interface{}{ "blobRoot": ui.BlobRoot, "searchRoot": ui.SearchRoot, "jsonSignRoot": ui.JSONSignRoot, "uploadHelper": "?camli.mode=uploadhelper", // hack; remove with better javascript "downloadHelper": "./download/", "publishRoots": pubRoots, }) rw.Write(bytes) if inCb { rw.Write([]byte{')'}) } }
func handle_http(responseWrite http.ResponseWriter, request *http.Request) { var proxyResponse *http.Response var proxyResponseError os.Error proxyHost := strings.Split(request.URL.Path[6:], "/")[0] fmt.Printf("%s %s %s\n", request.Method, request.RawURL, request.RemoteAddr) //TODO https url := "http://" + request.URL.Path[6:] proxyRequest, _ := http.NewRequest(request.Method, url, nil) proxy := &http.Client{} proxyResponse, proxyResponseError = proxy.Do(proxyRequest) if proxyResponseError != nil { http.NotFound(responseWrite, request) return } for header := range proxyResponse.Header { responseWrite.Header().Add(header, proxyResponse.Header.Get(header)) } contentType := strings.Split(proxyResponse.Header.Get("Content-Type"), ";")[0] if proxyResponseError != nil { fmt.Fprintf(responseWrite, "pizda\n") } else if ReplacemendContentType[contentType] { body, _ := ioutil.ReadAll(proxyResponse.Body) defer proxyResponse.Body.Close() bodyString := replace_url(string(body), "/http/", proxyHost) responseWrite.Write([]byte(bodyString)) } else { io.Copy(responseWrite, proxyResponse.Body) } }
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 }
func (h *JSONSignHandler) handleSign(rw http.ResponseWriter, req *http.Request) { req.ParseForm() badReq := func(s string) { http.Error(rw, s, http.StatusBadRequest) log.Printf("bad request: %s", s) return } // TODO: SECURITY: auth jsonStr := req.FormValue("json") if jsonStr == "" { badReq("missing \"json\" parameter") return } if len(jsonStr) > kMaxJsonLength { badReq("parameter \"json\" too large") return } sreq := &jsonsign.SignRequest{ UnsignedJson: jsonStr, Fetcher: h.pubKeyFetcher, ServerMode: true, SecretKeyringPath: h.secretRing, } signedJson, err := sreq.Sign() if err != nil { // TODO: some aren't really a "bad request" badReq(fmt.Sprintf("%v", err)) return } rw.Write([]byte(signedJson)) }
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"`)) }
// tileHandler implements a tile renderer for use with the Google Maps JavaScript API. // See http://code.google.com/apis/maps/documentation/javascript/maptypes.html#ImageMapTypes func tileHandler(w http.ResponseWriter, r *http.Request) { c := appengine.NewContext(r) x, _ := strconv.Atoi(r.FormValue("x")) y, _ := strconv.Atoi(r.FormValue("y")) z, _ := strconv.Atoi(r.FormValue("z")) w.Header().Set("Content-Type", "image/png") // Try memcache first. key := fmt.Sprintf("mandelbrot:%d/%d/%d", x, y, z) if z < maxMemcacheLevel { if item, err := memcache.Get(c, key); err == nil { w.Write(item.Value) return } } b := render(x, y, z) if z < maxMemcacheLevel { memcache.Set(c, &memcache.Item{ Key: key, Value: b, Expiration: 3600, // TTL = 1 hour }) } w.Header().Set("Content-Length", strconv.Itoa(len(b))) w.Write(b) }
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 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 (redirector *HTTPRedirector) ServeHTTP(conn http.ResponseWriter, req *http.Request) { if req.URL.Path == redirector.PingPath { headers := conn.Header() headers.Set("Content-Type", "text/plain") headers.Set("Content-Length", redirector.PongLength) conn.WriteHeader(http.StatusOK) conn.Write(redirector.Pong) redirector.Log(HTTP_PING, http.StatusOK, req.Host, req) return } var url string if len(req.URL.RawQuery) > 0 { url = fmt.Sprintf("%s%s?%s", redirector.URL, req.URL.Path, req.URL.RawQuery) } else { url = fmt.Sprintf("%s%s", redirector.URL, req.URL.Path) } if len(url) == 0 { url = "/" } if redirector.HSTS != "" { conn.Header().Set("Strict-Transport-Security", redirector.HSTS) } conn.Header().Set("Location", url) conn.WriteHeader(http.StatusMovedPermanently) fmt.Fprintf(conn, redirector.Message, url) redirector.Log(HTTP_REDIRECT, http.StatusMovedPermanently, req.Host, req) }
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 (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 (v *tplView) 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) } }() d := v.getData(req, s) // fmt.Printf("%#v\n", d) // DEBUG if ee, ok := d.(getDataError); ok { w.WriteHeader(ee.Code) e := tpl["error"].Execute(w, giveTplData{"Sess": s, "Error": ee, "Request": req}) if e != nil { w.Write([]byte(e.String())) } } else if rurl, ok := d.(redirectResponse); ok { w.Header().Add("Location", string(rurl)) w.WriteHeader(http.StatusFound) } else { e := tpl[v.tpl].Execute(w, giveTplData{"Sess": s, "Data": d, "Request": req}) if e != nil { w.Write([]byte(e.String())) } } }
func cookieHandler(w http.ResponseWriter, req *http.Request) { w.Header().Set("Content-Type", "text/html; charset=utf-8") if cn := req.FormValue("set"); cn != "" { cv, cp := req.FormValue("val"), req.FormValue("pat") trace("cookieHandler recieved cookie %s=%s; path=%s.", cn, cv, cp) w.Header().Set("Set-Cookie", fmt.Sprintf("%s=%s; Path=/de/index; Domain=my.domain.org; Secure;", cn, cv)) } if t := req.FormValue("goto"); t != "" { w.Header().Set("Location", "localhost:54123/"+t) w.WriteHeader(302) } else { w.WriteHeader(200) body := "<html><head><title>Cookies</title></head>\n<body><h1>All Submitted Cookies</h1>" for _, cookie := range req.Cookies() { body += "<div class=\"cookies\">\n" body += " <ul>\n" body += " <li>" + cookie.Name + " :: " + cookie.Value + "</li>\n" body += " </ul>\n" body += "</div>\n" } body += "</body></html>" w.Write([]byte(body)) } }
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 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 postHandler(w http.ResponseWriter, req *http.Request) { w.Header().Set("Content-Type", "text/html; charset=utf-8") if cv := req.FormValue("cookie"); cv != "" { trace("postHandler recieved param cookie %s.", cv) cp := strings.SplitN(cv, "=", 2) if cp[1] != "-DELETE-" { exp := time.SecondsToUTC(time.UTC().Seconds() + 7*24*3600).Format(http.TimeFormat) // Now + 7 days w.Header().Set("Set-Cookie", fmt.Sprintf("%s=%s; Path=/de/index; expires=%s; Domain=my.domain.org; Secure;", cp[0], cp[1], exp)) } else { trace("post-handler: Deleting cookie %s\n", cp[0]) w.Header().Set("Set-Cookie", fmt.Sprintf("%s=%s; Path=/de/index; MaxAge=-1; Domain=my.domain.org; Secure;", cp[0], "X")) } } t := req.FormValue("q") if req.Method != "POST" { fmt.Printf("====== called /post with GET! ======\n") } _, header, err := req.FormFile("datei") if err == nil { info("Recieved datei: %s. %v", header.Filename, header.Filename == "file äöü 1.txt") } if t != "" { // w.Header().Set("Location", "http://localhost:54123/"+t) // w.Header().Set("Location", "localhost:54123/"+t) w.Header().Set("Location", "/"+t) w.WriteHeader(302) } else { text := req.FormValue("text") w.WriteHeader(200) body := "<html><body><h1>Post Page</h1><p>t = " + html.EscapeString(text) + "</p></body></html>" w.Write([]byte(body)) } }
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) } }
// 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) }
// hello world, the web server func Capture(w http.ResponseWriter, req *http.Request) { url := req.FormValue("url") 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 } image := CaptureUrl(url) if len(image) == 0 { log.Printf("ERROR: failed to capture. (%s)\n", url) w.WriteHeader(http.StatusInternalServerError) header.Set("Content-Type", "text/plian;charset=UTF-8;") io.WriteString(w, "Internal Server Error: Failed to capture.\n") return } header.Set("Content-Type", "image/png") w.Write(image) }
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 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) }
func ReturnJson(conn http.ResponseWriter, data interface{}) { conn.Header().Set("Content-Type", "text/javascript") if m, ok := data.(map[string]interface{}); ok { statusCode := 0 if t, ok := m["error"].(string); ok && len(t) > 0 { statusCode = http.StatusInternalServerError } if t, ok := m["errorType"].(string); ok { switch t { case "server": statusCode = http.StatusInternalServerError case "input": statusCode = http.StatusBadRequest } } if statusCode != 0 { conn.WriteHeader(statusCode) } } 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")) }
func HTMLServer(w http.ResponseWriter, req *http.Request) { c, err := ioutil.ReadFile("proc.html") if err != nil { log.Fatal("ERR: html/index.html not openable") return } w.Write(c) }
func (h *JsonGetHandler) serveMessageJsonp(w http.ResponseWriter, hr *http.Request) { w.Header().Set("Content-Type", "text/javascript;charset=utf-8") out := GetMessage(GetFormValue(hr, "TrollId"), GetFormValue(hr, "ChrallVersion")) bout, _ := json.Marshal(out) fmt.Fprint(w, "chrall_receiveMessage(") w.Write(bout) fmt.Fprint(w, ")") }
func Index(w http.ResponseWriter, r *http.Request) { index, _ := ioutil.ReadFile("index.html") re := regexp.MustCompile("NAME") name := GetUsername() fmt.Println(name) index = re.ReplaceAll(index, []byte(name)) w.Write(index) }
func (h *JsonGetHandler) servePageKillometre(w http.ResponseWriter, hr *http.Request) { w.Header().Set("Content-Type", "text/javascript;charset=utf-8") out := h.tksManager.GetKillometreExtract(GetFormValue(hr, "cat"), GetFormValueAsInt(hr, "startIndex"), GetFormValueAsInt(hr, "pageSize"), GetFormValue(hr, "searched")) bout, _ := json.Marshal(out) fmt.Fprint(w, "chrall_receiveKillometreExtract(") w.Write(bout) fmt.Fprint(w, ")") }
// catch /tmb request and return thumbnail func tmb(w http.ResponseWriter, r *http.Request) { id := r.FormValue("id") buf := picstore.Read(id, "thumbs") w.Header().Set("Content-Type", "image/jpeg") w.Header().Set("cache-control", "no-cache") w.Header().Set("Expires", "-1") w.Write(buf) }