Home > Back-end >  How to retrieve values from the URL in Go?
How to retrieve values from the URL in Go?

Time:07-22

For example if the website is https://www.example.com/signup?campaign='new_york', I would like to strip out the value of campaign, 'new_york', into the database. If somebody has clicked on that URL, the first thing it does is assign an ID so that URL gets transformed into https://www.example.com/signup?user_id='1bcd93021' as soon as it's in the browser. But I'd like to get the campaign that it came from first to assign it to that id so it's tied with the user forever.

I'm new to Go so not too sure where even to start - I've looked at req.URL("campaign") but couldn't get the value inserting into the database (the DB is built, and everything's inserting, but I'm receiving an empty string where "campaign":"" is) - any help would be appreciated!

Sorry, I should also add that it's pulling into a column in the DB like:

type loginSessionType struct {
   userId      string   `json:"user_id"`
   campaign    string   `json:"campaign"` 
}

if user == "" {

   meta := &loginSessionType{

        userID:  req.Form.Get("user_id"),
        //my code would go here
        campaign: req.URL("campaign"),
   }
}

I've also tried req.Form.Get("campaign") like userId above it, but doesn't seem to be working even though it does successfully get the user_id into the DB.

CodePudding user response:

You should find the query parameters by using this

campaign := r.URL.Query().Get("campaign")

CodePudding user response:

You should get the query string value by this code:

http.HandleFunc("/signup", func(w http.ResponseWriter, r *http.Request) {
    q := r.URL.Query()
    campaign := q.Get("campaign")
    fmt.Println("campaign =>", campaign)
})
http.ListenAndServe(":8000", nil)
  • Related