Func Main () { http. Handlefunc ("/api", Apihandler) http. Handlefunc ("/query/main", MainHandler) http. Handlefunc ("/query/show", Showhandler) http. Handlefunc ("/", MainHandler) http. Listenandserve (": 8081", Nil)}
APIs and Web pages are handled by different URLs
Invoking the underlying service with Go-curl
Func Callcurl (postdatastring) (Resultstring, err Error) {Easy :=Curl. Easyinit () defer easy. Cleanup () easy. Setopt (Curl. Opt_url,"http://localhost:8540") easy. Setopt (Curl. Opt_post,true) easy. Setopt (Curl. Opt_verbose,true) easy. Setopt (Curl. Opt_httpheader, []string{"Content-type:application/json"}) easy. Setopt (Curl. Opt_postfieldsize, Len (postdata)) easy. Setopt (Curl. Opt_readfunction, Func (ptr []byte, _Interface{})int { returncopy (PTR, PostData)}) Easy. Setopt (Curl. Opt_writefunction, Func (buf []byte, _Interface{})BOOL{result=string(BUF)return true }) ifERR: = easy. Perform (); Err! =Nil {return "", err}returnresult, nil}
Json. Marshal/unmarshal the JSON string to go struct
Https://gobyexample.com/json
http. Template to write Web pages
https://golang.google.cn/doc/articles/wiki/
Format JSON to Web page:
Https://github.com/tidwall/pretty
the " <br> " " " false string(pretty. Prettyoptions ([]byte(result), opt)
Prevent HTML escape
http://blog.xiayf.cn/2013/11/01/unescape-html-in-golang-html_template/
Use template. HTML class encapsulation.
To do load balance with Nginx:
First configure/etc/nginx/nginx.conf:
Worker_processes 5; 8192 ; events { worker_connections 4096;} HTTP { Upstream MyApp1 { server server1:8081; Server Server2:8081; } server { 8080; / { proxy_pass http://MyApp1; } }}
Start nginx via ' Nginx '
Try it in browser via Nginx URL: ' http://nginx-server:8080 '
Golang JSON Webservice-nginx Load balance