Mohit Yadav
Mohit Yadav

Reputation: 157

how to parse multiple parameters in url in GoLang?

I am new in Go. So please provide an example with your answer. I am using julienschmidt/httprouter. I am able to parse one parameter with this but how can I parse multiple parameters using this or any other library? The output I want to achieve is to get [email protected] & dccccf from this url:-> http://localhost:8080/[email protected]&pwd=dccccf

my code is at:- https://github.com/mohit810/prog-1

I tried r.GET("/login",uc.LoginUser) in main.go and in controllers/user.go i added

func (uc UserController) LoginUser(w http.ResponseWriter, request *http.Request, params httprouter.Params) {
    emailId := params.ByName("id")
    pwd := params.ByName("pwd")

    u := models.User{}

    if err := uc.session.DB("go-web-dev-db").C("users").FindId(emailId + pwd).One(&u); err != nil {
        w.WriteHeader(404)
        return
    }

    uj, err := json.Marshal(u)
    if err != nil {
        fmt.Println(err)
    }

    w.Header().Set("Content-Type", "application/json")
    w.WriteHeader(http.StatusOK) // 200
    fmt.Fprintf(w, "%s\n", uj)
}

Upvotes: 0

Views: 10921

Answers (1)

Mohit Yadav
Mohit Yadav

Reputation: 157

Add the following in main.go

r.GET("/login",uc.LoginUser)

and add the following in controllers/user.go

func (uc UserController) LoginUser(w http.ResponseWriter, request *http.Request, params httprouter.Params) {
    emailId := request.URL.Query().Get("id")
    pwd := request.URL.Query().Get("pwd")

    u := models.User{}

    if err := uc.session.DB("go-web-dev-db").C("users").FindId(emailId + pwd).One(&u); err != nil {
        w.WriteHeader(404)
        return
    }

    uj, err := json.Marshal(u)
    if err != nil {
        fmt.Println(err)
    }

    w.Header().Set("Content-Type", "application/json")
    w.WriteHeader(http.StatusOK) // 200
    fmt.Fprintf(w, "%s\n", uj)

}

Upvotes: 3

Related Questions