golang JSON webservice - nginx load balance
2018-02-07 16:44
597 查看
func main() { http.HandleFunc("/api", apiHandler) http.HandleFunc("/query/main", mainHandler) http.HandleFunc("/query/show", showHandler) http.HandleFunc("/", mainHandler) http.ListenAndServe(":8081", nil) }
API 和网页 按不同的url处理
用go-curl调用底层service
func callCurl(postData string) (result string, 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 { return copy(ptr, postData) }) easy.Setopt(curl.OPT_WRITEFUNCTION, func(buf []byte, _ interface{}) bool { result = string(buf) return true }) if err := easy.Perform(); err != nil { return "", err } return result, nil }
json.Marshal/Unmarshal 把json字符串转 go struct
https://gobyexample.com/json
http.Template 来写 web页面
https://golang.google.cn/doc/articles/wiki/
格式化一下 json到网页:
https://github.com/tidwall/pretty
opt := &pretty.Options{Width: 80, Prefix: "<br>", Indent: " ", SortKeys: false} result = string(pretty.PrettyOptions([]byte(result), opt)
防止 html escape
http://blog.xiayf.cn/2013/11/01/unescape-html-in-golang-html_template/
用 template.HTML类 封装。
用nginx做load balance:
First configure /etc/nginx/nginx.conf:worker_processes 5; worker_rlimit_nofile 8192; events { worker_connections 4096; } http { upstream myapp1 { server server1:8081; server server2:8081; } server { listen 8080; location / { proxy_pass http://myapp1; } } }
Start nginx via `nginx`
Try it in browser via nginx URL: `http://nginx-server:8080`
相关文章推荐
- lab-bill-sys_NginxTomcatLoadbalance
- Load Balance Tomcat with Nginx and Store Sessions in Redis--reference
- Nginx TCP Load Balance
- LVS+Nginx for Load Balance
- Load Balance Tomcat with Nginx and Store Sessions in Redis
- Nginx 配置 多个VSFTP的loadbalance
- nginx load balance
- golang webservice[ json Martini webframe]
- jQuery调用WebService返回JSON数据及参数设置注意问题
- 本地访问json格式文件出现XMLHttpRequest cannot load的解决方法
- 返回xml或json过长时被nginx截断的解决办法
- Jquery读取.Net WebService Json数据 推荐
- Jquery中$.get(),$.post(),$.ajax(),$.getJSON(),$.getScript(),$.load()的用法总结【转】
- 使用json unmarshal数据到interface{}, 数字变成float64,,golang
- [译]Golang中JSON和结构体的组合使用
- Spring cloud - Feign / Eureka load balance does not and connetion refused
- lab-bill-sys_ApacheTomcatLoadbalance
- Golang 处理 Json(一):编码
- nginx作json api反向代理,如何返回json形式的错误代码?(绝对有效)
- Dubbo调度机制解析(LoadBalance扩展)