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!
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值