本文整理汇总了Golang中github.com/julienschmidt/httprouter.Params类的典型用法代码示例。如果您正苦于以下问题:Golang Params类的具体用法?Golang Params怎么用?Golang Params使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Params类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Golang代码示例。
示例1: AddFileHandler
// AddFileHandler adds the file path to the database. It should be usually be given to an POST endpoint
// with id as the parameter
// Ex: /file/:id
func AddFileHandler(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
decoder := json.NewDecoder(r.Body)
// TODO: ps is there for checking emptiness. Should be replaced
var js, ps jsonStruct
if err := decoder.Decode(&js); err != nil || js == ps {
w.WriteHeader(400)
return
}
couchServer, err := couchdb.NewClient("http://127.0.0.1:5984", nil)
db, _ := couchServer.CreateDB("files")
userID := memberlist.DefaultWANConfig().Name
_, err = db.Put(p.ByName("id"), file{UUID: uuid.NewV4().String(), Fname: path.Base(js.Path), UserID: userID}, "")
if err != nil {
w.WriteHeader(500)
fmt.Fprint(w, err)
return
}
// TODO: Send 409 for conflict
if err := AddFile(p.ByName("id"), js.Path); err != nil {
w.WriteHeader(500)
fmt.Fprint(w, err)
return
}
w.WriteHeader(201)
}
开发者ID:Gouthamve,项目名称:fshare,代码行数:32,代码来源:fhandlers.1.go
示例2: servePutService
// servePutService creates a service.
func (h *Handler) servePutService(w http.ResponseWriter, r *http.Request, params httprouter.Params) {
// Retrieve the path parameter.
service := params.ByName("service")
if err := ValidServiceName(service); err != nil {
hh.ValidationError(w, "", err.Error())
return
}
// Read config from the request.
config := &discoverd.ServiceConfig{}
if err := hh.DecodeJSON(r, config); err != nil {
hh.Error(w, err)
return
}
// Add the service to the store.
if err := h.Store.AddService(service, config); err == ErrNotLeader {
h.redirectToLeader(w, r)
return
} else if IsServiceExists(err) {
hh.ObjectExistsError(w, err.Error())
return
} else if err != nil {
hh.Error(w, err)
return
}
}
开发者ID:ably-forks,项目名称:flynn,代码行数:28,代码来源:handler.go
示例3: GrantVoteResponse
func GrantVoteResponse(rw http.ResponseWriter, req *http.Request, p httprouter.Params) {
vote = p.ByName("vote")
//ch <- 1
fmt.Println("Vote received:", vote)
if vote == "true" {
voteCount++
}
fmt.Println(voteCount)
if voteCount > total/2 && state != "leader" {
fmt.Println("Leader....")
state = "leader"
myDetails := MyDetails{}
myDetails.IsLeader = true
myDetails.IP = "localhost" //enter the IP address
myDetails.Port = "3001" //enter the port number
myDeatilsInJSON, _ := json.Marshal(myDetails)
myDetailsBuff := new(bytes.Buffer)
err := binary.Write(myDetailsBuff, binary.BigEndian, &myDeatilsInJSON)
if err != nil {
fmt.Errorf("Error in request API: %v", err)
}
url := fmt.Sprintf("http://localhost:9999/setleader")
client := http.Client{}
req, _ := http.NewRequest("POST", url, myDetailsBuff)
res, _ := client.Do(req)
res.Body.Close()
NotifyFollowers() //DK
}
}
开发者ID:DhruvKalaria,项目名称:RAFT-Implementation,代码行数:29,代码来源:n2.go
示例4: rawStats
// Raw stats: Entries from eugo_raw for the last 24 hours
// This file is getting a bit long
//
func rawStats(res http.ResponseWriter, req *http.Request, ps httprouter.Params) {
from := func() int64 {
urlPS, _ := url.ParseQuery(req.URL.RawQuery)
param, ok := urlPS["from"]
if ok {
ts, err := strconv.ParseInt(param[0], 10, 64)
if err == nil {
return ts
}
}
return (time.Now().UTC().UnixNano() / 1e6) - 864e5
}()
key := ps.ByName("key")
rawStats, err := getRawStats(key, from)
if err != nil {
res.WriteHeader(http.StatusInternalServerError)
return
}
jsonHandler(res, req, rawStats)
return
}
开发者ID:abtrout,项目名称:eugo,代码行数:28,代码来源:stats.go
示例5: GetUser
// GetUser retrieves an individual user resource
func (uc UserController) GetUser(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
// Grab id
id := p.ByName("id")
// Verify id is ObjectId, otherwise bail
if !bson.IsObjectIdHex(id) {
w.WriteHeader(404)
return
}
// Grab id
oid := bson.ObjectIdHex(id)
// Stub user
u := models.User{}
// Fetch user
if err := uc.session.DB("go_rest_tutorial").C("users").FindId(oid).One(&u); err != nil {
w.WriteHeader(404)
return
}
// Marshal provided interface into JSON structure
uj, _ := json.Marshal(u)
// Write content-type, statuscode, payload
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(200)
fmt.Fprintf(w, "%s", uj)
}
开发者ID:greatontime,项目名称:golangtut,代码行数:31,代码来源:user.go
示例6: GetTrips
func GetTrips(rw http.ResponseWriter, req *http.Request, p httprouter.Params) {
fmt.Println("Hello world")
session, err := mgo.Dial("mongodb://user1:[email protected]:45054/mydatabase")
if err != nil {
panic(err)
}
defer session.Close()
// Optional. Switch the session to a monotonic behavior.
session.SetMode(mgo.Monotonic, true)
c := session.DB("mydatabase").C("UberResult")
id := p.ByName("name")
Oid := bson.ObjectIdHex(id)
var UberGetResult UberPostRequest
c.FindId(Oid).One(&UberGetResult)
if err != nil {
log.Fatal(err)
}
b2, err := json.Marshal(UberGetResult)
if err != nil {
}
rw.WriteHeader(http.StatusOK)
fmt.Fprintf(rw, string(b2))
}
开发者ID:JasonGodinho,项目名称:Uber-Trip-Advisor,代码行数:30,代码来源:main.go
示例7: resendInvitationEmail
func (s *UserMgmtServer) resendInvitationEmail(w http.ResponseWriter, r *http.Request, ps httprouter.Params, creds api.Creds) {
id := ps.ByName("id")
if id == "" {
writeAPIError(w, http.StatusBadRequest, newAPIError(errorInvalidRequest, "id is required"))
return
}
resendEmailInvitationReq := schema.ResendEmailInvitationRequest{}
if err := json.NewDecoder(r.Body).Decode(&resendEmailInvitationReq); err != nil {
writeInvalidRequest(w, "cannot parse JSON body")
return
}
redirURL, err := url.Parse(resendEmailInvitationReq.RedirectURL)
if err != nil {
writeAPIError(w, http.StatusBadRequest,
newAPIError(errorInvalidRequest, "redirectURL must be a valid URL"))
return
}
resendEmailInvitationResponse, err := s.api.ResendEmailInvitation(creds, id, *redirURL)
if err != nil {
s.writeError(w, err)
return
}
writeResponseWithBody(w, http.StatusOK, resendEmailInvitationResponse)
}
开发者ID:ryanj,项目名称:dex,代码行数:27,代码来源:user.go
示例8: MusicUpsert
// MusicUpsert function
func MusicUpsert(w http.ResponseWriter, r *http.Request, params httprouter.Params) {
log.Println("access to user put api")
id := params.ByName("id")
if id == "" {
log.Print("put without _id")
} else {
log.Print("put with id")
}
if r.Body != nil {
defer r.Body.Close()
var data model.Music
body, _ := ioutil.ReadAll(r.Body)
if err := json.Unmarshal([]byte(body), &data); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
// if err := json.NewDecoder(r.Body).Decode(&user); err != nil {
// http.Error(w, err.Error(), http.StatusInternalServerError)
// return
// }
if err := db.Upsert(musicColname, data.ID, data); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
w.Write([]byte("{\"status\":\"ok\"}"))
}
}
开发者ID:kosuda,项目名称:golang-web,代码行数:35,代码来源:music.go
示例9: onGetChatHistory
func (c *ChatService) onGetChatHistory(w http.ResponseWriter, req *http.Request, p httprouter.Params) {
log.Println("Get chat history...")
groupId := p.ByName("id")
queryParams := req.URL.Query()
var offset uint = 0
var limit uint = 20
if o, err := strconv.ParseUint(queryParams.Get("offset"), 10, 32); err == nil {
offset = uint(o)
}
if l, err := strconv.ParseUint(queryParams.Get("limit"), 10, 32); err == nil {
limit = uint(l)
}
log.Println("Limit =", limit, "Offset =", offset)
log, err := c.chatStore.GetMessagesFor(groupId, offset, limit)
if err == nil {
response := make(map[string]interface{})
response["limit"] = limit
response["offset"] = offset
response["messages"] = log
response["id"] = groupId
json.NewEncoder(w).Encode(response)
} else {
w.WriteHeader(http.StatusInternalServerError)
json.NewEncoder(w).Encode(ErrorMessage{
Error: err.Error(),
})
}
}
开发者ID:CHH-Darick,项目名称:raspchat,代码行数:32,代码来源:chat_service.go
示例10: handleDelete
func (a *Admin) handleDelete(rw http.ResponseWriter, req *http.Request, ps httprouter.Params) {
slug := ps.ByName("slug")
model, ok := a.models[slug]
if !ok {
http.NotFound(rw, req)
return
}
id := 0
if idStr := ps.ByName("id"); len(idStr) > 0 {
var err error
id, err = parseInt(idStr)
if err != nil {
return
}
}
err := model.delete(id)
sess := a.getUserSession(req)
if err == nil {
sess.addMessage("success", fmt.Sprintf("%v has been deleted.", model.Name))
} else {
sess.addMessage("warning", err.Error())
}
url, _ := a.urls.URL("view", slug)
http.Redirect(rw, req, url, 302)
return
}
开发者ID:x4rMa,项目名称:admin-1,代码行数:29,代码来源:handlers.go
示例11: deletePhoto
func deletePhoto(w http.ResponseWriter, r *http.Request) {
// Get session
sess := session.Instance(r)
var params httprouter.Params
params = context.Get(r, "params").(httprouter.Params)
//userid := params.ByName("userid")
//userid := uint64(site_idInt)
userid := uint64(sess.Values["id"].(uint32))
picid := params.ByName("picid")
err := model.PhotoDelete(userid, picid)
if err != nil {
log.Println(err)
sess.AddFlash(view.Flash{"An error occurred on the server. Please try again later.", view.FlashError})
sess.Save(r, w)
} else {
/*err = os.Remove(photoPath + fmt.Sprintf("%v", userid) + "/" + picid + ".jpg")
if err != nil {
log.Println(err)
}*/
sess.AddFlash(view.Flash{"Photo removed!", view.FlashSuccess})
sess.Save(r, w)
}
}
开发者ID:kizbitz,项目名称:webapp,代码行数:28,代码来源:photo.go
示例12: GetUser
func (uc UserController) GetUser(rw http.ResponseWriter, req *http.Request, p httprouter.Params) {
// Grab id
id := p.ByName("location_id")
// Verify id is ObjectId, otherwise bail
if !bson.IsObjectIdHex(id) {
rw.WriteHeader(404)
return
}
// Grab id
oid := bson.ObjectIdHex(id)
// Stub user
u := UserLocation{}
// Fetch user
if err := uc.session.DB("mongodatabase").C("CMPE273").FindId(oid).One(&u); err != nil {
rw.WriteHeader(404)
return
}
// Marshal provided interface into JSON structure
uj, _ := json.Marshal(u)
// Write content-type, statuscode, payload
rw.Header().Set("Content-Type", "application/json")
rw.WriteHeader(200)
fmt.Fprintf(rw, "%s", uj)
}
开发者ID:DeepaDhingra,项目名称:cmpe273-assignment2,代码行数:29,代码来源:GetData.go
示例13: Slack
// Slack handles a request to publish a webhook to a Slack channel.
func (s *Server) Slack(w http.ResponseWriter, r *http.Request, params httprouter.Params) {
log.Printf("%s %s\n", r.Method, r.URL.RequestURI())
if r.Method != "POST" {
w.WriteHeader(http.StatusMethodNotAllowed)
return
}
data, err := ioutil.ReadAll(r.Body)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
log.Printf("Error parsing body: %v\n", err)
}
event, err := webhook.Parse(data)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
log.Printf("Error parsing event: %v\n", err)
}
slackAlpha, slackBeta, slackGamma := params.ByName("slackAlpha"), params.ByName("slackBeta"), params.ByName("slackGamma")
slackToken := fmt.Sprintf("%s/%s/%s", slackAlpha, slackBeta, slackGamma)
service := &SlackService{Token: slackToken}
text, err := service.PostEvent(event)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
log.Printf("Internal Error: %v\n", err)
}
fmt.Fprintln(w, text)
}
开发者ID:dnsimple,项目名称:strillone,代码行数:33,代码来源:server.go
示例14: servePutLeader
// servePutLeader sets the leader for a service.
func (h *Handler) servePutLeader(w http.ResponseWriter, r *http.Request, params httprouter.Params) {
// Retrieve path parameters.
service := params.ByName("service")
// Check if the service allows manual leader election.
config := h.Store.Config(service)
if config == nil || config.LeaderType != discoverd.LeaderTypeManual {
hh.ValidationError(w, "", "service leader election type is not manual")
return
}
// Read instance from the request.
inst := &discoverd.Instance{}
if err := hh.DecodeJSON(r, inst); err != nil {
hh.Error(w, err)
return
}
// Manually set the leader on the service.
if err := h.Store.SetServiceLeader(service, inst.ID); err == ErrNotLeader {
h.redirectToLeader(w, r)
return
} else if err != nil {
hh.Error(w, err)
return
}
}
开发者ID:ably-forks,项目名称:flynn,代码行数:28,代码来源:handler.go
示例15: servePutInstance
// servePutInstance adds an instance to a service.
func (h *Handler) servePutInstance(w http.ResponseWriter, r *http.Request, params httprouter.Params) {
// Read path parameter.
service := params.ByName("service")
// Read instance from request.
inst := &discoverd.Instance{}
if err := json.NewDecoder(r.Body).Decode(inst); err != nil {
hh.Error(w, err)
return
}
// Ensure instance is valid.
if err := inst.Valid(); err != nil {
hh.ValidationError(w, "", err.Error())
return
}
// Add instance to service in the store.
if err := h.Store.AddInstance(service, inst); err == ErrNotLeader {
h.redirectToLeader(w, r)
return
} else if IsNotFound(err) {
hh.ObjectNotFoundError(w, err.Error())
return
} else if err != nil {
hh.Error(w, err)
return
}
}
开发者ID:ably-forks,项目名称:flynn,代码行数:30,代码来源:handler.go
示例16: MusicDelete
// MusicDelete function
func MusicDelete(w http.ResponseWriter, r *http.Request, params httprouter.Params) {
log.Print("access to user delete api")
id := params.ByName("id")
if id == "" {
log.Print("remove by query")
if err := db.Remove(colname, nil); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
} else {
log.Print("remove by id")
if err := db.RemoveByID(musicColname, id); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(204)
w.Write([]byte("{\"status\":\"ok\"}"))
}
开发者ID:kosuda,项目名称:golang-web,代码行数:26,代码来源:music.go
示例17: updateLocation
func updateLocation(rw http.ResponseWriter, req *http.Request, p httprouter.Params) {
id, err1 := strconv.Atoi(p.ByName("locid"))
if err1 != nil {
panic(err1)
}
conn, err := mgo.Dial("mongodb://dbuser:[email protected]:45464/testgoogledatabase")
if err != nil {
panic(err)
}
defer conn.Close()
conn.SetMode(mgo.Monotonic, true)
c := conn.DB("testgoogledatabase").C("testgoogledatabase")
decoder := json.NewDecoder(req.Body)
var t modReqObj
err = decoder.Decode(&t)
if err != nil {
fmt.Println("Error")
}
colQuerier := bson.M{"id": id}
change := bson.M{"$set": bson.M{"address": t.Address, "city": t.City, "state": t.State, "zip": t.Zip}}
err = c.Update(colQuerier, change)
if err != nil {
panic(err)
}
}
开发者ID:adityasharmacs,项目名称:cmpe273-Assignment3,代码行数:32,代码来源:tripplanner.go
示例18: get
//GET function
func get(rw http.ResponseWriter, req *http.Request, p httprouter.Params) {
key := p.ByName("id")
key_int, _ := strconv.Atoi(key)
var port []string
var response Response
port = strings.Split(req.Host, ":")
if port[1] == "3000" {
response.Key = key_int
response.Value = server1_kvalue[key_int]
} else if port[1] == "3001" {
response.Key = key_int
response.Value = server2_kvalue[key_int]
} else {
response.Key = key_int
response.Value = server3_kvalue[key_int]
}
payload, err := json.Marshal(response)
if err != nil {
http.Error(rw, "Bad Request", http.StatusInternalServerError)
return
}
rw.Header().Set("Content-Type", "application/json")
rw.Write(payload)
}
开发者ID:pujaraniyadav,项目名称:cmpe273-lab3,代码行数:28,代码来源:server.go
示例19: getTrip
func getTrip(rw http.ResponseWriter, req *http.Request, p httprouter.Params) {
conn, err := mgo.Dial("mongodb://dbuser:[email protected]:45464/testgoogledatabase")
if err != nil {
panic(err)
}
defer conn.Close()
conn.SetMode(mgo.Monotonic, true)
c := conn.DB("testgoogledatabase").C("trips")
result := TripResponse{}
err = c.Find(bson.M{"id": p.ByName("tripid")}).One(&result)
if err != nil {
fmt.Println(err)
}
js, err := json.Marshal(result)
if err != nil {
fmt.Println("Error")
return
}
rw.Header().Set("Content-Type", "application/json")
rw.Write(js)
}
开发者ID:adityasharmacs,项目名称:cmpe273-Assignment3,代码行数:25,代码来源:tripplanner.go
示例20: pixieHandler
// @Title pixieHandler
// @Description Dictionary with kernel, intrd(s) and commandline for pixiecore
// @Param macaddr path string true "MacAddress"
// @Success 200 {object} string "Dictionary with kernel, intrd(s) and commandline for pixiecore"
// @Failure 404 {object} string "Not in build mode"
// @Failure 500 {object} string "Unable to find host definition for hostname"
// @Router /v1/boot/{macaddr} [GET]
func pixieHandler(response http.ResponseWriter, request *http.Request,
ps httprouter.Params, config Config) {
macaddr := ps.ByName("macaddr")
hostname, found := config.MachineBuild[macaddr]
if found == false {
log.Println(found)
http.Error(response, "Not in build mode", 404)
return
}
m, err := machineDefinition(hostname, config.MachinePath)
m.Token = config.Tokens[hostname]
if err != nil {
log.Println(err)
http.Error(response, fmt.Sprintf("Unable to find host definition for %s", hostname), 500)
return
}
pxeconfig, _ := m.pixieInit(config)
result, _ := json.Marshal(pxeconfig)
response.Write(result)
}
开发者ID:totallyunknown,项目名称:waitron,代码行数:34,代码来源:main.go
注:本文中的github.com/julienschmidt/httprouter.Params类示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论