本文整理匯總了Golang中github.com/julienschmidt/httprouter.Params類的典型用法代碼示例。如果您正苦於以下問題:Golang Params類的具體用法?Golang Params怎麽用?Golang Params使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。
在下文中一共展示了Params類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的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)
}
示例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
}
}
示例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
}
}
示例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
}
示例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)
}
示例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))
}
示例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)
}
示例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\"}"))
}
}
示例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(),
})
}
}
示例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
}
示例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)
}
}
示例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)
}
示例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)
}
示例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
}
}
示例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
}
}