Example of a package of the server on Golang

Source: Internet
Author: User
Tags package json readfile
This is a creation in Article, where the information may have evolved or changed. Example of a package of the server on Golang
Programming Go 1 year, months ago
In language Go, as a matter of fact, there is both basic essences:executed files, and packages. In this article I suggest to consider the second on a small example.


The package is a library of functions and structures. According to the destination it reminds standard, all well-known, linkuemye libraries. The package on Go defines visibility area. If the name of variables or structures begins with a small letter, they local (area of visibility of a package), if with B IG, the exported. The Local structures and functions can is used only in a package, the global inside and out of the A package. The Let feature are easy being know on a example's work with a package JSON, a part of the standard libraries of language.


The similar code would return an error.


Type Link struct {
Name string
URL string
Title string
Class string
}


Links: = Make (Map[string]link)
If Err = json. Unmarshal (response, &links;); Err! = Nil {
return err
}


The matter is and we use functions from a package JSON, transferring structure c fields of local visibility (in function Unmarshal to structure fields Link Simply There is no access).


The package code should settle down according to his name that's if the package is called Ru/sezn/server, which files *.go Would be is in a folder server which would be Podpapkoj sezn and Ru.


Let's consider a package of a simple Web server which are used in ours a web Applications:http://sezn.ru/and HTTP://HASHC ode.ru/


In language Go there are an own library representing the Http-server. As the majority of developers has more than one site, to use directly the built in Http-server it won't turn out (in S Ystem There is only one port). For start we'll use the module FastCGI WEB server Apache2. The file of adjustment virtual Hotsa applications is more low resulted.


<virtualhost *:80>
ServerAdmin webmaster@hashcode.ru


documentroot/path/to/bin/
ServerName sezn.ru


Errorlog/var/log/apache2/sezn_error.log
LogLevel warn
Customlog/var/log/apache2/sezn_warning.log combined


AddHandler Fastcgi-script Our_bin
Fastcgiexternalserver/path/to/bin/our_bin-host 127.0.0.1:3489


Rewriteengine on
Rewritecond%{document_root}%{request_filename}!-f
Rewriterule ^ (. *) $/our_bin [qsa,l]
</VirtualHost>


The server package was realised in the form of simple structure with a set of methods for processing of inquiries of files, Registration Vjushek, checks "Kapchi" and so on. At the heart of system of routeing we use the library Gorilla (http://www.gorillatoolkit.org/). For support Kapchi were the library Https://github.com/dchest/captcha is taken.


The basic structure of the server:


Type Server struct {
Router *mux. Router
Transport string
Addres string
MediaPath string
Cachedfiles Map[string]*cachedfile
fn404 func (w http. Responsewriter, R *http. Request)
}


For faster work we use Keshirvoanie all files in a folder with Mediej.


Type cachedfile struct {
FileName string
FullPath string
FilePath string
Fileext string
FileData []byte
}


The server realises the following public interface.


Addnamedhandler (Pattern string, handler func (HTTP. Responsewriter, *http. Request), name string)
AddHandler (Pattern string, handler func (HTTP. Responsewriter, *http. Request))
Reverse (name string) *mux. Route
Run () Error
Setrootmediapath (Path String)
Set404errorhandler (fn func (w http. Responsewriter, R *http. Request))
Servehttp (w http. Responsewriter, R *http. Request)


and Tazhe the interface with area of visibility of a.
Cachefiles ()
RenderFile (w http. Responsewriter, filename string) error


During initialization, we only create the basic structures.


Func Initserver (transport, addres string) *server {
Server: = &Server; {Router: &mux. Router; {}, Transport:transport, addres:addres}
Return server
}


Then, on a course of initialization of modules, the basic application adds the Called/not called functions output agents C Ausing a method Addnamedhandler Or AddHandler.


Code of function of registration of the output agent.


Func (server *server) Addnamedhandler (pattern string, handler func (HTTP. Responsewriter, *http. Request), name string) {
Server. Router.handlefunc (pattern, handler). Name (name)
}


For server start it was necessary to cause method Run. In it we keshiruem files (to a question on caching http://meta.hashcode.ru/questions/1158/) also register media the output Agent FastCGI the report.


Func (server *server) Run () error {
Server.cachefiles ()
L, Err: = Net. Listen (server. Transport, server. Addres)
If err! = Nil {
return err
}


fcgi. Serve (l, server. Router)
return Nil
}


Before method Run'll be caused, it's necessary to establish the output agent who'll be caused if the required file is Not found.


Func (server *server) Set404errorhandler (fn func (w http. Responsewriter, R *http. Request)) {
server.fn404 = fn
Server. Router.notfoundhandler = Server
}


Here there are a thin moment, we register the output agent of an error 404, transferring to library Gorilla our server. The server realises the interface of processing HTTP of inquiries. For it the method responds Servehttp.


Func (server *server) servehttp (w http. Responsewriter, R *http. Request) {
ERR: = Server.renderfile (W, R.url. Path)
If err! = Nil {
W.header (). Set ("Content-type", "text/html; Charset=utf-8 ")
W.writeheader (http. Statusnotfound)
Server.fn404 (W, R)
}
}


We register output Agents of Vjushek in system of routeing of the library Gorilla. If The output agent is not found, we try to find a file, with such name. If The file is not a present, we cause the output agent of an error 404.


Method of reading of media of files in memory:


Func (server *server) Cachefiles () {
Server. Cachedfiles = Make (Map[string]*cachedfile)
Dir, _: = FilePath. Abs (server. MediaPath)

FilePath. Walk (dir, func (path string, info OS). FileInfo, err Error) error {
If info. Isdir () {
return Nil
}
File, err: = Ioutil. ReadFile (PATH)
FilePath: = Strings. Replace (Path, dir, "",-1)
Server. Cachedfiles[filepath] = &CachedFile; {
Filename:info. Name (),
Fullpath:path,
Filepath:filepath,
Fileext:filepath. EXT (Path),
Filedata:file,
}
return Nil
});
}


At the moment of inquiry of a file, it's necessary for us-to-look only at occurrence of a corresponding how to the Dictio Nary with files and to generate the answer. If file with We request the address it's not found, we'll try to find it on a disk.


Func (server *server) renderfile (w http. Responsewriter, filename string) error {
var file []byte
var ext string
var err error

If cachedfile, exist: = Server. Cachedfiles[filename]; exist {
File = Cachedfile.filedata
ext = Cachedfile.fileext
} else {
File, err = Ioutil. ReadFile (server. MediaPath + filename)
If err! = Nil {
return err
}
ext = filepath. EXT (server. MediaPath + filename)
}

If ext! = "" {
W.header (). Set ("Content-type", mime. Typebyextension (EXT))
}
If file! = Nil {
W.write (file)
}


return Nil
}


The name "Server" is far from the unique. We Place packages using notation Java. When we'll want to export a package, the full name would look as Ru/sezn/server. For creation of a, we use the program delivered with language.


Go get ru/sezn/server


Here basically and all. I'll be glad-answer questions in comments-a post or in a corresponding branch on Heshkode (http://hashcode.ru/ques tions/tagged/go/).


P. S. The given package is altered last time under Go RC1 and can not work with later/early version of language.


http://sysmagazine.com/posts/178539/

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.