func (h *DBHandler) scenarioStubsHandler(rw http.ResponseWriter, req *http.Request) { // stubo ID, should be stored in database id := bone.GetValue(req, "id") u, err := strconv.ParseUint(id, 10, 64) if err != nil { http.Error(rw, "Bad stubo ID.", 400) return } var stubo Stubo // getting stubo from database stubo = h.getStuboDetails(u) // getting all scenarios client := &Client{&http.Client{}} scenarioName := bone.GetValue(req, "scenario") stuboURI := stubo.Protocol + "://" + stubo.Hostname + ":" + stubo.Port stubs, err := client.getScenarioStubs(stuboURI, scenarioName) if err != nil { http.Error(rw, "Failed to get scenario stubs from Stubo!", 400) return } newmap := map[string]interface{}{"metatitle": "Scenario Stubs", "Scenario": scenarioName, "Stubo": stubo, "Stubs": stubs} h.r.HTML(rw, http.StatusOK, "scenarioStubs", newmap) }
func varHandler(rw http.ResponseWriter, req *http.Request) { varr := bone.GetValue(req, "var") test := bone.GetValue(req, "test") log.Println("VAR = ", varr) log.Println("TEST = ", test) rw.Write([]byte(varr + " " + test)) }
func (ss *StaticServer) PutKey(rw http.ResponseWriter, req *http.Request) { key := bone.GetValue(req, "key") value := bone.GetValue(req, "value") ss.setS3RootIfPresent(key, value) if err := ss.mkv.Upsert(key, value); err != nil { util.WriteError(rw, "STAT-201", err) return } util.WriteJSON(rw, value) }
func (ss *StaticServer) GetIDForHash(rw http.ResponseWriter, req *http.Request) { name := bone.GetValue(req, "idname") hash := bone.GetValue(req, "hash") id, err := ss.mkv.GetIDFor(name, hash) if err != nil { util.WriteError(rw, "STAT-251", err) return } util.WriteJSON(rw, id) }
// Get the ADCP from the given serial number value. func vaultAPIAdcpSerialGetHandler(w http.ResponseWriter, r *http.Request) { // Get the value of the "id" parameters. id := bone.GetValue(r, "id") switch r.Method { case "GET": { adcp := getAdcp(id) fmt.Printf("Get ADCP from serial: %s %v", id, adcp) // Set data type and OK status w.Header().Set("Content-Type", "application/json; charset=UTF-8") w.WriteHeader(http.StatusOK) if err := json.NewEncoder(w).Encode(adcp); err != nil { panic(err) } } case "POST": { } default: { } } }
func DeliveryHandler(w http.ResponseWriter, r *http.Request) { keyId := bone.GetValue(r, "key") c := appengine.NewContext(r) key, err := datastore.DecodeKey(keyId) var dbRequest MainRequest if err = datastore.Get(c, key, &dbRequest); err != nil { c.Errorf("%s", err) } var status *postmates.Status if dbRequest.Pm_delivery_id == "" { status, err = postmates.RescueDelivery(c) if status != nil { dbRequest.Pm_delivery_id = status.ID if _, err := datastore.Put(c, key, &dbRequest); err != nil { c.Errorf("%s", err) } } } else { status, err = postmates.GetStatus(c, dbRequest.Pm_delivery_id) if err != nil { c.Errorf("%s", err) } } // send back important info err = json.NewEncoder(w).Encode(&status) if err != nil { c.Errorf("%s", err) } }
func (h *DBHandler) stuboDetailedHandler(rw http.ResponseWriter, req *http.Request) { id := bone.GetValue(req, "id") u, err := strconv.ParseUint(id, 10, 64) if err != nil { http.Error(rw, "Bad stubo ID.", 400) return } var stubo Stubo // getting stubo from database stubo = h.getStuboDetails(u) stuboURI := stubo.Protocol + "://" + stubo.Hostname + ":" + stubo.Port // getting all scenarios client := &Client{&http.Client{}} scenarios, err := client.getScenarios(stuboURI) if err != nil { http.Error(rw, "Failed to get scenarios from Stubo!", 400) return } log.WithFields(log.Fields{ "id": id, "url_path": req.URL.Path, "scenario_count": len(scenarios), }).Info("Stubo details fetched") newmap := map[string]interface{}{"metatitle": "Stubo Details", "Stubo": stubo, "Scenarios": scenarios} h.r.HTML(rw, http.StatusOK, "stuboDetails", newmap) }
/** * GetDevice() */ func GetDevice(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/json; charset=utf-8") Db := db.MgoDb{} Db.Init() defer Db.Close() id := bone.GetValue(r, "device_id") result := models.Device{} err := Db.C("devices").Find(bson.M{"id": id}).One(&result) if err != nil { log.Print(err) w.WriteHeader(http.StatusNotFound) str := `{"response": "not found", "id": "` + id + `"}` if err != nil { log.Print(err) } io.WriteString(w, str) return } w.WriteHeader(http.StatusOK) res, err := json.Marshal(result) if err != nil { log.Print(err) } io.WriteString(w, string(res)) }
// Handle a request tho the root reesource func usernameHandler(w http.ResponseWriter, r *http.Request) { username := bone.GetValue(r, "username") if err := json.NewEncoder(w).Encode(username); err != nil { panic(err) } }
// Set the Compass Cal Selected value. This will invert the value that is in the database. func vaultAPICompassCalSelectGetHandler(w http.ResponseWriter, r *http.Request) { // Get the value of the "id" parameters. id := bone.GetValue(r, "id") switch r.Method { case "GET": { compassCal := getCompassCalResultsID(id) compassCal.IsSelected = !compassCal.IsSelected // Invert the value // Pass the data back to the database updateCompassCal(compassCal) fmt.Printf("given CompassCal: %v\n", compassCal) // Set data type and OK status w.Header().Set("Content-Type", "application/json; charset=UTF-8") w.WriteHeader(http.StatusOK) if err := json.NewEncoder(w).Encode(compassCal); err != nil { panic(err) } } case "POST": { } default: { } } }
// Get the ADCP Cert info the given serial number value. func vaultAPIAdcpCertGetHandler(w http.ResponseWriter, r *http.Request) { // Get the value of the "id" parameters. serialNum := bone.GetValue(r, "id") // Get the value of the "id" parameters in the URL. switch r.Method { case "GET": { adcp := getAdcp(serialNum) // Get the ADCP data from the DB adcpCert := &AdcpCert{Adcp: *adcp} // Set the ADCP to struct adcpCert.CompassCal = getCompassCalCertData(serialNum) // Get Compass Cal from the DB adcpCert.TankTest = getTankTestResultCertData(serialNum) // Get Tank Test from the DB adcpCert.SnrTest = getSnrTestResultCertData(serialNum) // Get SNR Test from the DB adcpCert.WaterTest = getWaterTestResultCertData(serialNum) // Get Water Test from the DB fmt.Printf("Get ADCP from serial: %s %v", serialNum, adcpCert) // Set data type and OK status w.Header().Set("Content-Type", "application/json; charset=UTF-8") w.WriteHeader(http.StatusOK) if err := json.NewEncoder(w).Encode(adcpCert); err != nil { panic(err) } } case "POST": { } default: { } } }
func main() { db, err := sql.Open("postgres", "user=laptop dbname=estelle_test sslmode=disable") if err != nil { log.Fatal(err) } r := render.New(render.Options{ Directory: "views", Extensions: []string{".html"}, }) mux := bone.New() ServeResource := assets.ServeResource mux.HandleFunc("/img/", ServeResource) mux.HandleFunc("/css/", ServeResource) mux.HandleFunc("/js/", ServeResource) mux.HandleFunc("/pages", func(w http.ResponseWriter, req *http.Request) { rows, err := db.Query("SELECT id, title FROM pages") if err != nil { log.Fatal(err) } defer rows.Close() type yourtype struct { Id int Title string } s := []yourtype{} for rows.Next() { var t yourtype if err := rows.Scan(&t.Id, &t.Title); err != nil { log.Fatal(err) } fmt.Printf("%s", t.Title) s = append(s, t) } r.HTML(w, http.StatusOK, "foofoo", s) }) mux.HandleFunc("/bar", func(w http.ResponseWriter, req *http.Request) { r.HTML(w, http.StatusOK, "bar", nil) }) mux.HandleFunc("/home/:id", func(w http.ResponseWriter, req *http.Request) { id := bone.GetValue(req, "id") r.HTML(w, http.StatusOK, "index", id) }) mux.HandleFunc("/foo", func(w http.ResponseWriter, req *http.Request) { r.HTML(w, http.StatusOK, "foo", nil) }) mux.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) { r.HTML(w, http.StatusOK, "index", nil) }) http.ListenAndServe(":8080", mux) }
func (ss *StaticServer) RemoveKey(rw http.ResponseWriter, req *http.Request) { key := bone.GetValue(req, "key") err := ss.mkv.Remove(key) if err != nil { util.WriteError(rw, "STAT-231", err) } }
func dumpHandler(w http.ResponseWriter, r *http.Request) { database := bone.GetValue(r, "name") ignore := r.FormValue("ignore") // ignore=cache*,voting* tableIgnore := make([]string, 0) if ignore != "" { tableIgnore = strings.Split(ignore, ",") } // limit=5000 limitStr := r.FormValue("limit") var limit int64 if limitStr != "" { var err error limit, err = strconv.ParseInt(limitStr, 0, 0) if err != nil { w.WriteHeader(http.StatusBadRequest) w.Write([]byte(`Invalid limit variable supplied`)) log.Println(err) return } } log.Printf("Dump of %s requested from %s", database, r.RemoteAddr) dumpReady := make(chan DumpReady, 1) dumpSent := make(chan bool, 1) dr := &DumpRequest{ ID: database, Name: database, TableIgnore: tableIgnore, Limit: int(limit), Finished: dumpReady, Sent: dumpSent, } dumpQueue <- dr dur := <-dumpReady if dur.Error != nil { w.WriteHeader(http.StatusNotFound) w.Write([]byte(fmt.Sprint(dur.Error))) log.Println(dur.Error) } else { w.Header().Set("Content-Disposition", fmt.Sprintf("attachment; filename=%s-db-dump.tar.gz", database)) w.Header().Set("Content-Type", "application/x-gzip") w.Header().Set("Content-Transfer-Encoding", "binary") http.ServeFile(w, r, dur.File) log.Printf("Dump of %s sent to %s", database, r.RemoteAddr) } //w.(http.Flusher).Flush() // Notify that the file has been sent to the client dumpSent <- true }
func (ss *StaticServer) GenID(rw http.ResponseWriter, req *http.Request) { name := bone.GetValue(req, "idname") id, err := ss.mkv.GetNextID(name) if err != nil { util.WriteError(rw, "STAT-261", err) } util.WriteJSON(rw, id) }
func ImageHandler(w http.ResponseWriter, r *http.Request) { val := bone.GetValue(r, "rows") re := regexp.MustCompile("\\d*") rowsStr := re.FindString(val) rows, err := strconv.Atoi(rowsStr) if err != nil { fmt.Fprint(w, "Please pass in number of row") return } if rows > 5000 { fmt.Fprint(w, "Please pass in a row equal or smaller than 5000") return } cachedImage, ok := cache[rows] if ok { w.Header().Set("Content-type", "image/png") w.Header().Set("Cache-control", "public, max-age=259200") w.Write(cachedImage.Bytes()) return } ctx, err := cloudAuthContext(r) if err == nil { rc, err := storage.NewReader(ctx, bucket, rowsStr+".png") if err == nil { image, err := ioutil.ReadAll(rc) rc.Close() if err == nil { w.Header().Set("Content-type", "image/png") w.Header().Set("Cache-control", "public, max-age=259200") w.Write(image) return } } } m := image.NewPaletted(image.Rectangle{Min: image.Point{0, 0}, Max: image.Point{rows, rows}}, bwPalette) m.Pix[m.PixOffset(rows-1, 0)] = 1 for row := 1; row < rows; row++ { m.Pix[m.PixOffset(rows-1, row)] = 1 for j := rows - row; j < rows-1; j++ { mid := m.PixOffset(j, row-1) left, right := mid-1, mid+1 m.Pix[m.PixOffset(j, row)] = rulesUint8[m.Pix[left]][m.Pix[mid]][m.Pix[right]] } } w.Header().Set("Content-type", "image/png") w.Header().Set("Cache-control", "public, max-age=259200") buf := new(bytes.Buffer) png.Encode(buf, m) cache[rows] = buf w.Write(buf.Bytes()) }
func (ss *StaticServer) FindKey(rw http.ResponseWriter, req *http.Request) { key := bone.GetValue(req, "key") s, err := ss.mkv.FindOne(key) if err != nil { util.WriteNewWebError(rw, http.StatusNotFound, "STAT-221", "Couldn't find key "+key+": "+err.Error()) return } util.WriteJSON(rw, s) }
// stuboDestroyHandler deletes a stubo instance from the db. func (h *DBHandler) stuboDestroyHandler(rw http.ResponseWriter, req *http.Request) { id := bone.GetValue(req, "id") stubo := Stubo{} h.db.Delete(&stubo, id) log.WithFields(log.Fields{ "id": id, "url_path": req.URL.Path, }).Info("Stubo deleted") h.r.JSON(rw, http.StatusOK, map[string]string{"data": "Stubo instance deleted!"}) }
// Get the Ringing Tank Test data with the given serial number from the vault. func vaultAPITankSelectedSerialRingingHandler(w http.ResponseWriter, r *http.Request) { // Get the value of the "id" parameters. serial := bone.GetValue(r, "id") // Set data type and OK status w.Header().Set("Content-Type", "application/json; charset=UTF-8") w.WriteHeader(http.StatusOK) if err := json.NewEncoder(w).Encode(getTankTestResultsSelectedType(serial, "Ringing")); err != nil { panic(err) } }
// RedirectKey return a http.Handler that redirects to the URL in the store func RedirectKey(store storage.Database) func(http.ResponseWriter, *http.Request) { return func(w http.ResponseWriter, r *http.Request) { key := bone.GetValue(r, "key") status, err := store.Get(key) if err != nil { http.Error(w, err.Error(), http.StatusNotFound) } else { store.Incr(key) http.Redirect(w, r, html.EscapeString(status.URL), 301) } } }
// Update the Product. func productUpdateHandler(w http.ResponseWriter, r *http.Request) { if r.Method == "GET" { // Get the value of the "id" parameters. productNum := bone.GetValue(r, "id") product := getProduct(productNum) productData := &ProductUpdate{} productData.Product = *product displayProductUpdateTemplate(w, productData) } else { // Parse the form formData, err := forms.Parse(r) CheckError(err) // Check token token := r.Form.Get("token") if token != "" { // check token validity fmt.Println("Good token") } else { // give error if no token fmt.Println("Bad token") } // Validate data val := formData.Validator() val.Require("PartNumber") // Use data to create a user object product := getProduct(formData.Get("PartNumber")) product.PartNumber = formData.Get("PartNumber") product.Desc = formData.Get("Desc") product.ReferenceDes = formData.Get("ReferenceDes") product.UnitPrice = formData.GetFloat("UnitPrice") product.ListPrice = formData.GetFloat("ListPrice") product.Type = formData.Get("Type") product.Qty = formData.GetInt("Qty") product.UnitOfMeasure = formData.Get("UnitOfMeasure") product.Cost = formData.GetFloat("Cost") product.Modified = time.Now().Local() fmt.Printf("Product Update: %s\n", product.PartNumber) // Update the Product in DB updateProduct(product) // Go to the list of Products http.Redirect(w, r, "/product", http.StatusFound) } }
func GetMovie(rw http.ResponseWriter, req *http.Request) { id := bone.GetValue(req, "id") movie := &Movie{} err := db.C("movie").FindId(bson.ObjectIdHex(id)).One(movie) if err != nil { errLog.NewHTTPErr("NOT FOUND", "This movie doesn't exist").LogHTTP(req).SendHTTP(rw, 404) return } err = json.NewEncoder(rw).Encode(movie) if err != nil { errLog.NewHTTPErr("NOT FOUND", err).LogHTTP(req).SendHTTP(rw, 404) return } }
func (p *proxyAdminServer) DeleteProxyIteraction(response http.ResponseWriter, request *http.Request) { idString := bone.GetValue(request, "id") id := uuid.Parse(idString) p.Db.Update(func(tx *bolt.Tx) error { b := tx.Bucket([]byte("Proxies")) err := b.Delete([]byte(id)) return err }) response.WriteHeader(204) }
/** * UpdateChannel() */ func UpdateChannel(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/json; charset=utf-8") Db := db.MgoDb{} Db.Init() defer Db.Close() data, err := ioutil.ReadAll(r.Body) if err != nil { panic(err) } if len(data) == 0 { w.WriteHeader(http.StatusBadRequest) str := `{"response": "no data provided"}` io.WriteString(w, str) return } var body map[string]interface{} if err := json.Unmarshal(data, &body); err != nil { panic(err) } /** if validateJsonSchema("channel", body) != true { println("Invalid schema") w.WriteHeader(http.StatusBadRequest) str := `{"response": "invalid json schema in request"}` io.WriteString(w, str) return } **/ id := bone.GetValue(r, "channel_id") // Publish the channel update. // This will be catched by the MQTT main client (subscribed to all channel topics) // and then written in the DB in the MQTT handler token := clients.MqttClient.Publish("mainflux/"+id, 0, false, string(data)) token.Wait() // Wait on status from MQTT handler (which executes DB write) status := <-clients.WriteStatusChannel w.WriteHeader(status.Nb) str := `{"response": "` + status.Str + `"}` io.WriteString(w, str) }
func (ss *StaticServer) PostKey(rw http.ResponseWriter, req *http.Request) { key := bone.GetValue(req, "key") body, err := ioutil.ReadAll(req.Body) if err != nil { util.WriteWebError(rw, util.NewWebError(http.StatusBadRequest, "STAT-211", err.Error())) } b := string(body) value := getJSON(b) ss.setS3RootIfPresent(key, value) if err := ss.mkv.Upsert(key, value); err != nil { util.WriteError(rw, "STAT-212", err) return } util.WriteJSON(rw, value) }
// Display the RMA Report func rmaReportHandler(w http.ResponseWriter, r *http.Request) { fmt.Println("method:", r.Method) // get request method if r.Method == "GET" { rmaID := bone.GetValue(r, "id") // Get the value of the "id" parameters in the URL. rma := getRma(rmaID) // Get the RMA rmaReport := &RmaReport{} // Set the RMA Report rmaReport.RMA = *rma t, _ := template.ParseFiles("header.html", "rma_report.html", "footer.html") t.ExecuteTemplate(w, "header", nil) t.ExecuteTemplate(w, "content", rmaReport) t.ExecuteTemplate(w, "footer", nil) t.Execute(w, rmaReport) } }
func GetMovieByTitle(rw http.ResponseWriter, req *http.Request) { title := bone.GetValue(req, "title") movie := &Movie{} err := db.C("movie").Find(bson.M{"title": title}).One(movie) if err != nil { data := GetMovieData(title) err = json.NewEncoder(rw).Encode(&data) if err != nil { errLog.NewHTTPErr("NOT FOUND", "This movie doesn't exist").LogHTTP(req).SendHTTP(rw, 404) return } return } err = json.NewEncoder(rw).Encode(movie) if err != nil { errLog.NewHTTPErr("NOT FOUND", err).LogHTTP(req).SendHTTP(rw, 404) return } }
func RequestHandler(w http.ResponseWriter, r *http.Request) { c := appengine.NewContext(r) keyString := bone.GetValue(r, "key") decodedKey, err := datastore.DecodeKey(keyString) if err != nil { c.Errorf("Error decoding key %s", err) } var purchase_request MainRequest if err = datastore.Get(c, decodedKey, &purchase_request); err != nil { c.Errorf("Error retrieving request key from database", err) } // render the template request_template, err := template.ParseFiles("request.html") if err != nil { c.Errorf("Error parsing template %s", err) } request_template.ExecuteTemplate(w, "request", purchase_request) }
/** * GetChannel() */ func GetChannel(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/json; charset=utf-8") Db := db.MgoDb{} Db.Init() defer Db.Close() id := bone.GetValue(r, "channel_id") var vlimit int var err error s := r.URL.Query().Get("vlimit") if len(s) == 0 { // Set default limit to -5 vlimit = -5 } else { vlimit, err = strconv.Atoi(s) if err != nil { w.WriteHeader(http.StatusBadRequest) str := `{"response": "wrong limit"}` io.WriteString(w, str) return } } result := models.Channel{} if err := Db.C("channels").Find(bson.M{"id": id}). Select(bson.M{"values": bson.M{"$slice": vlimit}}). One(&result); err != nil { log.Print(err) w.WriteHeader(http.StatusNotFound) str := `{"response": "not found", "id": "` + id + `"}` io.WriteString(w, str) return } w.WriteHeader(http.StatusOK) res, err := json.Marshal(result) if err != nil { log.Print(err) } io.WriteString(w, string(res)) }
// Update the ADCP data func adcpCertHandler(w http.ResponseWriter, r *http.Request) { fmt.Println("method:", r.Method) // get request method if r.Method == "GET" { serialNum := bone.GetValue(r, "id") // Get the value of the "id" parameters in the URL. adcp := getAdcp(serialNum) // Get the ADCP data from the DB adcpCert := &AdcpCert{Adcp: *adcp} // Set the ADCP to struct adcpCert.CompassCal = getCompassCalCertData(serialNum) // Get Compass Cal from the DB adcpCert.TankTest = getTankTestResultCertData(serialNum) // Get Tank Test from the DB adcpCert.SnrTest = getSnrTestResultCertData(serialNum) // Get SNR Test from the DB adcpCert.WaterTest = getWaterTestResultCertData(serialNum) // Get Water Test from the DB t, _ := template.ParseFiles("header.html", "adcp_cert.html", "footer.html") t.ExecuteTemplate(w, "header", nil) t.ExecuteTemplate(w, "content", adcpCert) t.ExecuteTemplate(w, "footer", nil) t.Execute(w, adcpCert) } }