本文整理匯總了Golang中net/http.StatusText函數的典型用法代碼示例。如果您正苦於以下問題:Golang StatusText函數的具體用法?Golang StatusText怎麽用?Golang StatusText使用的例子?那麽, 這裏精選的函數代碼示例或許可以為您提供幫助。
在下文中一共展示了StatusText函數的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。
示例1: getTrips
func getTrips(rw http.ResponseWriter, req *http.Request, p httprouter.Params) {
sess, err := mgo.Dial(Url)
if err != nil {
fmt.Printf("Can't connect to mongo, go error %v\n", err)
os.Exit(1)
}
defer sess.Close()
sess.SetSafe(&mgo.Safe{})
collection := sess.DB("cmpe273").C("Trips")
data := PostResParams{}
id := p.ByName("trip_id")
fmt.Println("id:", id)
err = collection.Find(bson.M{"_id": bson.ObjectIdHex(id)}).Select(bson.M{}).One(&data)
if err != nil {
if err.Error() == "not found" {
rw.WriteHeader(http.StatusNotFound)
fmt.Fprintf(rw, http.StatusText(http.StatusNotFound))
} else {
rw.WriteHeader(http.StatusInternalServerError)
fmt.Fprintf(rw, err.Error())
}
} else {
rw.WriteHeader(http.StatusCreated)
fmt.Fprintf(rw, http.StatusText(http.StatusOK))
b, _ := json.Marshal(data)
fmt.Println(string(b))
fmt.Fprintf(rw, "\n************************\n")
fmt.Fprintf(rw, string(b))
fmt.Fprintf(rw, "\n************************\n")
}
}
示例2: updateApp
func (ctl *controller) updateApp(c web.C, w http.ResponseWriter, r *http.Request) {
app := api.Application{}
if err := json.NewDecoder(r.Body).Decode(&app); err != nil {
logger.Error("updateApp", "error", err)
http.Error(w, http.StatusText(400), 400)
return
}
app.ID = c.URLParams["app_id"]
app.TeamID = c.Env["team_id"].(string)
err := ctl.api.UpdateApp(&app)
switch err {
case nil:
default:
logger.Error("updatedApp", "error", err, "app", app)
http.Error(w, http.StatusText(400), 400)
return
}
appJSON, err := ctl.api.GetAppJSON(app.ID)
if err != nil {
logger.Error("updateApp", "error", err, "appID", app.ID)
http.Error(w, http.StatusText(400), 400)
return
}
w.Write(appJSON)
}
示例3: updateChannel
func (ctl *controller) updateChannel(c web.C, w http.ResponseWriter, r *http.Request) {
channel := api.Channel{}
if err := json.NewDecoder(r.Body).Decode(&channel); err != nil {
logger.Error("updateChannel", "error", err)
http.Error(w, http.StatusText(400), 400)
return
}
channel.ID = c.URLParams["channel_id"]
channel.ApplicationID = c.URLParams["app_id"]
err := ctl.api.UpdateChannel(&channel)
switch err {
case nil:
default:
logger.Error("updateChannel", "error", err, "channel", channel)
http.Error(w, http.StatusText(400), 400)
return
}
channelJSON, err := ctl.api.GetChannelJSON(channel.ID)
if err != nil {
logger.Error("updateChannel", "error", err, "channelID", channel.ID)
http.Error(w, http.StatusText(400), 400)
return
}
w.Write(channelJSON)
}
示例4: handlerLogger
func handlerLogger(fn Handler, w http.ResponseWriter, r *http.Request, p httprouter.Params) {
l := NewHandlerLogEntry(r)
l.Info("started handling request")
starttime := time.Now()
err := fn(w, r, p)
duration := time.Since(starttime)
l.Data["duration"] = duration
code := http.StatusOK
if err != nil {
code = err.Code
}
l.Data["status"] = code
l.Data["text_status"] = http.StatusText(code)
if err != nil {
if err.Error != nil {
l.Data["error_message"] = err.Error
l.Debug(errgo.Details(err.Error))
l.Error("completed handling request")
scode := strconv.Itoa(err.Code)
http.Error(w, scode+" ("+http.StatusText(err.Code)+") - "+err.Error.Error(), err.Code)
}
} else {
l.Info("completed handling request")
}
}
示例5: ServeHTTP
func (v Validator) ServeHTTP(w http.ResponseWriter, r *http.Request) {
if r.Method != "POST" {
http.Error(w, http.StatusText(405), 405)
return
}
var resp ValidationResult
render := func() {
if err := json.NewEncoder(w).Encode(resp); err != nil {
http.Error(w, http.StatusText(500), 500)
}
}
jsonDoc := r.FormValue("json")
resp.DocType = r.FormValue("doctype")
schema, ok := v[r.FormValue("doctype")]
if !ok {
resp.Errors = []string{fmt.Sprintf("This document type schema not yet implemented: %q", r.FormValue("doctype"))}
render()
return
}
loader := js.NewStringLoader(jsonDoc)
result, err := schema.Validate(loader)
if err != nil {
resp.Errors = []string{"JSON is not well-formed: " + err.Error()}
} else {
if result.Valid() {
resp.Valid = true
} else {
for _, err := range result.Errors() {
msg := err.Context.String() + ": " + err.Description
resp.Errors = append(resp.Errors, msg)
}
}
}
render()
}
示例6: serveTemplate
func serveTemplate(w http.ResponseWriter, templateName string, data interface{}) {
lp := path.Join("views", "layout.tmpl")
fp := path.Join("views", templateName+".tmpl")
// Return a 404 if the template doesn't exist
info, err := os.Stat(fp)
if err != nil {
if os.IsNotExist(err) {
http.Error(w, http.StatusText(http.StatusNotFound), http.StatusNotFound)
return
}
}
// Return a 404 if the request is for a directory
if info.IsDir() {
http.Error(w, http.StatusText(http.StatusNotFound), http.StatusNotFound)
return
}
// Create the template
tmpl, err := template.ParseFiles(lp, fp)
if err != nil {
log.Error("Failed to create the template:", err)
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return
}
// Execute the template and send it to the user
if err := tmpl.ExecuteTemplate(w, "layout", data); err != nil {
log.Error("Failed to execute the template:", err)
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
}
}
示例7: www_coffeecat_root
func www_coffeecat_root(w http.ResponseWriter, r *http.Request) {
f, err := os.Open("images/coffeecat")
if err != nil {
log.Print(err)
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return
}
images, err := f.Readdirnames(-1)
if err != nil {
log.Print(err)
return
}
sort.Sort(sort.Reverse(sort.StringSlice(images)))
last := -1
re := regexp.MustCompile("([0-9]+)[.]png$")
for i := 0; i < len(images); i++ {
m := re.FindStringSubmatch(images[i])
if len(m) == 2 {
last, _ = strconv.Atoi(m[1])
break
}
}
if last == -1 {
log.Print("no images matches to regexp.")
http.Error(w, http.StatusText(http.StatusNotFound), http.StatusNotFound)
return
}
http.Redirect(w, r, fmt.Sprintf("/coffeecat/%d", last), http.StatusFound)
}
示例8: TodoShow
func TodoShow(w http.ResponseWriter, r *http.Request) {
if r.Method != "GET" {
log.Printf("NOT GET")
http.Error(w, http.StatusText(405), 405)
return
}
id := r.FormValue("id")
if id == "" {
log.Printf("Bad ID")
http.Error(w, http.StatusText(400), 400)
return
}
row := db.QueryRow("SELECT * FROM todos WHERE Id = $1", id)
todo := new(Todo)
err := row.Scan(&todo.Id, &todo.Name, &todo.Completed)
if err == sql.ErrNoRows {
http.NotFound(w, r)
return
} else if err != nil {
http.Error(w, http.StatusText(500), 500)
return
}
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
w.WriteHeader(http.StatusOK)
if err := json.NewEncoder(w).Encode(todo); err != nil {
log.Printf("Error printing todos")
panic(err)
}
}
示例9: TodoIndex
func TodoIndex(w http.ResponseWriter, r *http.Request) {
rows, err := db.Query("SELECT * FROM todos")
if err != nil {
log.Printf("Error opening DB")
http.Error(w, http.StatusText(500), 500)
return
}
defer rows.Close()
todos := make([]*Todo, 0)
for rows.Next() {
todo := new(Todo)
err := rows.Scan(&todo.Id, &todo.Name, &todo.Completed)
if err != nil {
log.Printf("Error scanning DB")
http.Error(w, http.StatusText(500), 500)
return
}
todos = append(todos, todo)
}
if err = rows.Err(); err != nil {
log.Printf("Error closing DB")
http.Error(w, http.StatusText(500), 500)
return
}
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
w.WriteHeader(http.StatusOK)
if err := json.NewEncoder(w).Encode(todos); err != nil {
log.Printf("Error printing todos")
panic(err)
}
}
示例10: authorized
// ServeHTTP implementation of interface
func authorized(w http.ResponseWriter, r *http.Request) bool {
// Headers Authorization found ?
hAuth := r.Header.Get("authorization")
if hAuth == "" {
w.Header().Set("WWW-Authenticate", "Basic realm=tmail REST server")
http.Error(w, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized)
return false
}
// check credential
if hAuth[:5] != "Basic" {
http.Error(w, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized)
return false
}
decoded, err := base64.StdEncoding.DecodeString(hAuth[6:])
if err != nil {
logError(r, "on decoding http auth credentials:", err.Error())
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return false
}
credentials := bytes.SplitN(decoded, []byte{58}, 2)
if bytes.Compare([]byte(core.Cfg.GetRestServerLogin()), credentials[0]) != 0 || bytes.Compare([]byte(core.Cfg.GetRestServerPasswd()), credentials[1]) != 0 {
logError(r, "bad authentification. Login:", string(credentials[0]), "password:", string(credentials[1]))
http.Error(w, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized)
return false
}
return true
}
示例11: proxyError
func proxyError(w http.ResponseWriter, err error, status int) {
switch status {
case http.StatusBadRequest,
http.StatusUnauthorized,
http.StatusForbidden,
http.StatusNotFound,
http.StatusRequestTimeout,
http.StatusGatewayTimeout,
http.StatusGone:
err = nil
case 0:
switch err {
case format.ErrUnknownFormat, ErrTooSmall:
status = http.StatusUnsupportedMediaType
case ErrTooBig:
status = http.StatusRequestEntityTooLarge
default:
if isTimeout(err) {
err = nil
status = http.StatusGatewayTimeout
} else {
status = http.StatusInternalServerError
}
}
default:
err = fmt.Errorf("Proxy received %d %s", status, http.StatusText(status))
status = http.StatusBadGateway
}
if err == nil {
err = fmt.Errorf(http.StatusText(status))
}
http.Error(w, err.Error(), status)
}
示例12: VolumeUpdateHandler
// PUT /volume HTTP Handler
func VolumeUpdateHandler(c web.C, w http.ResponseWriter, r *http.Request) {
decoder := json.NewDecoder(r.Body)
rbody := &volumeUpdateReqBody{}
// Decode JSON
err := decoder.Decode(&rbody)
if err != nil {
log.Debug(err)
http.Error(w, http.StatusText(400), 400)
return
}
// Validate
res, err := v.ValidateStruct(rbody)
if err != nil {
log.Debug(res)
http.Error(w, http.StatusText(422), 422)
return
}
// Set the vol redis keys
if err := events.PublishVolumeEvent(c.Env["REDIS"].(*redis.Client), rbody.Level); err != nil {
log.Error(err)
http.Error(w, http.StatusText(500), 500)
return
}
// We got here! It's alllll good.
w.WriteHeader(200)
}
示例13: CheckRegistrationSMSConfirmation
//CheckRegistrationSMSConfirmation is called by the sms code form to check if the sms is already confirmed on the mobile phone
func (service *Service) CheckRegistrationSMSConfirmation(w http.ResponseWriter, request *http.Request) {
registrationSession, err := service.GetSession(request, SessionForRegistration, "registrationdetails")
if err != nil {
log.Error(err)
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return
}
response := map[string]bool{}
if registrationSession.IsNew {
// todo: registrationSession is new with SMS, something must be wrong
log.Warn("Registration is new")
response["confirmed"] = true //This way the form will be submitted, let the form handler deal with redirect to login
} else {
validationkey, _ := registrationSession.Values["phonenumbervalidationkey"].(string)
confirmed, err := service.phonenumberValidationService.IsConfirmed(request, validationkey)
if err == validation.ErrInvalidOrExpiredKey {
confirmed = true //This way the form will be submitted, let the form handler deal with redirect to login
return
}
if err != nil {
log.Error(err)
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return
}
response["confirmed"] = confirmed
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(response)
}
示例14: request
func (b *ContainerBackup) request(method, path string, body io.Reader) (*http.Response, error) {
req, err := http.NewRequest(method, path, body)
if err != nil {
return nil, err
}
conn, err := net.Dial(b.proto, b.addr)
if err != nil {
return nil, err
}
clientconn := httputil.NewClientConn(conn, nil)
resp, err := clientconn.Do(req)
if err != nil {
return nil, err
}
if resp.StatusCode < 200 || resp.StatusCode >= 400 {
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, err
}
if len(body) == 0 {
return nil, fmt.Errorf("Error: %s", http.StatusText(resp.StatusCode))
}
return nil, fmt.Errorf("HTTP %s: %s", http.StatusText(resp.StatusCode), body)
}
return resp, nil
}
示例15: OnPanic
// OnPanic is called when panic occur.
func (ja *jsonAPI) OnPanic(w http.ResponseWriter, r *http.Request) {
// if api.SafeWriter.Write called before occuring panic,
// this will not write response body and header.
// Because it is meaningless and foolish that jsonplugin.OnPanic break response body.
// Example: Write([]byte("{}") -> some proccess -> panic -> jsonplugin.OnPanic -> Write([]byte(`{"message": "Internal Server Error"}`))
// -> Response body is {}{"message": "Internal Server Error"}.
if sw, ok := w.(*dou.SafeWriter); ok {
if sw.Wrote {
return
}
}
var b string
j, err := json.Marshal(map[string]string{"message": http.StatusText(http.StatusInternalServerError)})
if err != nil {
w.Header().Set("Content-Type", "text/plain; charset=utf-8")
b = http.StatusText(http.StatusInternalServerError)
} else {
b = string(j)
}
w.WriteHeader(http.StatusInternalServerError)
_, err = fmt.Fprintln(w, b)
if err != nil {
// Skip error
// http.Error skip this error too.
log.Printf("dou: fail to fmt.Fpintln(http.ResponseWriter, string)\n%v", err)
}
}