Trying to run a servr from a shared library, so I did the below:
- Writting the shahred library as:
// 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)
}
}
- Compiling the shared library as:
$ go build -buildmode c-shared -o server.so server.go
- Writting the main file that is calling the
Run
function in the shared library as:
//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"))
}
- Running the main file as:
$ go run main.go
The main function had been terminated directly, and the srver had not been run at http://localhost:8090/hello