How to get value of url inside a function in golang

137 Views Asked by At

I have this router function with mux:

func InitRouter() {
    r := http.NewServeMux()
    r.HandleFunc("/{id}", getWords)
    log.Fatal(http.ListenAndServe(":8000", r))
}

I want that the getWords function output the value of id, for instance: if url is www.abc.com/cat, getWords will output cat if url is www.abc.com/3 getWords will output 3

I looked through out internet I didnt find explainations

2

There are 2 best solutions below

0
Ömer Sezer On

Please use github.com/gorilla/mux, and add using go get -u github.com/gorilla/mux:

Code:

package main

import (
    "fmt"
    "log"
    "net/http"
    "github.com/gorilla/mux"
)

func getWords(w http.ResponseWriter, r *http.Request) {
    vars := mux.Vars(r)
    id := vars["id"]
    fmt.Println("ID:", id)   // for stdout
    w.Write([]byte("ID: " + id))
}

func InitRouter() {
    r := mux.NewRouter()  // gorilla mux new router
    r.HandleFunc("/{id}", getWords)
    log.Fatal(http.ListenAndServe(":8000", r))
}

func main() {
    InitRouter()
}

Output (on Terminal & Browser):

ID: 3
ID: cat
1
Clearbreeze Flutterfeather On

The current version of http.ServeMux does parse path parameters. Write code to parse out path parameters. Here's an example:

func InitRouter() {
    r := http.NewServeMux()
    // The path / matches all paths.
    r.HandleFunc("/", getWords)
    log.Fatal(http.ListenAndServe(":8000", r))
}

func getWords(w http.ResponseWriter, r *http.Request) {
    // Trim the / prefix to get the id
    id := strings.TrimPrefix(r.URL.Path, "/")
    fmt.Fprintf(w, "the id is %s", id)
}

If / is not allowed in the id, then respond with an error when id contains a /.

func getWords(w http.ResponseWriter, r *http.Request) {
    id := strings.TrimPrefix(r.URL.Path, "/")
    if strings.Contains(id, "/") {
        http.Error(w, "Not Found", http.StatusNotFound)
        return
    }
    fmt.Fprintf(w, "the id is %s", id)
}