Created
November 14, 2017 08:07
-
-
Save dtx/13fbd92a4067fc0a2bfe98acd1e5a7dd to your computer and use it in GitHub Desktop.
GET library for C written in Go
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"C" | |
"net/http" | |
"io/ioutil" | |
"fmt" | |
) | |
//export MakeGetCall | |
func MakeGetCall(a string) *C.char{ | |
fmt.Printf("Go: Making a call to %s\n", a) | |
// Make a get request | |
rs, err := http.Get(a) | |
// Process response | |
if err != nil { | |
panic(err) // More idiomatic way would be to print the error and die unless it's a serious error | |
} | |
defer rs.Body.Close() | |
bodyBytes, err := ioutil.ReadAll(rs.Body) | |
if err != nil { | |
panic(err) | |
} | |
fmt.Printf("Go: returning\n", a) | |
return C.CString(string(bodyBytes)) | |
} | |
func main() {} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#build the C archive files from Go code, this will generate getclient.h and getclient.a | |
$> go build -buildmode=c-archive getclient.go | |
#compile our trial.c file. pthread option is needed because Go runtime makes use of threads | |
$> gcc -pthread trial.c main.a -o trial | |
#run the output | |
$> ./trial | |
C: This is a C Application. | |
Go: Making a call to https://google.com | |
Go: returning |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include "getclient.h" | |
#include <stdio.h> | |
int main(){ | |
printf("This is a C Application.\n"); | |
GoString url = {"https://google.com", 18}; | |
MakeGetCall(url); | |
//I am ignoring the returned char pointer above that contains the result of the GET call. | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment