本文整理汇总了Golang中http.Error函数的典型用法代码示例。如果您正苦于以下问题:Golang Error函数的具体用法?Golang Error怎么用?Golang Error使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了Error函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: serveFileTree
func (ui *UIHandler) serveFileTree(rw http.ResponseWriter, req *http.Request) {
if ui.Storage == nil {
http.Error(rw, "No BlobRoot configured", 500)
return
}
suffix := req.Header.Get("X-PrefixHandler-PathSuffix")
m := treePattern.FindStringSubmatch(suffix)
if m == nil {
httputil.ErrorRouting(rw, req)
return
}
blobref := blobref.Parse(m[1])
if blobref == nil {
http.Error(rw, "Invalid blobref", 400)
return
}
fth := &FileTreeHandler{
Fetcher: ui.Storage,
file: blobref,
}
fth.ServeHTTP(rw, req)
}
示例2: gamesPost
func gamesPost(w http.ResponseWriter, r *http.Request, u *user.User, c appengine.Context) {
game := Game{
P1: r.FormValue("player1"),
P2: r.FormValue("player2"),
Played: datastore.SecondsToTime(time.Seconds()),
}
scorefields := map[string]int{
"Player1score": 0,
"Player2score": 0,
}
for k, _ := range scorefields {
score, err := strconv.Atoi(r.FormValue(k))
if err != nil {
http.Error(w, err.String(), http.StatusInternalServerError)
return
}
scorefields[k] = score
}
game.P1score = scorefields["Player1score"]
game.P2score = scorefields["Player2score"]
_, err := datastore.Put(c, datastore.NewIncompleteKey("Game"), &game)
if err != nil {
http.Error(w, err.String(), http.StatusInternalServerError)
return
}
rurl := fmt.Sprintf("http://%v/", r.Host)
w.Header().Set("Location", rurl)
w.WriteHeader(http.StatusFound)
}
示例3: c1LoginHandler
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)
}
}
示例4: main
func main(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
}
tok, err := AddClient(c, u.Id)
if err != nil {
http.Error(w, err.String(), 500)
return
}
err = mainTemplate.Execute(w, map[string]string{
"token": tok,
"client_id": u.Id,
"client_email": u.Email,
})
if err != nil {
c.Errorf("mainTemplate: %v", err)
}
}
示例5: myWidgets
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)
}
示例6: testHandler
func testHandler(w http.ResponseWriter, r *http.Request) {
// read user code
userCode := new(bytes.Buffer)
defer r.Body.Close()
if _, err := userCode.ReadFrom(r.Body); err != nil {
http.Error(w, err.String(), http.StatusInternalServerError)
return
}
// put user code in harness
t := step1.Test
t.UserCode = userCode.String()
code := new(bytes.Buffer)
if err := TestHarness.Execute(code, t); err != nil {
http.Error(w, err.String(), http.StatusInternalServerError)
return
}
// run code
out, err := run(code.String())
if err != nil {
http.Error(w, err.String(), http.StatusInternalServerError)
return
}
if out.Output == t.Expect {
fmt.Fprint(w, "Well done!")
} else {
fmt.Fprintf(w, "Not quite.\n\n%s", out.Errors)
}
}
示例7: addWidget
func addWidget(w http.ResponseWriter, r *http.Request) {
var err os.Error
if fixup == nil {
fixup, err = regexp.Compile(`[^A-Za-z0-9\-_. ]`)
if err != nil {
http.Error(w, err.String(), http.StatusInternalServerError)
return
}
}
ctx := appengine.NewContext(r)
name := fixup.ReplaceAllString(r.FormValue("name"), "")
if len(name) == 0 {
http.Error(w, "Invalid/no name provided", http.StatusInternalServerError)
return
}
widget := NewWidget(ctx, name)
err = widget.Commit()
if err != nil {
http.Error(w, err.String(), http.StatusInternalServerError)
return
}
http.Redirect(w, r, "/widget/list", http.StatusFound)
}
示例8: root
func root(w http.ResponseWriter, r *http.Request) {
c := appengine.NewContext(r)
client := urlfetch.Client(c)
resp, err := client.Get("http://en.wikipedia.org/wiki/Special:Random")
if err != nil {
http.Error(w, err.String(), http.StatusInternalServerError)
}
body := resp.Body
var allData []byte
allData = make([]byte, resp.ContentLength)
body.Read(allData)
firstLine := getFirstLine(string(allData))
url := getUrl(string(allData))
if firstLine == "" {
c.Errorf("Saw empty first line for url: %s", url)
}
data := map[string]string{
"firstLine": firstLine,
"url": url,
}
err2 := mainPageTemplate.Execute(w, data)
if err2 != nil {
http.Error(w, err2.String(), http.StatusInternalServerError)
}
}
示例9: LoginHandler
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"))
}
示例10: registration
func registration(w http.ResponseWriter, r *http.Request) {
c := appengine.NewContext(r)
u := User{
Name: "TestHendrik",
StartDate: datastore.SecondsToTime(time.Seconds()),
}
if g := user.Current(c); g != nil {
var u2 User
u.Account = g.String()
if err := datastore.Get(c, datastore.NewKey("user", g.String(), 0, nil), &u2); err == datastore.ErrNoSuchEntity {
key, err := datastore.Put(c, datastore.NewKey("user", u.Account, 0, nil), &u)
if err != nil {
http.Error(w, err.String(), http.StatusInternalServerError)
return
}
fmt.Fprintf(w, "User %q stored %q", u.Account, key)
return
} else {
fmt.Fprintf(w, "User %q is already logged in", g.String())
return
}
} else {
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
}
}
示例11: fileSchemaRefFromBlob
// Given a described blob, optionally follows a camliContent and
// returns the file's schema blobref and its fileinfo (if found).
func (pr *publishRequest) fileSchemaRefFromBlob(des *search.DescribedBlob) (fileref *blobref.BlobRef, fileinfo *search.FileInfo, ok bool) {
if des == nil {
http.NotFound(pr.rw, pr.req)
return
}
if des.Permanode != nil {
// TODO: get "forceMime" attr out of the permanode? or
// fileName content-disposition?
if cref := des.Permanode.Attr.Get("camliContent"); cref != "" {
cbr := blobref.Parse(cref)
if cbr == nil {
http.Error(pr.rw, "bogus camliContent", 500)
return
}
des = des.PeerBlob(cbr)
if des == nil {
http.Error(pr.rw, "camliContent not a peer in describe", 500)
return
}
}
}
if des.CamliType == "file" {
return des.BlobRef, des.File, true
}
http.Error(pr.rw, "failed to find fileSchemaRefFromBlob", 404)
return
}
示例12: show
func show(w http.ResponseWriter, r *http.Request) {
c := appengine.NewContext(r)
q := datastore.NewQuery("Guest").Order("Date")
count, err := q.Count(c)
if err != nil {
http.Error(w, err.String(), http.StatusInternalServerError)
return
}
guests := make([]Guest, 0, count)
guest_views :=([]Guest_View, count)
if keys, err := q.GetAll(c, &guests); err != nil {
http.Error(w, errString(), http.StatusInternalServerError)
return
} else {
for pos, guest := range guests {
guest_views[pos].Id = keys[pos].IntID()
guest_views[pos].Name = guest.Name
localTime := time.SecondsToLocalTime(int64(guest.Date) / 1000000)
guest_views[pos].Date = fmt.Sprintf("%04d/%02d/%02d %02d:%02d:%02d", localTime.Year, localTime.Month, localTime.Day, localTime.Hour, localTime.Minute, localTime.Second)
}
}
if err := showHTMLTemplate.Execute(w, guest_views); err != nil {
http.Error(w, err.String(), http.StatusInternalServerError)
}
}
示例13: Act
// POST /jobs/id/stop or POST /jobs/id/kill
func (this RestJsonMongo) Act(rw http.ResponseWriter, parts []string, r *http.Request) (item interface{}) {
logger.Debug("Act(%v):%v", r.URL.Path, parts)
if len(parts) < 2 {
if err := this.LoadJson(r, item); err != nil {
http.Error(rw, err.String(), http.StatusBadRequest)
return
} else {
id := parts[1]
if err := this.Store.Update(id, item); err != nil {
http.Error(rw, err.String(), http.StatusBadRequest)
return
}
}
}
if this.Target == nil {
http.Error(rw, fmt.Sprintf("service not found %v", r.URL.Path), http.StatusNotImplemented)
return
}
preq, _ := http.NewRequest(r.Method, r.URL.Path, r.Body)
proxy := http.NewSingleHostReverseProxy(this.Target)
go proxy.ServeHTTP(rw, preq)
return
}
示例14: view
func view(w http.ResponseWriter, r *http.Request) {
id, _ := strconv.Atoi(r.FormValue("id"))
c := appengine.NewContext(r)
var view detail_view
// グループ情報を取得
if group, err := model.GetGroup(c, id); err != nil {
http.Error(w, err.String(), http.StatusInternalServerError)
return
} else {
view.Group = group
}
// メンバー情報を取得
if memberlist, err := model.MemberList(c, id); err != nil {
http.Error(w, err.String(), http.StatusInternalServerError)
return
} else {
view.Member = memberlist
}
// 詳細画面を表示
if err := detailTemplate.Execute(w, view); err != nil {
http.Error(w, err.String(), http.StatusInternalServerError)
}
}
示例15: serveDownload
func (ui *UIHandler) serveDownload(rw http.ResponseWriter, req *http.Request) {
if ui.Storage == nil {
http.Error(rw, "No BlobRoot configured", 500)
return
}
suffix := req.Header.Get("X-PrefixHandler-PathSuffix")
m := downloadPattern.FindStringSubmatch(suffix)
if m == nil {
httputil.ErrorRouting(rw, req)
return
}
fbr := blobref.Parse(m[1])
if fbr == nil {
http.Error(rw, "Invalid blobref", 400)
return
}
dh := &DownloadHandler{
Fetcher: ui.Storage,
Cache: ui.Cache,
}
dh.ServeHTTP(rw, req, fbr)
}