コード例 #1
0
ファイル: router.go プロジェクト: ntfrnzn/bakingdish
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} ??

	}
}
コード例 #2
0
ファイル: router.go プロジェクト: ntfrnzn/bakingdish
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)

}
コード例 #3
0
// 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")

}
コード例 #4
0
ファイル: handler.go プロジェクト: frank12268/docker-wicket
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)
}
コード例 #5
0
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())
	}
}
コード例 #6
0
ファイル: server.go プロジェクト: eolexe/raphael-assignment
//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", "*")
}
コード例 #7
0
ファイル: rest_api.go プロジェクト: tenc/obc-peer-pre-public
// 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)
}
コード例 #8
0
ファイル: server.go プロジェクト: krisrang/fancypants
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)
}
コード例 #9
0
ファイル: renderer.go プロジェクト: SHMEDIALIMITED/server
// 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)
}
コード例 #10
0
ファイル: renderer.go プロジェクト: SHMEDIALIMITED/server
// 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)
}
コード例 #11
0
ファイル: context.go プロジェクト: SHMEDIALIMITED/server
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)
	}
}
コード例 #12
0
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)
	}

}
コード例 #13
0
ファイル: handler.go プロジェクト: frank12268/docker-wicket
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)
}
コード例 #14
0
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)
	}
}
コード例 #15
0
ファイル: handler.go プロジェクト: frank12268/docker-wicket
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)
}
コード例 #16
0
ファイル: server.go プロジェクト: crossyio/crossyinfo-service
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)
	}
}
コード例 #17
0
ファイル: root.go プロジェクト: 18F/cg-dashboard
// 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())
		}
	}
}
コード例 #18
0
ファイル: server.go プロジェクト: krisrang/fancypants
func (c *Context) Root(rw web.ResponseWriter, req *web.Request) {
	rw.Header().Set("Content-Type", "application/json")
	rw.Write([]byte("{\"hello\": \"world\"}"))
}
コード例 #19
0
ファイル: handler.go プロジェクト: frank12268/docker-wicket
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)
}
コード例 #20
0
func CorsMiddleware(rw web.ResponseWriter, r *web.Request, next web.NextMiddlewareFunc) {
	rw.Header().Set("Access-Control-Allow-Origin", "*")
	next(rw, r)
}
コード例 #21
0
ファイル: context.go プロジェクト: ahjdzx/dis
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)
}
コード例 #22
0
ファイル: server.go プロジェクト: crossyio/crossyinfo-service
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)
}
コード例 #23
0
ファイル: server.go プロジェクト: grepory/awsthingy
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)
}
コード例 #24
0
ファイル: server.go プロジェクト: grepory/awsthingy
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)
}
コード例 #25
0
ファイル: handler.go プロジェクト: frank12268/docker-wicket
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)
}
コード例 #26
0
ファイル: handler.go プロジェクト: frank12268/docker-wicket
func (c *context) ping(rw web.ResponseWriter, req *web.Request) {
	rw.Header().Set("X-Docker-Registry-Standalone", "false")
	http.Error(rw, "true", http.StatusOK)
}
コード例 #27
0
ファイル: router.go プロジェクト: ntfrnzn/bakingdish
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)
}