示例#1
0
func CreateGoal(enc encoder.Encoder, goal Goal) (int, []byte) {
	goalId, err := uuid.NewV4()
	if err != nil {
		return 500, encoder.Must(enc.Encode(""))
	}
	goal.Id = goalId.String()
	if goal.TargetType == "user" {
		user, ok := users[goal.Target]
		if !ok {
			return 400, encoder.Must(enc.Encode("Target does not exist"))
		}
		user.Goals[goal.Id] = &goal
	} else if goal.TargetType == "team" {
		team, ok := teams[goal.Target]
		if !ok {
			return 400, encoder.Must(enc.Encode("Target does not exist"))
		}
		team.Goals[goal.Id] = &goal
	} else {
		return 400, encoder.Must(enc.Encode("Unknown target type"))
	}

	goals[goal.Id] = &goal
	return 201, encoder.Must(enc.Encode(goal.Id))
}
示例#2
0
func GetUsers(dataStore DataStore, enc encoder.Encoder) (int, []byte) {
	users, err := dataStore.GetAllUsers()
	if err != nil {
		return http.StatusNoContent, encoder.Must(enc.Encode(NewError(ErrInternal, "Can't get users try again later")))
	}
	return http.StatusOK, encoder.Must(enc.Encode(users))
}
示例#3
0
func GetGoal(enc encoder.Encoder, params martini.Params) (int, []byte) {
	goal, ok := goals[params["id"]]
	if ok {
		return 200, encoder.Must(enc.Encode(goal))
	}
	return 404, encoder.Must(enc.Encode())
}
示例#4
0
func GetMac(res http.ResponseWriter, req *http.Request, enc encoder.Encoder) (int, []byte) {
	ip := strings.Split(req.RemoteAddr, ":")[0]
	mac, err := GetMacAddress("/proc/net/arp", ip)
	if err != nil {
		return http.StatusNotFound, encoder.Must(enc.Encode(NewError(ErrMacNotFound, err.Error())))
	}
	return http.StatusOK, encoder.Must(enc.Encode(map[string]string{"mac": mac}))
}
示例#5
0
文件: server.go 项目: yc850k/haha
func GetServer(enc encoder.Encoder, db database.DB, parms martini.Params) (int, []byte) {
	fmt.Printf("begin get server\n")
	id, err := strconv.ParseInt(parms["id"], 10, 64)
	al := db.Get(id)
	if err != nil || al == nil {
		msg := fmt.Sprintf("the album with id %s does not exist", parms["id"])
		return http.StatusNotFound, encoder.Must(enc.Encode(
			NewError{errcode: 404, errmsg: msg}))
	}
	return http.StatusOK, encoder.Must(enc.Encode(al))
}
示例#6
0
文件: server.go 项目: yc850k/haha
func FindServer(enc encoder.Encoder, db database.DB, r *http.Request) (int, []byte) {
	fmt.Printf("begin find server\n")
	params := r.URL.Query()
	roomId, err := strconv.ParseInt(params.Get("room_id"), 10, 64)
	al := db.Find(roomId)
	if err != nil || al == nil {
		msg := fmt.Sprintf("server witch room_id %s does not exist", params.Get("id"))
		return http.StatusNotFound, encoder.Must(enc.Encode(
			NewError{errcode: 404, errmsg: msg}))
	}
	return http.StatusOK, encoder.Must(enc.Encode(al))
}
示例#7
0
func GetUser(dataStore DataStore, enc encoder.Encoder, params martini.Params) (int, []byte) {
	id, err := strconv.Atoi(params["id"])
	if err != nil {
		return http.StatusNotFound, encoder.Must(enc.Encode(NewError(ErrInternal, "Invalid id")))
	}

	user, dbErr := dataStore.GetUser(id)
	if dbErr != nil {
		return http.StatusNotFound, encoder.Must(enc.Encode(NewError(ErrUserNotFound, dbErr.Error())))
	}
	return http.StatusOK, encoder.Must(enc.Encode(user))
}
示例#8
0
func main() {
	api := &api.API{
		ApiKey: "122cc483be92bd806b696e7d458596ac",
		DataCacheRenewalInterval: 15,
	}
	api.Setup()
	go api.CyclicCacheRenewal()

	m := martini.Classic()
	m.Map(api)

	m.Use(cors.Allow(&cors.Options{
		AllowAllOrigins:  true,
		AllowCredentials: true,
	}))

	m.Use(func(c martini.Context, w http.ResponseWriter) {
		c.MapTo(encoder.JsonEncoder{}, (*encoder.Encoder)(nil))
		w.Header().Set("Content-Type", "application/json; charset=utf-8")
	})

	m.Get("/photos/:name", func(params martini.Params,
		enc encoder.Encoder) (int, []byte) {
		name, ok := params["name"]

		if ok {
			photos, _ := api.GetPhotosForUser(name)
			return http.StatusOK, encoder.Must(enc.Encode(photos))
		}

		return 404, []byte("Not Found")
	})
	m.Run()
}
示例#9
0
func FetchStatus(s *Status, ms *mgo.Session, enc encoder.Encoder, r *http.Request) (int, []byte) {
	s.Log["MongoDB"] = NewLog(true, "")
	if err := ms.Ping(); err != nil {
		s.Log["MongoDB"] = NewLog(false, err.Error())
	}
	return http.StatusOK, encoder.Must(enc.Encode(s))
}
示例#10
0
func CompleteGoal(enc encoder.Encoder, params martini.Params, jsonParams GoalCompleteParams) (int, []byte) {
	goal, ok := goals[params["id"]]
	if !ok {
		return 404, encoder.Must(enc.Encode())
	}
	if _, ok := users[jsonParams.UserId]; !ok {
		return 400, encoder.Must(enc.Encode("User does not exist"))
	}
	goal.NumberOfCompletions--
	if goal.NumberOfCompletions > 0 {
		goal.State = "progress"
		return 200, encoder.Must(enc.Encode(goal.State)) //what should be returned here?
	}

	goal.State = "completed"
	return 200, encoder.Must(enc.Encode(goal.Reward))
}
示例#11
0
func CreatePreset(
	params martini.Params, w http.ResponseWriter,
	r *http.Request, enc encoder.Encoder) (int, []byte) {
	bytes, err := ioutil.ReadAll(r.Body)
	if err != nil {
		return http.StatusBadRequest,
			encoder.Must(enc.Encode(&Error{err.Error()}))
	}
	preset := &Preset{}
	err = json.Unmarshal(bytes, &preset)
	if err != nil {
		return http.StatusBadRequest,
			encoder.Must(enc.Encode(&Error{err.Error()}))
	}
	presets.Add(preset)
	w.Header().Set("Content-Type", "application/json; charset=utf-8")
	return http.StatusCreated, encoder.Must(enc.Encode(preset))
}
示例#12
0
func NewEncoder(opts ...Options) martini.Handler {
	return func(c martini.Context, w http.ResponseWriter) {
		wrappedWriter := newWrappedResponseWriter(w)
		c.MapTo(wrappedWriter, (*http.ResponseWriter)(nil))
		c.MapTo(encoder.JsonEncoder{PrettyPrint: true}, (*encoder.Encoder)(nil))

		var rtnHandler martini.ReturnHandler
		rtnHandler = func(ctx martini.Context, vals []reflect.Value) {
			rv := ctx.Get(inject.InterfaceOf((*http.ResponseWriter)(nil)))
			res := rv.Interface().(http.ResponseWriter)
			var responseVal reflect.Value
			if len(vals) > 1 && vals[0].Kind() == reflect.Int {
				res.WriteHeader(int(vals[0].Int()))
				responseVal = vals[1]
			} else if len(vals) > 0 {
				responseVal = vals[0]
			}
			if isNil(responseVal) {
				wrappedRes := res.(*wrappedResponseWriter)
				code := wrappedRes.statusCode
				if code == 0 {
					panic(errors.New("No return code set for error"))
				}
				responseVal = reflect.ValueOf(errorResponse{Error: code, Message: http.StatusText(code)})
			}
			if canDeref(responseVal) {
				responseVal = responseVal.Elem()
			}
			if isByteSlice(responseVal) {
				res.Write(responseVal.Bytes())
			} else if isStruct(responseVal) || isStructSlice(responseVal) {
				encv := ctx.Get(inject.InterfaceOf((*encoder.Encoder)(nil)))
				enc := encv.Interface().(encoder.Encoder)
				res.Header().Set("Content-Type", "application/json; charset=utf-8")
				buf := bytes.NewBuffer(encoder.Must(enc.Encode(responseVal.Interface())))
				if len(opts) > 0 {
					if opts[0].Html {
						val := buf.Bytes()
						buf.Reset()
						json.HTMLEscape(buf, val)
					}
					if opts[0].Indent {
						val := buf.Bytes()
						buf.Reset()
						json.Indent(buf, val, "", "\t")
					}
				}
				res.Write(buf.Bytes())
			} else {
				res.Write([]byte(responseVal.String()))
			}
		}
		c.Map(rtnHandler)
	}
}
示例#13
0
func listLocations(enc encoder.Encoder, r *http.Request, db *mgo.Database) (int, []byte) {
	var locations []Location

	c := db.C("locations")
	err := c.Find(nil).All(&locations)
	if err != nil {
		return http.StatusInternalServerError, []byte("Impossible to retrieve the locations: " + err.Error())
	}

	return http.StatusOK, encoder.Must(enc.Encode(locations))
}
示例#14
0
func main() {
	// 使用crawldata包里面的Crawl()抓取需要的数据存到数据库
	// crawldata.Crawl()

	m := martini.New()
	route := martini.NewRouter()

	var (
		results Results
		err     error
	)

	m.Use(func(c martini.Context, w http.ResponseWriter, r *http.Request) {
		// 将 encoder.JsonEncoder{} 按照 encoder.Encoder 接口(注意大小写)类型注入到内部
		c.MapTo(encoder.JsonEncoder{}, (*encoder.Encoder)(nil))
		w.Header().Set("Content-Type", "application/json; charset=utf-8")
	})

	route.Get("/", func(enc encoder.Encoder) (int, []byte) {
		result := Results{10001, "Not Found Data", nil}
		return http.StatusOK, encoder.Must(enc.Encode(result))
	})

	route.Get("/api", func(enc encoder.Encoder) (int, []byte) {
		results.Datas, err = crawldata.GetAllImages()
		if err != nil {
			fmt.Println(s.Join([]string{"获取数据失败", err.Error()}, "-->"))

			result := Results{10001, "Data Error", nil}
			return http.StatusOK, encoder.Must(enc.Encode(result))
		} else {
			results.Err = 10000
			results.Msg = "获取数据成功"
			return http.StatusOK, encoder.Must(enc.Encode(results))
		}
	})

	m.Action(route.Handle)
	m.Run()
}
示例#15
0
func getLocation(params martini.Params, enc encoder.Encoder, db *mgo.Database) (int, []byte) {
	var location Location

	if !bson.IsObjectIdHex(params["id"]) {
		return http.StatusNotFound, []byte("Location with id \"" + params["id"] + "\" not found")
	}

	c := db.C("locations")
	err := c.FindId(bson.ObjectIdHex(params["id"])).One(&location)
	if err != nil {
		return http.StatusNotFound, []byte("Location with id \"" + params["id"] + "\" not found")
	}

	return http.StatusOK, encoder.Must(enc.Encode(location))
}
示例#16
0
文件: http.go 项目: hyprstack/eevy
// Satisfies the Source interface and starts listening to the specified port
func (s *Http) Listen(wg sync.WaitGroup) {

	s.Log.Info("Start listening (http:%s:%d)", s.BindIp, s.Port)

	m := martini.New()
	route := martini.NewRouter()

	m.Use(func(c martini.Context, w http.ResponseWriter, r *http.Request) {
		// Use indentations. &pretty=1
		pretty, _ := strconv.ParseBool(r.FormValue("pretty"))
		// Use null instead of empty object for json &null=1
		null, _ := strconv.ParseBool(r.FormValue("null"))
		// Some content negotiation
		switch r.Header.Get("Accept") {
		case "application/xml":
			c.MapTo(encoder.XmlEncoder{PrettyPrint: pretty}, (*encoder.Encoder)(nil))
			w.Header().Set("Content-Type", "application/xml; charset=utf-8")
		default:
			c.MapTo(encoder.JsonEncoder{PrettyPrint: pretty, PrintNull: null}, (*encoder.Encoder)(nil))
			w.Header().Set("Content-Type", "application/json; charset=utf-8")
		}
	})

	route.Post("/event", func(enc encoder.Encoder, w http.ResponseWriter, r *http.Request) (int, []byte) {

		defer r.Body.Close()
		body, err := ioutil.ReadAll(r.Body)
		if err != nil {
			return http.StatusInternalServerError, []byte{}
		}

		result := s.processRaw(string(body))
		return http.StatusOK, encoder.Must(enc.Encode(result))
	})

	m.Action(route.Handle)

	port := fmt.Sprintf("%s:%d", s.BindIp, s.Port)
	if err := http.ListenAndServe(port, m); err != nil {
		s.Log.Error(err.Error())
	}

	wg.Done()
}
示例#17
0
func main() {
	runtime.GOMAXPROCS(runtime.NumCPU())

	pool := newPool(":6379")
	defer pool.Close()

	db := newDB(pool)
	defer db.Close()

	m := martini.New()
	m.Map(db)

	m.Use(func(c martini.Context, w http.ResponseWriter) {
		c.MapTo(encoder.JsonEncoder{}, (*encoder.Encoder)(nil))
		w.Header().Set("Content-Type", "application/json; charset=utf-8")
	})

	r := martini.NewRouter()

	r.Post("/users", binding.Bind(User{}), func(db *DB, u User) (int, string) {
		if err := db.SaveUser(&u); err != nil {
			return http.StatusInternalServerError, err.Error()
		}
		return http.StatusCreated, "OK"
	})

	r.Get("/users/:id", func(db *DB, params martini.Params, enc encoder.Encoder) (int, []byte) {
		str := params["id"]
		id, err := strconv.Atoi(str)
		if err != nil {
			return http.StatusBadRequest, []byte{}
		}

		u, err := db.LoadUser(id)
		if err != nil {
			return http.StatusNotFound, []byte{}
		}
		return http.StatusOK, encoder.Must(enc.Encode(u))
	})

	m.Action(r.Handle)

	m.Run()
}
示例#18
0
func createLocation(newLocation NewLocationForm, enc encoder.Encoder, db *mgo.Database) (int, []byte) {
	// transform the form struct into a real Location
	location := Location{
		ID: bson.NewObjectId(),
		Coordinates: Coordinates{
			Lat:  newLocation.Lat,
			Long: newLocation.Long,
		},
		Name:        newLocation.Name,
		Description: newLocation.Description,
		Visited:     newLocation.Visited,
		CreatedAt:   time.Now(),
	}

	// and try to insert it
	c := db.C("locations")
	err := c.Insert(&location)

	if err != nil {
		return http.StatusInternalServerError, []byte("Impossible to insert the location: " + err.Error())
	}

	return http.StatusCreated, encoder.Must(enc.Encode(location))
}
示例#19
0
func GetTeams(enc encoder.Encoder) (int, []byte) {
	return 200, encoder.Must(enc.Encode(teams))
}
示例#20
0
func GetUsers(enc encoder.Encoder) (int, []byte) {
	return 200, encoder.Must(enc.Encode(users))
}
示例#21
0
func CreateTeam(enc encoder.Encoder, team Team) (int, []byte) {
	team.Users = make(map[string]string)
	team.Goals = make(map[string]*Goal)
	teams[team.Id] = &team
	return 201, encoder.Must(enc.Encode(team.Id))
}
示例#22
0
func CreateUser(enc encoder.Encoder, user User) (int, []byte) {
	user.Teams = make(map[string]string)
	user.Goals = make(map[string]*Goal)
	users[user.Id] = &user
	return 201, encoder.Must(enc.Encode(user.Id))
}
示例#23
0
func GetPreset(enc encoder.Encoder, w http.ResponseWriter) (int, []byte) {
	w.Header().Set("Content-Type", "application/json; charset=utf-8")
	return http.StatusOK, encoder.Must(enc.Encode(&presets))
}
示例#24
0
func init() {
	m = martini.New()

	// Setup middleware
	m.Use(martini.Recovery())
	m.Use(martini.Logger())
	m.Use(martini.Static("public"))

	// Setup encoder
	m.Use(func(c martini.Context, w http.ResponseWriter) {
		c.MapTo(encoder.JsonEncoder{}, (*encoder.Encoder)(nil))
		w.Header().Set("Content-Type", "application/json; charset=utf-8")
	})

	// Setup and inject event broker
	b = NewBroker()
	m.Map(b)

	// Setup routes
	r := martini.NewRouter()

	r.Get("/", func(w http.ResponseWriter, r *http.Request) {
		files, _ := filepath.Glob("dashboards/*.gerb")

		for _, file := range files {
			dashboard := file[11 : len(file)-5]
			if dashboard != "layout" {
				http.Redirect(w, r, "/"+dashboard, http.StatusTemporaryRedirect)
				return
			}
		}

		http.NotFound(w, r)
		return
	})

	r.Get("/events", func(w http.ResponseWriter, r *http.Request, e encoder.Encoder, b *Broker) {
		f, ok := w.(http.Flusher)
		if !ok {
			http.Error(w, "Streaming unsupported!", http.StatusInternalServerError)
			return
		}

		c, ok := w.(http.CloseNotifier)
		if !ok {
			http.Error(w, "Close notification unsupported!", http.StatusInternalServerError)
			return
		}

		// Create a new channel, over which the broker can
		// send this client events.
		events := make(chan *Event)

		// Add this client to the map of those that should
		// receive updates
		b.newClients <- events

		// Remove this client from the map of attached clients
		// when the handler exits.
		defer func() {
			b.defunctClients <- events
		}()

		w.Header().Set("Content-Type", "text/event-stream")
		w.Header().Set("Cache-Control", "no-cache")
		w.Header().Set("Connection", "keep-alive")
		w.Header().Set("X-Accel-Buffering", "no")
		closer := c.CloseNotify()

		for {
			select {
			case event := <-events:
				data := event.Body
				data["id"] = event.ID
				data["updatedAt"] = int32(time.Now().Unix())
				if event.Target != "" {
					fmt.Fprintf(w, "event: %s\n", event.Target)
				}
				fmt.Fprintf(w, "data: %s\n\n", encoder.Must(e.Encode(data)))
				f.Flush()
			case <-closer:
				log.Println("Closing connection")
				return
			}
		}
	})

	r.Get("/:dashboard", func(r *http.Request, w http.ResponseWriter, params martini.Params) {
		template, err := gerb.ParseFile(true, "dashboards/"+params["dashboard"]+".gerb", "dashboards/layout.gerb")

		if err != nil {
			http.NotFound(w, r)
			return
		}

		w.Header().Set("Content-Type", "text/html; charset=UTF-8")

		template.Render(w, map[string]interface{}{
			"dashboard":   params["dashboard"],
			"development": os.Getenv("DEV") != "",
			"request":     r,
		})
		return
	})

	r.Post("/dashboards/:id", func(r *http.Request, params martini.Params, b *Broker) (int, string) {
		if r.Body != nil {
			defer r.Body.Close()
		}

		var data map[string]interface{}

		if err := json.NewDecoder(r.Body).Decode(&data); err != nil {
			return 400, ""
		}

		b.events <- &Event{params["id"], data, "dashboards"}
		return 204, ""
	})

	r.Post("/widgets/:id", func(r *http.Request, params martini.Params, b *Broker) (int, string) {
		if r.Body != nil {
			defer r.Body.Close()
		}

		var data map[string]interface{}

		if err := json.NewDecoder(r.Body).Decode(&data); err != nil {
			return 400, ""
		}

		b.events <- &Event{params["id"], data, ""}
		return 204, ""
	})

	r.Get("/views/:widget.html", func(w http.ResponseWriter, r *http.Request, params martini.Params) {
		template, err := gerb.ParseFile(true, "widgets/"+params["widget"]+"/"+params["widget"]+".html")

		if err != nil {
			http.NotFound(w, r)
			return
		}

		w.Header().Set("Content-Type", "text/html; charset=UTF-8")

		template.Render(w, nil)
		return
	})

	// Add the router action
	m.Action(r.Handle)
}
示例#25
0
文件: response.go 项目: kennylixi/as
func (this *Response) Error(message interface{}) (int, []byte) {
	enc := encoder.JsonEncoder{}
	return 400, encoder.Must(enc.Encode(map[string]interface{}{
		"message": message,
	}))
}
示例#26
0
func main() {
	// TODO move to own handler
	// create a global App var to hold your app id and secret.
	globalApp := fb.New(os.Getenv("FACEBOOK_APP_ID"), os.Getenv("FACEBOOK_SECRET"))
	globalApp.RedirectUri = "http://localhost:3000/auth/facebook/callback" // TODO

	// https://developers.facebook.com/docs/graph-api/securing-requests
	globalApp.EnableAppsecretProof = true

	// instantiate Martini
	m := martini.Classic()
	m.Use(martini.Logger())

	// setup database
	dbmap = initDb()
	defer dbmap.Db.Close()

	// CORS
	m.Use(cors.Allow(&cors.Options{
		AllowOrigins:     []string{"http://localhost:*"},
		AllowMethods:     []string{"GET", "POST"},
		AllowHeaders:     []string{"Origin", "Authorization", "Content-Type"},
		ExposeHeaders:    []string{"Content-Length"},
		AllowCredentials: true,
	}))

	// Authentication
	m.Use(func(c martini.Context, res http.ResponseWriter, req *http.Request) {
		accessToken := req.Header.Get("Authorization") // TODO expect "Bearer: {TOKEN}" format?
		session := globalApp.Session(accessToken)

		// TODO DELETE ME
		log.Printf("accessToken=%s", accessToken)

		// TODO make currentUser globally available
		// TODO add User struct and use res.Decode(&user)
		var user *User
		attrs, err := session.Get("/me", nil)

		if err != nil {
			// err can be an facebook API error.
			// if so, the Error struct contains error details.
			if e, ok := err.(*fb.Error); ok {
				log.Printf("Facebook error. [message:%v] [type:%v] [code:%v] [subcode:%v]", e.Message, e.Type, e.Code, e.ErrorSubcode)
			}

			res.WriteHeader(http.StatusUnauthorized)
		} else {
			user = findOrCreateUser(attrs)
			c.Map(user)
		}

		if user != nil {
			log.Printf("Logged in as: %s %s", user.FirstName, user.LastName)
		}
	})

	// Encoding
	m.Use(func(c martini.Context, w http.ResponseWriter, r *http.Request) {
		// Use indentations. &pretty=1
		pretty, _ := strconv.ParseBool(r.FormValue("pretty"))
		// Use null instead of empty object for json &null=1
		null, _ := strconv.ParseBool(r.FormValue("null"))
		// JSON no matter what
		c.MapTo(encoder.JsonEncoder{PrettyPrint: pretty, PrintNull: null}, (*encoder.Encoder)(nil))
		w.Header().Set("Content-Type", "application/json; charset=utf-8")
	})

	m.Get("/", func(user *User) string {
		// serve SPA ?
		return "Hello world" + user.FirstName
	})

	m.Get("/tells", func(enc encoder.Encoder, user *User) (int, []byte) {
		// get all tells for user and render JSON array
		tells := user.getTells()
		return http.StatusOK, encoder.Must(enc.Encode(tells))
	})

	m.Post("/tells", binding.Bind(Tell{}), func(enc encoder.Encoder, user *User, tell Tell) (int, []byte) {
		// create new tell for user
		tell = user.Tell(tell)
		return http.StatusOK, encoder.Must(enc.Encode(tell))
	})

	m.Run()
}
示例#27
0
文件: response.go 项目: tmchojo/as
func (this *Response) Error(message interface{}) (int, []byte) {
	fmt.Println(message)
	enc := encoder.JsonEncoder{}
	return 400, encoder.Must(enc.Encode(message))
}
示例#28
0
func GetTeam(enc encoder.Encoder, params martini.Params) (int, []byte) {
	if team, ok := teams[params["id"]]; ok {
		return 200, encoder.Must(enc.Encode(team))
	}
	return 404, encoder.Must(enc.Encode())
}
示例#29
0
func GetUserGoals(enc encoder.Encoder, params martini.Params) (int, []byte) {
	if user, ok := users[params["id"]]; ok {
		return 200, encoder.Must(enc.Encode(user.Goals))
	}
	return 404, encoder.Must(enc.Encode())
}
示例#30
0
文件: response.go 项目: tmchojo/as
func (this *Response) Success(data interface{}) (int, []byte) {
	enc := encoder.JsonEncoder{}
	return 200, encoder.Must(enc.Encode(data))
}