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) }
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 (c *Context) Log(rw web.ResponseWriter, r *web.Request, next web.NextMiddlewareFunc) { c.Job = stream.NewJob(r.RoutePath()) id, err := uuid.NewV4() if err == nil { c.Job.KeyValue("request-id", id.String()) } path := r.URL.Path c.Job.EventKv("api.request", health.Kvs{"path": path}) next(rw, r) code := rw.StatusCode() kvs := health.Kvs{ "code": fmt.Sprint(code), "path": path, } // Map HTTP status code to category. var status health.CompletionStatus if c.Panic { status = health.Panic } else if code < 400 { status = health.Success } else if code == 422 { status = health.ValidationError } else if code < 500 { status = health.Junk // 404, 401 } else { status = health.Error } c.Job.CompleteKv(status, kvs) }
// Get counter events in a optionally given time range // Query parameters: start,end func (c *Context) CounterByCodeEventsHandler(rw web.ResponseWriter, req *web.Request) { code := parseStringPathParameter(req, "code") var counter orm.Counter db.Where(&orm.Counter{Code: code}).First(&counter) if counter.ID == 0 { rw.WriteHeader(http.StatusNotFound) rw.Write([]byte("Counter not found")) return } start, err := c.parseUintQueryParameter(rw, "start") if err != nil { return } end, err := c.parseUintQueryParameter(rw, "end") if err != nil { return } var counterEvents []orm.CounterEvent orm.GetOrderedWindowedQuery(db, "counter_id", counter.ID, start, end).Find(&counterEvents) lastEvent := orm.NewLastCounterEvent(counter) if lastEvent.Timestamp > end { counterEvents = append(counterEvents, lastEvent) } marshal(rw, counterEvents) }
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} ?? } }
// 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) UserRequired(rw web.ResponseWriter, req *web.Request, next web.NextMiddlewareFunc) { var userInfo map[string]interface{} if req.URL.Path == "/healthcheck" { next(rw, req) return } if req.URL.Path == "/signup" { next(rw, req) return } auth := req.Header.Get("Authorization") if !strings.HasPrefix(strings.ToLower(auth), "bearer ") { rw.WriteHeader(http.StatusUnauthorized) return } token := auth[7:] client := &http.Client{} authReq, err := http.NewRequest("GET", "https://meshblu.octoblu.com/v2/whoami", nil) authReq.Header.Add("Authorization", "Bearer "+token) resp, err := client.Do(authReq) if err != nil { panic(err) return } if err := json.NewDecoder(resp.Body).Decode(&userInfo); err != nil { panic(err) } c.Token = token c.UserInfo = userInfo next(rw, req) }
func (c *apiContext) HealthMiddleware(rw web.ResponseWriter, r *web.Request, next web.NextMiddlewareFunc) { c.Job = c.hd.stream.NewJob(r.RoutePath()) path := r.URL.Path c.EventKv("starting_request", health.Kvs{"path": path}) next(rw, r) code := rw.StatusCode() kvs := health.Kvs{ "code": fmt.Sprint(code), "path": path, } // Map HTTP status code to category. var status health.CompletionStatus // if c.Panic { // status = health.Panic // } else if code < 400 { status = health.Success } else if code == 422 { status = health.ValidationError } else if code < 500 { status = health.Junk // 404, 401 } else { status = health.Error } c.CompleteKv(status, kvs) }
// TODO Should rewrite to send a 'fail' or an 'error' func ErrorHandler(rw web.ResponseWriter, err error) { if rw.Written() { panic(fmt.Sprintf("Data already started to be sent to the client and i had an error: %s", err)) } rw.WriteHeader(http.StatusBadRequest) fmt.Fprintf(rw, "{\"Error\": \"%s\"}", err) }
func ReturnJSON(rw web.ResponseWriter, object interface{}) { j, err := json.MarshalIndent(object, "", "\t") if err != nil { http.Error(rw, "500: "+err.Error(), http.StatusInternalServerError) return } rw.Write(j) }
func (this *RequestHandler) getServerConfiguration(response web.ResponseWriter, request *web.Request) error { json, err := json.Marshal(this.ServerConfiguration) if err != nil { return err } response.Write(json) return nil }
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) }
func (c *ApiContext) ValidateAwsCredentials(rw web.ResponseWriter, r *web.Request, next web.NextMiddlewareFunc) { if ok := validatePresenceRequest(r, "AWS_ACCESS_KEY_ID", "AWS_SECRET_ACCESS_KEY"); !ok { rw.WriteHeader(http.StatusUnauthorized) writeJson(rw, map[string]string{ "error": "missing credentials", }) } else { creds := credentials.NewStaticCredentials(r.FormValue("AWS_ACCESS_KEY_ID"), r.FormValue("AWS_SECRET_ACCESS_KEY"), "") c.AwsCredentials = creds next(rw, r) } }
func (c *WidgetContext) MMUInfo(rw web.ResponseWriter, req *web.Request) { build := mmu.Build{Name: appName, Version: appVersion} git := mmu.Git{Branch: buildCommitBranch, Commit: mmu.Commit{ID: buildCommit, Time: buildCommitTime}} mgtEndpoints := mmu.ManagementEndpoints{Info: "/internal/info", Health: "/internal/health"} serviceDependencies := []mmu.ServiceDependency{mmu.ServiceDependency{ServiceID: "auth", Version: "2"}} info := mmu.Info{Build: build, Git: git, ManagementEndpoints: mgtEndpoints, ServiceDependencies: serviceDependencies, SDK: buildGoSDK} if data, err := json.Marshal(&info); err != nil { rw.WriteHeader(500) return } else { rw.Write(data) } }
//SaveTask handles the endpoint POST /todo func (c *Context) SaveTask(rw web.ResponseWriter, req *web.Request) { var task db.Task decoder := json.NewDecoder(req.Body) if decoder != nil { if err := decoder.Decode(&task); err == nil { man.Create(&task) rw.WriteHeader(http.StatusOK) } else { fmt.Fprint(rw, jsonError("trying decode, but "+err.Error())) } } }
func (c *Context) QueryVarsMiddleware(rw web.ResponseWriter, r *web.Request, next web.NextMiddlewareFunc) { values, err := parseQueryParams(rw, r) if err != nil { log.Println(err) rw.WriteHeader(http.StatusBadRequest) rw.Write([]byte("Malformed URL")) return } c.values = &values next(rw, r) }
// Get specific thermometer by code func (c *Context) ThermometerByCodeHandler(rw web.ResponseWriter, req *web.Request) { code := parseStringPathParameter(req, "code") var thermometer orm.Thermometer db.Where(&orm.Thermometer{Code: code}).First(&thermometer) if thermometer.ID == 0 { rw.WriteHeader(http.StatusNotFound) rw.Write([]byte("Thermometer not found")) return } marshal(rw, thermometer) }
// GetBlockByNumber returns the data contained within a specific block in the // blockchain. The genesis block is block zero. func (s *ServerOpenchainREST) GetBlockByNumber(rw web.ResponseWriter, req *web.Request) { // Parse out the Block id blockNumber, err := strconv.ParseUint(req.PathParams["id"], 10, 64) // Check for proper Block id syntax if err != nil { // Failure rw.WriteHeader(400) fmt.Fprintf(rw, "{\"Error\": \"Block id must be an integer (uint64).\"}") } else { // Retrieve Block from blockchain block, err := s.server.GetBlockByNumber(context.Background(), &pb.BlockNumber{Number: blockNumber}) // Check for error if err != nil { // Failure switch err { case oc.ErrNotFound: rw.WriteHeader(http.StatusNotFound) default: rw.WriteHeader(http.StatusInternalServerError) } fmt.Fprintf(rw, "{\"Error\": \"%s\"}", err) } else { // Success rw.WriteHeader(http.StatusOK) encoder := json.NewEncoder(rw) encoder.Encode(block) } } }
// GoSlow waits until you are ready func GoSlow(response web.ResponseWriter, request *web.Request) { rawDelayStr := request.PathParams["delay"] delayStr := fmt.Sprintf("%vms", rawDelayStr) delay, err := time.ParseDuration(delayStr) if err != nil { log.Printf("error: %v", err.Error()) response.WriteHeader(http.StatusNotAcceptable) fmt.Fprint(response, `{"error": "'GET /:delay', delay must be an integer"}`) return } time.Sleep(delay) response.WriteHeader(http.StatusOK) fmt.Fprintf(response, `{"delay": %v}`, rawDelayStr) }
// MeshbluAuth checks auth headers and puts them into the context func (context *AuthContext) MeshbluAuth(response web.ResponseWriter, request *web.Request, next web.NextMiddlewareFunc) { if request.URL.Path == "/healthcheck" { next(response, request) return } uuid, token, ok := request.BasicAuth() if !ok { response.WriteHeader(http.StatusForbidden) fmt.Fprint(response, `{"error": "Not Authorized"}`) return } context.uuid = uuid context.token = token next(response, request) }
func (this *RequestHandler) getJobStatus(response web.ResponseWriter, request *web.Request) error { payload, err := GetStatusRequestPayloadFromRequest(request) if err != nil { return err } status, err := this.Repository.GetJobStatus(payload.JobIds) if err != nil { return err } json, err := json.Marshal(status) if err != nil { return err } response.Write(json) return nil }
// GetBlockchainInfo returns information about the blockchain ledger such as // height, current block hash, and previous block hash. func (s *ServerOpenchainREST) GetBlockchainInfo(rw web.ResponseWriter, req *web.Request) { info, err := s.server.GetBlockchainInfo(context.Background(), &google_protobuf.Empty{}) encoder := json.NewEncoder(rw) // Check for error if err != nil { // Failure rw.WriteHeader(400) fmt.Fprintf(rw, "{\"Error\": \"%s\"}", err) } else { // Success rw.WriteHeader(200) encoder.Encode(info) } }
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) } }
// GetPeers returns a list of all peer nodes currently connected to the target peer. func (s *ServerOpenchainREST) GetPeers(rw web.ResponseWriter, req *web.Request) { peers, err := s.server.GetPeers(context.Background(), &google_protobuf.Empty{}) encoder := json.NewEncoder(rw) // Check for error if err != nil { // Failure rw.WriteHeader(http.StatusBadRequest) fmt.Fprintf(rw, "{\"Error\": \"%s\"}", err) restLogger.Error(fmt.Sprintf("{\"Error\": \"Querying network peers -- %s\"}", err)) } else { // Success rw.WriteHeader(http.StatusOK) encoder.Encode(peers) } }
func (c *Context) parseUintQueryParameter(rw web.ResponseWriter, name string) (ret uint64, err error) { s := c.values.Get(name) if s == "" { return 0, nil } ret, err = parseUintFromString(s) if err != nil { log.Println("Error parsing uint64 " + name + ": " + s) log.Println(err) rw.WriteHeader(http.StatusBadRequest) rw.Write([]byte("Malformed parameter " + name)) } return }
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) } }