Unknown gRPC error with no error message - gRPC-web and goproxy - flutter-web

I'm trying to build a web application with the following stack:
Flutter/Dart
Go/goproxy
gRPC
MongoDB
I was able to successfully define and compile a protobuf into Dart and Go, however now that I'm trying to integrate the UI with the backend, I am running into the following issue:
Error: gRPC Error (code: 2, codeName: UNKNOWN, message:
null, details: [], rawResponse: null, trailers: {})
Here is my client code:
import 'package:grpc/grpc_web.dart';
import 'package:proj/protos/cards.pb.dart';
import 'package:proj/protos/cards.pbgrpc.dart';
class FiltersService {
static ResponseFuture<Filters> getFilters() {
GrpcWebClientChannel channel =
GrpcWebClientChannel.xhr(Uri.parse('http://localhost:9000'));
FiltersServiceClient clientStub = FiltersServiceClient(
channel,
);
return clientStub.getFilters(Void());
}
}
The server controller code:
const (
port = 9000
)
var (
grpcServer *grpc.Server
)
func StartServer() {
log.Println("Starting server")
listener, err := net.Listen("tcp", fmt.Sprintf(":%v", port))
if err != nil {
log.Fatalf("Unable to listen to port %v\n%v\n", port, err)
}
repositories.ConnectToMongoDB()
grpcServer = grpc.NewServer()
registerServices()
grpcWebServer := grpcweb.WrapServer(grpcServer)
httpServer := &http.Server{
Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.ProtoMajor == 2 {
grpcWebServer.ServeHTTP(w, r)
} else {
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE")
w.Header().Set("Access-Control-Allow-Headers", "Accept, Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization, X-User-Agent, X-Grpc-Web")
w.Header().Set("grpc-status", "")
w.Header().Set("grpc-message", "")
if grpcWebServer.IsGrpcWebRequest(r) {
grpcWebServer.ServeHTTP(w, r)
}
}
}),
}
httpServer.Serve(listener)
}
// Register services defined in protobufs to call from UI
func registerServices() {
cardsService := &services.CardsService{}
protos.RegisterCardsServiceServer(grpcServer, cardsService)
filtersService := &services.FiltersService{}
protos.RegisterFiltersServiceServer(grpcServer, filtersService)
}
I can tell that the server is receiving the request properly, and when I output the response of the service, I am getting the expected response.
Here is the service I am calling:
func (service *FiltersService) GetFilters(ctx context.Context, void *protos.Void) (*protos.Filters, error) {
filters := repositories.GetFilters()
return converters.FiltersStructToFiltersProtoConverter(filters), nil
}
When I output the response of converters.FiltersStructToFiltersProtoConverter(filters), I get the correct output, so it looks like there's still an issue with the way my server is set up.
I know this isn't a lot of info to go on, however I'm not sure what other information you may need, but can add as needed.

Related

Using node Modules from binding in Next.js

