从共享库运行服务器

尝试从共享库运行 servr,所以我做了以下操作:


将shahred图书馆写成:

// server.go

package main


import (

    "fmt"

    "net/http"

)

import "C"


func hello(w http.ResponseWriter, req *http.Request) {

    fmt.Fprintf(w, "hello\n")

}

func headers(w http.ResponseWriter, req *http.Request) {

    for name, headers := range req.Header {

        for _, h := range headers {

            fmt.Fprintf(w, "%v: %v\n", name, h)

        }

    }

}

func main() {}


// export Run server

func Run(port string) {

    http.HandleFunc("/hello", hello)

    http.HandleFunc("/headers", headers)

    if err := http.ListenAndServe("localhost:"+port, nil); err == nil {

        fmt.Println("listening to 8090")

    } else {

        fmt.Println("ListenAndServe: ", err)

    }

}

将共享库编译为:

$ go build -buildmode c-shared -o server.so server.go

将调用共享库中的函数的主文件写入为:Run

//main.go

package main


/*

#cgo LDFLAGS: -ldl

#include <dlfcn.h>


void Run(char* port){}


*/

import "C"


func main() {

    // handle := C.dlopen(C.CString("server.so"), C.RTLD_LAZY)

    // C.dlsym(handle, C.CString("8090"))


    C.dlopen(C.CString("server.so"), C.RTLD_LAZY)

    C.run(C.CString("8090"))

}

将主文件运行为:

$ go run main.go

主功能已直接终止,并且 srver 尚未在http://localhost:8090/hello


慕斯709654
浏览 114回答 1
1回答

qq_花开花谢_0

你为什么不把它分成一个go包(例如:包服务器)和导入这个包的主应用程序:yourproject/cmd/server/main.gopackage mainimport (&nbsp; &nbsp; "yourproject/internal/server")func main() {&nbsp; &nbsp; srv := server.New()&nbsp; &nbsp; // ...&nbsp; &nbsp; port := "8443"&nbsp; &nbsp; // do some logic here&nbsp; &nbsp; srv.Run(port)}和 yourproject/internal/server/server.gopackage serverimport (&nbsp; &nbsp; "fmt"&nbsp; &nbsp; "net/http")import "C"type Server struct{}func New() *Server {&nbsp; &nbsp; return &Server{}}func hello(w http.ResponseWriter, req *http.Request) {&nbsp; &nbsp; fmt.Fprintf(w, "hello\n")}func headers(w http.ResponseWriter, req *http.Request) {&nbsp; &nbsp; for name, headers := range req.Header {&nbsp; &nbsp; &nbsp; &nbsp; for _, h := range headers {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; fmt.Fprintf(w, "%v: %v\n", name, h)&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }}// export Run serverfunc (s *Server) Run(port string) {&nbsp; &nbsp; http.HandleFunc("/hello", hello)&nbsp; &nbsp; http.HandleFunc("/headers", headers)&nbsp; &nbsp; if err := http.ListenAndServe("localhost:"+port, nil); err == nil {&nbsp; &nbsp; &nbsp; &nbsp; fmt.Println("listening to 8090")&nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; fmt.Println("ListenAndServe: ", err)&nbsp; &nbsp; }}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go