本文整理匯總了Golang中github.com/flynn/flynn/pkg/httphelper.Error函數的典型用法代碼示例。如果您正苦於以下問題:Golang Error函數的具體用法?Golang Error怎麽用?Golang Error使用的例子?那麽, 這裏精選的函數代碼示例或許可以為您提供幫助。
在下文中一共展示了Error函數的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。
示例1: createDatabase
func (a *API) createDatabase(ctx context.Context, w http.ResponseWriter, req *http.Request) {
username, password, database := random.Hex(16), random.Hex(16), random.Hex(16)
if _, err := a.db.Exec(fmt.Sprintf("CREATE USER '%s'@'%%' IDENTIFIED BY '%s'", username, password)); err != nil {
httphelper.Error(w, err)
return
}
if _, err := a.db.Exec(fmt.Sprintf("CREATE DATABASE `%s`", database)); err != nil {
a.db.Exec(fmt.Sprintf("DROP USER '%s'", username))
httphelper.Error(w, err)
return
}
if _, err := a.db.Exec(fmt.Sprintf("GRANT ALL ON `%s`.* TO '%s'@'%%'", database, username)); err != nil {
a.db.Exec(fmt.Sprintf("DROP DATABASE `%s`", database))
a.db.Exec(fmt.Sprintf("DROP USER '%s'", username))
httphelper.Error(w, err)
return
}
url := fmt.Sprintf("mysql://%s:%[email protected]%s:3306/%s", username, password, serviceHost, database)
httphelper.JSON(w, 200, resource.Resource{
ID: fmt.Sprintf("/databases/%s:%s", username, database),
Env: map[string]string{
"FLYNN_MYSQL": serviceName,
"MYSQL_HOST": serviceHost,
"MYSQL_USER": username,
"MYSQL_PWD": password,
"MYSQL_DATABASE": database,
"DATABASE_URL": url,
},
})
}
示例2: ping
func (a *API) ping(ctx context.Context, w http.ResponseWriter, req *http.Request) {
logger := a.logger().New("fn", "ping")
logger.Info("checking status", "host", serviceHost)
if status, err := sirenia.NewClient(serviceHost + ":3306").Status(); err == nil && status.Database != nil && status.Database.ReadWrite {
logger.Info("database is up, skipping scale check")
} else {
scaled, err := scale.CheckScale(app, controllerKey, "mariadb", a.logger())
if err != nil {
httphelper.Error(w, err)
return
}
// Cluster has yet to be scaled, return healthy
if !scaled {
w.WriteHeader(200)
return
}
}
db, err := a.connect()
if err != nil {
httphelper.Error(w, err)
return
}
defer db.Close()
if _, err := db.Exec("SELECT 1"); err != nil {
httphelper.Error(w, err)
return
}
w.WriteHeader(200)
}
示例3: ServeTemplate
func (api *httpAPI) ServeTemplate(w http.ResponseWriter, req *http.Request, params httprouter.Params) {
if req.Header.Get("Accept") == "application/json" {
s, err := api.Installer.FindBaseCluster(params.ByName("id"))
if err != nil {
httphelper.ObjectNotFoundError(w, err.Error())
return
}
httphelper.JSON(w, 200, s)
return
}
manifest, err := api.AssetManifest()
if err != nil {
httphelper.Error(w, err)
api.logger.Debug(err.Error())
return
}
w.Header().Add("Content-Type", "text/html; charset=utf-8")
w.Header().Add("Cache-Control", "max-age=0")
err = htmlTemplate.Execute(w, &htmlTemplateData{
ApplicationJSPath: manifest.Assets["application.js"],
ApplicationCSSPath: manifest.Assets["application.css"],
ReactJSPath: manifest.Assets["react.js"],
})
if err != nil {
httphelper.Error(w, err)
api.logger.Debug(err.Error())
return
}
}
示例4: Update
func (h *jobAPI) Update(w http.ResponseWriter, req *http.Request, _ httprouter.Params) {
log := h.host.log.New("fn", "Update")
log.Info("decoding command")
var cmd host.Command
if err := httphelper.DecodeJSON(req, &cmd); err != nil {
log.Error("error decoding command", "err", err)
httphelper.Error(w, err)
return
}
log.Info("updating host")
err := h.host.Update(&cmd)
if err != nil {
httphelper.Error(w, err)
return
}
// send an ok response and then shutdown after 1s to give the response
// chance to reach the client.
httphelper.JSON(w, http.StatusOK, cmd)
log.Info("shutting down in 1s")
time.AfterFunc(time.Second, func() {
log.Info("exiting")
os.Exit(0)
})
}
示例5: createDatabase
func (p *pgAPI) createDatabase(ctx context.Context, w http.ResponseWriter, req *http.Request) {
username, password, database := random.Hex(16), random.Hex(16), random.Hex(16)
if err := p.db.Exec(fmt.Sprintf(`CREATE USER "%s" WITH PASSWORD '%s'`, username, password)); err != nil {
httphelper.Error(w, err)
return
}
if err := p.db.Exec(fmt.Sprintf(`CREATE DATABASE "%s"`, database)); err != nil {
p.db.Exec(fmt.Sprintf(`DROP USER "%s"`, username))
httphelper.Error(w, err)
return
}
if err := p.db.Exec(fmt.Sprintf(`GRANT ALL ON DATABASE "%s" TO "%s"`, database, username)); err != nil {
p.db.Exec(fmt.Sprintf(`DROP DATABASE "%s"`, database))
p.db.Exec(fmt.Sprintf(`DROP USER "%s"`, username))
httphelper.Error(w, err)
return
}
url := fmt.Sprintf("postgres://%s:%[email protected]%s:5432/%s", username, password, serviceHost, database)
httphelper.JSON(w, 200, resource.Resource{
ID: fmt.Sprintf("/databases/%s:%s", username, database),
Env: map[string]string{
"FLYNN_POSTGRES": serviceName,
"PGHOST": serviceHost,
"PGUSER": username,
"PGPASSWORD": password,
"PGDATABASE": database,
"DATABASE_URL": url,
},
})
}
示例6: Login
func (api *API) Login(ctx context.Context, w http.ResponseWriter, req *http.Request) {
var info LoginInfo
if strings.Contains(req.Header.Get("Content-Type"), "form-urlencoded") {
if err := req.ParseForm(); err != nil {
httphelper.Error(w, err)
return
}
info = LoginInfo{Token: req.PostForm.Get("token")}
} else {
if err := json.NewDecoder(req.Body).Decode(&info); err != nil {
httphelper.Error(w, err)
return
}
}
if len(info.Token) != len(api.conf.LoginToken) || subtle.ConstantTimeCompare([]byte(info.Token), []byte(api.conf.LoginToken)) != 1 {
httphelper.Error(w, httphelper.JSONError{
Code: httphelper.UnauthorizedErrorCode,
Message: "Invalid login token",
})
return
}
api.SetAuthenticated(ctx, w, req)
if strings.Contains(req.Header.Get("Content-Type"), "form-urlencoded") {
http.Redirect(w, req, api.conf.CookiePath, 302)
} else {
w.WriteHeader(200)
}
}
示例7: dropDatabase
func (p *pgAPI) dropDatabase(ctx context.Context, w http.ResponseWriter, req *http.Request) {
id := strings.SplitN(strings.TrimPrefix(req.FormValue("id"), "/databases/"), ":", 2)
if len(id) != 2 || id[1] == "" {
httphelper.ValidationError(w, "id", "is invalid")
return
}
// disable new connections to the target database
if err := p.db.Exec(disallowConns, id[1]); err != nil {
httphelper.Error(w, err)
return
}
// terminate current connections
if err := p.db.Exec(disconnectConns, id[1]); err != nil {
httphelper.Error(w, err)
return
}
if err := p.db.Exec(fmt.Sprintf(`DROP DATABASE "%s"`, id[1])); err != nil {
httphelper.Error(w, err)
return
}
if err := p.db.Exec(fmt.Sprintf(`DROP USER "%s"`, id[0])); err != nil {
httphelper.Error(w, err)
return
}
w.WriteHeader(200)
}
示例8: UpdateRoute
func (api *API) UpdateRoute(ctx context.Context, w http.ResponseWriter, req *http.Request) {
log, _ := ctxhelper.LoggerFromContext(ctx)
params, _ := ctxhelper.ParamsFromContext(ctx)
var route *router.Route
if err := json.NewDecoder(req.Body).Decode(&route); err != nil {
log.Error(err.Error())
httphelper.Error(w, err)
return
}
route.Type = params.ByName("route_type")
route.ID = params.ByName("id")
l := api.router.ListenerFor(route.Type)
if l == nil {
httphelper.ValidationError(w, "type", "Invalid route type")
return
}
if err := l.UpdateRoute(route); err != nil {
if err == ErrNotFound {
w.WriteHeader(404)
return
}
log.Error(err.Error())
httphelper.Error(w, err)
return
}
httphelper.JSON(w, 200, route)
}
示例9: CreateCert
func (api *API) CreateCert(ctx context.Context, w http.ResponseWriter, req *http.Request) {
var cert *router.Certificate
if err := json.NewDecoder(req.Body).Decode(&cert); err != nil {
httphelper.Error(w, err)
return
}
l := api.router.HTTP.(*HTTPListener)
err := l.AddCert(cert)
if err != nil {
jsonError := httphelper.JSONError{}
switch err {
case ErrConflict:
jsonError.Code = httphelper.ConflictErrorCode
jsonError.Message = "Duplicate cert"
case ErrInvalid:
jsonError.Code = httphelper.ValidationErrorCode
jsonError.Message = "Invalid cert"
default:
httphelper.Error(w, err)
return
}
}
httphelper.JSON(w, 200, cert)
}
示例10: DeleteRoute
func (api *API) DeleteRoute(ctx context.Context, w http.ResponseWriter, req *http.Request) {
log, _ := ctxhelper.LoggerFromContext(ctx)
params, _ := ctxhelper.ParamsFromContext(ctx)
l := api.router.ListenerFor(params.ByName("route_type"))
if l == nil {
w.WriteHeader(404)
return
}
err := l.RemoveRoute(params.ByName("id"))
if err != nil {
switch err {
case ErrNotFound:
w.WriteHeader(404)
return
case ErrInvalid:
httphelper.Error(w, httphelper.JSONError{
Code: httphelper.ValidationErrorCode,
Message: "Route has dependent routes",
})
return
default:
log.Error(err.Error())
httphelper.Error(w, err)
return
}
}
w.WriteHeader(200)
}
示例11: dropDatabase
func (a *API) dropDatabase(ctx context.Context, w http.ResponseWriter, req *http.Request) {
id := strings.SplitN(strings.TrimPrefix(req.FormValue("id"), "/databases/"), ":", 2)
if len(id) != 2 || id[1] == "" {
httphelper.ValidationError(w, "id", "is invalid")
return
}
db, err := a.connect()
if err != nil {
httphelper.Error(w, err)
return
}
defer db.Close()
if _, err := db.Exec(fmt.Sprintf("DROP DATABASE `%s`", id[1])); err != nil {
httphelper.Error(w, err)
return
}
if _, err := db.Exec(fmt.Sprintf("DROP USER '%s'", id[0])); err != nil {
httphelper.Error(w, err)
return
}
w.WriteHeader(200)
}
示例12: NewCredential
func (api *httpAPI) NewCredential(w http.ResponseWriter, req *http.Request, params httprouter.Params) {
creds := &Credential{}
if err := httphelper.DecodeJSON(req, &creds); err != nil {
httphelper.Error(w, err)
return
}
if creds.Type == "azure" {
oauthCreds := make([]*OAuthCredential, 0, 2)
for _, resource := range []string{azure.JSONAPIResource, azure.XMLAPIResource} {
token, err := azure.OAuth2Config(creds.ID, creds.Endpoint, resource).Exchange(oauth2.NoContext, creds.Secret)
if err != nil {
httphelper.Error(w, err)
return
}
oauthCreds = append(oauthCreds, &OAuthCredential{
ClientID: creds.ID,
AccessToken: token.AccessToken,
RefreshToken: token.RefreshToken,
ExpiresAt: &token.Expiry,
Scope: resource,
})
}
creds.Secret = ""
creds.OAuthCreds = oauthCreds
}
if err := api.Installer.SaveCredentials(creds); err != nil {
if err == credentialExistsError {
httphelper.ObjectExistsError(w, err.Error())
return
}
httphelper.Error(w, err)
return
}
w.WriteHeader(200)
}
示例13: dropDatabase
func (a *API) dropDatabase(w http.ResponseWriter, req *http.Request, _ httprouter.Params) {
id := strings.SplitN(strings.TrimPrefix(req.FormValue("id"), "/databases/"), ":", 2)
if len(id) != 2 || id[1] == "" {
httphelper.ValidationError(w, "id", "is invalid")
return
}
user, database := id[0], id[1]
session, err := mgo.DialWithInfo(&mgo.DialInfo{
Addrs: []string{net.JoinHostPort(serviceHost, "27017")},
Username: "flynn",
Password: os.Getenv("MONGO_PWD"),
Database: "admin",
})
if err != nil {
httphelper.Error(w, err)
return
}
defer session.Close()
// Delete user.
if err := session.DB(database).Run(bson.D{{"dropUser", user}}, nil); err != nil {
httphelper.Error(w, err)
return
}
// Delete database.
if err := session.DB(database).Run(bson.D{{"dropDatabase", 1}}, nil); err != nil {
httphelper.Error(w, err)
return
}
w.WriteHeader(200)
}
示例14: Send
func (api *HTTPAPI) Send(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
volumeID := ps.ByName("volume_id")
if !strings.Contains(r.Header.Get("Accept"), snapshotContentType) {
httphelper.ValidationError(w, "", fmt.Sprintf("must be prepared to accept a content type of %q", snapshotContentType))
return
}
w.Header().Set("Content-Type", snapshotContentType)
var haves []json.RawMessage
if err := httphelper.DecodeJSON(r, &haves); err != nil {
httphelper.Error(w, err)
return
}
err := api.vman.SendSnapshot(volumeID, haves, w)
if err != nil {
switch err {
case volume.ErrNoSuchVolume:
httphelper.ObjectNotFoundError(w, fmt.Sprintf("no volume with id %q", volumeID))
return
default:
httphelper.Error(w, err)
return
}
}
}
示例15: servePutLeader
// servePutLeader sets the leader for a service.
func (h *Handler) servePutLeader(w http.ResponseWriter, r *http.Request, params httprouter.Params) {
// Retrieve path parameters.
service := params.ByName("service")
// Check if the service allows manual leader election.
config := h.Store.Config(service)
if config == nil || config.LeaderType != discoverd.LeaderTypeManual {
hh.ValidationError(w, "", "service leader election type is not manual")
return
}
// Read instance from the request.
inst := &discoverd.Instance{}
if err := hh.DecodeJSON(r, inst); err != nil {
hh.Error(w, err)
return
}
// Manually set the leader on the service.
if err := h.Store.SetServiceLeader(service, inst.ID); err == ErrNotLeader {
h.redirectToLeader(w, r)
return
} else if err != nil {
hh.Error(w, err)
return
}
}