本文整理汇总了Golang中github.com/couchbase/sync_gateway/base.HTTPErrorf函数的典型用法代码示例。如果您正苦于以下问题:Golang HTTPErrorf函数的具体用法?Golang HTTPErrorf怎么用?Golang HTTPErrorf使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了HTTPErrorf函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: verifyFacebook
func verifyFacebook(fbUrl, accessToken string) (*FacebookResponse, error) {
params := url.Values{"fields": []string{"id,name,email"}, "access_token": []string{accessToken}}
destUrl := fbUrl + "/me?" + params.Encode()
res, err := http.Get(destUrl)
if err != nil {
return nil, err
}
defer res.Body.Close()
if res.StatusCode >= 300 {
return nil, base.HTTPErrorf(http.StatusUnauthorized,
"Facebook verification server status %d", res.StatusCode)
}
decoder := json.NewDecoder(res.Body)
var response FacebookResponse
err = decoder.Decode(&response)
if err != nil {
return nil, base.HTTPErrorf(http.StatusBadGateway, "Invalid response from Facebook verifier")
}
return &response, nil
}
示例2: handleOidcTestProviderAuthorize
/*
* From OAuth 2.0 spec
* Handle OAuth 2.0 Authorize request
* This might display a login page with a form to collect user credentials
* which is part of an internal authentication flow
*/
func (h *handler) handleOidcTestProviderAuthorize() error {
if !h.db.DatabaseContext.Options.UnsupportedOptions.OidcTestProvider.Enabled {
return base.HTTPErrorf(http.StatusForbidden, "OIDC test provider is not enabled")
}
requestParams := h.rq.URL.RawQuery
base.LogTo("OIDC", "handleOidcTestProviderAuthorize() raw authorize request raw query params = %v", requestParams)
scope := h.rq.URL.Query().Get("scope")
if scope == "" {
return base.HTTPErrorf(http.StatusBadRequest, "missing scope parameter")
}
err := validateAuthRequestScope(scope)
if err != nil {
return err
}
p := &Page{Title: "Oidc Test Provider", Query: requestParams}
t := template.New("Test Login")
if t, err := t.Parse(login_html); err != nil {
return base.HTTPErrorf(http.StatusInternalServerError, err.Error())
} else {
t.Execute(h.response, p)
}
return nil
}
示例3: verifyGoogle
func verifyGoogle(idToken string, allowedAppID []string) (*GoogleResponse, error) {
destUrl := googleTokenInfoURL + idToken
res, err := http.Get(destUrl)
if err != nil {
return nil, err
}
defer res.Body.Close()
decoder := json.NewDecoder(res.Body)
var response GoogleResponse
err = decoder.Decode(&response)
if err != nil {
return nil, base.HTTPErrorf(http.StatusBadGateway, "Invalid response from Google token verifier")
}
if response.ErrorDescription != "" {
return nil, base.HTTPErrorf(http.StatusUnauthorized, response.ErrorDescription)
}
if !isValidAud(response.Aud, allowedAppID) {
return nil, base.HTTPErrorf(http.StatusUnauthorized, "Invalid application id, please add it in the config")
}
return &response, nil
}
示例4: makeSessionFromEmail
func (h *handler) makeSessionFromEmail(email string, createUserIfNeeded bool) error {
// Email is verified. Look up the user and make a login session for her:
user, err := h.db.Authenticator().GetUserByEmail(email)
if err != nil {
return err
}
if user == nil {
// The email address is authentic but we have no user account for it.
if !createUserIfNeeded {
return base.HTTPErrorf(http.StatusUnauthorized, "No such user")
}
if len(email) < 1 {
return base.HTTPErrorf(http.StatusBadRequest, "Cannot register new user: email is missing")
}
// Create a User with the given email address as username and a random password.
user, err = h.db.Authenticator().RegisterNewUser(email, email)
if err != nil {
return err
}
}
return h.makeSession(user)
}
示例5: getDbConfigFromServer
// Fetch a configuration for a database from the ConfigServer
func (sc *ServerContext) getDbConfigFromServer(dbName string) (*DbConfig, error) {
if sc.config.ConfigServer == nil {
return nil, base.HTTPErrorf(http.StatusNotFound, "not_found")
}
urlStr := *sc.config.ConfigServer
if !strings.HasSuffix(urlStr, "/") {
urlStr += "/"
}
urlStr += url.QueryEscape(dbName)
res, err := sc.HTTPClient.Get(urlStr)
if err != nil {
return nil, base.HTTPErrorf(http.StatusBadGateway,
"Error contacting config server: %v", err)
} else if res.StatusCode >= 300 {
return nil, base.HTTPErrorf(res.StatusCode, res.Status)
}
var config DbConfig
j := json.NewDecoder(res.Body)
if err = j.Decode(&config); err != nil {
return nil, base.HTTPErrorf(http.StatusBadGateway,
"Bad response from config server: %v", err)
}
if err = config.setup(dbName); err != nil {
return nil, err
}
return &config, nil
}
示例6: ReadJSONFromMIME
// Parses a JSON MIME body, unmarshaling it into "into".
func ReadJSONFromMIME(headers http.Header, input io.Reader, into interface{}) error {
contentType := headers.Get("Content-Type")
if contentType != "" && !strings.HasPrefix(contentType, "application/json") {
return base.HTTPErrorf(http.StatusUnsupportedMediaType, "Invalid content type %s", contentType)
}
switch headers.Get("Content-Encoding") {
case "gzip":
var err error
if input, err = gzip.NewReader(input); err != nil {
return err
}
case "":
break
default:
return base.HTTPErrorf(http.StatusUnsupportedMediaType, "Unsupported Content-Encoding; use gzip")
}
decoder := json.NewDecoder(input)
if err := decoder.Decode(into); err != nil {
base.Warn("Couldn't parse JSON in HTTP request: %v", err)
return base.HTTPErrorf(http.StatusBadRequest, "Bad JSON")
}
return nil
}
示例7: QueryDesignDoc
func (db *Database) QueryDesignDoc(ddocName string, viewName string, options map[string]interface{}) (*sgbucket.ViewResult, error) {
// Regular users have limitations on what they can query
if db.user != nil {
// * Regular users can only query when user views are enabled
if !db.GetUserViewsEnabled() {
return nil, base.HTTPErrorf(http.StatusForbidden, "forbidden")
}
// * Admins can query any design doc including the internal ones
// * Regular users can query non-internal design docs
if isInternalDDoc(ddocName) {
return nil, base.HTTPErrorf(http.StatusForbidden, "forbidden")
}
}
result, err := db.Bucket.View(ddocName, viewName, options)
if err != nil {
return nil, err
}
if isInternalDDoc(ddocName) {
if options["include_docs"] == true {
for _, row := range result.Rows {
stripSyncProperty(row)
}
}
} else {
applyChannelFiltering := options["reduce"] != true && db.GetUserViewsEnabled()
result = filterViewResult(result, db.user, applyChannelFiltering)
}
return &result, nil
}
示例8: handlePersonaPOST
// POST /_persona creates a browserID-based login session and sets its cookie.
// It's API-compatible with the CouchDB plugin: <https://github.com/iriscouch/browserid_couchdb/>
func (h *handler) handlePersonaPOST() error {
if len(h.rq.Header["Origin"]) > 0 {
// CORS not allowed for login #115
return base.HTTPErrorf(http.StatusBadRequest, "No CORS")
}
var params struct {
Assertion string `json:"assertion"`
}
err := h.readJSONInto(¶ms)
if err != nil {
return err
}
origin := h.server.config.Persona.Origin
if origin == "" {
base.Warn("Can't accept Persona logins: Server URL not configured")
return base.HTTPErrorf(http.StatusInternalServerError, "Server url not configured")
}
// OK, now verify it:
base.Logf("Persona: Verifying assertion %q for %q", params.Assertion, origin)
verifiedInfo, err := VerifyPersona(params.Assertion, origin)
if err != nil {
base.Logf("Persona: Failed verify: %v", err)
return err
}
base.Logf("Persona: Logged in %q!", verifiedInfo.Email)
createUserIfNeeded := h.server.config.Persona.Register
return h.makeSessionFromEmail(verifiedInfo.Email, createUserIfNeeded)
}
示例9: VerifyPersona
// Verifies a Persona/BrowserID assertion received from a client, returning either the verification
// response (which includes the verified email address) or an error.
// The 'audience' parameter must be the same as the 'origin' parameter the client used when
// requesting the assertion, i.e. the root URL of this website.
func VerifyPersona(assertion string, audience string) (*PersonaResponse, error) {
// See <https://developer.mozilla.org/en-US/docs/Persona/Remote_Verification_API>
res, err := http.PostForm("https://verifier.login.persona.org/verify",
url.Values{"assertion": {assertion}, "audience": {audience}})
if err != nil {
return nil, err
}
defer res.Body.Close()
if res.StatusCode >= 300 {
return nil, base.HTTPErrorf(http.StatusBadGateway,
"Persona verification server status %d", res.StatusCode)
}
responseBody, err := ioutil.ReadAll(res.Body)
if err != nil {
return nil, base.HTTPErrorf(http.StatusBadGateway, "Invalid response from Persona verifier")
}
var response PersonaResponse
if err = json.Unmarshal(responseBody, &response); err != nil {
return nil, base.HTTPErrorf(http.StatusBadGateway, "Invalid response from Persona verifier")
}
if response.Status != "okay" {
return nil, base.HTTPErrorf(http.StatusUnauthorized, response.Reason)
}
return &response, nil
}
示例10: handleOidcTestProviderCerts
/*
* From OAuth 2.0 spec
* Return public certificates for signing keys
*/
func (h *handler) handleOidcTestProviderCerts() error {
if !h.db.DatabaseContext.Options.UnsupportedOptions.OidcTestProvider.Enabled {
return base.HTTPErrorf(http.StatusForbidden, "OIDC test provider is not enabled")
}
base.LogTo("OIDC", "handleOidcTestProviderCerts() called")
privateKey, err := privateKey()
if err != nil {
return base.HTTPErrorf(http.StatusInternalServerError, "Error getting private RSA Key")
}
oidcPrivateKey := key.PrivateKey{
KeyID: testProviderKeyIdentifier,
PrivateKey: privateKey,
}
jwk := oidcPrivateKey.JWK()
h.response.Write([]byte("{\r\n\"keys\":[\r\n"))
if bytes, err := jwk.MarshalJSON(); err == nil {
h.response.Write(bytes)
}
h.response.Write([]byte("\r\n]\r\n}"))
return nil
}
示例11: handleBulkDocs
// HTTP handler for a POST to _bulk_docs
func (h *handler) handleBulkDocs() error {
body, err := h.readJSON()
if err != nil {
return err
}
newEdits, ok := body["new_edits"].(bool)
if !ok {
newEdits = true
}
docs, ok := body["docs"].([]interface{})
if !ok {
err = base.HTTPErrorf(http.StatusBadRequest, "missing 'docs' property")
return err
}
h.db.ReserveSequences(uint64(len(docs)))
result := make([]db.Body, 0, len(docs))
for _, item := range docs {
doc := item.(map[string]interface{})
docid, _ := doc["_id"].(string)
var err error
var revid string
if newEdits {
if docid != "" {
revid, err = h.db.Put(docid, doc)
} else {
docid, revid, err = h.db.Post(doc)
}
} else {
revisions := db.ParseRevisions(doc)
if revisions == nil {
err = base.HTTPErrorf(http.StatusBadRequest, "Bad _revisions")
} else {
revid = revisions[0]
err = h.db.PutExistingRev(docid, doc, revisions)
}
}
status := db.Body{}
if docid != "" {
status["id"] = docid
}
if err != nil {
code, msg := base.ErrorAsHTTPStatus(err)
status["status"] = code
status["error"] = base.CouchHTTPErrorName(code)
status["reason"] = msg
base.Logf("\tBulkDocs: Doc %q --> %d %s (%v)", docid, code, msg, err)
err = nil // wrote it to output already; not going to return it
} else {
status["rev"] = revid
}
result = append(result, status)
}
h.writeJSONStatus(http.StatusCreated, result)
return nil
}
示例12: handleCreateTarget
// Stub handler for hadling create DB on the public API returns HTTP status 412
// if the db exists, and 403 if it doesn't.
// fixes issue #562
func (h *handler) handleCreateTarget() error {
dbname := h.PathVar("targetdb")
if _, err := h.server.GetDatabase(dbname); err != nil {
return base.HTTPErrorf(http.StatusForbidden, "Creating a DB over the public API is unsupported")
} else {
return base.HTTPErrorf(http.StatusPreconditionFailed, "Database already exists")
}
}
示例13: parseClockSequenceID
func parseClockSequenceID(str string, sequenceHasher *sequenceHasher) (s SequenceID, err error) {
if str == "" {
return SequenceID{
SeqType: ClockSequenceType,
Clock: base.NewSequenceClockImpl(),
}, nil
}
s.SeqType = ClockSequenceType
components := strings.Split(str, ":")
if len(components) == 1 {
// Convert simple zero to empty clock, to handle clients sending zero to mean 'no previous since'
if components[0] == "0" {
s.Clock = base.NewSequenceClockImpl()
} else {
// Standard clock hash
if s.Clock, err = sequenceHasher.GetClock(components[0]); err != nil {
return SequenceID{}, err
}
}
} else if len(components) == 2 {
// TriggeredBy Clock Hash, and vb.seq sequence
if s.TriggeredByClock, err = sequenceHasher.GetClock(components[0]); err != nil {
return SequenceID{}, err
}
sequenceComponents := strings.Split(components[1], ".")
if len(sequenceComponents) != 2 {
base.Warn("Unexpected sequence format - ignoring and relying on triggered by")
return
} else {
if vb64, err := strconv.ParseUint(sequenceComponents[0], 10, 16); err != nil {
base.Warn("Unable to convert sequence %v to int.", sequenceComponents[0])
} else {
s.vbNo = uint16(vb64)
s.Seq, err = strconv.ParseUint(sequenceComponents[1], 10, 64)
}
}
} else if len(components) == 3 {
// Low hash, and vb.seq sequence. Use low hash as clock, ignore vb.seq
if s.Clock, err = sequenceHasher.GetClock(components[0]); err != nil {
return SequenceID{}, err
}
} else {
err = base.HTTPErrorf(400, "Invalid sequence")
}
if err != nil {
err = base.HTTPErrorf(400, "Invalid sequence")
}
return s, err
}
示例14: handleSessionDELETE
// DELETE /_session logs out the current session
func (h *handler) handleSessionDELETE() error {
if len(h.rq.Header["Origin"]) > 0 {
// CORS not allowed for login #115
return base.HTTPErrorf(http.StatusBadRequest, "No CORS")
}
cookie := h.db.Authenticator().DeleteSessionForCookie(h.rq)
if cookie == nil {
return base.HTTPErrorf(http.StatusNotFound, "no session")
}
http.SetCookie(h.response, cookie)
return nil
}
示例15: handleGetAttachment
// HTTP handler for a GET of a specific doc attachment
func (h *handler) handleGetAttachment() error {
docid := h.PathVar("docid")
attachmentName := h.PathVar("attach")
revid := h.getQuery("rev")
body, err := h.db.GetRev(docid, revid, false, nil)
if err != nil {
return err
}
if body == nil {
return kNotFoundError
}
meta, ok := db.BodyAttachments(body)[attachmentName].(map[string]interface{})
if !ok {
return base.HTTPErrorf(http.StatusNotFound, "missing attachment %s", attachmentName)
}
digest := meta["digest"].(string)
data, err := h.db.GetAttachment(db.AttachmentKey(digest))
if err != nil {
return err
}
status, start, end := h.handleRange(uint64(len(data)))
if status > 299 {
return base.HTTPErrorf(status, "")
} else if status == http.StatusPartialContent {
data = data[start:end]
}
h.setHeader("Content-Length", strconv.FormatUint(uint64(len(data)), 10))
h.setHeader("Etag", strconv.Quote(digest))
if contentType, ok := meta["content_type"].(string); ok {
h.setHeader("Content-Type", contentType)
}
if encoding, ok := meta["encoding"].(string); ok {
if h.getOptBoolQuery("content_encoding", true) {
h.setHeader("Content-Encoding", encoding)
} else {
// Couchbase Lite wants to download the encoded form directly and store it that way,
// but some HTTP client libraries like NSURLConnection will automatically decompress
// the HTTP response if it has a Content-Encoding header. As a workaround, allow the
// client to add ?content_encoding=false to the request URL to disable setting this
// header.
h.setHeader("X-Content-Encoding", encoding)
h.setHeader("Content-Type", "application/gzip")
}
}
if h.privs == adminPrivs { // #720
h.setHeader("Content-Disposition", fmt.Sprintf("attachment; filename=%q", attachmentName))
}
h.response.WriteHeader(status)
h.response.Write(data)
return nil
}