Skip to content

Learning Go – Miniblog #12 – Server Objects

January 23, 2013

This carries on from here, and started here.

So, I have a bunch of functions that implement my CSV server, but really I would like to encapsulate the code in an object of some sort. I’d also like to be able to create more than one server, listening on different ports and with different configurations. Basically, I want to be able to say something like this:

s1 := csvsrv.NewServer( "8080", "My Little Server", "csvdata" )
s1.Serve()

and have the server listen on port 8080, display "My Little Server" as the title for the index page, and look for its data in the "csvdata" directory. How do I do that?

Go does not directly support object-oriented programming (there is no "class" keyword, for example), but it does provide structures, and the means of specifying functions that can work on those structures. So my first attempt was to create a structure with members for the configuration parameters:

type Server struct {
    Port, Title, Datadir string
}

I also created a constructor function:

func NewServer( port, title, datadir string ) (*Server) { 
    return &Server{port, title,datadir}
}

This allows me to create instances of the server class. Unfortunately, it also exposes the configuration data to the outside world – basically, any name  that begins with an upper-case letter is effectively public. So, I need to make the struct’s members have lower-case names, and provide accessors that look like this:

func (s *Server) Port() (string) {
    return s.port;
}

That (s *Server) business in front of the function says that this function can be applied to a Server instance. As it is in the same package as the Server struct, it gets access to what would otherwise be private data, and as the function name begins with an upper-case letter, it is effectively public. So with some other suitable accessors, I can write stuff like this:

s1 := csvsrv.NewServer( "8080", "My Little Server", "csvdata" )
fmt.Printf( "Port: %s Title: %s Data: %s\n", s1.Port(), s1.Title(), s1.Datadir() )

and have it print out:

Port: 8080 Title: My Little Server Data: csvdata

Now I need to work out how to add an HTTP server instance to the struct…

Advertisements

From → golang

Leave a Comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: