2

Learning Go – Miniblog #12 – Server Objects | Late Developer

 2 years ago
source link: https://latedev.wordpress.com/2013/01/23/learning-go-miniblog-12-server-objects/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

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
Report this ad

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK