func (c *Context) SearchRecipe(rw web.ResponseWriter, req *web.Request) { body, err := getPostedBody(req) if err != nil { panic(err) return } var query models.Query err = json.Unmarshal(body, &query) if err != nil { handleUnmarshalError(rw, err) return } results, err := (*c).api.SearchRecipe(&query) if err != nil { rw.WriteHeader(http.StatusInternalServerError) panic(err) } else { rw.Header().Set("Content-Type", "application/json") json.NewEncoder(rw).Encode(results) // prefaces with {"Offset": 0} ?? } }
func (c *Context) PostRecipe(rw web.ResponseWriter, req *web.Request) { var recipe models.Recipe body, err := getPostedBody(req) if err != nil { panic(err) return } err = json.Unmarshal(body, &recipe) if err != nil { handleUnmarshalError(rw, err) return } id, err := (*c).api.PostRecipe(&recipe) if err != nil { panic(err) return } var result models.RecipeId result.Id = id result.Name = recipe.Name rw.WriteHeader(http.StatusCreated) rw.Header().Set("Content-Type", "application/json; charset=UTF-8") json.NewEncoder(rw).Encode(result) }
// creatKeyValue creates a new book in the collection func (c *Context) createKeyValue(w web.ResponseWriter, r *web.Request) { document, result, err := validateRequestData( "file://"+schemaDir+"/keyvalue.post.body.json", r, ) // lazy output & not setting headers if err != nil || !result.Valid() { w.Header() fmt.Fprintf(w, "The document is not valid. see errors :\n") if result != nil { for _, desc := range result.Errors() { fmt.Fprintf(w, "- %s\n", desc) } } else { fmt.Fprint(w, "The document wasn't valid JSON.") } return } fmt.Fprint(w, "success", "\n") fmt.Fprint(w, document, "\n") fmt.Fprint(w, result, "\n") }
func (c *context) generateToken(rw web.ResponseWriter, req *web.Request, next web.NextMiddlewareFunc) { if req.Header.Get("X-Docker-Token") == "true" { a, ok := accessMap[req.Method] if !ok { http.Error(rw, "", http.StatusMethodNotAllowed) return } sig, err := runningContext.TokenAuth.CreateToken(&handler.AuthRequest{ Name: fmt.Sprintf("%v/%v", c.namespace, c.repo), Actions: []string{a.name}, Service: runningContext.TokenAuth.Service, }) if !ok { http.Error(rw, err.Error(), http.StatusInternalServerError) return } t := fmt.Sprintf(`signature=%v,repository="%v/%v",access=%v`, sig, c.namespace, c.repo, a.name) rw.Header().Set("X-Docker-Endpoints", runningContext.Endpoints) rw.Header().Set("WWW-Authenticate", "Token "+t) rw.Header().Set("X-Docker-Token", t) } next(rw, req) }
func (this *RequestHandler) handleRequestWithPossibleErrors(response web.ResponseWriter, request *web.Request, handler func(web.ResponseWriter, *web.Request) error) { response.Header().Add("Access-Control-Allow-Origin", "*") err := handler(response, request) if err != nil { response.WriteHeader(http.StatusInternalServerError) fmt.Fprint(response, err.Error()) } }
//CorsMiddleware add the header Access-Control-Allow-Origin to the OPTIONS req. func (c *Context) CorsMiddleware(rw web.ResponseWriter, r *web.Request, next web.NextMiddlewareFunc) { if r.Method != "OPTIONS" { next(rw, r) return } rw.Header().Set("Access-Control-Allow-Origin", "*") }
// SetResponseType is a middleware function that sets the appropriate response // headers. Currently, it is setting the "Content-Type" to "application/json" as // well as the necessary headers in order to enable CORS for Swagger usage. func (s *ServerOpenchainREST) SetResponseType(rw web.ResponseWriter, req *web.Request, next web.NextMiddlewareFunc) { rw.Header().Set("Content-Type", "application/json") // Enable CORS rw.Header().Set("Access-Control-Allow-Origin", "*") rw.Header().Set("Access-Control-Allow-Headers", "accept, content-type") next(rw, req) }
func (c *Context) RetrieveStats(rw web.ResponseWriter, req *web.Request) { rw.Header().Set("Content-Type", "application/json") stats := Stats.Data() b, _ := json.Marshal(stats) rw.Write(b) }
// Format Error to JSON with moreInfo link func (c *Renderer) RenderError(rw web.ResponseWriter, err error, info string, status int) { js, err := json.MarshalIndent(&JSONError{err.Error(), info}, "", " ") if err != nil { http.Error(rw, err.Error(), http.StatusInternalServerError) log.Error("RenderError failed to marshall JSONError", err) return } header := rw.Header() header.Set("Content-Type", "application/json") rw.WriteHeader(status) rw.Write(js) }
// Renders from struct to JSON func (a *Renderer) Render(rw web.ResponseWriter, model interface{}, status int) { jsonString, err := json.MarshalIndent(&model, "", " ") if err != nil { http.Error(rw, err.Error(), http.StatusInternalServerError) log.Error("Render failed to marshall model", err) return } header := rw.Header() header.Set("Content-Type", "application/json") header.Set("Access-Control-Allow-Origin", "*") header.Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE") header.Set("Access-Control-Allow-Headers", "Authorization") rw.WriteHeader(status) rw.Write(jsonString) }
func (c *Context) ResourceConfigMiddleware(rw web.ResponseWriter, req *web.Request, next web.NextMiddlewareFunc) { var err error c.Resource, err = c.Config.FindResourceByRequest(req.Request) if err != nil { if err.Error() == "Method" { rw.Header().Set("Allow", strings.Join(c.Resource.Methods, ", ")) c.RenderError(rw, errors.New("Method Not Allowed"), "", http.StatusMethodNotAllowed) } else { c.RenderError(rw, errors.New("Access Forbidden"), "", http.StatusForbidden) } } else { c.Params = core.Params(req.URL.Path, c.Resource.Regex, c.Resource.Keys) next(rw, req) } }
func marshal(rw web.ResponseWriter, v interface{}) { buffer, err := json.Marshal(v) if err != nil { log.Println("Error marshalling JSON") rw.WriteHeader(http.StatusInternalServerError) return } rw.Header().Set("Content-Type", "application/json; charset=utf-8") if _, err = rw.Write(buffer); err != nil { log.Println("Error writing JSON to buffer") rw.WriteHeader(http.StatusInternalServerError) } }
func (c *context) getImages(rw web.ResponseWriter, req *web.Request) { rw.Header().Set("Content-Type", "application/json") m, err := runningContext.Index.GetIndexImages(c.namespace, c.repo) if err != nil { http.Error(rw, err.Error(), http.StatusInternalServerError) } b, err := json.Marshal(m) if err != nil { http.Error(rw, err.Error(), http.StatusInternalServerError) } rw.Write(b) }
func (c *Context) GeneratePresigned(rw web.ResponseWriter, req *web.Request) { rw.Header().Set("Content-Type", "application/json; charset=UTF-8") rw.WriteHeader(http.StatusOK) parts := []string{ c.CrossyInfo["username"].(string), req.PathParams["organization"], req.PathParams["project"], req.PathParams["packager"], req.PathParams["version"], req.PathParams["platform"], req.PathParams["arch"], req.PathParams["file"], } path := strings.Join(parts, "/") presignedURL := GetS3Presigned("contribute-crossy-io", path, 90) if err := json.NewEncoder(rw).Encode(presignedURL); err != nil { panic(err) } }
func (c *context) writeToken(rw web.ResponseWriter, req *web.Request) { token, err := runningContext.TokenAuth.CreateToken(&c.authReq) if err != nil { http.Error(rw, err.Error(), http.StatusInternalServerError) return } rw.Header().Set("Content-Type", "application/json") result, err := json.Marshal(&map[string]string{"token": token}) if err != nil { http.Error(rw, err.Error(), http.StatusInternalServerError) return } rw.Write(result) }
func (c *Context) GetUserInfo(rw web.ResponseWriter, req *web.Request) { rw.Header().Set("Content-Type", "application/json; charset=UTF-8") session, err := mgo.Dial(os.Getenv("MONGODB_URI")) if err != nil { panic(err) return } collection := session.DB("crossyio-main").C("users") query := make(map[string]interface{}) query["uuid"] = c.UserInfo["uuid"] result := User{} merr := collection.Find(query).One(&result) if merr != nil { panic(merr) return } fmt.Println(result) if err := json.NewEncoder(rw).Encode(result); err != nil { panic(err) } }
// LoginRequired is a middleware that requires a valid toker or redirects to the handshake page. func (c *Context) LoginRequired(rw web.ResponseWriter, r *web.Request, next web.NextMiddlewareFunc) { // If there is no request just continue if r == nil { next(rw, r) return } // Don't cache anything // right now, there's a problem where when you initially logout and then // revisit the server, you will get a bad view due to a caching issue. // for now, we clear the cache for everything. // TODO: revist and cache static assets. rw.Header().Set("cache-control", "no-cache, no-store, must-revalidate, private") rw.Header().Set("pragma", "no-cache") rw.Header().Set("expires", "-1") token := helpers.GetValidToken(r.Request, c.Settings) tokenPresent := token != nil publicUrls := map[string]struct{}{ "/handshake": {}, "/oauth2callback": {}, "/ping": {}, "/assets/img/dashboard-uaa-icon.jpg": {}, } // Check if URL is public so we skip validation _, public := publicUrls[r.URL.EscapedPath()] if public || tokenPresent { next(rw, r) } else { err := c.redirect(rw, r) if err != nil { fmt.Println("Error on oauth redirect: ", err.Error()) } } }
func (c *Context) Root(rw web.ResponseWriter, req *web.Request) { rw.Header().Set("Content-Type", "application/json") rw.Write([]byte("{\"hello\": \"world\"}")) }
func (c *context) commonHeader(rw web.ResponseWriter, req *web.Request, next web.NextMiddlewareFunc) { rw.Header().Set("Docker-Distribution-Api-Version", "registry/2.0") next(rw, req) }
func CorsMiddleware(rw web.ResponseWriter, r *web.Request, next web.NextMiddlewareFunc) { rw.Header().Set("Access-Control-Allow-Origin", "*") next(rw, r) }
func (c *Context) OutputJson(rw web.ResponseWriter, req *web.Request, next web.NextMiddlewareFunc) { next(rw, req) rw.Header().Set("Content-Type", "application/json; charset=UTF-8") resultJson, _ := json.Marshal(c.response) rw.Write(resultJson) }
func (c *Context) RedirectOauth(rw web.ResponseWriter, req *web.Request) { rw.Header().Set("Location", "https://oauth.crossy.io/?callbackUrl=https://info.crossy.io/oauth/callback") rw.WriteHeader(http.StatusFound) }
func (c *Context) SetContentType(rw web.ResponseWriter, r *web.Request, next web.NextMiddlewareFunc) { header := rw.Header() header.Set("Content-Type", "application/json; charset=utf-8") next(rw, r) }
func (c *Context) Cors(rw web.ResponseWriter, r *web.Request, next web.NextMiddlewareFunc) { header := rw.Header() header.Set("Access-Control-Allow-Origin", "*") next(rw, r) }
func (c *context) commonHeader(rw web.ResponseWriter, req *web.Request, next web.NextMiddlewareFunc) { rw.Header().Set("X-Docker-Registry-Version", "0.9.1") next(rw, req) }
func (c *context) ping(rw web.ResponseWriter, req *web.Request) { rw.Header().Set("X-Docker-Registry-Standalone", "false") http.Error(rw, "true", http.StatusOK) }
func (c *Context) GetRecipe(rw web.ResponseWriter, req *web.Request) { id := req.PathParams["id"] r, _ := (*c).api.GetRecipe(id) rw.Header().Set("Content-Type", "application/json") json.NewEncoder(rw).Encode(r) }