nginx反向代理 + go web服务器实践 - Go语言中文社区

nginx反向代理 + go web服务器实践


首先下载nginx

下载页面

作者用的是windows,所以我这里就下window的1.13.12版本。
下载完成后解压到C盘:


nginx

打开我们的命令行窗口,定位到我们的nginx目录,
start nginx

start nginx

我们可以打开浏览器访问以下http://localhost

nginx 安装成功

如果你能看到上图,就说明安装成功了。

且放一边。。。

下载Go
同样的,还是选择window版本,下载完成后,一路next,就默认装到C盘。

下载Goland
激活码搜一下http://idea.youbbs.org

New Project命名为GoTest
依次新建 src目录,新建http1目录,并新建一个http1.go

GoTest项目结构

http1.go:

package main

import (
    "fmt"
    "net/http"
    "strings"
    "log"
)

func printRequest(r *http.Request) {
    fmt.Println("r.Form=", r.Form)         //这些信息是输出到服务器端的打印信息 , Get参数
    fmt.Println("r.PostForm=", r.PostForm) //Post参数
    fmt.Println("path=", r.URL.Path)
    fmt.Println("scheme=", r.URL.Scheme)
    fmt.Println("method=", r.Method) //获取请求的方法

    fmt.Println("Http Get参数列表 begin:")
    for k, v := range r.Form {
        fmt.Println("Http Get["+k+"]=", strings.Join(v, " ; "))
    }
    fmt.Println("Http Get参数列表 end:")

    fmt.Println("Http Post参数列表 begin:")
    for k, v := range r.PostForm {
        fmt.Println("Http Post["+k+"]=", strings.Join(v, " ; "))
    }
    fmt.Println("Http Post参数列表 end:")

    arraA := r.Form["a"]
    fmt.Println("r.Form['a']=", arraA)
    if len(arraA) > 0 {
        fmt.Println("r.Form['a'][0]=", arraA[0])
    }
}

func sayhelloName(w http.ResponseWriter, r *http.Request) {
    r.ParseForm() //解析参数,默认是不会解析的
    fmt.Println("******************************************sayhelloName")
    printRequest(r)

    fmt.Fprintf(w, "<h1>Hello 世界!</h1>") //这个写入到w的是输出到客户端的
}

func sayMore(w http.ResponseWriter, r *http.Request) {
    r.ParseForm() //解析参数,默认是不会解析的
    fmt.Println("******************************************sayMore")
    printRequest(r)

    fmt.Fprintf(w, "<h1>Hello More!</h1>") //这个写入到w的是输出到客户端的
}

func sayMore1(w http.ResponseWriter, r *http.Request) {
    r.ParseForm() //解析参数,默认是不会解析的
    fmt.Println("******************************************sayMore1")
    printRequest(r)

    fmt.Fprintf(w, "<h1>Hello More1!</h1>") //这个写入到w的是输出到客户端的
}

func main() {
    http.HandleFunc("/", sayhelloName)       //设置访问的路径
    http.HandleFunc("/more", sayMore)        //设置访问的路径
    http.HandleFunc("/more/", sayMore1)      //设置访问的路径
    err := http.ListenAndServe(":9090", nil) //设置监听的端口
    if err != nil {
        log.Fatal("ListenAndServe: ", err)
    }
}

运行http1.go

运行http1.go

运行之后,我们打开浏览器访问http://localhost:9090

访问结果

在goland中,我们也能看到打印的日志:


访问日志

设置nginx反向代理
打开


nginx.conf

修改之后的文件
nginx.conf:

#运行用户
#user nobody;
#启动进程,通常设置成和cpu的数量相等
worker_processes  1;

#全局错误日志及PID文件
#error_log  logs/error.log;
#error_log  logs/error.log  notice;
#error_log  logs/error.log  info;

#pid        logs/nginx.pid;

#工作模式及连接数上限
events {
    #epoll是多路复用IO(I/O Multiplexing)中的一种方式,
    #仅用于linux2.6以上内核,可以大大提高nginx的性能
    #use   epoll; 

    #单个后台worker process进程的最大并发链接数    
    worker_connections  1024;

    # 并发总数是 worker_processes 和 worker_connections 的乘积
    # 即 max_clients = worker_processes * worker_connections
    # 在设置了反向代理的情况下,max_clients = worker_processes * worker_connections / 4  为什么
    # 为什么上面反向代理要除以4,应该说是一个经验值
    # 根据以上条件,正常情况下的Nginx Server可以应付的最大连接数为:4 * 8000 = 32000
    # worker_connections 值的设置跟物理内存大小有关
    # 因为并发受IO约束,max_clients的值须小于系统可以打开的最大文件数
    # 而系统可以打开的最大文件数和内存大小成正比,一般1GB内存的机器上可以打开的文件数大约是10万左右
    # 我们来看看360M内存的VPS可以打开的文件句柄数是多少:
    # $ cat /proc/sys/fs/file-max
    # 输出 34336
    # 32000 < 34336,即并发连接总数小于系统可以打开的文件句柄总数,这样就在操作系统可以承受的范围之内
    # 所以,worker_connections 的值需根据 worker_processes 进程数目和系统可以打开的最大文件总数进行适当地进行设置
    # 使得并发总数小于操作系统可以打开的最大文件数目
    # 其实质也就是根据主机的物理CPU和内存进行配置
    # 当然,理论上的并发总数可能会和实际有所偏差,因为主机还有其他的工作进程需要消耗系统资源。
    # ulimit -SHn 65535
}


