Avoid global variables in Http handlers

141 views
Skip to first unread message

Tong Sun

unread,
Jun 3, 2019, 11:48:42 PM6/3/19
to golang-nuts

Here is a BAD example (using global variables):


var globalThing string

func specificHandler(w http.ResponseWriter, r *http.Request) {
    w.Write(globalConfigThing)
}

func main() {
    globalThing = "Hello world!"
    http.HandleFunc("/something", specificHandler)
    http.ListenAndServe(":8080", nil)
}

How to avoid using global variables? 

thx



Aldrin Leal

unread,
Jun 3, 2019, 11:55:46 PM6/3/19
to Tong Sun, golang-nuts
wrapping into a typedef?

typedef MyHandler struct {
  GlobalThing string
}

func (h *MyHandler) handle(w http.ResponseWriter, r *http.Request) {
}

func main() {
  h := MyHandler{}

  http.HandleFunc("/", MyHandler.handle)
}

--
You received this message because you are subscribed to the Google Groups "golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/golang-nuts/1bc9f505-9638-49e2-b873-6f4d7b88dfbc%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Tong Sun

unread,
Jun 4, 2019, 7:55:01 AM6/4/19
to golang-nuts
Oh, yeah, that works. Thanks Aldrin.

The reason that I'm asking is that the "solution" that I found on the web isn't working for me:

Here is a BETTER example (not using global variables):


type specificHandler struct {
    Thing string
}

func (h *specificHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
    w.Write(h.Thing)
}

func main() {
    http.Handle("/something", &specificHandler{Thing: "Hello world!"})
    http.ListenAndServe(":8080", nil)
}


On Monday, June 3, 2019 at 11:55:46 PM UTC-4, Aldrin Leal wrote:
wrapping into a typedef?

typedef MyHandler struct {
  GlobalThing string
}

func (h *MyHandler) handle(w http.ResponseWriter, r *http.Request) {
}

func main() {
  h := MyHandler{}

  http.HandleFunc("/", MyHandler.handle)
}

On Mon, Jun 3, 2019 at 10:48 PM Tong Sun <sunto...@gmail.com> wrote:

Here is a BAD example (using global variables):


var globalThing string

func specificHandler(w http.ResponseWriter, r *http.Request) {
    w.Write(globalConfigThing)
}

func main() {
    globalThing = "Hello world!"
    http.HandleFunc("/something", specificHandler)
    http.ListenAndServe(":8080", nil)
}

How to avoid using global variables? 

thx



--
You received this message because you are subscribed to the Google Groups "golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email to golan...@googlegroups.com.

setha...@gmail.com

unread,
Jun 9, 2019, 2:25:36 PM6/9/19
to golang-nuts
You are passing the struct and not the method on the struct to the handle function.
Reply all
Reply to author
Forward
0 new messages