Go黑魔法之导出API供C调用

Go黑魔法之导出函数供C调用

go build 包含一个选项-buildmode可通过配置c-archive & c-shared两种模式分别生成可供C调用的静态 & 动态库.
具体详情可通过go help buildmode查看帮助.

示例

go 代码

这是FastCGI unix socket 简单示例, 响应FastCGI请求回应”Hello World!”.
注意:
import “C” 与 “//export FCGI_run ” 为必须配置,启用export用于导出Library函数名称;

package main
import (
    "C"
    "fmt"
    "net"
    "net/http"
    "net/http/fcgi"
)

func handler(res http.ResponseWriter, req *http.Request) {
    fmt.Fprint(res, "Hello World!")
}

//export FCGI_run
func FCGI_run() {
    l, err := net.Listen("unix", "/var/run/go-fcgi.sock")
    if err != nil {
        return
    }
    http.HandleFunc("/", handler)
    fcgi.Serve(l, nil)
}

func main () {}

编译动态库

go build -a -v -buildmode=c-shared  -o libfcgi_api.so  fcgi_api.go

分别生成 fcgi_api.h & libfcgi_api.so.

C 代码

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <stdint.h>

#include "fcgi_api.h"
int main(int argc, char **argv)
{
    FCGI_run();
    return 0;
}

编译

gcc fcgi_api_test.c  -o fcgi_api_test -L./ -lfcgi_api -Wl,-rpath="\$ORIGIN/"

测试

nginx 配置

转发FastCGI请求

...
server {
    listen       80;
    server_name  example.com;

    location / {
        fastcgi_pass  unix:/var/run/go-fcgi.sock;
        include       fastcgi_params;
    }
}
...

启动NGINX

nginx -c goapp.conf 

FastCGI

./fcgi_api_test &

cURL 测试

curl -q -v  http://example.com/
*   Trying 127.0.0.1...
* TCP_NODELAY set
* Connected to example.com (127.0.0.1) port 80 (#0)
> GET / HTTP/1.1
> Host: example.com
> User-Agent: curl/7.55.1
> Accept: */*
>
< HTTP/1.1 200 OK
< Server: nginx/1.12.1
< Content-Type: text/html; charset=utf-8
< Transfer-Encoding: chunked
< Connection: keep-alive
< Date: Fri, 17 Aug 2018 04:05:19 GMT
<
* Connection #0 to host example.com left intact
Hello World!

猜你喜欢

转载自blog.csdn.net/force_eagle/article/details/81775514