Brian Voelker
Brian Voelker

Reputation: 859

golang import struct pointer

Ok i have a main package and a http handler package. Essentially what i am trying to do is setup a global struct so that way i can call upon information in that struct at any time.

Basic outline of my attempted example below: Main package imports handler function Main package calls handlerfunc Handlerfunc sets http.ResponseWriter and other items into UrlInfo struct Handlerfunc runs passed in function (without having to pass UrlStruct into function) Run function (home in this example) Function home can call upon variable uinfo at any time cause its a pointer UrlInfo struct

Obviously this doesnt work, but this is essentially what i would like to do so that way im not having to pass all this info into my home function. Keeping it clean and simple.

Any thoughts and ideas are welcome. Thanks.

Handler Package

package handler

// Struct containing http requests and variables
type UrlInfo struct {
    Res http.ResponseWriter
    Req *http.Request
    Item string
}

func HandleFunc(handlepath string, runfunc func()) {
    // Set handler and setup struct
    http.HandleFunc(handlepath, func(w http.ResponseWriter, r *http.Request) {
        url := new(UrlInfo)
        url.Res = w
        url.Req = r
        url.Item = "Item information"

        runfunc()
    })
}

Main Package

import "handler"

var uinfo = &handler.UrlInfo{}

func init() {
    handler.HandleFunc("/home/", home)
}

func home() {
    fmt.Println(uinfo.Item)
}

Upvotes: 3

Views: 2316

Answers (1)

jimt
jimt

Reputation: 26370

From what I gather from your question, you are attempting to define a single, global instance of a structure which, among other things, holds a reference to the current Request and ResponseWriter.

If this is the intention, I should warn you this is going to cause problems. Go's http package executes each request handler in a separate goroutine. This means that you can have arbitrarily many requests being handled simultaneously. Therefore they can not all refer to the same global structure safely and expect it to contain request information relevant only to that particular request. The global instance should not be used if you expect your server to be thread safe.

Keeping the code clean by grouping extraneous parameters in a structure can be handy, but in your case, I do not believe you can (or should) avoid passing a new instance of UrlInfo structure directly to home() as a parameter. It will make things unnecessarily complex and unpredictable.

Upvotes: 5

Related Questions