http {
    #设定mime类型,类型由mime.type文件定义
    include    mime.types;
    default_type  application/octet-stream;
    #设定日志格式
    #log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
    #                  '$status $body_bytes_sent "$http_referer" '
    #                  '"$http_user_agent" "$http_x_forwarded_for"';

    #access_log  logs/access.log  main;

    #sendfile 指令指定 nginx 是否调用 sendfile 函数(zero copy 方式)来输出文件,
    #对于普通应用,必须设为 on,
    #如果用来进行下载等应用磁盘IO重负载应用,可设置为 off,
    #以平衡磁盘与网络I/O处理速度,降低系统的uptime.
    sendfile     on;
    #tcp_nopush     on;

    #连接超时时间
    #keepalive_timeout  0;
    keepalive_timeout  65;
    #tcp_nodelay     on;

    #开启gzip压缩
    #gzip  on;
    #gzip_disable "MSIE [1-6].";

    #设定请求缓冲
    #client_header_buffer_size    128k;
    #large_client_header_buffers  4 128k;


    #设定虚拟主机配置
    server {
        #侦听80端口
        listen    80;
        #定义使用 www.nginx.cn访问
        server_name  www.nginx.cn;

        #定义服务器的默认网站根目录位置
        root html;

        #设定本虚拟主机的访问日志
        #access_log  logs/nginx.access.log  main;

        #默认请求
        location / {
            #定义首页索引文件的名称
            index index.php index.html index.htm;   

        }

        # 定义错误提示页面
        error_page   500 502 503 504 /50x.html;
        location = /50x.html {
        }

        #静态文件,nginx自己处理
        location ~ ^/(images|javascript|js|css|flash|media|static)/ {
            
            #过期30天,静态文件不怎么更新,过期可以设大一点,
            #如果频繁更新,则可以设置得小一点。
            expires 30d;
        }

        #PHP 脚本请求全部转发到 FastCGI处理. 使用FastCGI默认配置.
        location ~ .php$ {
            fastcgi_pass 127.0.0.1:9000;
            fastcgi_index index.php;
            fastcgi_param  SCRIPT_FILENAME  $document_root$fastcgi_script_name;
            include fastcgi_params;
        }

        #禁止访问 .htxxx 文件
        location ~ /.ht {
            deny all;
        }

    }
    
    ## 设置反向代理,指向go服务器 ##
    server {
        listen 8081;
        #server_name  www.xxx.cn;
     
        #access_log  logs/quancha.access.log  main;
        #error_log  logs/quancha.error.log;
        root   html;
        index  index.html index.htm index.php;
     
        ## send request back to apache ##
        location / {
            proxy_pass  http://localhost:9090;#go 服务器可以指定到其他的机器上,这里设定本机服务器
     
            #Proxy Settings
            proxy_redirect     off;
            proxy_set_header   Host             $host;
            proxy_set_header   X-Real-IP        $remote_addr;
            proxy_set_header   X-Forwarded-For  $proxy_add_x_forwarded_for;
            #proxy_next_upstream error timeout invalid_header http_500 http_502 http_503 http_504;
            #proxy_max_temp_file_size 0;
            #proxy_connect_timeout      90;
            #proxy_send_timeout         90;
            #proxy_read_timeout         90;
            #proxy_buffer_size          4k;
            #proxy_buffers              4 32k;
            #proxy_busy_buffers_size    64k;
            #proxy_temp_file_write_size 64k;
       }
    }
    ## End 设置反向代理,指向go服务器 ##
}

打开我们的最早的命令行窗口,输入nginx -s reload

重载nginx配置

访问http://localhost:8081/

访问结果

OK成功访问到我们nginx配置的go服务器。

我们还可以使用Post的方式带上路径或者参数访问
比如:


postman 请求

打印日志:


goland 打印输出

上面那个日志可以看出r.Form包含了r.PostForm参数。

版权声明:本文来源简书,感谢博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
原文链接:https://www.jianshu.com/p/33d4a3fdc483
站方申明:本站部分内容来自社区用户分享,若涉及侵权,请联系站方删除。
  • 发表于 2020-01-12 11:44:50
  • 阅读 ( 2291 )
  • 分类:Go

0 条评论

请先 登录 后评论

官方社群

GO教程

猜你喜欢