I would like to access a Firebird database in a Next.js (13.1.2) application. Therefore, I am using the node-firebird-libfbclient module: https://github.com/xdenser/node-firebird-libfbclient.
All seems well using pure Node.js. I can access the database successfully.
The problem starts, when I try to use the node-firebird-libfbclient in Next.js. I am aware that I can only use the database access server side. For starters, I am therefore using it in an API route, e.g. pages/api/test.ts
// pages/api/test.ts
import type { NextApiRequest, NextApiResponse } from 'next'
export default function handler(req: NextApiRequest, res: NextApiResponse<{}>) {
switch (req.method) {
case 'GET':
const fb = require('firebird');
const con = fb.createConnection();
con.connectSync('database.fdb', "sysdba", "password", "");
const res = con.querySync("SELECT * FROM test_table");
const rows = res.fetchSync("all", true);
res.status(200).json(rows);
break;
default:
res.status(404).json({ error: "No such method: " + req.method });
}
}
Accessing this route using http//localhost:3000/api/test I receive the following error:
error - ../firebird/node-firebird-libfbclient/firebird.js:1:0
Module not found: Can't resolve './build/Release/binding'
> 1 | var binding = require("./build/Release/binding");
2 | var stream = require("stream");
3 | var util = require("util");
4 | var events = require('events');
Import trace for requested module:
./src/pages/api/test.ts
Using Node.js directly works:
$ node
Welcome to Node.js v19.3.0.
Type ".help" for more information.
> var fb = require("firebird");
undefined
> console.log("%o", fb);
{
createConnection: <ref *1> [Function (anonymous)] {
[length]: 1,
[name]: '',
[arguments]: null,
[caller]: null,
[prototype]: { [constructor]: [Circular *1] }
},`
:
:
I was already trying to change ../firebird/node-firebird-libfbclient/firebird.js to:
var binding = require("./build/Release/binding.node");
This lead to a different error:
error - ../firebird/node-firebird-libfbclient/build/Release/binding.node
Module parse failed: Unexpected character '�' (1:2)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
(Source code omitted for this binary file)
Import trace for requested module:
../firebird/node-firebird-libfbclient/build/Release/binding.node
../firebird/node-firebird-libfbclient/firebird.js`
Any ideas what I am missing?

gocql: unable to create session: unable to discover protocol version: tls: first record does not look like a TLS handshake

Help, I am quite new to AstraDB, and while connecting it via goCQL, I got an error that says
"Error creating cassandra session: gocql: unable to create session: unable to discover protocol version: dial tcp 34.93.79.117:34567: i/o timeout"
I want to connect my code with server using GoCQL, and I was following this tutorial :- https://community.datastax.com/questions/3753/has-anyone-managed-to-connect-to-astra-from-gocql.html
I did not make much changes in my code, just a few different things from this tutorial.
In my code, Cassandra is a struct
type Cassandra struct {
Host string `yaml:"host"`
Port string `yaml:"port"`
Username string `yaml:"username"`
Password string `yaml:"password"`
Keyspace string `yaml:"keyspace"`
}
type cassandra struct {
Session *gocqlx.Session
}
func NewCassandraConfig() *Cassandra {
return &Cassandra{
Host: "", //databaseid-db_region.db.astra.datastax.com
Port: "34567", //port
Username: "", //token id
Password: "", //token password
Keyspace: "test", //keyspace created at
}
}
func New(conf *Cassandra) (*cassandra, error) {
cluster := gocql.NewCluster(conf.Host)
cluster.Keyspace = conf.Keyspace
cluster.Consistency = gocql.Quorum
cluster.Authenticator = gocql.PasswordAuthenticator{
Username: conf.Username,
Password: conf.Password,
}
cluster.Hosts = []string{conf.Host + ":" + conf.Port}
certPath, _ := filepath.Abs("absolute path to //cert") //gotten from bundle
keyPath, _ := filepath.Abs("absolute path to //key")
caPath, _ := filepath.Abs("absolute path to //ca.crt")
cert, _ := tls.LoadX509KeyPair(certPath, keyPath)
caCert, _ := ioutil.ReadFile(caPath)
caCertPool := x509.NewCertPool()
caCertPool.AppendCertsFromPEM(caCert)
tlsConfig := &tls.Config{
Certificates: []tls.Certificate{cert},
RootCAs: caCertPool,
}
cluster.SslOpts = &gocql.SslOptions{
Config: tlsConfig,
EnableHostVerification: false,
}
session, err := gocqlx.WrapSession(cluster.CreateSession())
if err != nil {
// log via logrus
log.Errorf("Error creating cassandra session: %v", err)
return nil, err
}
return &cassandra{
Session: &session,
}, nil
}
func main() {
CassandraConfig := NewCassandraConfig()
CassandraSession, err := New(CassandraConfig)
if err != nil {
log.Println("Error")
}
query := "SELECT id, name from test.testdata"
result := &testdata{}
iter := CassandraSession.Session.Query(query, nil).Iter()
for iter.Scan(&result.id, &result.name) {
log.Println(result.id, " ", result.name)
}
}
Can anyone help me find out what mistakes I made, cause I am unable to find that.
The error you posted indicates that you have configured something incorrectly so the driver is unable to connect to your database. It could be the wrong password, wrong CQL port, or incorrect certificate credentials.
I wrote those instructions all the way back to 2020 and they are a bit obsolete.
My suggestion is that you have a look at Nathan Bak's https://github.com/NathanBak/easy-cass-go package which makes it very easy to connect to your Astra DB. Cheers!

Use swagger specification in GoLang for Azure functions

Curently i'm building an Azure serverless Function in GoLang. I must have a swagger specification inside the function.
I'm using gin as http framework and swaggo as the swagger specification generator.
Main function:
func main() {
port, exists := os.LookupEnv("FUNCTIONS_CUSTOMHANDLER_PORT")
if !exists {
port = "8080"
}
r := gin.Default()
v1 := r.Group("/api")
v1.GET("/ping", function.Ping)
v1.GET("/docs", function.Swagger)
url := ginSwagger.URL("http://localhost:7071/api/docs")
v1.GET("/swagger", ginSwagger.WrapHandler(swaggerFiles.Handler, url))
r.Run(":" + port)
}
The function that will return the swagger.json:
func Swagger(c *gin.Context) {
c.File("docs/swagger.json")
}
When we build the application and run it local the response is 404.

Golang route not working

I just started to get into golang and as I plan to host at least two websites, I chose to use Mux to display different routes by "filtering" domains. Whenever I try to access my main route, it just gives me an 404 error. (Also, the fact that the "www" part is absent is perfectly normal. I don't type that to access the site).
But if I launch the server as a file server, I can access my files, so the server in itself is working I guess
func redirect(w http.ResponseWriter, req *http.Request) {
target := "https://" + req.Host + req.URL.Path
http.Redirect(w, req, target,
http.StatusTemporaryRedirect)
}
func main() {
go http.ListenAndServe(":80", http.HandlerFunc(redirect)) // Redirection
// Serveur sécurisé
r := mux.NewRouter()
r.PathPrefix("/static/").Handler(http.StripPrefix("/static/", http.FileServer(http.Dir("/root/go/src/web/static/"))))
s := r.Host("echecderi.me").Subrouter()
s.HandleFunc("/", indexEchec)
http.ListenAndServeTLS(":443", "domain-crt.pem", "domain-key.pem", nil)
}
func indexEchec(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "<h1>Echec de rime</h1> </br> <img src=\"/static/echecderime/echec.gif\">")
}
I think you need to give r as the last parameter to http.ListenAndServeTLS.
you can also use a http.server instance
//create server instance
server := http.Server{
Addr: ":443",
TLSConfig: tlsConfig(cert),
}
rtr := mux.NewRouter()
rtr.HandleFunc("/profile", HandlerProfile).Methods("GET")
//rtr.HandleFunc( other routes...
//pass mux handler to server
server.Handler = rtr
server.ListenAndServeTLS("", "")

MVC5 and IIS 7.5 Configuration

I have virtual server where is configured IIS 7.5 to works with ASP.NET MVC.
When I deploy application everything works fine. Only one thing is not working when I run application, maybe I'm wrong but I thought that code is correct.
<script>
$(document).ready(function () {
$("#Subcode").prop("disabled", true);
$("#MasterId").change(function () {
if ($("#MasterId").val() != "Select Master Code") {
var CountryOptions = {};
CountryOptions.url = "/Audit/FindSubCode";
CountryOptions.type = "POST";
CountryOptions.data = JSON.stringify({ master_id: $("#MasterId").val() });
CountryOptions.datatype = "json";
CountryOptions.contentType = "application/json";
CountryOptions.success = function (SubCodeList) {
$("#Subcode").empty();
for (var i = 0; i < SubCodeList.length; i++) {
$("#Subcode").append("<option>" + SubCodeList[i] + "</option>");
}
$("#Subcode").prop("disabled", false);
};
CountryOptions.error = function () { alert("Error in Getting SubCodes!!"); };
$.ajax(CountryOptions);
}
else {
$("#Subcode").empty();
$("#Subcode").prop("disabled", true);
}
});
});
</script>
#Html.DropDownList("MasterId",ViewBag.MasterId as SelectList,"Select Master Code",new { #class = "form-control"})
<select id="Subcode"></select>
And code from controller
public JsonResult FindSubCode(int master_id)
{
List<string> SubCodeList = new List<string>();
switch(master_id)
{
case 1:
SubCodeList.Add("Test");
break;
case 2:
SubCodeList.Add("Test2");
break;
}
return Json(SubCodeList);
}
Why I'm writing this problem as IIS Configuration, because if I run locally this application, everything works fine. But when I run on server I got error from code "Error in Getting SubCodes!!".
I tried to debug and get next error: Error when devug
Any suggestion how I can fix this ?
I don't think it has to do with configuration. Verify your URL.
/Audit/FindSubCode would be pointing to the root of the server which may be a different path to where the application is being served from.
Try not to hard code the path but rather use razor engin UrlHelper to generate the path.
CountryOptions.url = "#(Url.Action("FindSubCode","Audit")";

Resources