Golang JSON Webservice-nginx Load balance

Source: Internet
Author: User

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> " " &nbsp;&nbsp;&nbsp;&nbsp; " 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

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.