Pedro Vieira
Pedro Vieira

Reputation: 2316

How to use variable as the pattern for http.HandleFunc()

I have some HTTP requests that share a lot of common functions:

package main

import (
    "net/http"
    "mypackage"
)

func main() {
    http.HandleFunc("/myurl1", func(w http.ResponseWriter, r *http.Request) {
        mypackage.Common()
        mypackage.Different1()
    })
    http.HandleFunc("/myurl2", func(w http.ResponseWriter, r *http.Request) {
        mypackage.Common()
        mypackage.Different2()
    })
    http.ListenAndServe(":8080", nil)
}

Could I use a variable in the place of /myurl and use a switch case to reduce my code repetition, like this:

package main

import (
    "net/http"
    "mypackage"
)

func main() {
    http.HandleFunc(variable string, func(w http.ResponseWriter, r *http.Request) {

         mypackage.Common()

         switch variable {
         case "myurl1":
             mypackage.Different1()
         case "myurl2":
             mypackage.Different2()
         }
    })
    http.ListenAndServe(":8080", nil)
}

Upvotes: 0

Views: 1024

Answers (1)

Pajri Aprilio
Pajri Aprilio

Reputation: 322

You can route to / first then call Different1 or Different2 based on the path. Please refer to this code.

Upvotes: 1

Related Questions