Last active
January 6, 2023 18:24
-
-
Save pallabpain/fd0bc78f0d51973c05d2698ba253b0f6 to your computer and use it in GitHub Desktop.
A sample program to connect to a headscale server over gRPC
This file contains 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
// A sample program that connects to the headscale gRPC server | |
// and lists all the API keys | |
// | |
// Usage Example: go run main.go -server=localhost:50443 -apikey=3GbSjH5IqA.1FPG5ZiqB3a8idtvJnhBjCSb_V5pffuaLyFJyYZNPlQ | |
package main | |
import ( | |
"context" | |
"flag" | |
"fmt" | |
"os" | |
"os/signal" | |
v1 "github.com/juanfont/headscale/gen/go/headscale/v1" | |
"google.golang.org/grpc" | |
"google.golang.org/grpc/credentials/insecure" | |
) | |
var ( | |
HeadscaleServer string | |
ApiKey string | |
) | |
func main() { | |
flag.StringVar(&HeadscaleServer, "server", "", "<headscale-grpc-endpoint:port>") | |
flag.StringVar(&ApiKey, "apikey", "", "") | |
flag.Parse() | |
ctx, cancel := signal.NotifyContext(context.Background(), os.Interrupt, os.Kill) | |
defer cancel() | |
client, err := getHeadscaleClient(ctx, HeadscaleServer, ApiKey) | |
if err != nil { | |
fmt.Println(err) | |
os.Exit(1) | |
} | |
res, err := client.ListApiKeys(ctx, &v1.ListApiKeysRequest{}) | |
if err != nil { | |
fmt.Println(err) | |
os.Exit(1) | |
} | |
fmt.Println(res) | |
} | |
type tokenAuth struct { | |
token string | |
} | |
// Return value is mapped to request headers. | |
func (t tokenAuth) GetRequestMetadata( | |
ctx context.Context, | |
in ...string, | |
) (map[string]string, error) { | |
return map[string]string{ | |
"authorization": "Bearer " + t.token, | |
}, nil | |
} | |
func (tokenAuth) RequireTransportSecurity() bool { return false } | |
func getHeadscaleClient( | |
ctx context.Context, server, | |
apiKey string, | |
) (v1.HeadscaleServiceClient, error) { | |
grpcOptions := []grpc.DialOption{ | |
grpc.WithBlock(), | |
grpc.WithPerRPCCredentials(tokenAuth{ | |
token: ApiKey, | |
}), | |
grpc.WithTransportCredentials(insecure.NewCredentials()), | |
} | |
conn, err := grpc.DialContext(ctx, HeadscaleServer, grpcOptions...) | |
if err != nil { | |
return nil, err | |
} | |
client := v1.NewHeadscaleServiceClient(conn) | |
return client, nil | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment