本文整理汇总了Golang中github.com/martini-contrib/encoder.Must函数的典型用法代码示例。如果您正苦于以下问题:Golang Must函数的具体用法?Golang Must怎么用?Golang Must使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了Must函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Golang代码示例。
示例1: CreateGoal
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))
}
开发者ID:FP7Collage,项目名称:GoalSetting,代码行数:25,代码来源:goals.go
示例2: GetUsers
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))
}
开发者ID:Blagomir,项目名称:WhoIsInTheLab,代码行数:7,代码来源:registration.go
示例3: GetGoal
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())
}
开发者ID:FP7Collage,项目名称:GoalSetting,代码行数:7,代码来源:goals.go
示例4: GetMac
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}))
}
开发者ID:Blagomir,项目名称:WhoIsInTheLab,代码行数:8,代码来源:registration.go
示例5: GetServer
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))
}
开发者ID:yc850k,项目名称:haha,代码行数:11,代码来源:server.go
示例6: FindServer
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))
}
开发者ID:yc850k,项目名称:haha,代码行数:12,代码来源:server.go
示例7: GetUser
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))
}
开发者ID:Blagomir,项目名称:WhoIsInTheLab,代码行数:12,代码来源:registration.go
示例8: main
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()
}
开发者ID:pboehm,项目名称:flickrit,代码行数:34,代码来源:flickrit.go
示例9: FetchStatus
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))
}
开发者ID:ranveerkunal,项目名称:admin,代码行数:7,代码来源:admin.go
示例10: CompleteGoal
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))
}
开发者ID:FP7Collage,项目名称:GoalSetting,代码行数:17,代码来源:goals.go
示例11: CreatePreset
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))
}
开发者ID:kevinjqiu,项目名称:imposter,代码行数:18,代码来源:imposter.go
示例12: NewEncoder
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)
}
}
开发者ID:jsimnz,项目名称:martini-contrib,代码行数:55,代码来源:response.go
示例13: listLocations
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))
}
开发者ID:K-Phoen,项目名称:BeThere,代码行数:11,代码来源:locations_api.go
示例14: main
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()
}
开发者ID:ArronYR,项目名称:GO_CrawlData_MySQL,代码行数:40,代码来源:indiepic.go
示例15: getLocation
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))
}
开发者ID:K-Phoen,项目名称:BeThere,代码行数:15,代码来源:locations_api.go
示例16: Listen
// 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()
}
开发者ID:hyprstack,项目名称:eevy,代码行数:45,代码来源:http.go
示例17: main
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()
}
开发者ID:xmikus01,项目名称:fibrous,代码行数:44,代码来源:martini.go
示例18: createLocation
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))
}
开发者ID:K-Phoen,项目名称:BeThere,代码行数:24,代码来源:locations_api.go
示例19: GetTeams
func GetTeams(enc encoder.Encoder) (int, []byte) {
return 200, encoder.Must(enc.Encode(teams))
}
开发者ID:FP7Collage,项目名称:GoalSetting,代码行数:3,代码来源:users.go
示例20: GetUsers
func GetUsers(enc encoder.Encoder) (int, []byte) {
return 200, encoder.Must(enc.Encode(users))
}
开发者ID:FP7Collage,项目名称:GoalSetting,代码行数:3,代码来源:users.go
注:本文中的github.com/martini-contrib/encoder.Must函数示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论